← All notes
Course chapters
On this page

Lesson 14 · Natural language processing

The probability game of language: N-grams

Can counting predict the next word? Build a conditional frequency table, explore context windows and see why unseen combinations cause trouble.

1. How could a keyboard guess the next word?

Imagine typing “The weather…” and seeing suggestions such as “is lovely”, “is nice” and “is hot”. How could a system produce these continuations?

One simple method is to inspect previous text and count what came next. If the same phrase has often been followed by a particular continuation, offer that continuation again.

After the phrase “The weather…”

is lovely
4,120
is nice
3,890
is changing
2,540
is hot
1,870
is terrible
980
Figure 14-1. Illustrative continuation counts, adapted into English. These teaching numbers are not measurements from a real messaging dataset. Frequent continuations can supply suggestions without consulting the weather.

This method does not need to check a weather forecast or represent the meaning of weather. It uses regularities in text. It is a useful historical starting point for language modelling, rather than a complete account of modern keyboard systems, which may also use neural models, personalisation and other signals.

Pause and think

If a model only looks at the final few words, can it use something you said much earlier in the conversation to choose the next word?

I've thought about it — show the answerHide answer

No. Two prefixes with the same final context receive the same distribution from this fixed-context model, even if their earlier content differs. Counting recent continuations can capture useful local patterns while missing information outside the chosen window.

Producing a plausible continuation is therefore not evidence that the system understood the whole conversation.

2. Make the rule general: use an N-gram

Rather than build a separate rule for every complete phrase, estimate the next token from a fixed recent context.

An N-gram is a sequence of NN tokens. When predicting its final token, the model conditions on the preceding N−1N-1 tokens:

  • Unigram, N=1N=1: no preceding context; use overall token frequencies.
  • Bigram, N=2N=2: use one preceding token.
  • Trigram, N=3N=3: use two preceding tokens.

The predicted token is included in NN. A model using the previous two words is therefore a trigram, not a bigram.

Predict the next token with a trigram model

theshykittenventuredoutsideforthefirst→ ?

N = 3: use “the first” → predict “time”. Earlier tokens are outside the window.

Figure 14-2. A trigram consists of two context tokens and the next token. The highlighted tokens are the only context used by this model.

For a token sequence w1,…,wTw_1,\ldots,w_T, the probability chain rule is:

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

The N-gram assumption replaces the full prefix with the most recent N−1N-1 tokens:

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

Near the beginning of a sentence, we must define how shorter contexts are handled. Practical models often use sentence-boundary markers. Our small experiment below omits them and counts only windows fully inside each sentence.

Train by counting, predict by looking up

Given a context cc, count how often each candidate token ww follows it. The basic maximum-likelihood estimate is:

P(w∣c)=C(c,w)∑v∈VC(c,v).P(w\mid c)=\frac{C(c,w)}{\sum_{v\in\mathcal V}C(c,v)}.

The denominator counts all observed continuation events for that context. It is not necessarily every occurrence of the context anywhere: an occurrence at the end of a sentence has no following token unless an end marker is included.

Training a basic count model means extracting token windows and storing their frequencies. It does not require gradient descent or backpropagation.

Next wordCount after “weather”Probability
lovely2,30023.0%
nice2,10021.0%
forecast1,80018.0%
changing1,50015.0%
hot1,00010.0%
banana30.03%
Other words combined1,29713.0%
Total continuation events10,000100%
Figure 14-3. An illustrative bigram table for the token “weather”. Counts total 10,000. The rare “banana” continuation has probability 0.03%; displayed rounded entries may not sum to exactly 100%.

The candidate “banana” was observed three times out of 10,000 continuation events, so its probability is:

P(banana∣weather)=310,000=0.0003=0.03%.P(\text{banana}\mid\text{weather})=\frac3{10{,}000}=0.0003=0.03\%.

The frequency table is a conditional probability distribution. Choosing the most likely continuation and sampling from the distribution are different prediction strategies.

Try an actual count table

The following experiment counts windows in ten short English teaching sentences. Unlike the illustrative large counts above, every result here is derived from the displayed corpus.

Used context: weather. Earlier tokens are discarded.

P(w∣c)=C(c,w)∑vC(c,v),P+1(w∣c)=C(c,w)+1∑vC(c,v)+VP(w\mid c)=\frac{C(c,w)}{\sum_v C(c,v)},\qquad P_{+1}(w\mid c)=\frac{C(c,w)+1}{\sum_v C(c,v)+V}

Observed continuation events: 5 · Vocabulary size: 12

Probability sum: 1.000000

Next wordCountProbability
is4
80.0%
forecast1
20.0%
cat0
0.0%
cold0
0.0%
good0
0.0%
kitten0
0.0%
likes0
0.0%
milk0
0.0%
nice0
0.0%
quiet0
0.0%
the0
0.0%
weather0
0.0%

Ties use alphabetical order. This selects the maximum; it does not sample randomly.

