Search

Search papers and lessons

N-gram Language Model

Level 2 · 12 min read

An n-gram language model predicts the next word from the previous n minus 1 words, using counts from a text corpus.

On this page

  • Colour = topic mix
  • Probability
  • Language & LLMs
  • Sign in to see your progress

TL;DR

An n-gram language model gives a probability to the next word by looking only at the last few words. It counts how often each short word sequence appears in a large text, then divides those counts to get conditional probabilities. A bigram model uses one previous word, a trigram model uses two, and so on.

The model is simple and fast, and it is the baseline that neural language models had to beat. Its main weakness is that it has never seen most of the word sequences that are perfectly valid English.

Where you'll see it: in early speech recognisers and predictive keyboards, in spelling correction that ranks candidate words, and as the reference point when people measure how much a neural model improves on counting.

Intuition

Counting what usually follows

Suppose you have read a million sentences and someone types "I drink ___". You have seen "coffee" after "drink" thousands of times and "elephant" never. The simplest prediction is to count what followed the words you have just seen, and to use those counts as probabilities. That is an n-gram model.

The "n" is how many words you count together. An n-gram is a run of n consecutive words. A bigram is a pair, a trigram is a triple. The model's memory is limited to the last n minus 1 words, so a trigram model asks only what follows "drink coffee" and ignores everything said earlier in the paragraph.

This is the Markov idea from Markov chains applied to words: the next state depends only on a short window of the past. The difference is that here the transition probabilities are estimated from data rather than written down in advance.

flowchart LR
  A["Previous n minus 1 words"] --> B["Count matching n-grams in the corpus"]
  B --> C["Divide by the count of the context"]
  C --> D["Probability for each next word"]

Why the window is a trade

A longer window carries more context. "The dog that chased the cat ran" needs the subject "dog" to predict "ran", and a bigram model cannot see that far. But a longer window also makes the counts sparse. Most three-word sequences in English appear rarely or never, even in a large corpus, so the counts are mostly zero. The n-gram model is always choosing between too little context and too few examples.

The math

Chain rule over words

For a sentence of words w1,…,wTw_1, \dots, w_T, the chain rule of probability gives

P(w1,…,wT)=∏t=1TP(wt∣w1,…,wt−1).P(w_1, \dots, w_T) = \prod_{t=1}^{T} P(w_t \mid w_1, \dots, w_{t-1}).

Each factor is a conditional probability of a word given everything before it. The trouble is that the history grows with every word, and no corpus contains every possible history.

The n-gram approximation

An n-gram model assumes the next word depends only on the previous n−1n - 1 words:

P(wt∣w1,…,wt−1)≈P(wt∣wt−n+1,…,wt−1).P(w_t \mid w_1, \dots, w_{t-1}) \approx P(w_t \mid w_{t-n+1}, \dots, w_{t-1}).

For a bigram model (n=2n = 2), this is P(wt∣wt−1)P(w_t \mid w_{t-1}). For a trigram model it is P(wt∣wt−2,wt−1)P(w_t \mid w_{t-2}, w_{t-1}). The approximation is a Markov assumption of order n−1n - 1, which is why the model belongs to the same family as the Markov chain.

Maximum likelihood estimation

The simplest estimate is the relative frequency. Let c(⋅)c(\cdot) be a count in the training corpus. For a bigram model:

P(w∣v)=c(v,w)c(v).P(w \mid v) = \frac{c(v, w)}{c(v)}.

This is the maximum likelihood estimate: among all ways to set the probabilities, it is the one that makes the training corpus most probable. For a trigram model, replace the pair with a triple and the single word with a pair: P(w∣u,v)=c(u,v,w)/c(u,v)P(w \mid u, v) = c(u, v, w) / c(u, v).

Sentence probability

Putting the pieces together, a bigram model gives the probability of a sentence as a product of bigram probabilities:

