Skip to content

Lab: train and score a smoothed bigram model

The language chapter's first lab (LNG-A). Count bigrams, smooth them so unseen pairs keep some probability, choose the smoothing on validation sentences and score the test sentences once.

Applied ~22 min6 steps

What runs in CodeSplash

You will be able to

  • Estimate bigram probabilities by counting
  • Explain why an unsmoothed model gives unseen test pairs an infinite perplexity
  • Apply add-k smoothing and compute held-out perplexity
  • Choose the smoothing strength on validation text, never on the test

Read first

01

The question

Read

A bigram model predicts each word from the one before it, with probabilities estimated by counting pairs in training text. Some pairs in new text never appeared in training, and counting gives them probability zero. How should probability be moved to them, how much, and how do you know? The lab answers on sentences from a small grammar, split into training, validation and test before anything is counted.

02

Explore it

Explore

DExplorable · N-gram smoothing and perplexity

Why does a language model need to give probability to word pairs it never saw, and how much?

Sentences

A tiny training set and three held-out sentences.

Model

A unigram ignores context; a bigram conditions on the previous word.

0.10

Pseudo-count added to every possible next word; 0 is maximum likelihood.

  • Held-out sentences
  • Training sentences
Training perplexity
3.30
Held-out perplexity
5.66
Held-out tokens with probability 0
0
Unseen held-out bigrams
4
Probability of the shown pair
0.1038
  • Puzzle: With the bigram model, find a k that gives the lowest held-out perplexity on the sweep.
  • Puzzle: Make the held-out perplexity infinite.
Bigram model with k = 0.10 over 16 vocabulary entries: training perplexity 3.30, held-out perplexity 5.66. The held-out text has 4 word pairs the model never saw, and smoothing gives each of them some probability. Low training perplexity with infinite held-out perplexity is overfitting in its purest form.

Bigram model with k = 0.10 over 16 vocabulary entries: training perplexity 3.30, held-out perplexity 5.66. The held-out text has 4 word pairs the model never saw, and smoothing gives each of them some probability. Low training perplexity with infinite held-out perplexity is overfitting in its purest form.

Change the smoothing strength and watch training and held-out perplexityPerplexityRoughly how many neighbors each row attends to in t-SNE; small values show fine detail, and can invent it. move. Very little smoothing fits training text best and fails on new pairs; too much flattens every prediction. Press Break it to see an unseen pair with no smoothing at all.

03

Do it yourself

Explore

The notebook counts bigrams, applies add-k smoothingAdditive smoothingAdds a constant α to every count before turning counts into probabilities, so unseen events keep a small share., and picks k from a short list on the validation sentences before scoring the test sentences.

Notebook exercise · ~15 min

Train and score a smoothed bigram model

Count bigrams, smooth them so unseen pairs keep some probability, and choose the smoothing on validation sentences, never on the test.

  1. A bigram probability by counting

    From the training sentences, estimate P(cat | the): the number of times "the" is followed by "cat", divided by the number of times "the" is followed by anything. Store it in p_mle.

    Show a solution
    Python
    pair = Counter(bigrams(train))
    prev = Counter(p for p, _ in bigrams(train))
    p_mle = pair[("the", "cat")] / prev["the"]
    R
    b <- bigrams(train)
    p_mle <- sum(b[, 1] == "the" & b[, 2] == "cat") / sum(b[, 1] == "the")
  2. Add-one smoothing and test perplexity

    Some test bigrams never occur in training, so counting gives them probability 0. Smooth with add-one: P(w | p) = (count(p, w) + 1) / (count(p) + V). Store the perplexity of the test sentences, exp(−mean log P) over all their bigrams, in ppl_add1.

    Show a solution
    Python
    def ppl(ss, k):
        return math.exp(-np.mean([math.log((pair[b] + k) / (prev[b[0]] + k * V)) for b in bigrams(ss)]))
    ppl_add1 = ppl(test, 1)
    R
    pair <- table(paste(b[, 1], b[, 2])); prev <- table(b[, 1])
    ppl <- function(ss, k) {
      tb <- bigrams(ss)
      cp <- as.numeric(pair[paste(tb[, 1], tb[, 2])]); cp[is.na(cp)] <- 0
      cv <- as.numeric(prev[tb[, 1]]); cv[is.na(cv)] <- 0
      exp(-mean(log((cp + k) / (cv + k * V))))
    }
    ppl_add1 <- ppl(test, 1)
  3. Choose the smoothing on validation sentences

    Add-one is a choice, not a law. Try k = 0.01, 0.1, 0.5 and 1 in P(w | p) = (count(p, w) + k) / (count(p) + kV), and store in best_k the k with the lowest perplexity on the validation sentences.

    Show a solution
    Python
    best_k = min([0.01, 0.1, 0.5, 1], key=lambda k: ppl(valid, k))
    R
    best_k <- c(0.01, 0.1, 0.5, 1)[which.min(sapply(c(0.01, 0.1, 0.5, 1), function(k) ppl(valid, k)))]

In the app this opens as a Python or R notebook with the sample data, and its checks mark your progress.

04

In CodeSplash

In the app

N-gram language model perplexity in Analyze fits n-gram models to a text column with add-one, Kneser–Ney or modified Kneser–Ney smoothing, and reports held-out perplexity with a bootstrap interval. Use a training/test column you made in advance, so the held-out rows are fixed before you compare settings.

05

Check: the lab

Checkpoint

Check yourself

A test sentence contains a word pair never seen in training. What is its perplexity under the unsmoothed counting model?

Show the answer

Answer: a

One zero probability makes the whole sentence's likelihood zero. Smoothing reserves some probability for unseen pairs.

Check yourself

On the training sentences, the smallest k always gives the lowest perplexity. Why choose k on validation sentences instead?

Show the answer

Answer: a

The point of smoothing is new text. Only held-out sentences show the trade-off, and the test sentences stay untouched until the end.

06

Recap

Recap
  • Counting gives unseen pairs probability zero; smoothing moves some probability to them.
  • Add-k: (count + k) / (count of the previous word + kV).
  • Choose k on validation text; score the test text once.

Concepts in this lesson