Course contents 06 / 28

06 / 28 · Classical NLP

N-gram language models

Count local continuations, define message boundaries and unknown words, and derive normalized smoothing and perplexity on an original four-message corpus.

On this page 6

A library status message ends with lamp is. A count vector records the words already present, but a completion system must assign probabilities to what comes next. The distinction matters: ready and charging are possible continuations; another lamp may be much less plausible in this particular position. We can build a complete small language model by counting such transitions, provided we specify where messages begin and end.

From a joint probability to a product of conditionals#

Let w1,…,wTw_1,\ldots,w_T be the tokens of a message. Introduce a start marker and an end marker. The start marker is supplied as context; the end marker is a prediction. The chain rule gives a probability for the entire finite message:

P(w1,…,wT,EOS)=∏t=1T+1P(wt∣w<t),P(w_1,\ldots,w_T,\mathrm{EOS}) =\prod_{t=1}^{T+1}P(w_t\mid w_{<t}),

where the last target is EOS. This factorization is exact. An n-gram model adds a modeling assumption: only the previous n−1n-1 tokens determine the next-token distribution. A bigram model keeps one previous token; a trigram model keeps two. The context shrinks at the beginning unless we pad it with explicit start markers.

P(wt∣w<t)≈P(wt∣wt−n+1:t−1).P(w_t\mid w_{<t})\approx P(w_t\mid w_{t-n+1:t-1}).

The approximation discards history. Two messages ending in is receive the same next-token distribution under a bigram model even if their earlier subjects require different completions. Increasing nn distinguishes more histories, but every additional distinction needs observations. This is the central statistical tradeoff; a larger context does not create more training evidence.

Conditional probabilities must sum to one over a declared prediction vocabulary. EOS belongs to that vocabulary; the supplied start marker does not. The probability assigned to a complete message therefore depends on both its words and its length. Omitting EOS would leave the stopping decision outside the model.

Baseline: estimate the conditionals by counting#

For a history hh, let C(h,w)C(h,w) count observed transitions to ww, and let C(h)C(h) count all predicted tokens after hh. Maximum likelihood estimates the distribution separately for each observed history:

P^(w∣h)=C(h,w)C(h).\widehat P(w\mid h)=\frac{C(h,w)}{C(h)}.

To see why, collect the likelihood terms for that history. Its log-likelihood is a weighted sum of log probabilities. A Lagrange multiplier for normalization gives a probability proportional to the count; summing those counts fixes the denominator. The resulting model allocates no mass to an unobserved continuation.

For an unseen history, the denominator is zero and this formula is undefined. Returning an all-zero row would violate normalization. A practical implementation needs an explicit fallback, smoothing rule or error. Our executable example raises an error for an unseen maximum-likelihood history instead of silently presenting such a row as a distribution.

Worked example#

Consider four invented status messages, with whitespace tokenization:

lamp is ready
lamp is charging
tripod is ready
lamp stays ready

The prediction vocabulary is lamp, tripod, is, stays, ready, charging, EOS and UNK: eight symbols. UNK is reserved for any future token outside this fixed vocabulary. It has no training occurrence here. Each message contributes its start transition, internal transitions and end transition, for sixteen predicted tokens in total.

HistoryNonzero next-token counts
startlamp: 3; tripod: 1
lampis: 2; stays: 1
tripodis: 1
isready: 2; charging: 1
staysready: 1
readyEOS: 3
chargingEOS: 1

The probability of lamp is ready includes four factors:

P(lamp is ready,EOS)=34⋅23⋅23⋅1=13.\begin{aligned} P(\text{lamp is ready},\mathrm{EOS}) &=\frac34\cdot\frac23\cdot\frac23\cdot1\\ &=\frac13. \end{aligned}

This is a fitted probability on a constructed training corpus, not an estimate of how often people write that message. The distinction is useful even in a tiny example: repeated messages can change the model without introducing any new vocabulary.

Generation#

Generation starts at the start marker, samples a token, replaces the history with that token and repeats until EOS. The probability of a particular generated path is the product of its transition probabilities, which is exactly the score used above.

To expose the sampling steps without dependence on a random-number generator, the saved example supplies quantiles 0.6, 0.4, 0.5 and 0.2 to cumulative distributions in the declared vocabulary order. They select lamp, is, ready, EOS. These are chosen inputs to a trace, not evidence that a random generator always produces this message. Greedy decoding would instead choose the largest probability at each step and could collapse many possible outputs into one.

A general transition model can loop without stopping. A generation service therefore also needs a length limit and an explicit result when that limit is reached. In this particular unsmoothed example, every reachable path ends after three words. Smoothing will allow additional paths, including loops, even though each individual transition remains normalized.

Perplexity: from probability to a number#

For MM predicted tokens in an evaluation set, mean negative log-likelihood and perplexity are

H=−1M∑t=1Mln⁡P(wt∣ht),PP=exp⁡(H).\begin{aligned} H&=-\frac1M\sum_{t=1}^{M}\ln P(w_t\mid h_t),\\ \mathrm{PP}&=\exp(H). \end{aligned}

We use natural logarithms and include each message’s EOS. Equivalently, perplexity is the inverse geometric mean of the probabilities assigned to the actual tokens. Logs turn products into sums and avoid underflow on long messages. The base-two convention produces the same perplexity when its cross-entropy is exponentiated with base two, as in the NLTK API.

For the four predictions in our worked message,

PP=31/4≈1.316074.\mathrm{PP}=3^{1/4}\approx1.316074.