P(w1,…,wT)≈∏t=1TP(wt∣wt−1).P(w_1, \dots, w_T) \approx \prod_{t=1}^{T} P(w_t \mid w_{t-1}).

Sentences are padded with special START and END symbols so that the first word and the end of the sentence also have probabilities. Products of many small numbers underflow quickly, so implementations sum logarithms instead.

Smoothing

A count of zero is a disaster: one unseen bigram makes the whole sentence probability zero. Add-one (Laplace) smoothing fixes this by pretending every possible bigram occurred one extra time. With vocabulary size VV:

Padd-1(w∣v)=c(v,w)+1c(v)+V.P_{\text{add-1}}(w \mid v) = \frac{c(v, w) + 1}{c(v) + V}.

Every probability is now positive and the rows still sum to 1. Add-one is crude, since it gives too much mass to unseen pairs, but it makes the mechanics clear. Better methods such as backoff and Kneser-Ney smoothing move probability from frequent n-grams to the rare ones in a more careful way.

123456051015n, the n-gram orderlog10 of the number of entries
  • log10 of the number of parameters, V = 50000
A full table of n-gram probabilities has V to the power n entries. With V = 50,000 words, the trigram table already has about 10 to the 14th entries, and most are never observed.

Worked examples

Example
Bigram probabilities from a three-sentence corpus

Use this corpus, with START and END marking sentence boundaries:

  • START I like cats END
  • START I like dogs END
  • START I love cats END

Step 1: count. The word "I" appears 3 times and is followed by "like" twice and "love" once. The word "like" appears twice and is followed by "cats" once and "dogs" once. The word "love" appears once and is followed by "cats". The word "cats" appears twice and is followed by END both times.

Step 2: divide. P(like∣I)=2/3P(\text{like} \mid \text{I}) = 2/3, P(love∣I)=1/3P(\text{love} \mid \text{I}) = 1/3, P(cats∣like)=1/2P(\text{cats} \mid \text{like}) = 1/2, P(dogs∣like)=1/2P(\text{dogs} \mid \text{like}) = 1/2, P(cats∣love)=1P(\text{cats} \mid \text{love}) = 1.

Step 3: score "I like cats". Multiply the bigram probabilities: P(I∣START)×P(like∣I)×P(cats∣like)×P(END∣cats)=1×2/3×1/2×1=1/3P(\text{I} \mid \text{START}) \times P(\text{like} \mid \text{I}) \times P(\text{cats} \mid \text{like}) \times P(\text{END} \mid \text{cats}) = 1 \times 2/3 \times 1/2 \times 1 = 1/3.

Interpretation: the model gives this sentence probability 1/3, which matches the corpus: exactly one of the three training sentences is "I like cats". The other two get 1/3 each, so the probabilities of the three sentences sum to 1.

Example
One unseen bigram, and add-one smoothing

Score "START I love dogs END" with the same corpus. The bigram "love dogs" never occurs.

  1. Unsmoothed: P(dogs∣love)=0P(\text{dogs} \mid \text{love}) = 0, so the whole sentence has probability 0. The model says the sentence is impossible, which is wrong. It is grammatical and could easily be said.
  2. Add-one smoothing with V=6V = 6 (the words I, like, love, cats, dogs, END): P(dogs∣love)=(0+1)/(1+6)=1/7≈0.143P(\text{dogs} \mid \text{love}) = (0 + 1)/(1 + 6) = 1/7 \approx 0.143.
  3. The other factors are P(I∣START)=(3+1)/(3+6)=4/9P(\text{I} \mid \text{START}) = (3+1)/(3+6) = 4/9, P(love∣I)=(1+1)/(3+6)=2/9P(\text{love} \mid \text{I}) = (1+1)/(3+6) = 2/9, and P(END∣dogs)=(1+1)/(1+6)=2/7P(\text{END} \mid \text{dogs}) = (1+1)/(1+6) = 2/7.
  4. Product: 4/9×2/9×1/7×2/7≈0.00404/9 \times 2/9 \times 1/7 \times 2/7 \approx 0.0040.

