Majid Al-RaimiGeneralization, overfitting and add-one smoothing

ICS 582Lecture 03Part 06

Generalization, overfitting and add-one smoothing

How higher-order n-grams memorize sparse training data and depend on genre, why unseen n-grams create zero probabilities, and how Laplace and add-k smoothing fix zeros at a cost.

Concepts
6
Slides
54-67
Reading
36 min
Understood
0/6 concepts

Why this part matters

The maximum likelihood bigram and trigram models from the previous parts are easy to build and easy to sample from, but they fail in two ways that decide whether an n-gram language model is usable at all. They memorize, or simply mismatch, the text they were trained on. And they give probability zero to perfectly plausible text, which breaks perplexity and any application that multiplies probabilities.

This part diagnoses both failures and then introduces the first cure, smoothing, in its simplest form: Laplace (add-one) smoothing and its softer cousin add-k. Smoothing is the bridge to every serious count-based model in the rest of the lecture, the add-one bigram is a standard exam computation, and the samepseudo-count trick reappears in Naive Bayes text classification and in any research project that estimates probabilities from limited data, Arabic dialect corpora very much included.

By the end you can

  1. Explain why higher-order n-grams become more fluent but copy training text on small corpora.
  2. Argue why training data must match the target genre, domain and dialect.
  3. Distinguish unseen tokens from unseen n-grams and show why one zero makes perplexity undefined.
  4. Explain smoothing as moving a fixed probability budget from seen to unseen events, using the 'denied the' counts.
  5. Compute Laplace unigram probabilities on a toy corpus, then bigram probabilities and reconstituted counts on BeRP numbers.
  6. Explain why add-one over-discounts, and write and tune add-k with a dev set.

Longer context buys fluency, then memorization

Train four models on the complete works of Shakespeare, a unigram, a bigram, a trigram and a 4-gram model, and generate sentences from each by sampling one word at a time. The unigram model produces "To him swallowed confess hear both." Every word is Shakespearean, but no word knows its neighbor. The bigram model produces "What means, sir. I confess she?": each adjacent pair is locally fluent, yet the sentence has no plan. The trigram output starts to sound like a play. And the 4-gram model produces "It cannot be but so.", which is not an imitation of Shakespeare at all. It is a line from King John, copied word for word.

OrderSampleWhat it shows
UnigramTo him swallowed confess hear both. Which. Of save on trail for are ay device and rote life haveReal Shakespearean words, no relation between neighbors
BigramWhat means, sir. I confess she? then all sorts, he is trim, captain.Each adjacent pair is plausible; the sentence as a whole is not
TrigramThis shall forbid it should be branded, if renown made it empty.Reads like Shakespeare for several words at a time
4-gramIt cannot be but so.Copied word for word from King John
Samples from n-gram models trained on Shakespeare (SLP3 Fig. 3.4)

Why does more context first help and then turn into copying? A longer context makes the model fit the training set more closely, because each prediction is conditioned on more of what actually happened. But the count table becomes far sparser at the same time. The Shakespeare corpus has N = 884,647 tokens and a vocabulary of V = 29,066 types. There are V² ≈ 844 million possible bigrams, so even the bigram table is overwhelmingly empty, and there are V⁴ ≈ 7 × 10¹⁷ possible 4-grams against fewer than a million observed positions. This is sparsity at its most extreme: almost every long prefix was seen once or a handful of times.

Once the 4-gram sampler has generated "It cannot be", the corpus offers only six words that ever followed that prefix: but, I, that, thus, this and the period. The conditional distribution has only six nonzero entries, each one a continuation that actually occurs in the plays, so sampling from it does not invent anything. It replays training text. That is overfitting in an n-gram model: the parameters describe the particular sentences in the training data rather than the language they came from.

As the prefix grows from 'It' to 'It cannot be', the fan of observed continuations shrinks to the six words Shakespeare ever wrote next. The teal line is the one the 4-gram model follows to copy 'but so.' from King John.

Recall

Why does the 4-gram Shakespeare model copy 'It cannot be but so' verbatim?

With N ≈ 885K tokens, the prefix "It cannot be" has only six observed continuations, so the conditional distribution is a short list of real continuations and sampling replays training text. The model has overfit through sparsity.

Quick check

A 4-gram model trained on Shakespeare generates 'It cannot be but so.' word for word. What is the best explanation?

A model only knows its own genre

