Sub topic 3
Precision, recall, and F1 applied to text overlap
This chapter assumes you know precision, recall, and F1 from classification, and that you can use collections.Counter in Python. It applies those three quantities to a new setting, comparing two token lists. BLEU, ROUGE, and BERTScore are all built from them. If you can compute them by hand on text, the later chapters need little new machinery.
From classification to text
In classification, precision is the share of positive predictions that were correct, and recall is the share of true positives that were found. Text overlap metrics reuse that idea by treating tokens as the things being retrieved.
- The candidate is the generated text, such as a translation or a summary.
- The reference is the human-written text you compare against.
- A match is a candidate token that also appears in the reference.
The classification terms then map onto text like this:
| Quantity | Question it answers | Formula |
|---|---|---|
| Precision | How much of what the model wrote is supported by the reference? | matches / number of candidate tokens |
| Recall | How much of the reference did the model cover? | matches / number of reference tokens |
| F1 | Are both high at once? | harmonic mean of precision and recall |
Both quantities share the same numerator, the match count. They differ only in the denominator. Precision divides by the candidate length, and recall divides by the reference length. Most of the design choices in BLEU and ROUGE come down to which denominator they use and how they count matches.
Counting matches with multisets
A sentence can repeat a word, so a match count needs a rule. Suppose the candidate contains "the" four times and the reference contains it twice. The natural rule is that each reference token can be used at most once. The candidate then earns two matches for "the", not four.
This is a multiset intersection. For each token, take the smaller of its two counts. Python's Counter implements it with the & operator.
from collections import Counter
def overlap_prf(candidate, reference):
"""Unigram overlap precision, recall, and F1 for two token lists."""
cand_counts = Counter(candidate)
ref_counts = Counter(reference)
matches = sum((cand_counts & ref_counts).values())
if matches == 0:
return 0.0, 0.0, 0.0
precision = matches / len(candidate)
recall = matches / len(reference)
f1 = 2 * precision * recall / (precision + recall)
return precision, recall, f1
reference = "the cat is on the mat".split()
examples = {
"similar": "the cat sat on the mat".split(),
"too short": "the cat".split(),
"too long": "the cat is on the mat and the dog sat on the rug".split(),
"repeated": "the the the the the the the".split(),
}
for name, candidate in examples.items():
p, r, f = overlap_prf(candidate, reference)
print(f"{name:10s} P={p:.4f} R={r:.4f} F1={f:.4f}")Running it prints:
similar P=0.8333 R=0.8333 F1=0.8333
too short P=1.0000 R=0.3333 F1=0.5000
too long P=0.4615 R=1.0000 F1=0.6316
repeated P=0.2857 R=0.3333 F1=0.3077Here is how each row comes about.
- Similar. The candidate and reference are both 6 tokens long. Five tokens match: "the" twice, "cat", "on", and "mat". The other candidate token, "sat", has no counterpart, and "is" in the reference is missed. Precision and recall are both 5/6.
- Too short. Both candidate tokens are correct, so precision is perfect. The candidate covers only 2 of the 6 reference tokens, so recall is 2/6.
- Too long. Every reference token appears in the candidate, so recall is perfect. Only 6 of the 13 candidate tokens are matched, so precision is 6/13. The extra words "and", "dog", "sat", "rug", and a second "on" and "the" have no counterpart.
- Repeated. The candidate has 7 tokens, all "the". The reference contains "the" twice, so only 2 matches count and precision is 2/7. Without the multiset rule, precision would be a perfect 1.0.
The last row previews the next chapter. Counting each reference token only once is the core idea of BLEU's modified (clipped) precision.
Why F1 and not an average
F1 combines the two scores with the harmonic mean:
F1 = 2 · P · R / (P + R)
The harmonic mean punishes imbalance. A system that outputs one safe word has perfect precision and almost no recall. An arithmetic mean would give it about 0.5, while F1 does not.
| Precision | Recall | Arithmetic mean | F1 |
|---|---|---|---|
| 0.50 | 0.50 | 0.50 | 0.50 |
| 0.90 | 0.30 | 0.60 | 0.45 |
| 1.00 | 0.10 | 0.55 | 0.18 |
For unigram overlap there is a convenient identity. Because both scores share the same numerator, F1 simplifies to
F1 = 2 · matches / (candidate length + reference length)
You can check it on the "too long" row: 2 · 6 / (13 + 6) = 12/19 = 0.6316. This form shows that F1 depends only on the match count and the two lengths. It also avoids dividing by zero in the middle of the calculation.
Which side does a metric emphasize
The two denominators suit different jobs, and that is why the metrics differ.
- Precision-oriented metrics ask whether the candidate says only things the reference supports. Machine translation fits this view. A translation that adds invented content is wrong, even if it also contains the right words. BLEU is built on precision.
- Recall-oriented metrics ask whether the candidate covers what the reference contains. Summarization fits this view. A summary that omits key points has failed, and a summary is usually much shorter than its source. ROUGE was originally designed around recall.
- F1 is the neutral choice when you care about both. Many libraries report precision, recall, and F-measure together. Check which number a paper quotes before comparing scores.
Precision alone rewards short, safe output, and recall alone rewards long output that lists everything. BLEU deals with the first problem by adding a brevity penalty, which a later chapter covers.
Edge cases and pitfalls
- Empty candidate or no matches. Precision divides by the candidate length, so an empty candidate would cause a division by zero. Return 0.0 explicitly, as
overlap_prfdoes whenmatches == 0. Without that early return, the F1 line would divide by zero when precision and recall are both 0. - Tokenization changes the score. With
split(), "mat." and "mat" are different tokens, so a trailing full stop turns a match into a miss. Lowercasing, punctuation handling, and word versus subword units all change the match count. Real metric libraries fix these choices. Your own code must make them explicit and keep them identical for every system you compare. - Word order is ignored. The candidate "mat the on cat the is" scores precision, recall, and F1 of 1.0 against the reference above, although it is not a sentence. Unigram overlap sees only bags of words. Higher-order n-grams and the longest common subsequence, covered in later chapters, bring word order back in.
- Different words, same meaning. "A feline rested on the rug" shares only "on" and "the" with the reference. Exact-match overlap cannot see paraphrase, which is the motivation for embedding-based matching in BERTScore.
- Multiple references. With several references, you must decide what to count as the reference. BLEU takes the maximum count of each token across references. ROUGE usually scores each reference separately and keeps the best result. Both are covered in later chapters.
Exercises
Exercise
The reference is "the cat is on the mat" (6 tokens). The candidate is "the cat sat on the mat today" (7 tokens). Using the multiset overlap rule, what are the match count, precision, recall, and F1?
Show answer
The matches are "the" (2), "cat" (1), "on" (1), and "mat" (1), so there are 5 matches. Precision is 5/7 ≈ 0.714 and recall is 5/6 ≈ 0.833. F1 is 2 · 5 / (7 + 6) = 10/13 ≈ 0.769. The words "sat" and "today" are unmatched, and "is" in the reference is missed.
Exercise
A system has precision 0.9 and recall 0.3 on a summarization task. Compute its F1, and explain why it is lower than the arithmetic mean of 0.6.
Show answer
F1 = 2 · 0.9 · 0.3 / (0.9 + 0.3) = 0.54 / 1.2 = 0.45. The harmonic mean is pulled toward the smaller of the two values, so a large gap between precision and recall lowers F1. The system writes accurate content but covers only a third of the reference, and F1 reflects that.
Exercise
Why does the "repeated" candidate (seven copies of "the") get precision 2/7 and not 1.0, and which later metric is built on this idea?
Show answer
Each reference token can be matched at most as many times as it occurs in the reference, and "the" occurs twice. The multiset intersection therefore gives 2 matches against 7 candidate tokens. Clipping counts this way is the basis of BLEU's modified n-gram precision.