A uniform distribution over eight symbols has perplexity eight for any sequence of those symbols. This gives a useful scale, but perplexity need not be an integer or literally count the options a person considers. It summarizes probabilities assigned to the observed sequence; it does not test factual accuracy, helpfulness or whether a completion is safe to act upon.

When two perplexities can be compared#

Hold the evaluation text, tokenization, vocabulary policy and boundary convention fixed. A word model and a character model predict different numbers of events; their per-token perplexities cannot be ranked directly. Mapping many distinct words into UNK also makes prediction easier by merging outcomes, so a lower score after that change does not establish better modeling of the original words.

Fit tokenization and vocabulary rules on training data, choose hyperparameters on validation data and reserve a final test set. Report whether EOS is counted and how unknown words are handled. Our four-message calculation checks arithmetic and conventions only; it contains no held-out evidence. Comparing training perplexities would mostly reward the ability to fit these same sixteen transitions.

Unseen n-grams make perplexity explode#

The new message tripod stays ready contains only known tokens. Its transition from tripod to stays was never observed, so the maximum-likelihood message probability is zero and its perplexity is infinite. The failure comes from a missing combination, not an unknown word.

One zero factor is sufficient, regardless of the other probabilities. Replacing zero with a tiny constant solely while calculating the metric hides the modeling choice and can leave rows unnormalized. We need to change the predictive distribution itself. Increasing the context length usually creates more such sparse combinations, which is why context size and smoothing must be considered together.

Smoothing#

Additive smoothing gives every vocabulary outcome a positive pseudo-count α\alpha:

Pα(w∣h)=C(h,w)+αC(h)+αV,P_\alpha(w\mid h)=\frac{C(h,w)+\alpha}{C(h)+\alpha V},

where VV is the prediction-vocabulary size. The denominator adds exactly the mass added to the numerator across all outcomes. For an unseen history the result is uniform. This corresponds to a symmetric Dirichlet posterior predictive distribution when that prior model is appropriate.

Set α=1/2\alpha=1/2 and keep all eight symbols. After is, ready receives 5/14, charging receives 3/14 and each of the other six symbols receives 1/14. The probabilities sum to one. Every unseen symbol maps to the single UNK outcome before scoring; we do not give each possible spelling a separate pseudo-count.

For the previously impossible message,

P1/2(tripod stays ready,EOS)=316⋅110⋅310⋅12=93200,PP≈4.342370.\begin{aligned} P_{1/2}(\text{tripod stays ready},\mathrm{EOS}) &=\frac3{16}\cdot\frac1{10}\cdot\frac3{10}\cdot\frac12\\ &=\frac9{3200},\\ \mathrm{PP}&\approx4.342370. \end{aligned}

Its probability becomes positive because mass has been taken from observed transitions. Larger α\alpha pushes every row toward uniformity; smoothing cannot improve all sequence probabilities simultaneously. For a large vocabulary, the total pseudo-count can overwhelm a short history. Validation, rather than a universal constant, should determine the strength.

Interpolation combines already normalized distributions. For example, mixing a bigram model with a unigram model gives

Pmix(w∣h)=λP2(w∣h)+(1−λ)P1(w).P_{\mathrm{mix}}(w\mid h) =\lambda P_2(w\mid h)+(1-\lambda)P_1(w).

With weight 3/4 on the observed bigram row after is, our empirical unigram counts give 35/64 for ready and 17/64 for charging. The entire row sums to one. UNK still has probability zero because both component models give it zero. Interpolation alone therefore does not guarantee support for every outcome; the lower-order model and the treatment of unseen histories matter. Discounting methods reserve count mass and redistribute it more selectively, while a simple score-only backoff rule need not define a normalized language model.

What changed#

The count classifier from bag of words summarized a whole message. The n-gram model predicts local continuations and assigns a probability to a finite message. Smoothing turns missing local combinations into low-probability events under a specified vocabulary. The history still remains a discrete key, so lamp is and tripod is cannot share statistical strength in a trigram model unless we introduce a further mechanism.

Limitations#

Memory grows with the distinct observed contexts and continuations. Most logically possible contexts never appear. A short history forgets distant constraints, while a long history becomes sparse. Domain changes alter both transition frequencies and the vocabulary. Probabilities fitted to library status strings carry no automatic interpretation on ordinary conversation.

Neither a finite perplexity nor a fluent sampled message proves that the system understands the equipment or the real world. The model has no sensor reading and no representation of which item is actually ready. Its evidence consists entirely of the counted strings.

What you should remember#

The chain rule is exact; truncating history is the modeling assumption. Count denominators must include every predicted continuation. EOS and UNK are part of the declared contract. Smoothing reallocates probability mass. Perplexity comparisons require the same prediction units and evaluation protocol.

Reproducible example#

Run the original standard-library script. Its ngram result records every count, both exact message probabilities, perplexities, the interpolation row and the supplied-quantile generation trace. Assertions check normalization for observed and unseen histories and explicit unknown-token mapping. Saved results were produced with Python 3.9.7; final floating digits can differ on another runtime. No external corpus or model is downloaded.

Next#

A discrete history treats two different word IDs as unrelated. Word embeddings introduce shared numerical representations, so evidence involving one word can influence predictions involving another. We first separate what a vector stores from what an objective can teach it.

References#

  • NLTK Project; Ilia Kurenkov and Manu Joseph. Language-model estimators, MLE, Lidstone, Laplace and StupidBackoff; language-model API, entropy and perplexity. Revision 89e9098, Apache-2.0. Definitions and conventions are referenced; the corpus and implementation above are independently specified.