何为Top-1,Top-5

众所周知,神经网络预测类别是以概率的形式给出。

像这样:用一个CNN来预测图像6个类别:香蕉,苹果,大鸭梨,草莓,葡萄,大西瓜。

假设一个batch中有两条数据,batch_1和batch_2,(也就是有两张图像)。它们的label值为2(大鸭梨)和5(大西瓜)。

预测的概率值如下表所示

类别香蕉苹果大鸭梨草莓葡萄大西瓜label
batch_10.050.20.30.20.20.152
batch_20.030.10.30.070.40.15

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.)

 

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值