Sub topic 2
BLEU part 3: combining n-gram orders, corpus-level scoring, and smoothing
This chapter assumes you know Python lists, collections.Counter, precision, recall, F1, and clipped n-gram precision from the previous chapter.
Combining n-gram orders
BLEU computes clipped precision for n = 1 to 4, then combines them with a geometric mean. The geometric mean multiplies the precisions and takes the n-th root, so one zero precision makes the whole score zero. Code computes it in log space to avoid underflow.
Corpus-level scoring
BLEU is usually reported over a whole test set, not one sentence. Clipped match counts and lengths are summed across all sentences first. Precision and the brevity penalty are computed once from those totals. Long sentences therefore carry more weight, which is intended.
Smoothing
Short sentences often have no 4-gram matches, which sets the score to zero. Add-one smoothing adds 1 to the matched and total counts for each order above 1.
import math
def bleu_from_counts(clipped, totals, cand_len, ref_len, smooth=False):
"""clipped and totals hold one entry per n-gram order, n = 1 to 4."""
precisions = []
for n, (c, t) in enumerate(zip(clipped, totals), start=1):
if smooth and n > 1:
c, t = c + 1, t + 1
if c == 0:
return 0.0
precisions.append(c / t)
log_mean = sum(math.log(p) for p in precisions) / len(precisions)
bp = 1.0 if cand_len > ref_len else math.exp(1 - ref_len / cand_len)
return bp * math.exp(log_mean)
# Candidate "the cat sat on the mat" against "the cat is on the mat"
clipped, totals = [5, 3, 1, 0], [6, 5, 4, 3]
print(bleu_from_counts(clipped, totals, 6, 6)) # 0.0, no 4-gram match
print(bleu_from_counts(clipped, totals, 6, 6, smooth=True)) # about 0.49Computing BLEU reproducibly with SacreBLEU
Tokenization and settings change BLEU values, so papers that use different code often report incomparable numbers. SacreBLEU applies a fixed internal tokenization and reports its configuration.
import sacrebleu
hyps = ["the cat sat on the mat", "there is a dog in the garden"]
refs = [["the cat is on the mat", "a dog is in the garden"]] # one reference stream
bleu = sacrebleu.corpus_bleu(hyps, refs)
print(bleu.score)
print(bleu) # score plus the configuration usedROUGE-N: n-gram overlap oriented toward recall
ROUGE-N counts overlapping n-grams. Recall divides the overlap by the number of reference n-grams. Precision divides it by the number of candidate n-grams. For "the cat sat on the mat" against "the cat is on the mat", ROUGE-1 has 5 overlapping unigrams out of 6 in each text, so precision and recall are both 5/6. ROUGE-2 has 3 overlapping bigrams out of 5 in each text, so both are 3/5.
ROUGE-L: longest common subsequence
ROUGE-L uses the longest common subsequence (LCS), the longest word sequence that appears in both texts in order, without needing to be contiguous. In the example above, the LCS is "the cat on the mat", with length 5. Recall is 5/6, precision is 5/6, and F1 follows from them.
ROUGE in practice: stemming, ROUGE-Lsum, and multiple references
Set use_stemmer=True so that "sitting" and "sit" match. ROUGE-Lsum splits texts into sentences at newlines and computes the LCS per sentence, which suits multi-sentence summaries. With several references, take the best F1 for each metric.
from rouge_score import rouge_scorer
scorer = rouge_scorer.RougeScorer(["rouge1", "rouge2", "rougeL", "rougeLsum"], use_stemmer=True)
refs = ["The cat is on the mat.", "A cat lies on the mat."]
pred = "The cat sat on the mat."
best = {}
for ref in refs:
for name, s in scorer.score(ref, pred).items(): # (target, prediction)
best[name] = max(best.get(name, 0.0), s.fmeasure)
print(best)Exercise
The candidate "the the the the the the the" is scored with unsmoothed BLEU-1 against "the cat is on the mat". Why does clipping matter here?
Show answer
Clipping caps each candidate count at the largest count in any reference. "the" appears twice in the reference, so only 2 of the 7 candidate tokens count, and precision is 2/7 instead of 7/7.