Inspect the complete teaching corpus
  1. the weather is good
  2. the weather is good
  3. the weather is nice
  4. the weather is cold
  5. the weather forecast is good
  6. the cat is quiet
  7. the kitten is quiet
  8. the cat likes milk
  9. the kitten likes milk
  10. the forecast is cold

Words are lowercased and extracted from English letter sequences. Sentences are counted separately, with no start/end markers. This deliberately small tokenizer and corpus are educational examples.

Experiment 14-A. Calculate actual continuation counts from the ten displayed teaching sentences. Change the model order or prefix, compare “cat” with “kitten”, and test an unseen context with and without add-one smoothing.

Try these comparisons:

  • With bigram, “the weather” uses only “weather”. The corpus has four continuations “is” and one “forecast”, giving probabilities 4/54/5 and 1/51/5.
  • With trigram, the same prefix uses “the weather”. This corpus happens to contain the same five events, so the result matches here. A larger context does not necessarily change every prediction.
  • For unigram, the prefix is ignored and the distribution comes from overall word counts.
  • “purple dragon” has no observed continuation. Without smoothing, the conditional estimate has a zero denominator and is undefined, rather than a normalised all-zero distribution.

3. Short memory and sparse data

Consider a sentence about a shy kitten that has never met a stranger. A completion far later in the sentence might depend on those earlier details. A short-context model cannot recover them once they leave its window.

Why not increase NN? Larger windows distinguish more contexts, but exact combinations become rarer. There may be many perfectly sensible contexts that never appeared in the training corpus.

This is data sparsity:

  • For a seen context, an unseen continuation receives probability zero under the unsmoothed frequency estimate.
  • For an unseen context, the frequency estimate has no observed denominator.
  • Longer exact contexts often have fewer examples supporting each estimate.

A single zero-probability event also makes an unsmoothed sequence probability zero when we multiply its conditional probabilities. “Not observed” does not mean “impossible in real language”.

Smoothing and backoff help, but do not solve everything

Add-one smoothing adds a count of one to every candidate in a fixed vocabulary of size VV:

P+1(w∣c)=C(c,w)+1∑vC(c,v)+V.P_{+1}(w\mid c)=\frac{C(c,w)+1}{\sum_v C(c,v)+V}.

This assigns positive probability to vocabulary words that were not observed after that context. For an entirely unseen context it produces a uniform distribution over that vocabulary. That distribution comes from the smoothing assumption, not new evidence.

Enable smoothing in the experiment and compare the results. On a tiny corpus, adding one everywhere can substantially flatten the distribution. It is easy to understand, but often too crude for serious language modelling.

Other methods include backoff, which uses shorter contexts when a longer context lacks evidence, and interpolation, which combines estimates from several orders. More sophisticated smoothing redistributes probability mass more carefully. These improve sparse estimates while retaining the limits of the chosen context representation.

Words outside a fixed vocabulary need their own treatment, such as an unknown-token symbol. Add-one smoothing over the current vocabulary does not automatically cover every possible new word.

Pause and think

If the model has seen a continuation after 'cat', why does that not automatically teach it the same continuation after 'kitten'?

I've thought about it — show the answerHide answer

A basic word-level count table treats “cat” and “kitten” as different symbols with separate rows. It has no representation that says their meanings are related.

In our corpus, their rows look similar because we explicitly included similar sentences for both. The model does not infer that similarity from the words themselves. Backoff or smoothing can provide fallback probabilities, but does not by itself give these symbols a shared semantic representation.

The next lesson introduces word vectors as one way to represent relationships between words.

4. What N-grams can and cannot do

Many nearby word combinations are regular. “weather forecast” is more common than “weather banana”, and counts can capture that difference cheaply.

Count-based language models have historically been useful for text suggestions, speech recognition and statistical machine translation. N-gram features can also be useful in text classification, including spam detection, even when that system is not itself generating language.

Their strengths include simple training, inspectable counts and useful local patterns. Their limitations include short context, sparse combinations and the lack of learned semantic relationships between distinct word symbols.

Tokenisation matters too. Word-level, character-level and other token choices produce different tables. Our experiment lowercases simple English word tokens, so its results should not be read as a general model of punctuation, multilingual text or sentence structure.

N-grams remain a useful baseline and teaching tool. They are not a claim that all contemporary language systems simply consult a small count table.

5. What you have discovered

A language model assigns probabilities to possible next tokens. An N-gram model estimates them from local counts.

  • Order NN includes the predicted token, leaving N−1N-1 context tokens.
  • Training counts observed windows; prediction looks up a conditional distribution.
  • Sparsity gives zero probabilities for unseen continuations and no raw estimate for entirely unseen contexts.
  • Smoothing, backoff and interpolation provide ways to use limited evidence more effectively.
  • A fixed context window ignores older information, and separate word symbols do not automatically share meaning.

The next lesson asks how to turn a word into a representation that can express its relationship with other words.

Check your understanding

1. How does an N-gram language model estimate the next-word probability?
2. What does data sparsity mean for an unsmoothed N-gram model?