完全匹配(EM)与 Token 级精确率、召回率及 F1 值
Agent 辅助工程检查
前置要求
第 70 天基准任务构建与 Python 文本处理基础。
学习目标
数学推导完全匹配(EM)与基于 SQuAD 文本规范化的多重集合 Token 级 F1 指标并编写实现代码。
操作指引
学习来源:在本活动现有的阅读与练习时段内,参考 Hugging Face LLM Evaluation Guidebook (legacy edition) 的 contents/automated-benchmarks/designing-your-automatic-evaluation.md: Choosing a metric; contents/troubleshooting/troubleshooting-reproducibility.md,用自己的话解释一处与本地任务的联系。保留现有练习与验收检查;若外部资料无法访问,使用课程自写的解释。1. 掌握完全匹配(Exact Match, EM):二值化判定指标,当且仅当模型预测文本在规范化后与真实标签字符串完全一致时输出 1.0,否则输出 0.0。
2. 学习标准 SQuAD 规范化流程(Rajpurkar et al. 2016):(a) 全文转小写、(b) 剔除所有标点符号、(c) 剔除英语常见冠词('a'、'an'、'the')、(d) 合并多余连续空格。
3. 推导基于多重集合(Multiset)的 Token 级指标:设 P 和 T 分别为预测与参考 Token 列表。共通 Token 计数 = sum(min(count_P(w), count_T(w)))。
4. 计算 Precision = 共通数 / |P|;Recall = 共通数 / |T|;F1 = 2 * P * R / (P + R)。严谨处理边界:若两者均为空字符串则 F1=1.0;若仅有一方为空则 F1=0.0。
自主演练与记录
编写 Python 函数 compute_token_f1(prediction, ground_truth),严格执行 SQuAD 文本规范化,计算并返回包含 {'em': float, 'f1': float} 的字典结果。
利用 collections.Counter 计算多重集合的交集,保证重复词汇的频次被正确最小化截断。
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}
独立推导并编码实现多重集合 Token F1 与 EM 指标,100% 覆盖各类空值与异常边界条件。
权威源资源与权利证明
Hugging Face LLM Evaluation Guidebook (legacy edition)
对应章节 / 时间戳: contents/automated-benchmarks/designing-your-automatic-evaluation.md: Choosing a metric; contents/troubleshooting/troubleshooting-reproducibility.md
验证版本与日期: 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.
对比候选资源与选型分析 (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
对应章节 / 时间戳: Section 6.1 Model Evaluation (Exact match and macro-averaged F1)
验证版本与日期: 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.
对比候选资源与选型分析 (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
对应章节 / 时间戳: Section 2.1.1 Modified n-gram precision on blocks of text; Section 2.3 BLEU details
验证版本与日期: 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.
对比候选资源与选型分析 (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.