Bigram Probabilities with Add-1 Smoothing

NLPHard+20 XP+20

Bigram Probabilities with Add-1 Smoothing

A bigram language model predicts the next word from the current one, by counting how often each pair appeared in the training text:

P(w2∣w1)=count(w1,w2)count(w1)P(w_2 \mid w_1) = \frac{\text{count}(w_1, w_2)}{\text{count}(w_1)}P(w2​∣w1​)=count(w1​)count(w1​,w2​)​

That has a fatal flaw. Any pair that never appeared gets probability exactly zero, so a single unseen pair makes an entire sentence impossible — and in logs, negative infinity.

Add-1 (Laplace) smoothing fixes it by pretending every possible pair was seen once more than it was:

P(w2∣w1)=count(w1,w2)+1count(w1)+VP(w_2 \mid w_1) = \frac{\text{count}(w_1, w_2) + 1}{\text{count}(w_1) + V}P(w2​∣w1​)=count(w1​)+Vcount(w1​,w2​)+1​

where V is the vocabulary size. The +V on the bottom is there because you added 1 to each of V numerators — without it the row no longer sums to 1.

Task: write bigram_probs(tokens, vocabulary) returning a V × V table where row i, column j is the probability that vocabulary[j] follows vocabulary[i], each rounded to 4 decimal places.

  • tokens is the training text as a list of words. Count every consecutive pair in it: the pairs are (tokens[0], tokens[1]), (tokens[1], tokens[2]), and so on.
  • count(w1) is how many times w1 appeared as the first word of a pair — which is its total count excluding a final appearance at the very end of the text, since nothing follows it there.
  • Rows and columns both follow the order of vocabulary. Every word in tokens is in the vocabulary.
  • A word that never starts a pair still gets a row: every entry becomes 1/V, a uniform guess, which is exactly the right thing to say about a word you've never seen followed by anything.

Each row should sum to about 1 (up to rounding) — the quickest way to catch a wrong denominator.

Examples

tokens = ['a', 'b', 'a']
vocabulary = ['a', 'b']
returns [[0.3333, 0.6667], [0.6667, 0.3333]]
tokens = ['x', 'x', 'x']
vocabulary = ['x', 'y']
returns [[0.75, 0.25], [0.5, 0.5]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run