Sub topic 4
BLEU part 1: clipped n-gram precision
BLEU (Bilingual Evaluation Understudy) compares a generated sentence, the candidate, with one or more human-written references. Its core quantity is a modified form of n-gram precision. This chapter covers that quantity and why it is modified. The brevity penalty and the final score come in the next two chapters.
This chapter assumes you know precision as "correct items divided by items produced," can read Python with collections.Counter, and know what a token and an n-gram are from the previous chapter. Tokens here are plain whitespace-separated, lowercase words.
Plain precision and why it fails
Precision measures how much of what you produced is correct. For text, "correct" means the n-gram also appears in a reference. For unigrams (n = 1), the naive score is:
precision = (candidate tokens that appear in any reference) / (candidate tokens)Take this degenerate candidate and two references:
- Candidate:
the the the the the the the - Reference 1:
the cat is on the mat - Reference 2:
there is a cat on the mat
Every candidate token, "the", appears in a reference. Naive precision is 7/7 = 1.0, a perfect score for a useless output. A translation system could game this by emitting only common words. BLEU needs a rule that stops one reference word from being credited more times than it actually occurs.
The clipping rule
BLEU's modified precision gives each distinct n-gram a credit limit. The limit is the largest number of times that n-gram appears in any single reference. The candidate's count is clipped to that limit.
For each n-gram g in the candidate:
clipped(g) = min(count_in_candidate(g), max over references of count_in_reference(g))The modified precision is the sum of clipped(g) over all distinct n-grams, divided by the total number of n-grams in the candidate.
For the "the the the" candidate, "the" appears 2 times in reference 1 and 1 time in reference 2. The maximum is 2. The candidate used "the" 7 times, so 7 is clipped to 2. The score is 2/7 ≈ 0.286 instead of 1.0.
| Item | Value |
|---|---|
| Candidate count of "the" | 7 |
| Count in reference 1 | 2 |
| Count in reference 2 | 1 |
| Clipping limit (maximum over references) | 2 |
| Clipped count | min(7, 2) = 2 |
| Total candidate unigrams | 7 |
| Modified unigram precision | 2/7 ≈ 0.286 |
Implementation
The code below follows the definition directly. ngrams returns a Counter of n-gram tuples. modified_precision builds the per-n-gram maximum across references, then clips.
from collections import Counter
def ngrams(tokens, n):
return Counter(tuple(tokens[i:i + n]) for i in range(len(tokens) - n + 1))
def modified_precision(candidate, references, n):
cand_counts = ngrams(candidate, n)
max_ref_counts = Counter()
for ref in references:
for gram, count in ngrams(ref, n).items():
max_ref_counts[gram] = max(max_ref_counts[gram], count)
clipped = sum(min(count, max_ref_counts[gram]) for gram, count in cand_counts.items())
total = sum(cand_counts.values())
return clipped / total if total else 0.0
references = [
"the cat is on the mat".split(),
"there is a cat on the mat".split(),
]
degenerate = "the the the the the the the".split()
print(modified_precision(degenerate, references, 1)) # 2/7 = 0.2857...
candidate = "the cat sat on the mat".split()
print(modified_precision(candidate, references, 1)) # 5/6 = 0.8333...
print(modified_precision(candidate, references, 2)) # 3/5 = 0.6Three details of this code matter.
max, notsum, across references. Summing would let a candidate use "the" 3 times because reference 1 has 2 and reference 2 has 1. No single human sentence uses it 3 times, so the credit would be unearned.Counterreturns 0 for missing keys.max_ref_counts[gram]is 0 for an n-gram that appears in no reference, somin(count, 0)is 0 and that n-gram earns nothing. Reading a missing key from aCounterdoes not raise an error.- The guard
if total else 0.0. A candidate shorter thanntokens has no n-grams, sototalis 0. Without the guard you would divide by zero.
Working through the example
Use the candidate the cat sat on the mat against the same two references.
Unigrams. The candidate has 6 tokens. The "the" token appears twice and its limit is 2, so both count. Then "cat", "on", and "mat" each appear once and each has a limit of at least 1, so each counts. "sat" appears in no reference, so it earns 0. The sum is 2 + 1 + 1 + 1 + 0 = 5, and the precision is 5/6 ≈ 0.833.
Bigrams. The candidate has 5 bigrams: the cat, cat sat, sat on, on the, the mat. The references contain these bigrams:
- Reference 1:
the cat,cat is,is on,on the,the mat - Reference 2:
there is,is a,a cat,cat on,on the,the mat
Three candidate bigrams match: the cat (reference 1), on the, and the mat. cat sat and sat on match nothing. The precision is 3/5 = 0.6.
Higher-order precision is almost always lower than unigram precision. Unigrams measure whether the right words are present, which BLEU treats as adequacy. Longer n-grams measure whether words appear in a plausible order, which BLEU treats as fluency. One wrong word breaks up to n n-grams of order n, so the score falls fast as n grows.
Clipping across repeated n-grams
Clipping applies per distinct n-gram, not per sentence position. Suppose a candidate says the cat the cat on the mat and the reference is the cat is on the mat. The bigram the cat appears twice in the candidate but once in the reference, so only one occurrence earns credit.
This is why clipping handles repetition well. A system that loops ("the cat the cat the cat ...") gets no extra credit after the reference's own count is used up. It also has a cost. If a reference legitimately repeats a phrase, a candidate that repeats it the same number of times is fine, but a candidate that repeats it more is penalized for the excess.
Edge cases to watch
- Tokenization changes the numbers.
mat.andmatare different tokens unless you split off punctuation. The example above uses punctuation-free text. Real scoring needs one fixed tokenizer. Chapter 7 covers SacreBLEU, which fixes this. - Case matters unless you normalize.
Theandtheare different tokens in the code above. Lowercase both sides if you want case-insensitive scoring. - Zero precision at any order. If no 4-gram in the candidate matches a reference, the order-4 precision is 0.0. Because BLEU takes a geometric mean, one zero makes the whole score 0 unless you smooth. This is common on short sentences and is covered in the third BLEU chapter.
- Candidates shorter than n. A 3-token candidate has no 4-grams. The code returns 0.0, which then zeroes the score. Treat this as a known limitation of sentence-level BLEU, not a bug in your code.
- Duplicate references. Repeating a reference changes nothing, because the maximum count is unchanged. Adding a reference can only raise the limits, so it can only raise or hold the score.
- Precision ignores missing content. A one-word candidate
cathas unigram precision 1.0, since it is in the references and appears once. Clipping does not fix this, because the candidate omits most of the reference. The brevity penalty in the next chapter handles this case.
Why precision and not recall
Clipped precision asks "how much of what the system said is supported by a reference?" It does not ask how much of the reference the system covered. BLEU was designed for machine translation with several valid references, where many different wordings are acceptable. Recall against any one reference would punish valid wordings, while precision against the pooled references rewards any candidate word that some human translator also used. The length gap that precision leaves open is closed by a separate length penalty, not by recall. ROUGE, later in this tutorial, takes the opposite emphasis.
Exercise
A candidate is the cat the cat on the mat and the only reference is the cat is on the mat. Compute the modified bigram precision (n = 2). Show the candidate bigrams, the clipping limits, and the result.
Show answer
Candidate bigrams (6 total): the cat x2, cat the x1, cat on x1, on the x1, the mat x1. Reference bigrams: the cat x1, cat is x1, is on x1, on the x1, the mat x1. Clipped counts: the cat min(2, 1) = 1, cat the min(1, 0) = 0, cat on min(1, 0) = 0, on the min(1, 1) = 1, the mat min(1, 1) = 1. The sum is 3, so the modified bigram precision is 3/6 = 0.5.
Exercise
Why does the implementation take the maximum of each n-gram's count over the references instead of the sum? Give a concrete case where summing would give a wrong credit.
Show answer
Clipping is meant to cap credit at the number of times a single human writer used the n-gram. Summing would add counts from different references that no one sentence contains. With references the cat is on the mat (two "the") and there is a cat on the mat (one "the"), summing gives a limit of 3. A candidate with three "the" tokens would then get full unigram credit for "the", although no reference uses it three times. The maximum gives a limit of 2.