Text from chance: Markov chains
Can a program write? A very simple one can – it only has to read something first. The idea goes back to the Russian mathematician Andrey Markov, who in 1913 went through Pushkin's verse novel Eugene Onegin letter by letter and counted how often a vowel follows a consonant and the other way round. Our version works with words: note for every word which words came after it in a text, then make up a new text by always picking one of those followers at random. Here is the story Chunky has read, cut into words. each_cons(2) walks through them in overlapping pairs – the first and the second, the second and the third, and so on:
text = <<~TEXT
the fox eats chunky bacon and the fox sings about chunky bacon
and the cat eats toast and the toast sings to the moon
TEXT
words = text.split
words.each_cons(2).first(5)Every pair says: “this word once came after that one.” Now gather the pairs into a table that holds, for every word, the list of words that followed it. A hash with a list for each word – but which empty list does a new word get? Hash.new(0) from lesson 11 gives missing keys a default value, so Hash.new([]) looks like the obvious choice. It is a trap:
trap = Hash.new([])
trap["fox"] << "eats"
trap["cat"] << "naps"
p trap
trap["owl"]{} – the hash is still empty, and yet trap["owl"] answers ["eats", "naps"]. The default is one single array, shared by every missing key, and << pushes the words into that shared array without ever storing a key. (Hash.new(0) only works because += 1 stores a new number under the key.) The way out is the block form: Hash.new { |hash, key| hash[key] = [] } runs the block for every missing key, and the block stores a new empty array under that key:
table = Hash.new { |hash, key| hash[key] = [] }
words.each_cons(2) { |a, b| table[a] << b }
tableThat table is everything our program “knows”. The repeats matter: after "the" came "fox" twice. tally counts them, and the counts are the chances – in 2 of 5 cases "the" is followed by "fox", that is 40 %:
p table["the"]
table["the"].tallyNow let it write. Start with a word, pick one of its followers at random, then one of that word's followers, and so on. sample draws from the list, so a follower that is in it twice gets drawn twice as often – the chances take care of themselves. To get the same text on every run, the die gets a seed: Random.new(24) is a die of its own, and sample(random: dice) rolls with it – like srand in lesson 10, but only for this one die. One more trap: with the block form, even reading a missing word would store an empty list under it, so the followers are looked up with fetch(word, []). A word without followers ends the text:
dice = Random.new(24)
word = "the"
story = [word]
10.times do
followers = table.fetch(word, [])
break if followers.empty?
word = followers.sample(random: dice)
story << word
end
story.join(" ")"the cat eats toast and the fox sings about chunky bacon" – every pair of neighbouring words comes from Chunky's story, but the sentence as a whole does not. Try other seeds: with Random.new(16) the chain runs into "moon", which nothing ever followed, and stops early.
The same trick works with letters, and then it invents names. Put a . before and after every name: a letter that follows a . is a first letter, and a . that follows a letter means “the name ends here”:
names = %w[chunky foxy rufus fenna roxy reynard]
letters = Hash.new { |hash, key| hash[key] = [] }
names.each do |name|
".#{name}.".chars.each_cons(2) { |a, b| letters[a] << b }
end
letters["."]Those are the first letters of the six names. Now the same chain as before, letter by letter, from the . to the next .:
dice = Random.new(4)
5.times.map do
name = ""
letter = letters["."].sample(random: dice)
until letter == "."
name += letter
letter = letters[letter].sample(random: dice)
end
name.capitalize
endFour new fox names and an old one: Foxy comes back because the chain happened to walk along an original name. The table remembers only one step back, which is why the results sound nearly right and then wander off. Remember two words back – a table from each_cons(3) – and the texts sound much more like the original (and copy it more often). The keyboard on your phone that suggests the next word works on the same idea, and today's large language models are a distant, enormously bigger relative: they look back over thousands of words instead of one.
follower_counts(text): a hash that maps every word of text to a hash of its followers and how often each one came – the table from above with tally applied to every list. follower_counts("the fox and the fox naps") is { "the" => { "fox" => 2 }, "fox" => { "and" => 1, "naps" => 1 }, "and" => { "the" => 1 } }.# def follower_counts(text)
# ... # every word => { follower => how often it came after the word }
# end
# p follower_counts("the fox and the fox naps")
babble(table, start, n, random): a text of at most n words, as a string, beginning with start. Each next word is a random follower of the word before it, drawn with sample(random: random); the text ends early at a word without followers – one that isn't in the table at all, or whose list is empty. The same seed must give the same text: babble(table, "the", 12, Random.new(24)) gives the same words every time.# def babble(table, start, n, random)
# ... # start, then a random follower of the last word, and so on:
# ... # at most n words, fewer when a word has no followers
# end
# babble(table, "the", 12, Random.new(24))