172. Compute sentence BLEU with brevity penalty
Why it matters Machine translation and many multilingual LLM benchmarks still report BLEU.
BLEU scores a translation by clipped n-gram precision against references, times a brevity penalty.
Write bleu(cand, refs, N=4). cand is a token list, refs a list of token lists. For n = 1..N, p_n = (sum over candidate n-grams of min(count in cand, max count in any ref)) / (number of candidate n-grams). If any p_n is 0 or the candidate is empty return 0.0. Let c = len(cand) and r = the reference length closest to c (smaller on ties). BP = 1 if c > r else exp(1 - r / c). Return BP * exp(mean of log p_n).
def bleu(cand, refs, N=4)Example 1
Input: bleu(["a", "b", "c", "d"], [["a", "b", "c", "d"]])
Output: 1.0
Example 2
Input: cand = ['the', 'the', 'the', 'the'], refs = [['the', 'cat', 'the', 'mat']], 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
Use collections.Counter for n-grams; clip with the max over references.
Hint 2
Counter of tuple n-grams.
Hint 3
Clip each count by its max over references.
Hint 4
Closest reference length, smaller on ties.
Hint 5
Geometric mean via exp of mean logs.
Common mistakes
- Not clipping counts.
- Applying the brevity penalty when the candidate is longer.
- Picking the shortest reference instead of the closest.
Understand the idea
BLEU checks how many of a candidate's n-grams also appear in a reference, for n from 1 to N, then averages those precisions in log space and applies a penalty if the candidate is too short. Counts are clipped so a candidate cannot win by repeating one common word. Worked example with N = 2: cand = [the, the, cat], ref = [the, cat, sat]. Unigrams: 'the' appears 2 times but only 1 time in the ref, so it is clipped to 1, plus 'cat' 1, giving p1 = 2/3. Bigrams: (the, the) 0, (the, cat) 1, giving p2 = 1/2. c = 3 and r = 3, so BP = 1. BLEU = exp((ln(2/3) + ln(1/2)) / 2) = sqrt(1/3) = about 0.577. If c were 2 and r were 4, BP would be exp(1 - 4/2) = about 0.368.
p_n = sum of min(count in cand, max count in any ref) / number of cand n-grams; return 0 if any p_n is 0 or cand is empty; r is the ref length closest to c (smaller on ties); BP = 1 if c > r else exp(1 - r/c)
Used in: machine translation evaluation.
Shapes and data flow
cand -> n-gram Counter per n refs -> per n-gram max count over refs p_n = clipped / total, BLEU = BP * geo-mean(p_1..p_N)