Train a bigram language model and measure perplexity

Perplexity is how surprised a language model is by text; lower is better. The smallest real language model is a bigram model: the next word depends only on the previous one.

Write bigram_perplexity(train, test, k) where train and test are token lists and k is the add-k smoothing constant.
- Vocabulary V = the set of tokens in train plus test, plus the start token "<s>".
- Prefix both sequences with "<s>".
- P(w | prev) = (count(prev, w) + k) / (count(prev) + k |V|), counting pairs from the prefixed train sequence, where count(prev) counts prev as the first element of a pair.
- Perplexity = exp(-mean log P) over every pair in the prefixed test sequence.

Signaturedef bigram_perplexity(train, test, k)

Understand the idea

A bigram language model guesses each word using only the previous word. Add-k smoothing adds k to every pair count so an unseen pair never gets probability 0. Perplexity measures surprise: it is exp of the average negative log probability, roughly how many equally likely choices the model feels it has at each step. Lower is better. Worked example: train [a, b], test [a, b], k = 1. Vocabulary {a, b, <s>} has size 3. Prefixed train [<s>, a, b] gives pairs (<s>, a) and (a, b); count(<s>) = 1, count(a) = 1 as a pair start. Test pairs: P(a | <s>) = (1 + 1) / (1 + 3) = 0.5 and P(b | a) = (1 + 1) / (1 + 3) = 0.5. Mean log P = ln 0.5, so perplexity = exp(0.693) = 2. Rule: P(w | prev) = (count(prev, w) + k) / (count(prev) + k |V|); perplexity = exp(-mean log P) over prefixed test pairs. Returning the mean itself is cross-entropy, not perplexity. LLMs are still compared by perplexity.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: seen textbigram_perplexity(_tr, 'the cat sat'.split(), 1.0)
  • Sample 2: unseen wordbigram_perplexity(_tr, 'the dog sat'.split(), 1.0)