-
Notifications
You must be signed in to change notification settings - Fork 0
/
metrics.py
31 lines (25 loc) · 982 Bytes
/
metrics.py
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
import torch
def cal_recall(label, predict, ks):
label = torch.cat(label, dim=0).unsqueeze(-1)
predict = torch.cat(predict, dim=0).cpu()
max_ks = max(ks)
_, topk_predict = torch.topk(predict, k=max_ks, dim=-1)
hit = label == topk_predict
recall = [hit[:, :ks[i]].sum().item()/label.size()[0] for i in range(len(ks))]
return recall
def cal_ndcg(label, predict, ks):
label = torch.cat(label, dim=0).unsqueeze(-1)
predict = torch.cat(predict, dim=0).cpu()
max_ks = max(ks)
_, topk_predict = torch.topk(predict, k=max_ks, dim=-1)
hit = (label == topk_predict).int()
ndcg = []
for k in ks:
max_dcg = dcg(torch.tensor([1] + [0] * (k-1)))
predict_dcg = dcg(hit[:, :k])
ndcg.append((predict_dcg/max_dcg).mean().item())
return ndcg
def dcg(hit):
log2 = torch.log2(torch.arange(1, hit.size()[-1] + 1) + 1).unsqueeze(0)
rel = (hit/log2).sum(dim=-1)
return rel