168. 计算 QA 答案的 Exact Match 和 Token F1
重要性 EM 和 token F1 仍然是抽取式 QA 以及许多 RAG 答案检查的核心指标。
抽取式 QA 基准测试在经过归一化步骤后,通过 exact match (EM) 和 token 级别的 F1 来衡量预测答案与一个或多个参考答案之间的匹配程度。
编写 qa_scores(pred, golds)。归一化字符串的方法为:转为小写,移除 string.punctuation 中的所有字符,移除单词 "a", "an" 和 "the",并合并多余空格。Token 是通过空格切分后的单词。对于单个 gold 答案:如果归一化后的字符串相等,则 EM 为 1.0,否则为 0.0;F1 使用 token 的 multiset overlap(每个共同 token 出现的次数为 min(count_pred, count_gold)),precision = overlap / len(pred tokens),recall = overlap / len(gold tokens)。如果任何一方没有 token,则当两者都为空时 F1 为 1.0,否则为 0.0。返回所有 golds 中的 (max EM, max F1)。
def qa_scores(pred, golds)示例 1
输入: qa_scores("The Eiffel Tower!", ["Eiffel Tower"])
输出: (1.0, 1.0)
约束条件
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
提示 1
collections.Counter & Counter 可以计算 multiset overlap。
提示 2
Counter intersection 会保留最小计数。
提示 3
移除冠词时请使用单词边界。
提示 4
在 golds 中取最大值。
常见错误
- 使用了 set overlap 而不是 multiset overlap。
- 只归一化了 prediction 而没有归一化 gold answers。
理解思路
Exact match 非常严格:多出一个单词得分就是 0。Token F1 通过将答案视为 bag of words 来提供部分分数,类似于根据作文答案与标准答案共享了多少关键词来评分。
首先进行归一化,这样 "The Eiffel Tower!" 和 "eiffel tower" 都会变成 "eiffel tower"。
预测值 "in the city of Paris" 变为 "in city of paris" (4 tokens),gold "Paris France" 变为 "paris france" (2 tokens)。共享部分: "paris" 出现 1 次。Precision 为 1/4,recall 为 1/2,F1 = 2 * 0.25 * 0.5 / 0.75 = 0.333。对比 gold "Paris" 时,F1 为 2 * 0.25 * 1 / 1.25 = 0.4,因此最高分为 0.4。EM 为 0。
F1 = 2PR / (P + R),其中 overlap = sum over words of min(count in pred, count in gold);在所有 gold answers 中取最大值。
这是 SQuAD 风格基准测试所使用的评分方式,RAG pipeline 也使用相同的函数来检查生成的答案与参考答案的匹配情况。