Compare "START I like cats END" under the same smoothing: 4/9×3/9×(1+1)/(2+6)×(2+1)/(2+6)≈0.01394/9 \times 3/9 \times (1+1)/(2+6) \times (2+1)/(2+6) \approx 0.0139. The model now ranks "I like cats" about 3.4 times above "I love dogs". That ratio reflects the counts, and the smoothed score is still well above zero.

Tradeoffs and failure modes

SituationProblemBetter choice
Long-range dependency, such as a subject far from its verbThe window is too short to see itA neural model with attention, such as a Transformer
Rare or new wordsCounts are zero, so probabilities are poorSmoothing, backoff, or subword units from Subword Tokenization
Large vocabulary and high orderThe table has VnV^n entries and most are emptyStore only observed n-grams, prune rare ones, or use a neural model
Text unlike the training corpusProbabilities reflect the wrong domainTrain or adapt on text from the target domain
Needing meaning, not only surface patternsSynonyms like "car" and "automobile" are unrelated counts[[word-embedding

A common mistake is comparing perplexity (a standard score that measures how surprised a model is by held-out text; lower is better) across models trained on different corpora or with different vocabularies. Those numbers are not comparable. Another is treating the best n-gram order as a fixed fact. It depends on corpus size: with more data, a higher order helps, and with less data it hurts.

History

Claude Shannon's 1948 paper on information theory used letter and word n-gram approximations of English to show how much structure a message carries. He generated text from those statistics and used it to illustrate the idea of entropy. Andrey Markov had earlier, in the early 1910s, counted letter transitions in a Russian novel, which is the origin of the Markov chain.

In the 1970s and 1980s, speech recognition groups at IBM and elsewhere used trigram models as a core component, scoring which word sequences were most likely given the acoustic signal. Their need to handle unseen word sequences led to the smoothing and backoff methods still in use. Kneser-Ney smoothing, published in the mid-1990s, became the strongest classic method and was the standard for years.

The model fell out of favour once neural language models became accurate and fast enough, first in the 2000s and then with large transformers. It remains a useful baseline and a teaching tool, because every idea in later models, from conditional probability to next-token prediction, is visible in it.

Check yourself

QuestionIn a bigram model, what does the approximation assume about the word wtw_t?Show answer

It assumes wtw_t depends only on the single previous word wt−1w_{t-1}, and not on any earlier word. Every longer dependency is ignored. This is the Markov assumption of order 1.

QuestionIn a corpus, the word vv appears 10 times and the bigram (v,w)(v, w) appears 4 times. What is the maximum likelihood estimate of P(w∣v)P(w \mid v)?Show answer

P(w∣v)=c(v,w)/c(v)=4/10=0.4P(w \mid v) = c(v, w) / c(v) = 4/10 = 0.4.

QuestionA trigram model with add-one smoothing and vocabulary size V=1000V = 1000 sees the context (u,v)(u, v) 2 times, and the trigram (u,v,w)(u, v, w) 0 times. What is the smoothed probability?Show answer

Add-one gives (0+1)/(2+1000)=1/1002≈0.001(0 + 1)/(2 + 1000) = 1/1002 \approx 0.001. The unseen trigram gets a small positive probability instead of zero.

QuestionWhy does a trigram model often outperform a bigram model on a large corpus but may do worse on a small one?Show answer

A trigram captures more context, so with enough data its counts are reliable and its predictions improve. With little data most trigrams are unseen or seen once, so their estimates are noisy and the bigram's denser counts win. The best order depends on how much text you have.

QuestionWhy is the chain rule over all previous words not used directly for estimating a language model?Show answer

The number of possible histories grows exponentially with the length of the history, so almost every full history is unseen in any corpus and cannot be estimated from counts. The n-gram approximation shortens the history to n−1n - 1 words, so the counts become estimable.

Sources