N-gram language models
Watch a model count the words of a tiny corpus and predict the next one.
Explain it simply
Each chip is one token: a word, or a marker for the start or the end of a sentence. The ochre window covers 2 tokens in a row. A run like that is called an n-gram. A language model built only from counts of these runs is an n-gram model.
Six rows of token chips, one row per sentence. An ochre window of 2 tokens slides along sentence 1. A list on the right shows the 11 tokens the model can predict.
An n-gram is n tokens in a row.
Show the code ▾Hide the code ▴ · Try it yourself · Python 3
import math
from collections import Counter
corpus = [
"the cat sat on the mat",
"the dog sat on the rug",
"the cat ran to the dog",
"a dog sat on a mat",
"the cat sat on a rug",
"a cat ran to the mat",
]
test = "the dog sat on the mat"
n, k = 2, 1 # n-gram size, add-k smoothing
def tokens(s):
return ["<s>"] + s.split() + ["</s>"]
def context(t, i):
return tuple(t[max(0, i - (n - 1)):i]) # the last n - 1 tokens
vocab = [] # every token a model can predict (not <s>)
for s in corpus:
for w in s.split():
if w not in vocab:
vocab.append(w)
vocab.append("</s>")
counts, totals = Counter(), Counter()
for s in corpus:
t = tokens(s)
for i in range(1, len(t)):
counts[context(t, i), t[i]] += 1
totals[context(t, i)] += 1
def prob(h, w):
den = totals[h] + k * len(vocab)
return (counts[h, w] + k) / den if den else 0.0
t = tokens(test)
log_p = 0.0
for i in range(1, len(t)):
h = context(t, i)
p = prob(h, t[i])
print(" ".join(h) or "(none)", "->", t[i], f"{p:.3f}")
log_p = log_p + math.log(p) if p > 0 and log_p > -math.inf else -math.inf
N = len(t) - 1 # tokens predicted, with </s>
pp = math.exp(-log_p / N)
print("perplexity", f"{pp:.2f}")
# prints:
# <s> -> the 0.294
# the -> dog 0.158
# dog -> sat 0.214
# sat -> on 0.333
# on -> the 0.200
# the -> mat 0.158
# mat -> </s> 0.286
# perplexity 4.43
Copy it into a file and run it. Change n, k or the test sentence.
Common mix-ups
MYTHA longer context always predicts the test sentence better.
FIXA longer context finds fewer matches, so its counts are thin. With add 1, the trigram perplexity is 5.19 against 4.43 for the bigram.
MYTHAn n-gram that the corpus never shows is impossible.
FIXThe corpus is small, so unseen does not mean impossible. Without smoothing, one zero makes the perplexity infinite.
Takeaways
- An n-gram model predicts the next token from counts of its context.
- A longer context gives sharper predictions but finds fewer matches.
- Smoothing keeps unseen n-grams above zero, so the perplexity stays finite.