Now train the same kinds of models on about 40 million words of the Wall Street Journal. The trigram model produces "They also point to ninety nine point six billion dollars from two hundred four oh six three percent of the rates of interest stores as Mexico and Brazil on market conditions." This is unmistakably newswire, read aloud with the numbers spelled out. Jurafsky and Martin point out that the Shakespeare and WSJ samples share no generated sentences, and barely even short phrases, although both models were trained on English.

ShakespeareWall Street Journal
Training size884,647 tokensAbout 40 million words
Vocabulary flavorthou, hath, forsooth, captain, King Henrypercent, corporation, billion, fiscal, Mexico
Trigram sampleThis shall forbid it should be branded, if renown made it empty.They also point to ninety nine point six billion dollars from two hundred four oh six three percent of the rates of interest...
Shared materialFunction words and short phrases at mostFunction words and short phrases at most
Two English corpora, two very different models

The lesson is that a language model is not a model of "English". It is a model of its own corpus, with that corpus's vocabulary, topics, register and sentence shapes. This is genre dependence, and it means the training data has to match the text the model will be used on, the test set in evaluation and the real input in deployment. Match it along several axes at once:

  • Genre and domain. An LM that helps translate legal documents needs legal text. A question-answering system needs a corpus of questions, whose word order and opening words differ sharply from declarative prose.
  • Dialect and variety. Tweets in African American English use forms such as finna and den with their own n-gram statistics, and Nigerian Pidgin tweets mix English and local vocabulary in patterns a standard-English model has never counted.
  • Style and time. Formal versus conversational register, and language from different decades, shift the counts just as much.

SLP3 puts it bluntly: statistical models are "pretty useless as predictors if the training sets and the test sets are as different as Shakespeare and the WSJ." For a research project on Arabic this is concrete. A model trained on Modern Standard Arabic news will assign low probability to Gulf or Egyptian dialect text and report a high perplexity, not because the model is weak but because it was built for a different variety.

Two vocabulary clusters, Shakespeare on the left and WSJ on the right. When they drift together they overlap only in a thin sliver of function words such as 'the', 'of' and 'and'.

Recall

Why is a Shakespeare-trained trigram model a poor model of WSJ text, and what should training data match?

An LM encodes the statistics of its own corpus. The two genres share almost no n-grams beyond function words, so WSJ n-grams get zero or tiny counts and perplexity is high. Training data should match the target genre and domain, dialect and style.

Suppose the training data contains the word ruby and the word slippers, but never the phrase ruby slippers. The maximum likelihood bigram estimate is then P(slippers | ruby) = C(ruby slippers) / C(ruby) = 0. A test sentence containing that phrase gets probability exactly zero, however natural it is.

It helps to separate two kinds of novelty. Older word-level systems faced unseen words, which they mapped to a special <UNK> token. Modern LMs work on subword or byte tokens (BPE from Lecture 02), and with byte-level BPE any word can be spelled from known pieces, so the test set can never contain an unseen token, even when it contains unseen words. But that guarantee is about single tokens. The sequences of known tokens are a different matter: most possible bigrams and trigrams never occur in any finite training set. SLP3 calls these zeros, "sequences that don't occur in the training set but do occur in the test set", and they occur all the time.

Zeros cause two separate problems.

  1. They underestimate plausible text. A speech recognizer or translation system that scores "ruby slippers" as impossible will prefer a worse but previously seen alternative.
  2. They destroy evaluation. A test-set probability is a product of conditional probabilities, so a single zero sends the whole product to zero, and perplexity is defined from that product.
PP(W)=P(w1w2…wN)−1N=1P(w1w2…wN)N\begin{aligned} \mathrm{PP}(W) &= P(w_1 w_2 \ldots w_N)^{-\frac{1}{N}} \\ &= \sqrt[N]{\frac{1}{P(w_1 w_2 \ldots w_N)}} \end{aligned}
Perplexity of a test sequence of N tokens

With P(W) = 0 the formula asks for 1/0. In SLP3's words, "we can't compute perplexity at all, since we can't divide by zero." This is the zero-probability problem, a direct consequence of sparsity.

Worked example

One zero in a four-token test sentence

  1. Write the bigram factors

    Test sentence <s> ruby slippers sparkle </s>, so N = 4 predicted tokens. Suppose the MLE gives P(ruby | <s>) = 0.01, P(slippers | ruby) = 0, P(sparkle | slippers) = 0.1 and P(</s> | sparkle) = 0.5.
  2. Multiply

    P(W) = 0.01 × 0 × 0.1 × 0.5 = 0. The three healthy factors are irrelevant.
  3. Try to compute perplexity

    PP(W) = 0^(-1/4) = 1/0, which is undefined. The whole test set inherits this if it contains the sentence.
  4. Replace the zero with a small smoothed value

    If smoothing gives P(slippers | ruby) = 0.001, then P(W) = 0.01 × 0.001 × 0.1 × 0.5 = 5 × 10⁻⁷ and PP(W) = (5 × 10⁻⁷)^(-1/4) ≈ 37.6.
  5. Result

    One unsmoothed zero makes perplexity undefined; any small nonzero value makes it finite and comparable.
