Introduction
In class you built a language model by hand. You tallied the words that came after each word in the rhyme, and then you generated new text by starting with a word, looking up its row, and rolling a die to choose the next word. In this tutorial you will build the same model in Python. Then you will run it on an entire book, which would take far too long to tally by hand. There are two research questions:
- Does Python’s model match the one you built by hand?
- What does the same model do with a whole book?
We will work with the rhyme for question 1 and then with Alice’s Adventures in Wonderland for question 2.
You will need everything from the last tutorial (loops, if statements, dictionaries, and your clean function). Along the way you will also meet range and the random module, and you will make your first plot.
Getting started
Keep working on this week’s lab. Make a new notebook called counting_model.ipynb in notebooks and choose the same kernel as for 020 (the lab’s own Python, .venv/bin/python). The first cell sets up the paths, defines clean, and reads the rhyme, as in the last tutorial.
As before, type and run each piece of code on this page in your notebook. You can copy clean from your repeating_and_deciding.ipynb notebook rather than typing it again. This notebook can’t use the copy in that one, because each notebook keeps its own variables and functions. (Remember that the checks GitHub runs when you push cover this notebook too.)
from pathlib import Path
DATA_RAW = Path("../data/raw")
OUTPUTS = Path("../outputs")
def clean(text):
"""Split text into lower-case words and strip punctuation from each one."""
words = text.lower().split()
clean_words = []
for word in words:
stripped = word.strip('.,!?;:"()')
if stripped != "":
clean_words.append(stripped)
return clean_words
rhyme_text = (DATA_RAW / "the_star.txt").read_text(encoding="utf-8")
rhyme = clean(rhyme_text)
rhyme[0:6]
['twinkle', 'twinkle', 'little', 'star', 'how', 'i']
The table of next words
The table you made in class had a row for each word, with a tally of the words that came right after it. To build it in Python, we go through the rhyme one pair of neighboring words at a time (the first word and the second, then the second and the third, and so on).
So far our loops have gone through a list item by item. Here we need the positions of the items, because the neighbor of the word at position i is the word at position i + 1. The range function gives us a sequence of positions. range(5) gives 0, 1, 2, 3, 4 (like a slice, it stops just before the number you give it).
for i in range(5):
print(i, rhyme[i], rhyme[i + 1])
0 twinkle twinkle
1 twinkle little
2 little star
3 star how
4 how i
The rhyme has 44 words but only 43 neighboring pairs, because the last word has nothing after it. To go through every pair we use range(len(rhyme) - 1).
In Python, the table will be a dictionary with a key for each word. The value for a word is a list of every word that came right after it, so a word you tallied twice in class appears in the list twice. For each pair, we add the second word to the first word’s list. If the first word doesn’t have a list yet, we give it an empty one before adding to it.
Let’s try this first on a list short enough to follow by hand.
short_words = ["the", "cat", "saw", "the", "dog", "saw", "the", "cat"]
Here is the loop. Before you run it, work through it on paper. For each value of i, write down word and following, and then what short_table holds after that pass through the loop. What will short_table be at the end?
short_table = {}
for i in range(len(short_words) - 1):
word = short_words[i]
following = short_words[i + 1]
if word not in short_table:
short_table[word] = []
short_table[word].append(following)
short_table
{'the': ['cat', 'dog', 'cat'],
'cat': ['saw'],
'saw': ['the', 'the'],
'dog': ['saw']}
The list has eight words and seven pairs, so the loop runs seven times, with i going from 0 to 6. On each pass, the if statement gives word an empty list if it doesn’t have one yet, and the last line adds following to the end of that list. “The” comes up three times, followed by “cat”, “dog”, and “cat”, which is why its list is ['cat', 'dog', 'cat']. If your table is different, go back to the first pass where your notes and Python disagree.
What would go wrong if we left out the if statement and the line under it? Think about the first pass through the loop, when short_table is still empty.
On the first pass, short_table is empty, so short_table[word] asks for a key, “the”, that isn’t there. Python stops with a KeyError, the same error you saw in the last tutorial when you looked up “moon” in counts.
Here is the same loop for the rhyme. This time we call the table next_words.
next_words = {}
for i in range(len(rhyme) - 1):
word = rhyme[i]
following = rhyme[i + 1]
if word not in next_words:
next_words[word] = []
next_words[word].append(following)
Let’s look up a few rows.
['twinkle', 'little', 'twinkle', 'all']
['world', 'sky', 'blazing', 'night']
Compare these with your table from class. In the rhyme, “twinkle” is followed by “twinkle” twice and by “little” and “all” once each, so “twinkle” is in its list twice. Most words, like “star”, have only one word that ever follows them.
Is there a row for “night”? Predict the answer, and why, before you run the cell.
No. “Night” is the last word of the rhyme, so no word ever follows it. In class, a line that reached “night” had to stop for the same reason.
Random choices
In class you rolled a die to choose the next word. In Python we use the random module, which comes with Python (like pathlib). Its function choice picks one item from a list at random, and every item in the list is equally likely.
import random
random.choice(next_words["twinkle"])
Run that cell several times, and you will get different words. “Twinkle” is two of the four items in the list, so choice picks it about half the time, the same chance it had with your die. We don’t need the counts, because a word that followed twice is in the list twice.
Randomness causes trouble when someone else (or you, later) wants to get the same results. A computer doesn’t actually roll dice, though. It computes a long sequence of numbers that only looks random, starting from a number called a seed, and the same seed always gives the same sequence. Set the seed, and then run the cell a few times.
random.seed(1851)
random.choice(next_words["twinkle"])
You should get the same word every time, and so will anyone else who sets the same seed and uses the same version of Python. We set a seed in this tutorial whenever we generate text, which is why your results should match the ones on this page.
Generating a line
To generate a line, we do what you did in class. Start with a word, look up its row, choose the next word at random, and add it to the line. Then look up the new word’s row and choose again. We stop after ten words, or sooner if we reach a word that has no row.
random.seed(1851)
word = "twinkle"
line = [word]
for step in range(9):
if word not in next_words:
break
word = random.choice(next_words[word])
line.append(word)
" ".join(line)
'twinkle all the world so high like a diamond in'
The loop runs at most nine times and adds a word each time, so with “twinkle” the line has at most ten words. If the model reaches a word with no row, break ends the loop early, but this line never reached one. The last line of the cell uses the string method join to put the words of the list together into one string, with a space between each pair.
The line begins with the end of the rhyme (“twinkle, all the”) and then switches to the first verse (“the world so high”). After “the”, the model could have gone on with any of the 4 words that ever followed “the” anywhere in the rhyme, because it looks only at the current word.
Making it a function
We will generate a lot of text, so let’s turn this code into a function. Our clean function took one input, and generate will take three (the table, a starting word, and how many words we want).
def generate(next_words, start, n_words):
"""Generate text from a table of next words, beginning with start."""
word = start
line = [word]
for step in range(n_words - 1):
if word not in next_words:
break
word = random.choice(next_words[word])
line.append(word)
return " ".join(line)
The three inputs are listed in the def line with commas between them. When we call generate, Python matches the values we give it with the inputs in order. In the cell below, generate(next_words, "twinkle", 10) gives the rhyme’s table to next_words, “twinkle” to start, and 10 to n_words. The loop runs n_words - 1 times, since the starting word is already in the line.
As with clean in the last tutorial, help shows the docstring.
Help on function generate in module __main__:
generate(next_words, start, n_words)
Generate text from a table of next words, beginning with start.
random.seed(1)
for trial in range(4):
print(generate(next_words, "twinkle", 10))
twinkle little star how i wonder what you show your
twinkle twinkle all the night
twinkle all the night
twinkle twinkle little star how i wonder what you show
We got four different lines from one model and one starting word. Each line is called a draw from the model. A chatbot works the same way, which is why it can answer the same question differently each time you ask.
A bigger text: Alice’s Adventures in Wonderland
The rhyme has only 44 words, which doesn’t give the model much to work with. For research question 2 we need a whole book. The file alice.txt in data/raw holds all of Lewis Carroll’s Alice’s Adventures in Wonderland (1865). We downloaded it from Project Gutenberg, and since books this old are in the public domain in the United States, anyone can use it. (We removed Project Gutenberg’s introduction and license from the file before putting it in data/raw. With your own text in Your turn, you will do that step in code.)
alice_text = (DATA_RAW / "alice.txt").read_text(encoding="utf-8")
alice_text[0:300]
'CHAPTER I.\nDown the Rabbit-Hole\n\n\nAlice was beginning to get very tired of sitting by her sister on the\nbank, and of having nothing to do: once or twice she had peeped into\nthe book her sister was reading, but it had no pictures or\nconversations in it, “and what is the use of a book,” thought Alice\n'
That is the first 300 characters of the book. How many characters are there in all?
Checking the words
Let’s clean it with our function and count the words.
alice_words = clean(alice_text)
len(alice_words)
Before we build anything from this list, we should check it. One quick check is to count the “words” that have something in them besides letters. The string method isalpha gives True when a string has only letters, and the loop below counts every word for which it gives False.
odd = {}
for word in alice_words:
if not word.isalpha():
if word in odd:
odd[word] = odd[word] + 1
else:
odd[word] = 1
len(odd)
There are a lot of odd words. Here are the first fifteen.
['rabbit-hole',
'“and',
'book,”',
'“without',
'conversations?”',
'daisy-chain',
'_very_',
'“oh',
'late!”',
'_took',
'waistcoat-pocket_',
'waistcoat-pocket',
'book-shelves',
'“orange',
'marmalade”']
A few of these, like rabbit-hole and daisy-chain, really are words. Most of the rest still have punctuation stuck to them. This book uses curly quotation marks and apostrophes (“ ” ‘ ’), and those are different characters from the straight quotation mark (") we told strip to remove. The book also marks italics with underscores (as in _very_), uses long dashes (—), and has rows of asterisks between sections.
Let’s add those characters to the ones strip removes. Apostrophes inside a word stay put, because strip only works on the ends of a word (don’t stays don’t). Most keyboards have no keys for curly quotation marks or long dashes, so copy the strip line from this page instead of typing it.
def clean(text):
"""Split text into lower-case words and strip punctuation from each one."""
words = text.lower().split()
clean_words = []
for word in words:
stripped = word.strip('.,!?;:"()“”‘’_—*')
if stripped != "":
clean_words.append(stripped)
return clean_words
alice_words = clean(alice_text)
len(alice_words)
Now run the same loop on the new list to see what is left.
odd = {}
for word in alice_words:
if not word.isalpha():
if word in odd:
odd[word] = odd[word] + 1
else:
odd[word] = 1
len(odd)
['rabbit-hole',
'daisy-chain',
'waistcoat-pocket',
'book-shelves',
'they’ll',
'wouldn’t',
'i’ve',
'that’s',
'distance—but',
'it’ll',
'didn’t',
'ma’am',
'spoke—fancy',
'you’re',
'she’ll']
Most of these fifteen are fine now. Rabbit-hole really has a hyphen, and we wanted contractions like didn’t to keep their apostrophes. Words joined by a long dash with no space, like distance—but, are still a problem, but only 155 of the book’s 26381 words are like that, and we will ignore them.
Building the model
Now we build the table the same way we did for the rhyme. You will need to do this again for your own text in Your turn, so this time we put the loop in a function.
def build_table(words):
"""For each word, list every word that follows it in words."""
next_words = {}
for i in range(len(words) - 1):
word = words[i]
following = words[i + 1]
if word not in next_words:
next_words[word] = []
next_words[word].append(following)
return next_words
alice_table = build_table(alice_words)
len(alice_table)
The table has a row for each of the 2777 different words in the book, and many of the rows are long. The row for “of” has 508 words, and here are the first ten.
['sitting',
'having',
'a',
'making',
'getting',
'the',
'its',
'it',
'time',
'the']
Inside build_table, next_words started as an empty dictionary and was filled with words from Alice. Did that change the next_words table we made for the rhyme? Predict what this cell gives before you run it.
['twinkle', 'little', 'twinkle', 'all']
It is still the rhyme’s row. Like words inside clean in the last tutorial, the next_words inside build_table belongs to the function, and building the Alice table did not touch the rhyme’s table. The next_words inside generate belongs to that function too. It is whatever table we give generate, which is how generate(alice_table, "alice", 15) in the next cell uses the Alice table.
Now generate some text.
random.seed(1851)
for trial in range(4):
print(generate(alice_table, "alice", 15))
alice replied rather sharply and with her friend of tiny hands so she asked why
alice thought alice soon finished the rabbit say you didn’t know he taught them i’m
alice rather glad to it and all the queen who in it there were animals
alice sharply do how the game the caterpillar and put a railway she gained courage
Each pair of neighboring words in these lines appears somewhere in the book (once the punctuation is gone), but most of the lines as a whole do not.
Counting words, and a first plot
In the last tutorial we counted words with a loop and a dictionary. Python has a tool that does this for us. Counter, from the collections module, counts the items in a list, and its method most_common gives the most frequent ones.
from collections import Counter
alice_counts = Counter(alice_words)
top_ten = alice_counts.most_common(10)
top_ten
[('the', 1630),
('and', 844),
('to', 721),
('a', 627),
('she', 537),
('it', 526),
('of', 508),
('said', 462),
('i', 400),
('alice', 385)]
most_common gives a list of pairs, each in parentheses. A pair like this is called a tuple, and it works like a list that can’t be changed. In the loop below, for word, count in top_ten takes each pair apart, putting the word in word and the count in count.
labels = []
values = []
for word, count in top_ten:
labels.append(word)
values.append(count)
labels
['the', 'and', 'to', 'a', 'she', 'it', 'of', 'said', 'i', 'alice']
Now let’s plot them. We make plots with a package called matplotlib, which this lab already has (it is listed in pyproject.toml). Python programmers usually import the part of matplotlib we need under the short name plt.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.bar(labels, values)
ax.set(xlabel="Word", ylabel="Times it appears", title="Most common words in Alice")
plt.show()
That is your first plot. Every plot we make this semester starts this way. In the second line, plt.subplots() makes a figure (the whole picture, which we call fig) and a set of axes (the plotting area inside it, which we call ax). Then ax.bar draws a bar chart on the axes, ax.set adds the labels and title, and plt.show() displays the plot. Some plots can be made with less code, but this way works for every kind of plot, and you will see it often in scientific Python code (including code that AI tools write).
To save the plot as an image, use the figure’s savefig method. Plots go in the lab’s outputs folder.
fig.savefig(OUTPUTS / "top_words_alice.png", dpi=200, bbox_inches="tight")
The option dpi=200 makes a sharp image, and bbox_inches="tight" trims the extra white space around it. Look in the outputs folder in the Explorer to find the file, and click it to see it.
Saving what you made
Let’s also save some generated text in outputs. The cell below generates five pieces of text and joins them into one string. This time join puts "\n\n" between them instead of a space. You saw \n, the newline character, in 010, and two of them in a row leave a blank line between the pieces. Then write_text writes the string to a file. It takes the same encoding option as read_text.
random.seed(1851)
generated = []
for trial in range(5):
generated.append(generate(alice_table, "the", 20))
generated_text = "\n\n".join(generated)
(OUTPUTS / "generated_alice.txt").write_text(generated_text, encoding="utf-8")
The number it shows is the number of characters written. Open the file from the Explorer to check it.
How real language models differ
Our model is about as simple as a language model gets. It looks at the last word, lists the words that came after it in the text, and picks one at random. A large language model also picks the next piece of text at random from a list of possibilities, but it works with tokens (words and pieces of words), and it looks back over much more of the text than one word. Its probabilities come from a neural network trained on an enormous amount of text instead of from a table of counts. The network can give sensible probabilities even to combinations of words it has never seen. (Chatbots also adjust how random the choice is, and they get further training to follow instructions.)
Answering the research questions
Yes, Python’s model matches the one you built by hand (research question 1). Its table has the same rows as yours, and generate picks each next word the way you did with your die. With a whole book (research question 2), the model writes lines that sound a bit like Alice, because every pair of neighboring words in them is from the book. Most of the lines are not in the book, though. When the model picks a word, it looks only at the word before it.
Your turn
Put your answers in your notebook after the tutorial code. Before each answer, add a Markdown cell with a heading that gives the question’s number and what it is about, such as ### 1. My own text. Give each part of a question with parts (3a, 3b, and so on) its own heading. When a question asks you to explain something or to answer in words, write the answer in a Markdown cell, in full sentences, right after any code it is about.
Your own text. Find a public-domain text that interests you, perhaps from your own field. Project Gutenberg has thousands, from Darwin’s On the Origin of Species to The Federalist Papers and W. E. B. Du Bois’s The Souls of Black Folk. On the book’s page, right click the Plain Text UTF-8 link, choose Save Link As… (Download Linked File in Safari), and save the file in data/raw. (If your browser puts it in Downloads, move it into data/raw in Finder or File Explorer.) Leave the file as it is. Your notebook will trim it, so anyone who downloads the same file can repeat what you did.
After you read the file in, keep only the book itself, which sits between a line that begins with *** START OF and a line that begins with *** END OF. (Project Gutenberg’s introduction and license are outside those lines.) The string method index gives the position where a piece of text first appears. If the book is in text, for example, text.index("*** START OF") is the position where that line starts. Find both positions, and use a slice to keep the text between them. (It is fine if the *** START OF line itself stays in.) Then clean the text, look for odd words as we did, and change your clean function if you need to. Build a table, generate a few lines, and save one generated text file and a bar chart of the ten most common words in outputs. In a Markdown cell, describe how the generated text compares with the Alice text.
Seeds. Generate four lines starting with “the” using seed 1, and then four using seed 2. Run each cell twice. What changes, and what stays the same? In a sentence or two, explain why setting a seed matters if you want someone else to check your work.
What-if questions. Answer each one in Markdown. For b and c, include the code that shows your answer.
- Our model looks one word back. Suppose it looked two words back, so that each row was for a pair of words (“the white”, “white rabbit”, …). What would the keys of the table be? Would the generated text be closer to the book or further from it? Would the model need more text or less to work well, and why?
- When our rhyme model reached “night”, it stopped. Could that ever happen with the Alice model? Use code to find the last word of the book and to check whether the model could stop there.
- The model made up sentences that do not appear in the book. Pick one of your generated lines and check whether it appears in the book. Search the cleaned words instead of the raw text, where line breaks and punctuation get in the way. The
in operator works on strings: "down the rabbit-hole" in " ".join(alice_words). Why would a model like this produce text that sounds right but was never written?
These are optional.
- Which word in Alice is followed by the most different words? (For one row,
len(set(alice_table["of"])) counts the different words in it, because a set keeps one copy of each item.) Then find a word that is common in the book but almost always followed by the same word.
- Build the two-word model from question 3a. A tuple such as
("the", "white") can be a dictionary key.
- Measure how original the model is. Generate a long stretch of text, and find the fraction of its four-word sequences that appear word for word in the book. (Compare tuples of four words instead of searching one long string, where “but i” would match inside “but it”.) How does that fraction change for the two-word model?
What to hand in
Click Restart and then Run All. Check that everything runs and that the results still match the tutorial and your notes, and save. Both notebooks from this week (repeating_and_deciding.ipynb and counting_model.ipynb) should be in your repository. Commit your work, including the files in outputs, and push it to GitHub by the week 2 deadline on the schedule.
Then look at the latest autograding result, linked from the Feedback pull request in your repository, as described at the end of 020. If a check does not pass, fix what it says, run the notebook again, and push.
Back to top