Sub topic 11
Measuring quality with exact match and F1
You can now get an answer string out of a model. This chapter covers how to score that string against human answers, so you can compare models, track fine-tuning, and spot regressions. It assumes you can run the question-answering pipeline and know that predictions are text spans cut from a context. It also assumes basic Python (strings, lists, collections.Counter).
Why string metrics
Extractive QA has no single correct output. "seven million square kilometres" and "about seven million square kilometres" are both reasonable answers to the same question. Annotators also disagree on span boundaries. A plain accuracy check would punish harmless differences, so SQuAD-style evaluation uses two metrics with different strictness:
- Exact match (EM) is 1 if the normalized prediction equals a normalized reference answer, and 0 otherwise.
- F1 measures word overlap between prediction and reference. It gives partial credit when the prediction is close.
Both are computed per question, then averaged over the dataset and reported on a 0 to 100 scale.
Normalization
Before comparing, the official SQuAD script applies four steps to both strings:
- Lowercase the text.
- Remove punctuation characters.
- Remove the articles "a", "an" and "the".
- Collapse repeated whitespace.
So "The United States." and "united states" are identical after normalization. This stops the metric from penalizing differences the question does not care about.
Normalization is shallow. It does not match "7 million" with "seven million", and it does not match "km" with "kilometres". It also does not know that "1,000" and "one thousand" are equal. (It does turn "1,000" into "1000", because it deletes the comma without inserting a space.)
Exact match
EM is strict. After normalization the strings must be identical, so one extra or missing word gives 0. A prediction of "about seven million square kilometres" fails against the reference "seven million square kilometres".
When a question has several references, the prediction is compared with each one, and the best score counts. The SQuAD development set has several human answers per question for this reason. A prediction that matches any of them scores 1.
F1
F1 treats the prediction and the reference as bags of words. It uses three quantities:
- Overlap is the number of tokens the two bags share. Repeated tokens count only as many times as they appear in both.
- Precision is overlap divided by the number of predicted tokens.
- Recall is overlap divided by the number of reference tokens.
F1 is the harmonic mean of the two: 2 * precision * recall / (precision + recall). The harmonic mean is low if either value is low, so a model cannot score well by predicting an entire paragraph (high recall, low precision) or a single word (high precision, low recall).
Two properties matter in practice:
- Word order is ignored. "river Amazon" and "Amazon river" get F1 = 1.
- Tokens are whitespace-separated words, not the model's subword tokens.
A from-scratch implementation
Writing the metric once makes it much easier to debug later. This code follows the official SQuAD logic and runs without extra dependencies.
import re
import string
from collections import Counter
PUNCTUATION = set(string.punctuation)
def normalize(text):
text = text.lower()
text = "".join(ch for ch in text if ch not in PUNCTUATION)
text = re.sub(r"\b(a|an|the)\b", " ", text)
return " ".join(text.split())
def exact_match(prediction, reference):
return float(normalize(prediction) == normalize(reference))
def f1_score(prediction, reference):
pred_tokens = normalize(prediction).split()
ref_tokens = normalize(reference).split()
if not pred_tokens or not ref_tokens:
# If either side is empty, the score is 1 only when both are empty.
return float(pred_tokens == ref_tokens)
overlap = sum((Counter(pred_tokens) & Counter(ref_tokens)).values())
if overlap == 0:
return 0.0
precision = overlap / len(pred_tokens)
recall = overlap / len(ref_tokens)
return 2 * precision * recall / (precision + recall)
def best_over_references(metric, prediction, references):
return max(metric(prediction, ref) for ref in references)
cases = [
("about seven million square kilometres", ["seven million square kilometres"]),
("seven million square kilometres", ["about seven million square kilometres"]),
("The United States.", ["united states"]),
("river", ["Amazon River"]),
("the Nile", ["Amazon River", "Congo River"]),
]
for prediction, references in cases:
em = best_over_references(exact_match, prediction, references)
f1 = best_over_references(f1_score, prediction, references)
print(f"EM={em:.0f} F1={f1:.3f} {prediction!r} vs {references}")The output is:
| Prediction | Reference | EM | F1 | Why |
|---|---|---|---|---|
| about seven million square kilometres | seven million square kilometres | 0 | 0.889 | 4 shared of 5 predicted (precision 0.8), 4 of 4 reference (recall 1.0) |
| seven million square kilometres | about seven million square kilometres | 0 | 0.889 | precision 1.0, recall 0.8 |
| The United States. | united states | 1 | 1.000 | Article and punctuation are removed |
| river | Amazon River | 0 | 0.667 | precision 1.0, recall 0.5 |
| the Nile | Amazon River, Congo River | 0 | 0.000 | After removing "the", "nile" shares no token |
Rows 1 and 2 show that F1 is symmetric: a prediction with an extra word and one with a missing word get the same score.
Using the evaluate library
For reported numbers, use the library implementation so your results are comparable with published ones. Install it with pip install evaluate. Loading the metric downloads its script from the Hugging Face Hub, so it needs network access.
import evaluate
squad_metric = evaluate.load("squad")
predictions = [{"id": "q1", "prediction_text": "seven million square kilometres"}]
references = [{
"id": "q1",
"answers": {"text": ["about seven million square kilometres"], "answer_start": [125]},
}]
print(squad_metric.compute(predictions=predictions, references=references))
# {'exact_match': 0.0, 'f1': 88.88888888888889}Three details cause most integration bugs:
- Each prediction and reference needs the same
id. Metrics are matched by id, not by list position. answersholds parallel lists,textandanswer_start. Scoring uses onlytext.answer_startis required by the schema, but it does not change the score.- Scores are on a 0 to 100 scale. Your own function above returns 0 to 1, so multiply by 100 before comparing.
To score the pipeline, pass qa(question=..., context=...)["answer"] as prediction_text. If you decode logits yourself, as in the earlier chapter on turning logits into an answer string, use the string you cut out with the offset mapping.
Reading the two numbers together
EM is always less than or equal to F1, because an exact match also has F1 = 1. The gap between them tells you what kind of errors the model makes.
| Pattern | Likely meaning |
|---|---|
| EM and F1 both high | The model finds the right span with the right boundaries |
| F1 much higher than EM | The model finds the right place but the boundaries are off by a word or two |
| Both low | The model picks the wrong sentence or the wrong entity |
For orientation, human annotators score roughly 82 EM and 91 F1 on SQuAD v1.1 when compared against the other annotators' answers. A model that nears the human F1 is within the noise of annotation disagreement, so small differences between systems need care.
Unanswerable questions
On SQuAD v2 style data, some questions have no answer. The reference is an empty string, and the model signals "no answer" through its null score, which you handled in an earlier chapter. The metric follows one rule: if the reference is empty, the prediction must also be empty to score 1 on both EM and F1. Any non-empty prediction scores 0. That is why f1_score above returns 1 for two empty strings.
The squad_v2 metric in evaluate reports more than one number. It splits results into HasAns_exact, HasAns_f1, NoAns_exact and NoAns_f1, and also gives best_exact and best_f1, which use the best threshold for the null decision. It additionally needs a no_answer_probability in each prediction. Read the split numbers. A model that always answers "no answer" gets a decent overall score on a mixed dataset, but its HasAns scores are 0.
Common mistakes
- Comparing with the wrong normalization. If you strip or keep punctuation differently from the official script, your EM no longer matches published results.
- Scoring against only one reference. On the development set, using only the first human answer lowers the scores and makes them incomparable with reported numbers.
- Mixing scales. A custom 0 to 1 F1 next to a library 0 to 100 F1 leads to confusing comparisons.
- Scoring window predictions directly. With long contexts, each window produces a candidate. Combine them into one answer per question before scoring, or the metric counts several predictions for one question.
- Evaluating on training data. Fine-tuning pushes these scores up on the training set, so report only held-out numbers.
Exercise
Exercise
A model predicts "the largest river in the world" and the only reference is "largest river". Compute the EM and the F1. Show the normalized tokens, the overlap, precision and recall.
Show answer
After lowercasing and removing the article "the", the prediction becomes "largest river in world", which has 4 tokens: largest, river, in, world. (The word "the" appears twice in the original and both are removed.) The reference becomes "largest river", with 2 tokens. The strings differ, so EM = 0. The overlap is 2 tokens (largest, river). Precision = 2/4 = 0.5, recall = 2/2 = 1.0. F1 = 2 0.5 1.0 / (0.5 + 1.0) = 1.0 / 1.5 ≈ 0.667, or 66.7 on the 0 to 100 scale.
Exercise
On a development set your model scores EM 70 and F1 90. What does the 20-point gap suggest, and what would you do next?
Show answer
The model usually finds the right region of the context but often gets the span boundaries wrong, for example by adding or dropping a few words. Print the predictions with an EM of 0 and an F1 above 0, then check whether the errors are consistent (extra qualifiers, missing units, partial names). Check also whether the reference spans themselves are inconsistent. If the errors come from the model, look at span-length limits and training label alignment.
Exercise
Why does the SQuAD metric take the maximum over reference answers instead of the average?
Show answer
Annotators can legitimately choose different spans for the same question. A prediction that matches any one valid human answer is correct, so the best match is the fair score. An average would punish the model for not matching all the annotators at once, which is impossible when their answers differ.