Four multiplied bigram probabilities. One tile is 0, so on activation the product bar collapses to nothing and the perplexity readout shows 1/0, undefined.

The standard fix is smoothing, also called discounting: lower the probability of what was seen and give the freed mass to what was not.

Recall

BPE guarantees no unseen tokens. Why do we still need smoothing?

Unseen combinations of known tokens (n-grams) still get MLE probability 0, and one zero makes P(test) = 0 and perplexity undefined.

Quick check

A trigram model assigns probability 0 to one trigram in the test set. What happens to test-set perplexity?

Look at the words that followed denied the in a small corpus: allegations three times, reports twice, claims once and request once, seven observations in all. The MLE gives P(allegations | denied the) = 3/7 and gives exactly zero to attack, man, outcome and offer, although "denied the offer" is an ordinary phrase.

Smoothing changes the counts before normalizing. In this example each seen count gives up half a unit, so the counts become 2.5, 1.5, 0.5 and 0.5, and the two freed units are pooled as "other" and shared among the unseen words. The total is still seven, so the distribution still sums to one, but now 2/7 ≈ 0.29 of the probability mass covers words the corpus never showed after denied the.

WordCount beforeCount after
allegations32.5
reports21.5
claims10.5
request10.5
attack, man, outcome, offer, ...0share of 2 ("other")
Total77
P(w | denied the) before and after smoothing (example modified from Dan Klein)
The 'denied the' counts as bars. On activation a half-unit slice lifts off each seen bar and reappears as short teal stubs on the unseen words; the total height of all bars stays at 7. How the 2 units split among unseen words is illustrative.

That is the whole idea of smoothing: when the statistics are sparse, steal a little probability mass from frequent events and give it to unseen ones, so that plausible unseen sequences such as "ruby slippers" or "denied the offer" get a nonzero probability. Every smoothing method answers two questions differently: how much mass to take from each seen count (the discount), and how to divide it among the unseen events. The rest of this part covers the simplest answer, and later parts cover better ones.

Recall

In the 'denied the' example, what fraction of the mass moves to unseen words, and which later method does this resemble?

Two of seven units, about 0.29, taken by subtracting 0.5 from each seen count. That fixed subtraction resembles absolute discounting.

Take a toy vocabulary of five types with counts a = 4, b = 3, c = 2, d = 1 and e = 0, so N = 10 tokens and V = 5 types. The MLE is the relative frequency: 0.4, 0.3, 0.2, 0.1 and a zero for e. Now pretend every type was seen once more than it was. The counts become 5, 4, 3, 2, 1, the total becomes 15, and the probabilities become 5/15, 4/15, 3/15, 2/15, 1/15. Nothing is zero, and the five values still sum to one.

TypeCountMLELaplace
a44 / 10 = 0.45 / 15 ≈ 0.333
b33 / 10 = 0.34 / 15 ≈ 0.267
c22 / 10 = 0.23 / 15 = 0.2
d11 / 10 = 0.12 / 15 ≈ 0.133
e00 / 10 = 01 / 15 ≈ 0.067
Sum10115 / 15 = 1
Add-one on a toy unigram distribution (N = 10, V = 5)

That is Laplace (add-one) smoothing. The detail that matters is the denominator. Adding one to each of V counts adds V to the total, so the denominator must grow from N to N + V. Forget it and the probabilities sum to more than one.

PLaplace(wi)=ci+1N+VP_{\text{Laplace}}(w_i)=\frac{c_i+1}{N+V}
Add-one unigram estimate

For bigrams the same reasoning applies row by row. Each row of the bigram table is the distribution of words following one prefix w_{n-1}. Add one to every cell of that row, including all the zero cells, and the row total grows by the number of cells, which is V.

PLaplace(wn∣wn−1)=C(wn−1wn)+1∑w(C(wn−1w)+1)=C(wn−1wn)+1C(wn−1)+V\begin{aligned} &P_{\text{Laplace}}(w_n\mid w_{n-1}) \\ &\quad =\frac{C(w_{n-1}w_n)+1}{\sum_w \left(C(w_{n-1}w)+1\right)} \\ &\quad =\frac{C(w_{n-1}w_n)+1}{C(w_{n-1})+V} \end{aligned}
Add-one bigram estimate: one pseudo-count per possible continuation

