Sub topic 5
Reference-based metrics: exact match, overlap, and their limits
This chapter assumes you can write basic Python, have a working evaluation harness like the one from the previous chapter (a function that runs your app over cases and applies a scorer), and know what a mean and a proportion are. It covers metrics that compare a model output to a stored reference answer, and it explains where those comparisons break down.
What "reference-based" means
A reference-based metric scores an output by comparing it to one or more known-good answers stored in your dataset. The reference is usually the expected field of each case. The metric is a function from (output, reference) to a number or a boolean.
These metrics are popular for good reasons. They are cheap, deterministic, and fast. They need no second model call. Running the same scorer on the same outputs always gives the same result, so any variation in your results comes from the application, not the scorer.
They also share one assumption: the reference captures what a correct answer looks like. That holds for short factual answers, classification labels, and extracted values. It holds poorly for summaries, explanations, and open-ended writing.
Exact match and normalization
Exact match returns true when the output equals the reference. The simplest version, from the harness chapter, lowercases and strips whitespace. That is almost always too strict. "Paris." and "paris" are the same answer, but a raw string comparison rejects the first.
The fix is normalization: transform both strings into a canonical form before comparing. A common recipe, popularized by question-answering benchmarks, is to lowercase, remove punctuation, remove the articles "a", "an", and "the", and collapse whitespace.
import re
import string
from collections import Counter
def normalize(text: str) -> str:
text = text.lower()
text = "".join(ch for ch in text if ch not in string.punctuation)
text = re.sub(r"\b(a|an|the)\b", " ", text)
return " ".join(text.split())
def exact_match(output: str, expected: str) -> bool:
return normalize(output) == normalize(expected)
print(exact_match("The Eiffel Tower.", "eiffel tower")) # True
print(exact_match("Paris, France", "Paris")) # FalseThe second result shows the core weakness. "Paris, France" is a correct answer, but exact match calls it wrong because it contains extra words.
Normalization can create false matches
Normalization is a choice about which differences do not matter. Choose carefully, because it can erase differences that do matter. The recipe above removes all punctuation, including the decimal point.
print(normalize("3.5")) # 35
print(exact_match("3.5", "35")) # True, which is wrongFor numeric answers, parse the numbers and compare them with a tolerance instead of comparing strings. Tailor normalization to the answer type: for dates, parse to a date object; for labels, map synonyms to a fixed set; for code or identifiers, do not lowercase at all.
Multiple references
Many questions have several acceptable answers ("USA", "United States", "United States of America"). Store a list of references and take the best score across them.
def best_over_references(scorer, output, references):
return max(scorer(output, ref) for ref in references)
refs = ["USA", "United States", "United States of America"]
print(best_over_references(exact_match, "united states", refs)) # Truemax works on booleans because True sorts above False, and it works on floats, so the same helper serves the overlap metrics below.
Token overlap: F1
When answers are phrases or sentences, a binary match is too blunt. Token overlap gives partial credit based on how many words the output and reference share.
Three quantities define it. Precision is the fraction of output tokens that appear in the reference. Recall is the fraction of reference tokens that appear in the output. F1 is their harmonic mean, which is high only when both are high. Count tokens with multiplicity, so a word repeated five times in the output does not get credit five times for one occurrence in the reference.
def token_f1(output: str, expected: str) -> float:
out_tokens = normalize(output).split()
ref_tokens = normalize(expected).split()
if not out_tokens or not ref_tokens:
return float(out_tokens == ref_tokens)
common = Counter(out_tokens) & Counter(ref_tokens)
overlap = sum(common.values())
if overlap == 0:
return 0.0
precision = overlap / len(out_tokens)
recall = overlap / len(ref_tokens)
return 2 * precision * recall / (precision + recall)
print(token_f1("Paris, France", "Paris")) # 0.6666666666666666
print(token_f1("The capital of France is Paris", "Paris")) # 0.3333333333333333The Counter intersection (&) keeps the minimum count of each token, which implements the multiplicity rule. The empty-string branch returns 1.0 only when both sides are empty, so an empty output against a real reference scores 0.
Token F1 is a reasonable metric for extractive question answering, where answers are short spans. It penalizes verbose answers through the precision term, which can be what you want or can punish helpful context. Decide which, and write it down in your success criteria.
Overlap metrics for longer text
Several well-known metrics extend the same idea to longer outputs. You will meet them in papers and libraries, so know what each measures.
| Metric | What it compares | Typical use | Main weakness |
|---|---|---|---|
| BLEU | Precision of n-grams (word sequences) against references | Machine translation | Ignores recall, and it is unreliable on single sentences |
| ROUGE-N | Recall of n-grams against a reference | Summarization | Rewards copying and misses paraphrase |
| ROUGE-L | Longest common subsequence | Summarization | Same as ROUGE-N, and it is insensitive to meaning |
| Embedding similarity | Cosine similarity of vector representations | Paraphrase-tolerant matching | Rates opposite statements as similar, and thresholds are arbitrary |
Embedding-based scores such as BERTScore reduce the paraphrase problem, but they trade a different failure for it. Two sentences with opposite meanings often share vocabulary and topic, so their embeddings sit close together. A similarity of 0.9 does not tell you the answer is right.
Where reference-based metrics fail
Three failure modes explain most bad evaluations built on these metrics.
Valid answers that differ from the reference
Language allows many correct phrasings. A summary may be excellent and share few words with your reference. Overlap metrics then report low scores for good outputs, and the metric ranks systems by similarity to one author's wording. This is the main reason they correlate poorly with human judgment on open-ended tasks.
Invalid answers that resemble the reference
The reverse is more dangerous. A single word can flip a meaning while overlap barely moves.
reference = "The treaty was not signed in 1990"
wrong = "The treaty was signed in 1990"
print(round(token_f1(wrong, reference), 3)) # 0.909The output contradicts the reference, yet it scores 0.909. A threshold of 0.8 would mark it as passing. Negation, wrong numbers, wrong entities, and swapped subjects and objects all slip through overlap metrics.
Reference quality limits the score
If a reference is wrong, stale, or ambiguous, correct outputs are penalized and the error is invisible in the aggregate number. Review failing cases by hand before trusting the metric, and check that the reference answers are still true.
Practical guidance
Use reference-based metrics where they are valid, and be explicit about where they are not.
- Match the metric to the answer type. Classification, extraction, and short factual answers suit exact match and token F1.
- Look at the per-case results, not only the mean. Read twenty failures and twenty passes. If failures contain correct answers or passes contain wrong ones, the metric is misleading you.
- Report a pass threshold with a reason. "F1 above 0.8" means little until you have read examples near the threshold.
- Pair an overlap metric with a check that catches its blind spots, such as a programmatic check for numbers and negation, or an LLM judge on a sample.
- Version your normalization function with your dataset. Changing it changes every historical score, so old and new numbers are not comparable.
Exercise
A model answers "The meeting is at 10:30" to a question whose reference is "10.30". Using the normalize and exact_match functions in this chapter, would the answer pass, and what does that tell you about using string normalization for times and numbers?
Show answer
Normalization removes punctuation, so "10:30" becomes "1030" and "10.30" becomes "1030", but the output also contains the extra words "meeting", "is", and "at" ("the" is dropped), so exact match returns False. If the output were just "10:30", it would pass, as would "1030" or "10,30". That shows that punctuation stripping erases the structure of numbers and times and can create false matches. For these answer types, parse the value into a time or number and compare the parsed values.
Exercise
A summarizer's output scores a token F1 of 0.92 against the reference but says the opposite of the reference on one key fact. Name the failure mode and one way to catch it.
Show answer
This is an invalid answer that resembles the reference. Overlap metrics are insensitive to negation and single-word changes. You could catch it with a programmatic check on the key fact (for example, verifying that a required number or entity appears with the correct polarity), or with an LLM judge or human review applied to a sample of high-overlap outputs.