完全匹配(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.