Fix bugs in metrics
#21
by tytskiy - opened
46 unmodified lines474849505152505354555680 unmodified lines13713813913714014114214314414514614714814915015115215315415515615715815916016116216316416516614416716816917017117217314617417517617751 unmodified lines22923023120423246 unmodified lines num_positives = targets.lengths.to(torch.float32) num_positives[num_positives == 0] = torch.inf
# there was a bug: we divided by num_positives instead of max(num_positives, k) # this may have slightly affected the absolute metric values, # but as far as we can judge it didn't change the ranking of the models reported in the paper. values[k] = target_mask[:, :k].to(torch.float32).sum(dim=-1) / num_positives values[k] = target_mask[:, :k].to(torch.float32).sum(dim=-1) / torch.clamp(num_positives, max=k)
values[k] = torch.mean(values[k]).item()
80 unmodified lines def __call__( self, ranked: Ranked | None, targets: Targets, target_mask: torch.Tensor, ks: Iterable[int] ) -> dict[int, float]: actual_dcg = DCG()(ranked, targets, target_mask, ks)
# there was a bug: we computed (dcg_1 + ... + dcg_n) / (idcg_1 + ... + idcg_n) # instead of (1 / n) * (dcg_1 / idcg_1 + ... + dcg_n / idcg_n) # this may have affected the absolute metric values, # but as far as we can judge it didn't change the ranking of the models reported in the paper.
assert all(0 < k <= target_mask.shape[1] for k in ks)
def calc_dcg(target_mask: torch.Tensor) -> dict[int, torch.Tensor]: values = {}
discounts = 1.0 / torch.log2( torch.arange(2, target_mask.shape[1] + 2, device=target_mask.device, dtype=torch.float32) )
for k in ks: dcg_k = torch.sum(target_mask[:, :k] * discounts[:k], dim=1) values[k] = dcg_k return values
actual_dcg = calc_dcg(target_mask)
ideal_target_mask = ( torch.arange(target_mask.shape[1], device=targets.device)[None, :] < targets.lengths[:, None] ).to(torch.float32) assert target_mask.shape == ideal_target_mask.shape
ideal_dcg = DCG()(ranked, targets, ideal_target_mask, ks) ideal_dcg = calc_dcg(target_mask)
def divide(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: assert x.shape == y.shape assert x.shape[0] == target_mask.shape[0] return torch.where(y == 0, 0, x / y).mean()
ndcg_values = {k: (actual_dcg[k] / ideal_dcg[k] if ideal_dcg[k] != 0 else 0.0) for k in ks} ndcg_values = {k: divide(actual_dcg[k], ideal_dcg[k]).item() for k in ks}
return ndcg_values
51 unmodified lines for name, ks in grouped_metrics.items(): result[name] = REGISTERED_METRIC_FN[name](ranked, targets, target_mask, ks=ks)
return result return resultbenchmarks/yambda/evaluation/metrics.py → Fix bugs in metricsRenamed+33-5