CSCE 471 Natural Language Processing · Spring 2027

N-Gram Language Models

Kuan-Hao Huang · Course Website

Note: This page was created with the help of AI as a supplementary reading. It may contain errors or simplifications. The lecture slides are the primary reference for this course; please refer to them first.

Read these sentences and decide how likely each one is to appear in ordinary English text:

The dog is barking at the stranger in the yard.
The sky colorful because painted an artist.
Plorp zix flanned the quibble through treemunk.

You can rank them instantly: the first is natural, the second uses real words in a broken order, and the third isn't English at all. A language model is a program that makes this judgment with numbers. It assigns a probability to every possible piece of text, so that natural text gets high probability and garbled text gets low probability.

This reading builds the simplest kind of language model, the n-gram language model, which estimates these probabilities by counting word sequences in a training corpus. We'll then see how to measure how good a language model is, using perplexity.

After reading this, you should be able to define a language model as a probability distribution over text · decompose a sentence's probability with the chain rule · state the unigram, bigram, trigram, and general n-gram assumptions · estimate n-gram probabilities by counting, including the <s> and </s> markers · compute the perplexity of a test corpus · explain why larger n is not always better.

1What is a language model?

Let a piece of text be a sequence of words $x=[w_1,w_2,\dots,w_l]$, and let $\mathcal X$ be the set of all finite pieces of text. A language model learns a probability distribution over $\mathcal X$:

$$P(x)=P(w_1,w_2,\dots,w_l),\qquad \sum_{x\in\mathcal X}P(x)=1$$

Every possible text, from “I love dogs.” to a full novel to random gibberish, gets a probability, and all of those probabilities add up to 1. Once we have such a distribution, we can use it in two ways:

2The chain rule: predicting one word at a time

There are infinitely many possible texts, so we can't simply store a probability for each one. Instead, we break the probability of a sequence into a product of simpler pieces using the chain rule of probability:

$$\begin{aligned} P(w_1,w_2,\dots,w_l)&=P(w_1)\,P(w_2,\dots,w_l\mid w_1)\\ &=P(w_1)\,P(w_2\mid w_1)\,P(w_3,\dots,w_l\mid w_1,w_2)\\ &=\cdots=\prod_{i=1}^{l}P(w_i\mid w_1,w_2,\dots,w_{i-1}) \end{aligned}$$

This is exact; no approximation has been made yet. It says that the probability of a sentence is the product of the probability of each word given all the words before it. For example,

$$P(\textit{she likes to go hiking})=P(\textit{she})\cdot P(\textit{likes}\mid\textit{she})\cdot P(\textit{to}\mid\textit{she likes})\cdot P(\textit{go}\mid\textit{she likes to})\cdot P(\textit{hiking}\mid\textit{she likes to go})$$

A model built this way is called an auto-regressive language model. The whole problem has become one question asked over and over: given the context $w_1,\dots,w_{i-1}$, what is the probability of the next token $w_i$? This is next-token prediction, and it is exactly what modern large language models are trained to do too.

The challenge is estimating $P(w_i\mid w_1,\dots,w_{i-1})$. The context can be arbitrarily long, and most long contexts have never appeared anywhere in our training data, so we can't just look them up.

3The n-gram assumption

The n-gram model makes a simplifying assumption: the next word depends only on the previous $n-1$ words. Everything earlier is ignored.

$$P(w_i\mid w_1,\dots,w_{i-1})\;\approx\;P(w_i\mid w_{i-n+1},\dots,w_{i-1})$$

Probabilities over such short contexts can be estimated by counting. Collect a training corpus, count how often each sequence of $n$ words (an n-gram) occurs, and divide:

$$P(w_i\mid w_{i-n+1},\dots,w_{i-1})=\frac{C_\text{train}(w_{i-n+1},\dots,w_{i-1},w_i)}{C_\text{train}(w_{i-n+1},\dots,w_{i-1})}$$

In words: of all the times the context appeared, what fraction of the time was it followed by $w_i$? This ratio of counts is the maximum likelihood estimate: it is the choice of probabilities that makes the training corpus as likely as possible. The three most common cases have their own names:

ModelnAssumptionEstimate
Unigram1$P(w_i\mid\cdots)\approx P(w_i)$$\dfrac{C(w_i)}{\sum_t C(w_t)}$
Bigram2$P(w_i\mid\cdots)\approx P(w_i\mid w_{i-1})$$\dfrac{C(w_{i-1},w_i)}{C(w_{i-1})}$
Trigram3$P(w_i\mid\cdots)\approx P(w_i\mid w_{i-2},w_{i-1})$$\dfrac{C(w_{i-2},w_{i-1},w_i)}{C(w_{i-2},w_{i-1})}$
Figure 1. Unigram, bigram, and trigram models. $C$ denotes a count in the training corpus.

The unigram model ignores context entirely: each word is drawn independently according to its overall frequency. It is the language-model version of a bag of words, so it assigns the same probability to a sentence and to any reordering of it. The bigram model looks one word back, and the trigram model two words back.

Sentence boundaries: <s> and </s>

Two special tokens make the model complete:

4A worked example

Here is the tiny corpus used throughout the slides, together with two test sentences. The first test sentence appears in the training data; the second does not, although it is perfectly good English.

Training corpus
she likes to go hiking
he likes to go swimming
she likes to read books
she wants to read books
Test sentences
she likes to go hiking
he likes to read books
Figure 2. The running example. Counting </s>, the training corpus has 24 tokens.

Use the calculator below to see each model's computation. Choose a model and a test sentence, or type your own sentence using words from the training corpus. Each factor shows the count of the n-gram over the count of its context.

Model:
Test sentence:
Figure 3 (interactive). Computing a sentence's probability with an n-gram model trained on the corpus in Figure 2. Factors equal to 0 are shown in red: one unseen n-gram makes the whole product 0.

The three models give these probabilities to the two test sentences:

she likes to go hikinghe likes to read books
Unigram$\frac{3}{24}\cdot\frac{3}{24}\cdot\frac{4}{24}\cdot\frac{2}{24}\cdot\frac{1}{24}\cdot\frac{4}{24}\approx 0.0000015$$\frac{1}{24}\cdot\frac{3}{24}\cdot\frac{4}{24}\cdot\frac{2}{24}\cdot\frac{2}{24}\cdot\frac{4}{24}\approx 0.0000010$
Bigram$\frac{3}{4}\cdot\frac{2}{3}\cdot\frac{3}{3}\cdot\frac{2}{4}\cdot\frac{1}{2}\cdot\frac{1}{1}=0.125$$\frac{1}{4}\cdot\frac{1}{1}\cdot\frac{3}{3}\cdot\frac{2}{4}\cdot\frac{2}{2}\cdot\frac{2}{2}=0.125$
Trigram$\frac{3}{4}\cdot\frac{2}{3}\cdot\frac{2}{2}\cdot\frac{2}{3}\cdot\frac{1}{2}\cdot\frac{1}{1}\approx 0.167$$\frac{1}{4}\cdot\frac{1}{1}\cdot\frac{1}{1}\cdot\frac{1}{3}\cdot\frac{2}{2}\cdot\frac{2}{2}\approx 0.083$
Figure 4. Sentence probabilities under each model (the same numbers as in the slides).

Several lessons are packed into this table:

5Evaluating language models: perplexity

How do we decide which language model is better? The idea is to train on one corpus and test on a different, unseen one. If the training corpus is representative of good text, a good model should assign high probability to the test corpus: it should be “unsurprised” by real sentences it hasn't seen.

For a test corpus $\mathcal X$ with sentences $x_1,\dots,x_n$, we can measure this in several equivalent ways:

MeasureFormula
Likelihood$P(\mathcal X)=\prod_{i=1}^{n}P(x_i)$higher is better
Log-likelihood$\ln P(\mathcal X)=\sum_{i=1}^{n}\ln P(x_i)$higher is better
Per-word log-likelihood$\text{WLL}(\mathcal X)=\frac{1}{W}\sum_{i=1}^{n}\ln P(x_i)$higher is better
Perplexity$\text{PPL}(\mathcal X)=e^{-\text{WLL}(\mathcal X)}$lower is better
Figure 5. From likelihood to perplexity. $W$ is the number of predicted tokens in the test corpus (words plus one </s> per sentence).

