Sub topic 6
BLEU part 3: combining n-gram orders, corpus-level scoring, and smoothing
Assume you know Python, Counter, and the definitions of precision, recall, and F1. This chapter assumes you already understand BLEU’s clipped n-gram precision and brevity penalty.
Combining n-gram orders
BLEU usually evaluates 1-grams through 4-grams. Each order tests a different kind of similarity:
| N-gram order | What it checks |
|---|---|
| 1-gram | Shared words |
| 2-gram | Local word pairs |
| 3-gram | Short phrase structure |
| 4-gram | Longer phrase structure |
BLEU combines the modified precisions with a geometric mean:
BLEU = BP × exp((log p1 + log p2 + log p3 + log p4) / 4)
Here, p1 through p4 are the clipped precisions, and BP is the brevity penalty. The geometric mean makes every n-gram order important. If any unsmoothed precision is zero, the complete sentence BLEU score becomes zero.
A candidate can therefore share many individual words with a reference but receive a low score if its longer phrases differ.
Sentence-level and corpus-level BLEU
A sentence may be too short to contain a matching 4-gram. Unsmoothed sentence BLEU then becomes zero, even when the output is useful. Corpus BLEU avoids much of this instability by adding clipped counts across the entire test set before calculating precisions.
For corpus BLEU, calculate:
- The total clipped count for each n-gram order across all sentences.
- The total candidate count for each order.
- One precision for each order from those totals.
- One brevity penalty from total candidate and reference lengths.
- The geometric mean of the corpus-level precisions.
Do not average sentence BLEU scores to obtain corpus BLEU. Averaging gives short and long sentences equal weight and does not produce the same statistic.
import math
from collections import Counter
def ngrams(tokens, n):
return Counter(tuple(tokens[i:i + n])
for i in range(len(tokens) - n + 1))
def corpus_bleu(candidates, references, max_n=4):
clipped_totals = [0] * max_n
candidate_totals = [0] * max_n
candidate_length = 0
reference_length = 0
for candidate, ref_list in zip(candidates, references):
candidate_length += len(candidate)
reference_length += min(
(len(ref) for ref in ref_list),
key=lambda length: (abs(length - len(candidate)), length)
)
for n in range(1, max_n + 1):
candidate_counts = ngrams(candidate, n)
maximum_reference_counts = Counter()
for ref in ref_list:
for gram, count in ngrams(ref, n).items():
maximum_reference_counts[gram] = max(
maximum_reference_counts[gram], count
)
clipped_totals[n - 1] += sum(
min(count, maximum_reference_counts[gram])
for gram, count in candidate_counts.items()
)
candidate_totals[n - 1] += sum(candidate_counts.values())
precisions = [
clipped / total if total else 0.0
for clipped, total in zip(clipped_totals, candidate_totals)
]
if min(precisions) == 0:
return 0.0
brevity_penalty = (
1.0 if candidate_length > reference_length
else math.exp(1 - reference_length / candidate_length)
)
geometric_mean = math.exp(
sum(math.log(p) for p in precisions) / max_n
)
return brevity_penalty * geometric_mean
candidates = [
"the cat sat on the mat".split(),
"a dog is in the garden".split(),
]
references = [
["the cat is on the mat".split()],
["there is a dog in the garden".split()],
]
print(corpus_bleu(candidates, references))Smoothing
Smoothing prevents a zero precision from erasing a sentence score. Common methods add a small value, assign decreasing weights to unseen n-grams, or use lower-order matches when higher-order matches are absent.
Smoothing is useful for sentence-level diagnostics, but it changes the metric. Always report the smoothing method. Corpus BLEU normally does not need sentence-level smoothing because larger test sets provide enough n-grams.
> callout note > Never compare BLEU scores unless tokenization, reference selection, case handling, n-gram limit, and smoothing settings match.
Computing reproducibly
For published or shared results, use a standard implementation such as SacreBLEU. It records the tokenization and configuration in its output, reducing accidental differences between experiments.
Exercise
Why should you avoid averaging sentence BLEU scores when reporting a test-set BLEU score?
Show answer
Corpus BLEU aggregates clipped and total n-gram counts across the test set before calculating precisions, while an average gives every sentence equal weight and measures something different.