|
| 1 | +"""GPU-friendly ranking metrics for leave-one-out evaluation. |
| 2 | +
|
| 3 | +All functions operate on PyTorch tensors and stay on the original device |
| 4 | +(CPU or CUDA), avoiding numpy/pandas roundtrips. Results are numerically |
| 5 | +identical to the corresponding RecTools metrics with default settings: |
| 6 | +
|
| 7 | +- :class:`rectools.metrics.HitRate` (k=K) |
| 8 | +- :class:`rectools.metrics.NDCG` (k=K, log_base=2, divide_by_achievable=False) |
| 9 | +- :class:`rectools.metrics.MRR` (k=K) |
| 10 | +
|
| 11 | +These functions assume **leave-one-out** evaluation: each user has exactly |
| 12 | +one ground-truth target item. |
| 13 | +""" |
| 14 | + |
| 15 | +import typing as tp |
| 16 | + |
| 17 | +import torch |
| 18 | + |
| 19 | + |
| 20 | +@torch.no_grad() |
| 21 | +def hitrate_at_k( |
| 22 | + topk_ids: torch.Tensor, |
| 23 | + targets: torch.Tensor, |
| 24 | +) -> torch.Tensor: |
| 25 | + """Hit Rate @ K (leave-one-out). |
| 26 | +
|
| 27 | + Parameters |
| 28 | + ---------- |
| 29 | + topk_ids : LongTensor (B, K) |
| 30 | + Top-K predicted item IDs per user. |
| 31 | + targets : LongTensor (B,) |
| 32 | + Ground-truth item ID per user. |
| 33 | +
|
| 34 | + Returns |
| 35 | + ------- |
| 36 | + Tensor (scalar) |
| 37 | + Mean hit rate across users. |
| 38 | + """ |
| 39 | + hits = (topk_ids == targets.unsqueeze(1)).any(dim=1) |
| 40 | + return hits.float().mean() |
| 41 | + |
| 42 | + |
| 43 | +@torch.no_grad() |
| 44 | +def ndcg_at_k( |
| 45 | + topk_ids: torch.Tensor, |
| 46 | + targets: torch.Tensor, |
| 47 | + log_base: int = 2, |
| 48 | +) -> torch.Tensor: |
| 49 | + """NDCG @ K (leave-one-out, divide_by_achievable=False). |
| 50 | +
|
| 51 | + Matches :class:`rectools.metrics.NDCG` with default parameters. |
| 52 | + IDCG is computed as the maximum possible DCG when all K positions are |
| 53 | + relevant (constant across users), which is the RecTools default. |
| 54 | +
|
| 55 | + Parameters |
| 56 | + ---------- |
| 57 | + topk_ids : LongTensor (B, K) |
| 58 | + Top-K predicted item IDs per user. |
| 59 | + targets : LongTensor (B,) |
| 60 | + Ground-truth item ID per user. |
| 61 | + log_base : int, default 2 |
| 62 | + Logarithm base for the discount factor. |
| 63 | +
|
| 64 | + Returns |
| 65 | + ------- |
| 66 | + Tensor (scalar) |
| 67 | + Mean NDCG across users. |
| 68 | + """ |
| 69 | + k = topk_ids.shape[1] |
| 70 | + hits = (topk_ids == targets.unsqueeze(1)).float() # (B, K) |
| 71 | + ranks = torch.arange(1, k + 1, device=topk_ids.device, dtype=torch.float) |
| 72 | + discounts = 1.0 / torch.log(ranks + 1) * (1.0 / _log(log_base)) |
| 73 | + dcg = (hits * discounts.unsqueeze(0)).sum(dim=1) # (B,) |
| 74 | + idcg = discounts.sum() |
| 75 | + return (dcg / idcg).mean() |
| 76 | + |
| 77 | + |
| 78 | +@torch.no_grad() |
| 79 | +def mrr_at_k( |
| 80 | + topk_ids: torch.Tensor, |
| 81 | + targets: torch.Tensor, |
| 82 | +) -> torch.Tensor: |
| 83 | + """MRR @ K (leave-one-out). |
| 84 | +
|
| 85 | + Parameters |
| 86 | + ---------- |
| 87 | + topk_ids : LongTensor (B, K) |
| 88 | + Top-K predicted item IDs per user. |
| 89 | + targets : LongTensor (B,) |
| 90 | + Ground-truth item ID per user. |
| 91 | +
|
| 92 | + Returns |
| 93 | + ------- |
| 94 | + Tensor (scalar) |
| 95 | + Mean reciprocal rank across users. |
| 96 | + """ |
| 97 | + hits = (topk_ids == targets.unsqueeze(1)) # (B, K) |
| 98 | + # For each user find the rank of the first hit (1-based), 0 if no hit |
| 99 | + has_hit = hits.any(dim=1) |
| 100 | + # argmax returns the first True index |
| 101 | + first_hit_rank = hits.float().argmax(dim=1) + 1 # (B,) |
| 102 | + rr = torch.zeros_like(first_hit_rank, dtype=torch.float) |
| 103 | + rr[has_hit] = 1.0 / first_hit_rank[has_hit].float() |
| 104 | + return rr.mean() |
| 105 | + |
| 106 | + |
| 107 | +@torch.no_grad() |
| 108 | +def compute_metrics( |
| 109 | + topk_ids: torch.Tensor, |
| 110 | + targets: torch.Tensor, |
| 111 | + ks: tp.Optional[tp.List[int]] = None, |
| 112 | + log_base: int = 2, |
| 113 | +) -> tp.Dict[str, float]: |
| 114 | + """Compute HR, NDCG, MRR at multiple K values. |
| 115 | +
|
| 116 | + Parameters |
| 117 | + ---------- |
| 118 | + topk_ids : LongTensor (B, K_max) |
| 119 | + Top-K_max predicted item IDs per user. |
| 120 | + targets : LongTensor (B,) |
| 121 | + Ground-truth item ID per user. |
| 122 | + ks : list of int, optional |
| 123 | + K values to evaluate. Defaults to ``[K_max]``. |
| 124 | + log_base : int, default 2 |
| 125 | + Logarithm base for NDCG discount. |
| 126 | +
|
| 127 | + Returns |
| 128 | + ------- |
| 129 | + dict |
| 130 | + Keys like ``"HR@10"``, ``"NDCG@10"``, ``"MRR@10"``. |
| 131 | + """ |
| 132 | + k_max = topk_ids.shape[1] |
| 133 | + if ks is None: |
| 134 | + ks = [k_max] |
| 135 | + results: tp.Dict[str, float] = {} |
| 136 | + for k in ks: |
| 137 | + if k > k_max: |
| 138 | + raise ValueError(f"k={k} exceeds topk_ids width {k_max}") |
| 139 | + top = topk_ids[:, :k] |
| 140 | + results[f"HR@{k}"] = hitrate_at_k(top, targets).item() |
| 141 | + results[f"NDCG@{k}"] = ndcg_at_k(top, targets, log_base=log_base).item() |
| 142 | + results[f"MRR@{k}"] = mrr_at_k(top, targets).item() |
| 143 | + return results |
| 144 | + |
| 145 | + |
| 146 | +def _log(base: int) -> float: |
| 147 | + """Natural log of base (cached constant).""" |
| 148 | + import math |
| 149 | + return math.log(base) |
0 commit comments