Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion metrics/trec_eval/trec_eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def _info(self):
"q0": datasets.Sequence(datasets.Value("string")),
"docid": datasets.Sequence(datasets.Value("string")),
"rank": datasets.Sequence(datasets.Value("int64")),
"score": datasets.Sequence(datasets.Value("float")),
"score": datasets.Sequence(datasets.Value("float64")),
"system": datasets.Sequence(datasets.Value("string")),
},
"references": {
Expand All @@ -108,6 +108,9 @@ def _compute(self, references, predictions):

df_run = pd.DataFrame(predictions[0])
df_qrel = pd.DataFrame(references[0])
# TrecEval.get_ndcg assumes the run is already ranked. Use the same
# score order and document ID tie-break as its other TREC metrics.
df_run = df_run.sort_values(["query", "score", "docid"], ascending=[True, False, False])

trec_run = TrecRun()
trec_run.filename = "placeholder.file"
Expand Down
38 changes: 38 additions & 0 deletions tests/test_trec_run_scores.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
from pathlib import Path

import pytest

import evaluate


@pytest.fixture
def metric(tmp_path):
pytest.importorskip("trectools")
path = Path(__file__).resolve().parents[1] / "metrics" / "trec_eval"
return evaluate.load(str(path), cache_dir=str(tmp_path), keep_in_memory=True)


def score_two_documents(metric, negative_score, positive_score):
run = {
"query": [0, 0],
"q0": ["Q0", "Q0"],
"docid": ["z-negative", "a-positive"],
"rank": [2, 1],
"score": [negative_score, positive_score],
"system": ["test", "test"],
}
qrel = {"query": [0, 0], "q0": ["0", "0"], "docid": ["z-negative", "a-positive"], "rel": [0, 1]}
return metric.compute(predictions=[run], references=[qrel])


def test_trec_scores_ndcg_in_run_score_order(metric):
result = score_two_documents(metric, 0.1, 0.9)
assert result["NDCG@5"] == pytest.approx(1.0)
assert result["recip_rank"] == pytest.approx(1.0)


def test_trec_distinguishes_close_scores_and_preserves_exact_ties(metric):
near_tie = score_two_documents(metric, 0.5, 0.50000001)
tie = score_two_documents(metric, 0.5, 0.5)
assert near_tie["map"] == near_tie["recip_rank"] == pytest.approx(1.0)
assert tie["map"] == tie["recip_rank"] == pytest.approx(0.5)