所以我想为我正在处理的推荐问题计算K个样本的命中率。对于那些不知道K点命中率的人来说,这意味着真正的样本类别是否在模型预测的前K个类别中。我想在批处理级别上执行此操作。
那么如果我有下面的代码
import torch
import torch.nn as nn
import numpy as np
# 5 samples of 5 dimensions
yhat = torch.tensor([[4, 9, 7, 4, 0],
[8, 1, 3, 1, 0],
[9, 8, 4, 4, 8],
[0, 9, 4, 7, 8],
[8, 8, 0, 1, 4]])
# I get the top 3 classes of each sample recommendation
values, indices = torch.topk(a, 3)
# print(indices)
# tensor([[1, 2, 0],
# [0, 2, 1],
# [0, 1, 4],
# [1, 4, 3],
# [1, 0, 4]])
# True sample classes
ytrue = torch.tensor([2], #hits on top 3
[5], #Doesnt hit on top 3
[4], #hits on top 3
[0], #Doesnt hit on top 3
[1]) #hits on top 3
我想在这里计算前3的命中率(HR3)。HR3==1表示我所有的预测都包含真实的样本类,而0表示没有。
对于给定的示例,我击中了3/5。结果应为3/5
pytorch最有效的方法是什么?
尝试:
(indices == ytrue.reshape(-1,1)).any(1)
输出:
tensor([ True, False, True, False, True])
如果你想要比率,将张量转换为float和mean:
(indices == ytrue.reshape(-1,1)).any(1).float().mean()
# tensor(0.6000)