Compute exact match and token F1 for QA answers

Why it matters EM and token F1 are still the headline metrics for extractive QA and many RAG answer checks.

Extractive QA benchmarks score a predicted answer against one or more reference answers with exact match (EM) and token-level F1, after a normalisation step.

Write qa_scores(pred, golds). Normalise a string by: lowercasing, removing all characters in string.punctuation, removing the words "a", "an" and "the", and collapsing whitespace. Tokens are the whitespace-split words. For one gold: EM is 1.0 if the normalised strings are equal else 0.0; F1 uses the multiset overlap of tokens (count each common token min(count_pred, count_gold) times), precision = overlap / len(pred tokens), recall = overlap / len(gold tokens). If either side has no tokens, F1 is 1.0 when both are empty and 0.0 otherwise. Return (max EM, max F1) over all golds.

Signaturedef qa_scores(pred, golds)

Example

qa_scores("The Eiffel Tower!", ["Eiffel Tower"]) is (1.0, 1.0).

Understand the idea

Exact match is strict: one extra word and the score is 0. Token F1 gives partial credit by treating answers as bags of words, like marking an essay answer by how many key words it shares with the model answer.

Normalise first, so "The Eiffel Tower!" and "eiffel tower" both become "eiffel tower".

Example: prediction "in the city of Paris" becomes "in city of paris" (4 tokens), gold "Paris France" becomes "paris france" (2 tokens). Shared: "paris" once. Precision 1/4, recall 1/2, F1 = 2 * 0.25 * 0.5 / 0.75 = 0.333. Against gold "Paris" the F1 is 2 * 0.25 * 1 / 1.25 = 0.4, so the best is 0.4. EM is 0.

Rule: F1 = 2PR / (P + R), with overlap = sum over words of min(count in pred, count in gold); take max over gold answers.

This is the scoring used by SQuAD-style benchmarks, and RAG pipelines use the same functions to check generated answers against references.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: exampleqa_scores('The Eiffel Tower!', ['Eiffel Tower'])
  • Sample 2: partialqa_scores('in the city of Paris', ['Paris', 'Paris France'])
  • Test 3: repeated wordsqa_scores('new new york', ['new york new jersey'])
  • Test 4: empty after normqa_scores('the', ['an'])