N-gram language models and smoothing
Notes on n‑gram language models (definition, MLE estimation, sparsity) and smoothing methods (add‑k, Good‑Turing, Witten‑Bell, Katz backoff, Kneser‑Ney) with formulas, derivations and worked examples.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Two or three sentences: where an engineer uses this.
N‑gram language models are simple, fast statistical models that predict the next word from a short history. Engineers use them in speech recognition, spelling correction, text autocompletion and as baseline models in many NLP pipelines (before moving to embeddings or neural language models).
Key ideas
Explain from first principles, define terms and give exact statements and derivations.
Probability (of an event): the number between 0 and 1 assigned to an event; probability of the sample space is 1. (Used implicitly throughout.)
Sentence (or token sequence): a finite sequence of words w1, w2, ..., wN. Tokens are dimensionless counts.
Joint probability of a sequence: For a word sequence W = w1 ... wN the exact probability by the chain rule is: P(w1 ... wN) = P(w1) · P(w2 | w1) · P(w3 | w1 w2) · ... · P(wN | w1 ... w_{N-1}). This is an identity (no approximation). Draw to explain: draw a row of boxes labelled w1, w2, ..., wN; beneath each arrow between boxes write the corresponding conditional probability.
Markov assumption (order n−1): the assumption that the next word depends only on the previous n−1 words. Exact statement: for an n‑gram model, assume P(wi | w1 ... w_{i-1}) ≈ P(wi | w_{i-(n-1)} ... w_{i-1}). If n=2 this is the bigram (first‑order Markov) assumption; if n=3 it's the trigram (second‑order) assumption.
N‑gram model (definition): An n‑gram is a contiguous sequence of n tokens. An n‑gram language model estimates P(wi | history) using counts from training text under the Markov assumption above.
Maximum likelihood estimate (MLE) for n‑gram: For history h = w_{i-(n-1)} ... w_{i-1} and word w, the MLE is the fraction of times w follows h in training data: MLE: P̂MLE(w | h) = c(h,w) / c(h), where c(h,w) is the count of the n‑gram (h followed by w), and c(h) = Σ{w'} c(h,w'). This follows from maximizing the multinomial likelihood.
Sparsity and zeros: Real corpora are finite, many possible n‑grams never appear (zero counts). MLE assigns zero probability to unseen n‑grams, which is undesirable because unseen events can occur in test data and make P(sequence)=0.
Smoothing (definition): Any method that adjusts raw MLE probabilities to (a) give non‑zero probability mass to unseen events and (b) better estimate probabilities of rare events. Smoothing redistributes probability mass from seen to unseen events.
Backoff vs Interpolation:
- Backoff: use a higher-order (longer history) probability if available (and discounted), otherwise "back off" to a lower-order model multiplied by a backoff weight.
- Interpolation: always take a weighted sum of higher‑ and lower‑order probabilities.
Perplexity (definition): a common evaluation measure for a model on a test sequence W of length N. Lower is better. See formulas section for exact definitions and the relation to cross-entropy.
Exact derivations usually asked in exams:
- Derive chain rule for joint probability: show P(w1...wN) = Π P(wi | w1^{i-1}) using conditional probability definition P(A∩B) = P(A|B)P(B) repeatedly.
- Apply (n−1)th order Markov assumption to reduce conditionals to at most n−1 preceding tokens; write resulting product of conditional probabilities — this is the n‑gram model probability.
- Show MLE by maximizing log-likelihood L = Σ counts · log P̂(w|h) subject to Σ_w P̂(w|h)=1 for each history h; use Lagrange multipliers to derive P̂ = counts / total counts.
Diagram to draw for an exam to illustrate backoff: Draw three horizontally stacked layers labelled "trigram", "bigram", "unigram". For a specific context (h), draw an arrow from trigram cell (h,w) to bigram cell (last word of h, w) labelled "if trigram unseen, back off". At each backoff arrow write the backoff weight λ(h).
Formulas
Each formula on its own line, then symbol meanings, SI unit and when it applies.
P(w1 ... wN) = Π_{i=1..N} P(wi | w1 ... w_{i-1})
- P(...): joint probability of token sequence; dimensionless; exact identity from chain rule; applies always.
P(wi | w1 ... w_{i-1}) ≈ P(wi | w_{i-(n-1)} ... w_{i-1})
- conditional probabilities; dimensionless; statement of (n−1)th order Markov assumption; applies when using an n‑gram model.
P̂_MLE(w | h) = c(h,w) / c(h)
- c(h,w): count (dimensionless) of observed n‑gram; c(h): count (dimensionless) of history h; P̂: estimated conditional probability; applies to MLE estimation from training corpus.
P_add-k(w | h) = (c(h,w) + k) / (c(h) + k·V)
- k: smoothing constant (dimensionless, k≥0); V: vocabulary size (number of distinct word types); dimensionless; applies to Lidstone/add‑k smoothing; k=1 is Laplace (add‑one).
c^*(r) = (r+1)·N_{r+1} / N_r
- c^*(r): Good‑Turing adjusted count for events seen r times; N_r: number of types with frequency r in the training set; dimensionless; applies when using Good‑Turing estimation for rare counts (requires N_r>0 and N_{r+1}>0).
P_GT(w) = c^*(c(w)) / N
- c(w): observed count of w; N: total number of tokens in relevant bucket (dimensionless); P_GT: Good‑Turing probability; applies after computing c^*.
PP(W) = P(W)^{-1/N} = exp(- (1/N) Σ_{i=1..N} log P(wi | history))
- PP(W): perplexity (dimensionless); N: number of tokens in test sequence; P(W): model probability of sequence; applies for evaluation of language models. Equivalently, cross-entropy H(W) = -(1/N) Σ_{i=1..N} log P(wi | history), and PP(W) = exp(H(W)) with natural logs; with log base 2, PP(W) = 2^{H_2(W)}.
P_{KN}(w|h) = max(c(h,w)-D, 0)/c(h) + λ(h)·P_cont(w)
- D: discount (dimensionless); λ(h): backoff weight for history h (dimensionless); P_cont(w): Kneser‑Ney continuation probability (dimensionless); applies to interpolated Kneser‑Ney smoothing with a single absolute discount D (bigram/trigram).
P_cont(w) = N_{·w} / Σ_{w'} N_{·w'}
- N_{·w}: number of unique histories that precede w (dimensionless); denominator is total number of unique bigram types; applies in Kneser‑Ney to define the lower-order (continuation) distribution.
λ(h) = D · (number_of_unique_continuations_after_h) / c(h)
- λ(h): fraction of mass moved to lower order; applies in Kneser‑Ney.
Interpolated: P_I(w|h) = α·P̂_high(w|h) + (1-α)·P̂_low(w|h')
- α: interpolation weight (0≤α≤1); h': shorter history; applies to linear interpolation smoothing.
Notes: All probabilities are dimensionless (no SI units). When applying formulas that refer to N_r or N_{·w}, verify counts are computed in the correct context (global corpus or per‑history bucket as required).
Worked examples
Two university‑exam standard numerical examples and one short derivation model answer.
Example 1 — Bigram MLE and add‑one smoothing (numerical) Data (training corpus): tokens = [I, want, coffee, I, want, tea] Step 1 — list bigram counts c(h,w) (dimensionless): c(I, want)=2; c(want, coffee)=1; c(coffee, I)=1; c(want, tea)=1; other bigrams seen 0. c(I)=2 (I followed by want twice), c(want)=2. Vocabulary size V = 4 (I, want, coffee, tea).
Question: Compute MLE P̂(want | I) and add‑one P_add1(want | I).
Solution steps:
- MLE:
P̂_MLE(want | I) = c(I,want)/c(I) = 2/2 = 1.0. - Add‑one:
P_add1(want | I) = (c(I,want)+1) / (c(I) + V) = (2+1)/(2+4) = 3/6 = 0.5.
Interpretation: MLE gives 1 because in training I is always followed by want; add‑one spreads mass to unseen continuations (e.g., I->coffee).
Example 2 — Good‑Turing frequency of frequencies (numerical) Assume we have counts for bigram types (toy): N_0 (unseen types) unknown, but observed frequency‑of‑frequencies from training bigram types: N_1 = 5 types occur once, N_2 = 3 types occur twice, N_3 = 2 types occur three times, total observed tokens N = Σ r·N_r = 1·5 + 2·3 + 3·2 = 5 + 6 + 6 = 17 tokens (dimensionless).
Use Good‑Turing to compute adjusted count for r=1.
Steps:
- c^*(1) = (1+1)·N_2 / N_1 = 2·3 / 5 = 6/5 = 1.2.
- Probability mass for a type with observed r=1: P_GT = c^*(1) / N = 1.2 / 17 ≈ 0.07059.
Also probability mass reserved for unseen types (r=0) can be estimated as P(unseen) ≈ N_1 / N = 5/17 ≈ 0.2941 (Good‑Turing approximation: probability mass for unseen events ≈ N_1/N). Bold final numeric answers: c^*(1)=1.2, P_GT≈0.0706, P(unseen)≈0.2941.
Notes: Good‑Turing requires nonzero N_{r+1}; for high r smoothing or regression is used — mention in answer.
Example 3 — Short exam derivation (model answer) Question: Derive the bigram model probability of a sentence from the chain rule and state the MLE for bigram probabilities.
Model answer (concise): Using chain rule P(w1...wN) = Π_i P(wi | w1...w_{i-1}). Under bigram (first‑order Markov) assumption P(wi | w1...w_{i-1}) ≈ P(wi | w_{i-1}), therefore P(w1...wN) ≈ Π_i P(wi | w_{i-1}). The MLE for the bigram conditional probability is P̂(wi | w_{i-1}) = c(w_{i-1}, wi) / c(w_{i-1}), derived by maximizing the log‑likelihood for each context using Lagrange multipliers (show L = Σ_{w} c(h,w) log P(w|h) + λ (Σ_w P(w|h)-1) and set ∂L/∂P=0 to get P = counts/total).
Common mistakes
- Confusing vocabulary size V (number of word types) with number of observable continuations for a given history. For context‑specific denominators, compute per‑history counts.
- Applying Kneser‑Ney continuation probability as simple unigram MLE; continuation counts are counts of distinct contexts, not token counts.
- Forgetting to re‑normalize probabilities after discounting in backoff methods (missing or wrong λ(h)).
- Calculating perplexity with natural log but forgetting exp() to convert back when using the exp formula; or using N=number of types instead of tokens.
For your exam
Kinds of questions and what full‑marks answers include:
- Definitions: define n‑gram, Markov assumption, smoothing, perplexity — give one short example each.
- Short notes: explain Laplace vs Good‑Turing vs Kneser‑Ney; include strengths/weaknesses and complexity.
- Derivations: derive chain rule → n‑gram model; derive MLE via Lagrange multipliers; derive perplexity relation to cross‑entropy.
- Numericals: compute counts, MLE probabilities, add‑one smoothing, Good‑Turing adjusted counts; show all steps, carry units (dimensionless) and give final values bold.
- Programs: small Python script to count n‑grams and compute MLE; include sample input and output (not included here). A full answer shows code and sample execution.
- Diagrams: draw layers for backoff/interpolation; label histories, backoff arrows, and λ(h).
Full marks answers must state assumptions (e.g., Markov order), define symbols, show intermediate algebra, and check edge cases (zero counts).
Quick check
Three short questions. Answer line below.
- What does add‑one (Laplace) smoothing do to every observed count?
- Give the Good‑Turing adjusted count formula for observed frequency r.
- In one line: what key idea makes Kneser‑Ney better than naive discounting for lower order distributions?
Answers: 1) It adds 1 to the count for every vocabulary item (including zero counts) in the context (and increases the denominator by V). 2) c^*(r) = (r+1)·N_{r+1} / N_r. 3) It uses continuation counts (how many distinct contexts precede a word) for the lower‑order distribution rather than raw unigram frequencies.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?