Level 0: Foundation
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.Guessing the next word from the last few
After “the cat sat on the”, the next word is probably “mat” or “floor”. An n-gram model makes this guess by counting: how often did each word follow these last few words in lots of text? The trouble is that most word combinations never appear, even in huge collections, and a raw count of zero would make them impossible. Smoothing shares out a little probability to things never seen. The demo shows how add-k smoothing gives an unseen word pair some probability.
n-gram models were the backbone of speech recognition, machine translation and phone keyboards for decades, and are still used where compute is tiny or for fast first-pass decoding.
- 1. An n-gram model predicts the next word from…
- 2. A word pair never seen in training gets, without smoothing…
- 3. Smoothing…
Level 1: Beginner
★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.By hand
- Markov assumption: P(w₁ … w_T) = Π_t P(w_t | w_(t−n+1) … w_(t−1)). A bigram model conditions on one word, a trigram model on two.
- Maximum likelihood: P(w | v) = c(v w) / c(v). With V words there are V^n possible n-grams (125,000 trigrams for V = 50), so most have count zero.
- Perplexity: PPL = exp(−(1/T) Σ log P(w_t | context)). It is the effective number of equally likely choices: a uniform model over 4 words has perplexity 4. One zero probability makes it infinite.
- Add-k (Laplace when k = 1): P = (c(v w) + k) / (c(v) + kV). Simple, but with large V it gives too much mass to unseen events.
- Interpolation: λ₃P(w | u v) + λ₂P(w | v) + λ₁P(w), with λ tuned on held-out data. Backoff (Katz) uses the lower order only when the higher count is zero.
- Kneser–Ney: subtract a discount d ≈ 0.75 from every count and give the freed mass to a lower-order model that counts in how many different contexts a word appears (“Francisco” is frequent but follows almost only “San”).
- 1. Perplexity of a uniform model over 4 words:
- 2. Possible trigrams with V = 50:
- 3. Kneser–Ney's lower order counts…
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.n-gram models in code
Exercise 1.
- Count bigrams and compute add-k probabilities, which sum to 1 over the vocabulary.
- Compute perplexity: familiar text scores lower than unfamiliar text.
Practice.
- KenLM builds and queries large modified-Kneser–Ney models quickly; NLTK’s
nltk.lmhas MLE, Laplace, Witten–Bell and Kneser–Ney for teaching. - Add sentence-boundary tokens
<s>and</s>, map rare words to<unk>, and fix the vocabulary on training data. - Tune interpolation weights or discounts on held-out data, never on test data.
- Compare perplexities only between models with the same vocabulary and tokenization.
from nltk.lm import KneserNeyInterpolated
from nltk.lm.preprocessing import padded_everygram_pipeline
train, vocab = padded_everygram_pipeline(3, tokenized_sentences)
lm = KneserNeyInterpolated(order=3); lm.fit(train, vocab)
print(lm.perplexity(list(nltk.ngrams(["<s>", "<s>"] + test + ["</s>"], 3))))- 1. A fast toolkit for large Kneser–Ney models:
- 2. Rare words are usually mapped to…
- 3. Perplexities are comparable only with…
Level 3: Advanced
★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.Theory
Why smoothing is necessary. With V^n possible n-grams and far fewer training tokens, most n-grams are unseen. MLE assigns them zero, so test perplexity is infinite. Smoothing is a bias–variance trade-off: it biases estimates towards a simpler distribution to reduce the variance of sparse counts.
Why add-one fails. It adds one pseudo-count to every possible next word. With V = 50 and a context seen 5 times, 50 of the 55 pseudo-observations are invented, so observed evidence is swamped. Small k is better but still treats all unseen words alike.
Why Kneser–Ney works. Absolute discounting matches empirical findings (Church and Gale): counts in held-out data are about 0.75 lower than training counts. The continuation-count lower order estimates how likely a word is to appear in a new context, which is exactly what backing off needs. Chen and Goodman (1998) found modified Kneser–Ney the best n-gram smoother across corpora. Its hierarchical Pitman–Yor interpretation (Teh, 2006) explains why.
- 1. Smoothing trades…
- 2. Add-one fails mainly because…
- 3. Chen and Goodman found the best n-gram smoother to be…
Level 4: Expert
★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.How much do different smoothing methods matter as data grows?
History.
- C. E. Shannon, “A mathematical theory of communication” (1948), with letter and word n-gram examples.
- R. Kneser and H. Ney, “Improved backing-off for m-gram language modeling” (ICASSP 1995).
- S. F. Chen and J. Goodman, “An empirical study of smoothing techniques for language modeling” (1998).
Exercise 2.
- Source: a language-like second-order Markov source over 50 words: a Zipfian unigram, bigrams drawn from Dirichlet(20 × unigram), and trigrams drawn from Dirichlet(5 × bigram). Its own perplexity on the test text is 5.12, the floor no model can beat.
- Training: 1000, 10,000 or 100,000 tokens; test on 5000 tokens.
- Models (trigram):
- unsmoothed MLE (reported as the fraction of test trigrams with probability 0);
- add-1 and add-0.01;
- Jelinek–Mercer interpolation with fixed weights (0.6, 0.25, 0.1, 0.05 uniform);
- interpolated Kneser–Ney (d = 0.75).
- Check: every model’s probabilities sum to 1 over the vocabulary.
| training tokens | MLE zero-probability fraction | add-1 | add-0.01 | interpolated | Kneser–Ney |
|---|---|---|---|---|---|
| 1000 | 0.388 | 25.04 | 16.78 | 11.33 | 10.23 |
| 10,000 | 0.107 | 10.57 | 7.68 | 7.08 | 6.47 |
| 100,000 | 0.015 | 6.21 | 5.46 | 6.28 | 5.36 |
- Without smoothing the model is unusable: 39% of test trigrams get probability zero after 1000 tokens, so perplexity is infinite.
- Kneser–Ney is best at every size and reaches 5.36 at 100k tokens, within 5% of the source’s 5.12.
- Add-one is worst, at more than twice Kneser–Ney’s perplexity with little data.
- Fixed interpolation weights stop improving: at 100k tokens they still put 40% weight on lower orders and fall behind even add-0.01. Weights must be tuned to the data size.
- Seeds: seeds 1 and 2 gave Kneser–Ney 10.50/9.85 at 1000 tokens and 5.33/5.35 at 100k, best in every row.
- Two mistakes I made first:
- my Kneser–Ney normalised its middle order by the number of distinct words instead of the sum of continuation counts, and scored below the true source, which is impossible. Checking that every distribution sums to 1 found it;
- my first source had no shared lower-order structure, which unfairly penalised every backoff method. Real language has such structure, so the source now does too.
n-gram models in AI, robotics and aerospace
- Speech recognition: n-gram language models for constrained vocabularies such as pilot–controller phraseology.
- On-device text input: tiny models for predictive keyboards.
- Baselines: perplexity floors and sanity checks for neural language models.
- Design lesson: never let a model assign probability zero to something that can happen; back off sensibly.
References
- R. Kneser and H. Ney (1995). “Improved backing-off for m-gram language modeling.” Proc. ICASSP.
- S. F. Chen and J. Goodman (1998). “An empirical study of smoothing techniques for language modeling.” Harvard TR-10-98.
- Y. W. Teh (2006). “A hierarchical Bayesian language model based on Pitman–Yor processes.” Proc. ACL.
- D. Jurafsky and J. H. Martin (2024). Speech and Language Processing, 3rd ed. draft, ch. 3.