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.
def 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.
Similar problems
- Find the most likely segmentation with a unigram model and ViterbiHardPro
- Encode a batch with CLS and SEP, truncation, padding side and an attention maskHardPro
- Recover the edit operations behind a Levenshtein distance by backtrackingHardPro
- Find collocations by ranking bigrams with pointwise mutual informationHardPro