Each step fixes a practical problem. Products of many small probabilities underflow to 0 on a computer, so we take the log. Longer test corpora always have lower total log-likelihood, so we divide by the number of words $W$ to get an average per word. Finally, exponentiating the negative average turns it back into an interpretable number. Because $e^{-x}$ is decreasing, minimizing perplexity is the same as maximizing the probability of the test corpus.

Intuition: perplexity as a branching factor. Perplexity equals the inverse of the geometric-mean probability per word: $\text{PPL}=\left(\prod P(\text{each word})\right)^{-1/W}$. If a model were always choosing uniformly among $k$ equally likely words, its perplexity would be exactly $k$. So a perplexity of 100 means the model is, on average, as uncertain as if it were picking among 100 equally likely next words. Note that this formula uses the natural log and $e$; using $\log_2$ with $2^{-\text{WLL}}$ gives the same perplexity.

Perplexity on the running example

Treat the two test sentences as a test corpus. Each has 5 words plus </s>, so $W=12$:

$$\text{PPL}=\exp\!\left(-\tfrac{1}{12}\big(\ln P(\text{test 1})+\ln P(\text{test 2})\big)\right)$$

For reference, a model that picks uniformly among the 11 tokens it can predict would have perplexity exactly 11.

Figure 6. Test-corpus perplexity for n = 1 to 4, computed exactly. (The slides compute the same quantities from the rounded probabilities, which gives 9.668 instead of 9.660 for the unigram model.)

The bigram model wins. The trigram model is slightly worse, and the 4-gram model's perplexity is infinite: the 4-gram he likes to read never occurs in training, so the second test sentence gets probability 0, and $\ln 0=-\infty$. This is the central tension of n-gram models:

With a realistic corpus of millions of words, trigram and 4-gram models do outperform bigrams. But the zero-probability problem never fully goes away, because language always contains new combinations of words. Practical n-gram models therefore use smoothing techniques that move a little probability mass to unseen n-grams; those are beyond the scope of this reading.

Perplexity on real benchmarks

On the Penn Treebank, a standard benchmark of about one million words of news text, well-tuned n-gram models reach perplexities around 140. Neural language models brought this down steadily: LSTM-based models reached roughly 80 by 2014 and around 50 a few years later, and large pretrained Transformers went lower still (GPT-3 reported about 21 zero-shot in 2020). Comparing perplexities only makes sense on the same test set with the same vocabulary and tokenization, because those choices change what $W$ counts and which tokens must be predicted.

6Check your understanding

Exercise: a bigram model by hand

Train a bigram model (with <s> and </s>) on the corpus I am Sam / Sam I am / I do not like green eggs. Compute (1) $P(\textit{I}\mid\text{<s>})$, $P(\textit{am}\mid\textit{I})$, $P(\text{</s>}\mid\textit{Sam})$; (2) the probability of the sentence I am Sam; (3) its perplexity as a one-sentence test corpus.

(1) Two of the three sentences start with I: $P(\textit{I}\mid\text{<s>})=2/3$. I occurs 3 times and is followed by am twice: $P(\textit{am}\mid\textit{I})=2/3$. Sam occurs twice and is followed by </s> once: $P(\text{</s>}\mid\textit{Sam})=1/2$.
(2) Also $P(\textit{Sam}\mid\textit{am})=1/2$ (am is followed once by Sam and once by </s>). So $P(\textit{I am Sam})=\frac{2}{3}\cdot\frac{2}{3}\cdot\frac{1}{2}\cdot\frac{1}{2}=\frac{1}{9}\approx0.111$.
(3) $W=4$ (three words plus </s>): $\text{PPL}=e^{-\frac{1}{4}\ln\frac{1}{9}}=9^{1/4}=\sqrt3\approx1.73$.
(This corpus is the classic example from Jurafsky & Martin, Ch. 3.)

Quick quiz

7Further reading