Download evaluation/metrics.py from continuum-oss/ccrb: direct link, hf CLI and curl.
- Browser
- Download file 4.18 kB
-
https://huggingface.co/datasets/continuum-oss/ccrb/resolve/main/evaluation/metrics.py
- Command line
-
hf download hf://datasets/continuum-oss/ccrb/evaluation/metrics.py
-
curl -L -o metrics.py https://huggingface.co/datasets/continuum-oss/ccrb/resolve/main/evaluation/metrics.py
4.18 kB
| """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 | |
| } | |