To see how much smoothing changed the model, it is useful to turn the smoothed probability back into a count on the original scale. Multiplying the smoothed probability by the prefix count gives the reconstituted (or adjusted) count C*, which can be compared directly with the raw count.

C∗(wn−1wn)=[C(wn−1wn)+1] C(wn−1)C(wn−1)+V\begin{aligned} &C^*(w_{n-1}w_n) \\ &\quad =\frac{\left[C(w_{n-1}w_n)+1\right]\,C(w_{n-1})}{C(w_{n-1})+V} \end{aligned}
Reconstituted count after add-one smoothing

Now apply this to the Berkeley Restaurant Project corpus from Part 03: 9332 sentences and V = 1446, with unigram counts i 2533, want 927, to 2417, eat 746, chinese 158, food 1093, lunch 341 and spend 278. The smoothed count table on the slides is simply the raw table plus one in every cell: i want goes from 827 to 828, want to from 608 to 609, chinese food from 82 to 83, and every former zero becomes 1.

Worked example

Add-one bigram probabilities on BeRP

  1. MLE baseline for P(want | i)

    C(i want) / C(i) = 827 / 2533 = 0.3265 ≈ 0.33.
  2. Add one to the numerator and V to the denominator

    P(want | i) = (827 + 1) / (2533 + 1446) = 828 / 3979 = 0.2081 ≈ 0.21, the value on the smoothed probability slide.
  3. Reconstitute the count

    C*(i want) = 828 × 2533 / 3979 ≈ 527.1, matching SLP3 Fig. 3.8. Smoothing took about 300occurrences away from one of the most frequent bigrams in the corpus.
  4. An unseen bigram in the same row

    C(i to) = 0, so P(to | i) = 1 / 3979 ≈ 0.00025. It is small but no longer zero, and every continuation of i that never occurred in training gets the same amount.
  5. Result

    P(want | i) drops from 0.33 to 0.21 and C* is about 527; the mass removed from seen bigrams pays for the 0.00025 each unseen one receives.
BigramCC(prefix)MLEAdd-one PC*
i want82725330.33828 / 3979 ≈ 0.21527
want to6089270.66609 / 2373 ≈ 0.26238
chinese food821580.5283 / 1604 ≈ 0.0528.2
i to (unseen)0253301 / 3979 ≈ 0.000250.64
MLE versus add-one on three BeRP bigrams and one unseen bigram (V = 1446)

Add-one is old. It goes back to Laplace's 1812 law of succession, and was applied to the zero-frequency problem by Jeffreys (1948) after Johnson (1932); Chen and Goodman also credit Lidstone (1920) with the idea of pretending each event occurred once more. SLP3 is clear that Laplace smoothing "does not perform well enough to be used in modern n-gram models", but it is the natural baseline and it works well enough in text classification, where you will meet it again in Naive Bayes.

Recall

Why does the add-one bigram denominator add V rather than 1?

One pseudo-count goes to each of the V possible continuations of w_{n-1}, so the row total grows by V. Adding only 1 would make the row sum exceed 1.

Recall

Compute the add-one P(want | i) given C(i want) = 827, C(i) = 2533, V = 1446, and the reconstituted count.

828 / 3979 ≈ 0.21, down from 0.33. C* = 828 × 2533 / 3979 ≈ 527.

Quick check

With C(i want) = 827, C(i) = 2533 and V = 1446, what is the add-one estimate of P(want | i)?

What add-one costs, and add-k as the softer fix

Compare raw and reconstituted counts. C(want to) falls from 608 to C* ≈ 238, a discount ratio d_c = C*/C = 0.39, and P(to | want) falls from 0.66 to 0.26. C(chinese food) falls from 82 to 8.2, a ratio of d_c = 0.10: the model now believes food follows chinese one time in twenty instead of about half the time. A frequent, highly predictable bigram has been cut by a factor of ten.

BigramCC*d_c = C* / CPseudo-counts in the denominator
want to6082380.391446 / 2373 ≈ 61%
i want8275270.641446 / 3979 ≈ 36%
chinese food828.20.101446 / 1604 ≈ 90%
How hard add-one discounts three BeRP bigrams

