File size: 4,178 Bytes
8510f62 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 | """Standard information-retrieval metrics for CCRB evaluation."""
from __future__ import annotations
import math
from collections.abc import Mapping, Sequence
def dcg_at_k(relevances: Sequence[int], k: int) -> float:
"""Compute Discounted Cumulative Gain at rank k using exponential gain (2^rel - 1)."""
if k <= 0:
raise ValueError(f"k must be positive, got {k}")
total = 0.0
for idx, rel in enumerate(relevances[:k], start=1):
if rel > 0:
total += ((2**rel) - 1) / math.log2(idx + 1)
return total
def ndcg_at_k(
ranked_doc_ids: Sequence[str],
qrels: Mapping[str, int],
k: int = 10,
) -> float:
"""Compute Normalized Discounted Cumulative Gain at rank k."""
if k <= 0:
raise ValueError(f"k must be positive, got {k}")
ideal_rels = sorted((rel for rel in qrels.values() if rel > 0), reverse=True)
idcg = dcg_at_k(ideal_rels, k)
if idcg == 0.0:
return 0.0
actual_rels = [qrels.get(doc_id, 0) for doc_id in ranked_doc_ids[:k]]
return dcg_at_k(actual_rels, k) / idcg
def mrr_at_k(
ranked_doc_ids: Sequence[str],
qrels: Mapping[str, int],
k: int = 10,
relevance_threshold: int = 1,
) -> float:
"""Compute Mean Reciprocal Rank contribution at rank k for a single query."""
if k <= 0:
raise ValueError(f"k must be positive, got {k}")
for idx, doc_id in enumerate(ranked_doc_ids[:k], start=1):
if qrels.get(doc_id, 0) >= relevance_threshold:
return 1.0 / idx
return 0.0
def recall_at_k(
ranked_doc_ids: Sequence[str],
qrels: Mapping[str, int],
k: int = 10,
relevance_threshold: int = 1,
) -> float:
"""Compute Recall at rank k for a single query."""
if k <= 0:
raise ValueError(f"k must be positive, got {k}")
relevant_docs = {
doc_id for doc_id, rel in qrels.items() if rel >= relevance_threshold
}
if not relevant_docs:
return 0.0
retrieved_relevant = sum(
1 for doc_id in ranked_doc_ids[:k] if doc_id in relevant_docs
)
return retrieved_relevant / len(relevant_docs)
def evaluate_track(
rankings: Mapping[str, Sequence[str]],
qrels: Mapping[str, Mapping[str, int]],
*,
relevance_threshold: int = 1,
) -> dict[str, float]:
"""Evaluate all standard CCRB metrics for a single track.
Queries present in `qrels` with no predictions in `rankings` receive 0.0.
Duplicate document IDs in a query's ranking are deduplicated preserving rank order.
"""
if not qrels:
raise ValueError("Cannot evaluate track with empty qrels")
totals = {
"ndcg@10": 0.0,
"mrr@10": 0.0,
"recall@10": 0.0,
"recall@100": 0.0,
}
num_queries = len(qrels)
for query_id, query_qrels in qrels.items():
raw_ranking = rankings.get(query_id, ())
deduped_ranking = list(dict.fromkeys(raw_ranking))
totals["ndcg@10"] += ndcg_at_k(deduped_ranking, query_qrels, k=10)
totals["mrr@10"] += mrr_at_k(
deduped_ranking,
query_qrels,
k=10,
relevance_threshold=relevance_threshold,
)
totals["recall@10"] += recall_at_k(
deduped_ranking,
query_qrels,
k=10,
relevance_threshold=relevance_threshold,
)
totals["recall@100"] += recall_at_k(
deduped_ranking,
query_qrels,
k=100,
relevance_threshold=relevance_threshold,
)
return {metric: round(score / num_queries, 6) for metric, score in totals.items()}
def macro_average_tracks(
track_scores: Mapping[str, Mapping[str, float]],
) -> dict[str, float]:
"""Compute equally weighted macro-average metrics across evaluated tracks."""
if not track_scores:
raise ValueError("Cannot aggregate empty track_scores")
metric_names = ("ndcg@10", "mrr@10", "recall@10", "recall@100")
num_tracks = len(track_scores)
return {
metric: round(
sum(scores[metric] for scores in track_scores.values()) / num_tracks,
6,
)
for metric in metric_names
}
|