众所周知,神经网络预测类别是以概率的形式给出。
像这样:用一个CNN来预测图像6个类别:香蕉,苹果,大鸭梨,草莓,葡萄,大西瓜。
假设一个batch中有两条数据,batch_1和batch_2,(也就是有两张图像)。它们的label值为2(大鸭梨)和5(大西瓜)。
预测的概率值如下表所示
类别 | 香蕉 | 苹果 | 大鸭梨 | 草莓 | 葡萄 | 大西瓜 | label |
batch_1 | 0.05 | 0.2 | 0.3 | 0.2 | 0.2 | 0.15 | 2 |
batch_2 | 0.03 | 0.1 | 0.3 | 0.07 | 0.4 | 0.1 | 5 |
Top-1 就是去每个batch中没组数据中的最大概率值的分类。可以通过函数torch.topk(input, k, dim=None, largest=True, sorted=True, *, out=None)函数来获得 。
经过torch.topk将返回两个值,分别为:values和 indices。
例如上面的那个例子,
top-1 value = [0.3,
0.4]
top-1 indices =[2,
4]
在计算准确率时,类别是对应的index值,所以讲top1 indices与label进行比较
[2,4] vs. [2,5] = [True,False] 准确率为1/2=0.5
同理,top-5 计算如下,准确率为100%。
top-5 value = [[0.3, 0.2, 0.2, 0.2, 0.15],
[0.4, 0.3, 0.1, 0.1, 0.07]]
top-5 indices =[[2, 1, 3, 4, 5],
[4, 2, 1, 5, 3]]
[[2, 1, 3, 4, 5], [[2],
VS. = [True True] = 2/2=1
[4, 2, 1, 5, 3]] [5]]
这也就是为什么top-5的值要大于top-1了,因为top-5的包容性更强。
以上就是我个人的理解,若有不正确的,请不吝赐教,大家一起进步!
以下是我找的一部分代码,具体出处不记得了。
import numpy as np
import torch
def cls_accuracy(output, target, topk=(1,)):
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
print("top-5 的 index:\n",pred)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].contiguous().view(-1).float().sum(0)
res.append(correct_k / batch_size)
return res
pre = np.random.randint(0,9,[4,10])
b = torch.from_numpy(pre)
print("预测的结果:\n",b)
label = np.random.randint(0,9,[4])
t = torch.from_numpy(label)
acc=cls_accuracy(b, t, topk=(1,5))
print("top-1 acc:",acc[0],"\ntop-5 acc:",acc[1])
预测的结果:
tensor([[6, 0, 2, 0, 1, 3, 1, 4, 1, 2],
[7, 2, 8, 8, 1, 2, 5, 2, 5, 2],
[4, 0, 5, 6, 6, 5, 8, 5, 1, 7],
[2, 8, 4, 6, 6, 5, 4, 5, 3, 5]], dtype=torch.int32)
top-5 的 index:
tensor([[0, 7, 5, 2, 9],
[2, 3, 0, 6, 8],
[6, 9, 3, 4, 2],
[1, 3, 4, 5, 7]])
top-1 acc: tensor(0.5000)
top-5 acc: tensor(1.)