All labs Animated labs The chapter Course home

Lab 07Smoothing and perplexity

An n-gram model scores a sentence by multiplying probabilities taken from counts. Any bigram it never saw gets probability zero, and one zero ruins the whole product. Smoothing fixes that by giving every event a little mass. Edit the corpus, the test sentence and the smoothing, and watch the perplexity move. The numbers use the conventions of ngram_lm.py, so they match the chapter.

1. Score a sentence

Try:

2. Why alpha has to be tuned on new text

Perplexity of a sentence the model memorised and of your test sentence, over the whole range of alpha. Less smoothing always looks better on text the model has seen. On new text it is a U.

What to look for

  • With the defaults, the cat sat has perplexity 3.2568 and the dog ran 4.4721. The bigram dog ran was never seen, so its row is shaded and it still has a probability.
  • Slide alpha to the left. The memorised sentence gets easier and easier, while the held-out sentence gets worse once alpha is too small. The best alpha for new text sits near 0.1.
  • Type the cat slept. The unseen word becomes <unk>, an ordinary member of the vocabulary, so the model still returns a number.
  • Switch to a trigram. Almost everything is unseen on a corpus this small, which is why longer contexts need far more text.

3. Mixing orders instead of backing off

Interpolation blends the unigram, bigram and trigram estimates. Move the weights and watch which rows change. Row 3 is the one that matters: the trigram says impossible, the bigram has seen it, and the mix keeps the sentence alive.

The weights are rescaled to sum to 1, the one constraint. Training text: the cat sat on the mat / the cat sat on the rug / the dog sat on the mat / a cat ran to the mat.

Where this fits

This is n-gram Language Models. Run ngram_lm.py to print the same tables as text, or build the model yourself in Project 4.