Open
【11月贡献大赛-缺陷修复】fix/docs: deduplicate Recall@k hits in eval_retrieval.py (#4106) #7331
Sophie LeeAdd on 6 hours ago
【11月贡献大赛-缺陷修复】fix/docs: deduplicate Recall@k hits in eval_retrieval.py (#4106) #7331
Open
Total: 3 files changed+151-7
| @@ -4,11 +4,13 @@ | |||
| 4 | 4 | ||
| 5 | ## 指标定义 | 5 | ## 指标定义 |
| 6 | 6 | ||
| 7 | -| 指标 | 公式 | 含义 | | 7 | +| 指标 | 公式 | 含义 | |
| 8 | -| ---------- | ------------------------------------ | ---------------------- | | 8 | +| ---------- | -------------------------------------------- | ---------------------- | |
| 9 | -| Recall@k | 命中相关文档数 / 相关文档总数 | 召回了多少真相关文档 | | 9 | +| Recall@k | 前 k 名去重命中相关文档数 / 相关文档总数 | 召回了多少真相关文档 | |
| 10 | -| MRR | 首个相关文档排名的倒数,取均值 | 首个正确答案排得多靠前 | | 10 | +| MRR | 首个相关文档排名的倒数,取均值 | 首个正确答案排得多靠前 | |
| 11 | -| Hit Rate@k | 前 k 名是否有相关文档(0/1),取均值 | 至少命中一条的比例 | | 11 | +| Hit Rate@k | 前 k 名是否有相关文档(0/1),取均值 | 至少命中一条的比例 | |
| 12 | + | ||
| 13 | +> 口径说明:`Recall@k` 对前 `k` 名内重复出现的同一文档 ID 只计入一次命中;重复项仍保留其原始名次占位,第 `k` 名之后的命中不向前补位。 | ||
| 12 | 14 | ||
| 13 | ## 输入格式 | 15 | ## 输入格式 |
| 14 | 16 | ||
| @@ -20,9 +20,9 @@ def evaluate(qrels: dict, runs: dict, k: int) -> dict: | |||
| 20 | mrr_sum = 0.0 | 20 | mrr_sum = 0.0 |
| 21 | hit_sum = 0.0 | 21 | hit_sum = 0.0 |
| 22 | for q, relevant in qrels.items(): | 22 | for q, relevant in qrels.items(): |
| 23 | - ranked = runs.get(q, [])[:k] | 23 | + ranked = (runs.get(q) or [])[:k] |
| 24 | rel_set = set(relevant) | 24 | rel_set = set(relevant) |
| 25 | - hits = [doc for doc in ranked if doc in rel_set] | 25 | + hits = {doc for doc in ranked if doc in rel_set} |
| 26 | recall_sum += len(hits) / max(1, len(rel_set)) | 26 | recall_sum += len(hits) / max(1, len(rel_set)) |
| 27 | hit_sum += 1.0 if hits else 0.0 | 27 | hit_sum += 1.0 if hits else 0.0 |
| 28 | for rank, doc in enumerate(ranked, start=1): | 28 | for rank, doc in enumerate(ranked, start=1): |
| @@ -0,0 +1,142 @@ | |||
| 1 | +"""Regression tests for npu-embedding-retrieval/scripts/eval_retrieval.py.""" | ||
| 2 | + | ||
| 3 | +import importlib.util | ||
| 4 | +import json | ||
| 5 | +from pathlib import Path | ||
| 6 | +import subprocess | ||
| 7 | +import sys | ||
| 8 | +import tempfile | ||
| 9 | +import unittest | ||
| 10 | + | ||
| 11 | +SCRIPT_PATH = Path(__file__).resolve().parent.parent / "scripts" / "eval_retrieval.py" | ||
| 12 | + | ||
| 13 | + | ||
| 14 | +def _load_module(): | ||
| 15 | + spec = importlib.util.spec_from_file_location("eval_retrieval", SCRIPT_PATH) | ||
| 16 | + module = importlib.util.module_from_spec(spec) | ||
| 17 | + assert spec.loader is not None | ||
| 18 | + spec.loader.exec_module(module) | ||
| 19 | + return module | ||
| 20 | + | ||
| 21 | + | ||
| 22 | +class TestEvalRetrieval(unittest.TestCase): | ||
| 23 | + """Verify Recall@k deduplication and existing retrieval metrics.""" | ||
| 24 | + | ||
| 25 | + @classmethod | ||
| 26 | + def setUpClass(cls): | ||
| 27 | + cls.mod = _load_module() | ||
| 28 | + | ||
| 29 | + def test_no_duplicates_regression_baseline(self): | ||
| 30 | + qrels = {"q1": ["d1", "d2"], "q2": ["d3"]} | ||
| 31 | + runs = {"q1": ["x", "d1", "d2"], "q2": ["d3", "y"]} | ||
| 32 | + res = self.mod.evaluate(qrels, runs, 2) | ||
| 33 | + self.assertEqual( | ||
| 34 | + res, | ||
| 35 | + { | ||
| 36 | + "k": 2, | ||
| 37 | + "num_queries": 2, | ||
| 38 | + "recall@k": 0.75, | ||
| 39 | + "mrr": 0.75, | ||
| 40 | + "hit_rate@k": 1.0, | ||
| 41 | + }, | ||
| 42 | + ) | ||
| 43 | + | ||
| 44 | + def test_duplicate_hits_counted_once(self): | ||
| 45 | + qrels = {"q": ["d"]} | ||
| 46 | + runs = {"q": ["d", "d"]} | ||
| 47 | + res = self.mod.evaluate(qrels, runs, 2) | ||
| 48 | + self.assertEqual(res["recall@k"], 1.0) | ||
| 49 | + self.assertEqual(res["mrr"], 1.0) | ||
| 50 | + self.assertEqual(res["hit_rate@k"], 1.0) | ||
| 51 | + | ||
| 52 | + def test_duplicate_preserves_rank_without_backfill(self): | ||
| 53 | + qrels = {"q": ["d1", "d2"]} | ||
| 54 | + runs = {"q": ["d1", "d1", "d2"]} | ||
| 55 | + res = self.mod.evaluate(qrels, runs, 2) | ||
| 56 | + self.assertEqual(res["recall@k"], 0.5) | ||
| 57 | + self.assertEqual(res["mrr"], 1.0) | ||
| 58 | + self.assertEqual(res["hit_rate@k"], 1.0) | ||
| 59 | + | ||
| 60 | + mrr_res = self.mod.evaluate({"q": ["d1"]}, {"q": ["x", "d1", "d1"]}, 3) | ||
| 61 | + self.assertEqual(mrr_res["recall@k"], 1.0) | ||
| 62 | + self.assertEqual(mrr_res["mrr"], 0.5) | ||
| 63 | + | ||
| 64 | + def test_partial_hits_denominator(self): | ||
| 65 | + qrels = {"q": ["d1", "d2", "d3"]} | ||
| 66 | + runs = {"q": ["d1", "d1", "d2", "x"]} | ||
| 67 | + res = self.mod.evaluate(qrels, runs, 4) | ||
| 68 | + self.assertEqual(res["recall@k"], 0.6667) | ||
| 69 | + self.assertEqual(res["mrr"], 1.0) | ||
| 70 | + self.assertEqual(res["hit_rate@k"], 1.0) | ||
| 71 | + | ||
| 72 | + def test_empty_and_missing_rankings(self): | ||
| 73 | + qrels = {"q_missing": ["d1"], "q_empty": ["d2"], "q_none": ["d3"]} | ||
| 74 | + runs = {"q_empty": [], "q_none": None} | ||
| 75 | + res = self.mod.evaluate(qrels, runs, 5) | ||
| 76 | + self.assertEqual( | ||
| 77 | + res, | ||
| 78 | + { | ||
| 79 | + "k": 5, | ||
| 80 | + "num_queries": 3, | ||
| 81 | + "recall@k": 0.0, | ||
| 82 | + "mrr": 0.0, | ||
| 83 | + "hit_rate@k": 0.0, | ||
| 84 | + }, | ||
| 85 | + ) | ||
| 86 | + empty_qrels = self.mod.evaluate({}, {}, 5) | ||
| 87 | + self.assertEqual( | ||
| 88 | + empty_qrels, | ||
| 89 | + { | ||
| 90 | + "k": 5, | ||
| 91 | + "num_queries": 1, | ||
| 92 | + "recall@k": 0.0, | ||
| 93 | + "mrr": 0.0, | ||
| 94 | + "hit_rate@k": 0.0, | ||
| 95 | + }, | ||
| 96 | + ) | ||
| 97 | + | ||
| 98 | + def test_cli_end_to_end_and_missing_file_exit_code(self): | ||
| 99 | + with tempfile.TemporaryDirectory() as tmp: | ||
| 100 | + tmp_dir = Path(tmp) | ||
| 101 | + qrels_path = tmp_dir / "qrels.json" | ||
| 102 | + runs_path = tmp_dir / "runs.json" | ||
| 103 | + qrels_path.write_text(json.dumps({"q": ["d"]}), encoding="utf-8") | ||
| 104 | + runs_path.write_text(json.dumps({"q": ["d", "d"]}), encoding="utf-8") | ||
| 105 | + | ||
| 106 | + ok = subprocess.run( | ||
| 107 | + [ | ||
| 108 | + sys.executable, | ||
| 109 | + str(SCRIPT_PATH), | ||
| 110 | + "--qrels", | ||
| 111 | + str(qrels_path), | ||
| 112 | + "--runs", | ||
| 113 | + str(runs_path), | ||
| 114 | + "--k", | ||
| 115 | + "2", | ||
| 116 | + ], | ||
| 117 | + capture_output=True, | ||
| 118 | + text=True, | ||
| 119 | + check=False, | ||
| 120 | + ) | ||
| 121 | + self.assertEqual(ok.returncode, 0, msg=ok.stderr) | ||
| 122 | + self.assertIn("'recall@k': 1.0", ok.stdout) | ||
| 123 | + | ||
| 124 | + missing = subprocess.run( | ||
| 125 | + [ | ||
| 126 | + sys.executable, | ||
| 127 | + str(SCRIPT_PATH), | ||
| 128 | + "--qrels", | ||
| 129 | + str(tmp_dir / "nonexistent.json"), | ||
| 130 | + "--runs", | ||
| 131 | + str(runs_path), | ||
| 132 | + ], | ||
| 133 | + capture_output=True, | ||
| 134 | + text=True, | ||
| 135 | + check=False, | ||
| 136 | + ) | ||
| 137 | + self.assertEqual(missing.returncode, 1) | ||
| 138 | + self.assertIn("[error]", missing.stdout) | ||
| 139 | + | ||
| 140 | + | ||
| 141 | +if __name__ == "__main__": | ||
| 142 | + unittest.main() | ||