A language model gives a probability to whatever comes next. The simplest one looks at a single previous character and gets every number by counting. This lesson pairs with The spelled-out intro to language modeling: building makemore by Andrej Karpathy, linked under Watch & read. You build the model in NumPy: a vocabulary, a table of counts, row-normalised probabilities with smoothing, a loss that scores words, and a sampler that writes new ones.
Start with the vocabulary. Words are lowercase strings, and one extra symbol, ., gets index 0. Put it at both ends of every word, so tea becomes .tea.. The leading . lets the model learn how words start, and the trailing one lets it learn when they stop. The other characters follow in sorted order. itos maps an index to its character and stoi maps back.
Every neighbouring pair of symbols is a bigram, and a word of n letters has n + 1 of them. Counting them fills a table where counts[i, j] is the number of times character j followed character i. Read a row as "I am on this character" and a column as "this is what came next".
. marks both ends of a word. The highlighted cell says that e followed t three times. All 16 cells add up to 16, the number of bigrams in four three-letter words.import numpy as np
words = ["tea", "tee", "eat", "ate"]
itos = ["."] + sorted(set("".join(words)))
stoi = {c: i for i, c in enumerate(itos)}
counts = np.zeros((4, 4), dtype=int)
for w in words:
ids = [0] + [stoi[c] for c in w] + [0]
for a, b in zip(ids, ids[1:]):
counts[a, b] += 1
print("".join(itos), counts.sum())
print(counts.tolist())Dividing each row by its total turns counts into the estimate of P(next = j | current = i). Row t above is [1, 0, 3, 0] with total 4, so after a t the model gives . a probability of 0.25 and e 0.75. The division has to be per row, which means the totals need the shape (V, 1). keepdims=True keeps that shape, and a column of totals broadcasts across each row.
import numpy as np
counts = np.array([[0, 1, 1, 2], [1, 0, 0, 2], [2, 2, 1, 0], [1, 0, 3, 0]])
totals = counts.sum(axis=1, keepdims=True)
print(totals.shape, totals.ravel().tolist())
print((counts / totals)[3].round(3).tolist()) # the row for t
print((counts / totals).sum(axis=1).tolist())A table that is square does not warn you when you normalise the wrong way. With axis=0 the totals have shape (1, V), the division still runs, and the result looks like probabilities. Its rows no longer sum to 1. Always check probs.sum(axis=1).
How good is the model? Score a set of words by the average of -log P(next | current) over all of their bigrams. This is the negative log-likelihood, and lower is better. Divide by the number of bigrams, never by the number of words: longer words contain more bigrams, so a per-word divisor inflates the loss. A uniform model over V symbols scores ln V on any text, which is the number to beat. Here V = 4, and the model trained on these four words scores 0.8495, against ln 4 = 1.3863 for guessing.
That score hides a problem. A pair that never occurred in training has probability 0, and one such pair makes the loss on new text infinite. The fix is smoothing: add a pseudo-count s to every cell before dividing, so row i has total (row sum) + s·V. The run below scores the training words and the new word tat, whose pair ta never appeared.
import numpy as np
counts = np.array([[0, 1, 1, 2], [1, 0, 0, 2], [2, 2, 1, 0], [1, 0, 3, 0]])
stoi = {".": 0, "a": 1, "e": 2, "t": 3}
def nll(words, probs):
ids = [[0] + [stoi[c] for c in w] + [0] for w in words]
pairs = [(a, b) for w in ids for a, b in zip(w, w[1:])]
with np.errstate(divide="ignore"):
return -np.mean([np.log(probs[a, b]) for a, b in pairs])
for s in (0, 1):
probs = (counts + s) / (counts + s).sum(axis=1, keepdims=True)
print(s, round(nll(["tea", "tee", "eat", "ate"], probs), 4), round(nll(["tat"], probs), 4))Smoothing makes the training score worse (0.8495 becomes 1.0654) and the unseen word finite (infinity becomes 1.3235). The size of s is a choice, and held-out words are how you make it. With 36 invented words for training, 12 held out and 19 symbols, the training loss rises steadily as s grows. The held-out loss falls first and then rises, with its best value near s = 0.25.
Sampling runs the table forward. Keep the index of the current character, starting at 0. Draw the next index from that row with the generator you were given, stop when you draw 0, and otherwise append the character. Cap the word at max_len, because a table with a loop in it can keep going. Passing the generator in, rather than reaching for a global one, is what makes a seeded run repeat exactly.
Three mistakes are worth knowing before you build. Normalising columns instead of rows is the quietest, because nothing crashes. Averaging per word makes the loss depend on word length. Reading counts[i, j] as the probability of i given j swaps the direction of the model.
The tests compare your counts with a dictionary count, your probabilities with the closed form (c + s) / (row + s·V), and your loss with an entropy identity: with s = 0, the training loss is exactly the entropy of the rows weighted by their counts. They also compare how often sampled words occur with the probabilities the model assigns. All of this confirms the code matches the definition. It does not show that one character of context is a good model of words. The video goes on to replace the table with a trained network, and the next lesson builds that.