Exact Match (EM) and Token-Level Precision, Recall, and F1
Agent-Assisted Engineering Check
Prerequisites
Day 70 Benchmark Task Formulations and Python text processing.
Learning Objective
Mathematically formulate Exact Match (EM) and token-level Precision, Recall, and F1 with canonical SQuAD text normalization.
Instructions
Study source: within this activity's existing reading/practice time, use Hugging Face LLM Evaluation Guidebook (legacy edition), contents/automated-benchmarks/designing-your-automatic-evaluation.md: Choosing a metric; contents/troubleshooting/troubleshooting-reproducibility.md, then explain one connection to the local task in your own words. Keep the local exercise and acceptance checks; use its original explanation if the external source is unavailable. 1. Analyze Exact Match (EM): binary score (1.0 or 0.0) indicating whether the normalized prediction matches ground truth exactly.
2. Study standard SQuAD normalization (Rajpurkar et al. 2016): (a) Lowercase text, (b) Strip punctuation, (c) Remove English articles ('a', 'an', 'the'), and (d) Collapse consecutive whitespace.
3. Derive token-level multiset metrics: let P and T be collections of tokens from normalized prediction and ground truth. Common tokens = sum of min(count_P(w), count_T(w)) for w in P cap T.
4. Precision = Common / |P|; Recall = Common / |T|; F1 = 2 * Precision * Recall / (Precision + Recall). Handle boundary condition |P| == 0 or |T| == 0: if both empty, F1=1.0; if only one empty, F1=0.0.
Practice & Prediction Log
Implement a pure Python function compute_token_f1(prediction, ground_truth) that applies full SQuAD normalization and computes Exact Match and Token F1, returning a dictionary {'em': float, 'f1': float}.
Use collections.Counter to compute the multiset intersection between predicted and reference tokens.
import re
from collections import Counter
def normalize_answer(s):
def remove_articles(text):
return re.sub(r'\b(a|an|the)\b', ' ', text)
def white_space_fix(text):
return ' '.join(text.split())
def remove_punc(text):
return re.sub(r'[^a-zA-Z0-9 ]', '', text)
def lower(text):
return text.lower()
return white_space_fix(remove_articles(remove_punc(lower(s))))
def compute_token_f1(prediction, ground_truth):
pred_tokens = normalize_answer(prediction).split()
gold_tokens = normalize_answer(ground_truth).split()
em = 1.0 if pred_tokens == gold_tokens else 0.0
if len(pred_tokens) == 0 or len(gold_tokens) == 0:
return {'em': em, 'f1': 1.0 if pred_tokens == gold_tokens else 0.0}
common = Counter(pred_tokens) & Counter(gold_tokens)
num_same = sum(common.values())
if num_same == 0:
return {'em': em, 'f1': 0.0}
precision = 1.0 * num_same / len(pred_tokens)
recall = 1.0 * num_same / len(gold_tokens)
f1 = (2 * precision * recall) / (precision + recall)
return {'em': em, 'f1': f1}
Derive and code canonical token-level F1 and EM passing all multiset tokenization edge cases.
Authoritative Source Resources & Provenance
Hugging Face LLM Evaluation Guidebook (legacy edition)
Relevant Section / Range: contents/automated-benchmarks/designing-your-automatic-evaluation.md: Choosing a metric; contents/troubleshooting/troubleshooting-reproducibility.md
Verified Version & Date: Public edition checked 2026-11-01; moving pages may change
Teaching-oriented evaluation design and reproducibility guidance complements the benchmark papers. Stable methodological chapters only; not a current tooling/version reference.
Held-out data, basic language-model metrics and experimental comparisons.
Use the original localized explanations, exercises and checks already present in this activity; no external account or purchase is required for that fallback.
Compared Candidate Sources & Selection Analysis (2)
Retained for the multi-metric framework; the guidebook makes practical choices easier to teach.
Useful implementation cross-check; tool configuration alone does not teach metric choice or evaluator limitations.
SQuAD: 100,000+ Questions for Machine Comprehension of Text
Relevant Section / Range: Section 6.1 Model Evaluation (Exact match and macro-averaged F1)
Verified Version & Date: EMNLP 2016 / arXiv:1606.05250v3 (Verified: 2026-10-30)
Defines the standard NLP Exact Match (EM) and token-level Macro/Micro F1 evaluation metrics, establishing standard text normalization rules (lowercasing, punctuation stripping, article removal).
Tokenization, text normalization, precision, recall, and harmonic mean F1.
Exact normalization code, multiset token intersection logic, and F1 calculations are completely coded in lesson exercises.
Compared Candidate Sources & Selection Analysis (2)
Adds unanswerable questions; SQuAD 1.1 formalizes the foundational token F1 and EM mathematical definitions.
Conversational multi-turn QA; SQuAD provides a widely adopted implementation of normalized token F1.
BLEU: a Method for Automatic Evaluation of Machine Translation
Relevant Section / Range: Section 2.1.1 Modified n-gram precision on blocks of text; Section 2.3 BLEU details
Verified Version & Date: ACL 2002 Anthology (Verified: 2026-10-30)
Foundational literature introducing modified n-gram precision and brevity penalties, providing the mathematical contrast between precision-oriented n-gram clipping and recall-oriented sequence metrics.
N-gram precision, modified n-gram clipping, brevity penalty.
N-gram clipping algorithms, geometric mean precision, and brevity penalty formulas are completely implemented in lesson code.
Compared Candidate Sources & Selection Analysis (2)
Incorporates stemming and WordNet synonymy; BLEU is the fundamental n-gram precision baseline required for quantitative comparison.
Character-level n-gram F-score; Papineni BLEU provides the historic foundation for token-based precision clipping.