869. Fix BLEU precision that counts repeated words
Why it matters BLEU still appears in MT and summarisation evals. Clipping is the part that makes it hard to game by repeating common words.
The starter code below runs, but it has a realistic bug. Read the spec, find the bug and fix it. Keep the function name and signature.
sentence_bleu(candidate, reference, max_n=2) should return sentence BLEU with one reference:
- for n = 1 .. max_n, modified precision p_n = (sum over candidate n-grams of min(count in candidate, count in reference)) / (number of candidate n-grams)
- if any p_n is 0, or the candidate has fewer than max_n tokens, return 0.0
- brevity penalty BP = 1 if c > r else exp(1 - r / c), where c and r are the candidate and reference lengths
- BLEU = BP * exp(mean of log p_n)
Inputs: candidate and reference are lists of string tokens. The reference is never empty.
Return a Python float rounded to 4 decimals.
def sentence_bleu(candidate, reference, max_n=2)Example 1
Input: sentence_bleu(['the', 'cat', 'sat'], ['the', 'cat', 'sat', 'down'])
Output: 0.7165
Example 2
Input: candidate = ['the', 'the', 'the', 'the'], reference = ['the', 'cat', 'the', 'mat'], max_n = 1
Output: 0.5
Constraints
- Python 3 standard library. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
Compute unigram precision for 'the the the the' by hand.
Hint 2
Each n-gram's credit is capped by the reference count.
Hint 3
Use min(cnt, ref[g]) in the sum.
Common mistakes
- Clipping by the candidate count instead.
- Brevity penalty with c / r instead of r / c.
- Averaging precisions instead of log precisions.
Understand the idea
Without clipping, the candidate 'the the the the' gets unigram precision 4/4 against 'the cat the mat'. BLEU clips each n-gram count at the number of times it appears in the reference, so 'the' can only be credited twice, giving 2/4. Counter makes this easy: missing keys count as 0.
Shapes and data flow
Lists of tokens. Output: scalar.