Week 03 · N-grams, smoothing, and perplexity

Assign probability to unseen transitions and measure the cost on held-out text.

← Week 2 · Subject contents · Week 4 →

Assign probability to unseen transitions and measure the cost on held-out text.

Work through the problem

A bigram model estimates P(w|h) from counts of a previous token h and next token w. Add-α smoothing gives (C(h,w)+α)/(C(h)+α|V|), reserving mass for vocabulary items unseen after h.

If red is followed twice by fox and vocabulary is {fox,bird}, α=1 gives P(fox|red)=3/4 and P(bird|red)=1/4. An unsmoothed model assigns zero to red bird. Perplexity is exp(mean negative log probability). A zero-probability target makes it infinite.

Run the Python lab

from collections import Counter
from math import exp,log
pairs = Counter([("red","fox"),("red","fox"),("blue","bird")])
heldout = [("red","bird"),("blue","bird"),("red","fox")]
for alpha in [0,.2,1]:
    probs = [(pairs[h,w]+alpha)/(sum(pairs[h,v] for v in ["fox","bird"])+2*alpha) for h,w in heldout]
    perplexity = exp(-sum(log(p) for p in probs)/len(probs)) if all(probs) else float("inf")
    print(alpha,[round(p,3) for p in probs],round(perplexity,3))
assert probs==[.25,2/3,.75]

Output from the lab

0 [0.0, 1.0, 1.0] inf
0.2 [0.083, 0.857, 0.917] 2.481
1 [0.25, 0.667, 0.75] 2.0

Practice

  1. Can you directly compare token perplexity across two tokenizers?

Check your reasoning

  1. Different tokens mean different units. Compare a common quantity such as bits per byte under consistent text handling.

← Week 2 · Subject contents · Week 4 →

Further reading · Jurafsky and Martin · Speech and Language Processing