The last column explains the pattern. In the chinese row the denominator is 158 + 1446 = 1604, and 1446 of that, about 90%, is pseudo-counts. The invented evidence outweighs the real evidence nine to one. In the i row the pseudo-counts are only 1446 / 3979 ≈ 36%, so the damage is milder. Add-one moves too much mass to unseen events, and it hits rare contexts hardest, because V is fixed while the real count of the prefix is small. In a realistic vocabulary of tens of thousands of types, almost every context is rare in this sense. That is why add-one is a teaching baseline rather than a production language model.

Add-k: a smaller pseudo-count

The obvious repair is to add less. Add-k smoothing adds a fractional k to every count, and therefore kV to the denominator.

PAdd-k(wn∣wn−1)=C(wn−1wn)+kC(wn−1)+kVP_{\text{Add-}k}(w_n\mid w_{n-1})=\frac{C(w_{n-1}w_n)+k}{C(w_{n-1})+kV}
Add-k bigram estimate; k = 1 is Laplace, k → 0 is the MLE

Nothing in the training counts tells you what k should be: 0.5, 0.1, 0.01? It is a hyperparameter, chosen by trying several values and keeping the one with the lowest perplexity on a development set. The table shows the trade-off on the chinese and want rows. Here the pseudo-count share is kV / (C(h) + kV), the part of the denominator made of pseudo-counts. It is not the same as the mass given to unseen words, because some pseudo-counts land on seen words too.

kP(food | chinese)C*(chinese food)Pseudo-count share, chinese rowP(to | want)
10.05178.20.900.2566
0.50.093614.80.820.3688
0.10.271342.90.480.5675
0.010.475575.10.0840.6458
0 (MLE)0.5198200.656
Add-k on BeRP: P(food | chinese) has MLE 0.519 and P(to | want) has MLE 0.656

As k shrinks, the smoothed estimates climb back toward the MLE, and at k = 0 they are the MLE again, zeros included. So k slides between "trust the counts" and "trust the uniform distribution". Try it yourself below.

SimulatorAdd-k on a BeRP bigram row

Upper bar: MLE C(h w) / C(h). Lower bar: add-k (C(h w) + k) / (C(h) + kV) with V = 1446 and C(chinese) = 158. Eight of the 1446 columns are shown.

  • chinese i0.006330.00125
  • chinese want00.000623
  • chinese to00.000623
  • chinese eat00.000623
  • chinese chinese00.000623
  • chinese food0.5190.0517
  • chinese lunch0.006330.00125
  • chinese spend00.000623
P(food | chinese)0.0517MLE 0.519
C* (chinese food)8.2of 82discount d = 0.0997
Pseudo-count share90.1%of rowkV out of 1,604 in the denominator

Even a well-tuned k does not make additive smoothing a good language model. Gale and Church (1994), as summarized in SLP3, found that add-k gives counts with poor variances and often inappropriate discounts, and Chen and Goodman's large comparison concludes flatly that "additive smoothing performs poorly". The flaw is structural: every unseen continuation of a prefix gets the same pseudo-count, whether it is offer or a random rare word, and the same k is used for every context regardless of how much evidence it has. Real systems use interpolation, backoff and Kneser-Ney, which start in Part 07 with absolute discounting.

Recall

How is k chosen in add-k, and what happens as k → 0?

k is a hyperparameter tuned on a dev set by minimizing perplexity. As k → 0 the estimate returns to the MLE, zeros included.

Quick check

Add-one cut C(chinese food) from 82 to 8.2 but C(want to) only from 608 to 238. Why?

Recap

If you remember nothing else

  • Higher n fits the training set better. On Shakespeare (N = 884,647, V = 29,066) the 4-gram copies "It cannot be but so" because only six words ever follow "It cannot be".
  • LMs encode their corpus. Shakespeare and WSJ samples barely overlap, so match genre, domain and dialect.
  • Subword tokenization removes unseen tokens but not unseen n-grams (zeros).
  • One zero makes P(test) = 0 and PP = P^(-1/N) undefined. The fix is smoothing, also called discounting.
  • Smoothing moves mass from seen to unseen events while keeping the total at 1 (denied the: 2 of 7 units go to "other").
  • Laplace: (c+1)/(N+V) for unigrams and (C(w_{n-1}w_n)+1)/(C(w_{n-1})+V) for bigrams. P(want | i) goes from 0.33 to 0.21.
  • C* = (C+1)·C(w_{n-1})/(C(w_{n-1})+V). want to falls from 608 to 238 (d_c = C*/C = 0.39) and chinese food from 82 to 8.2 (d_c = 0.10).
  • Add-k replaces 1 with a small k tuned on a dev set. It is still a poor LM smoother and serves as a baseline.

Sources