pytorch【output.topk】用法

output是tensor类型数据,则topk是output的固有函数(pytorch里固有的)
用法

a=torch.randn((4,6))
print(a)
tensor([[ 0.7042,  0.2533,  1.1596, -0.7436,  0.5264,  0.2085],
        [ 0.2641,  0.9683,  0.4469, -1.9215, -0.7564,  1.1776],
        [ 1.0520, -1.6003, -0.8634,  1.7596, -0.8464,  0.7166],
        [-0.0492, -0.7746,  1.2592, -0.8273,  0.1266,  1.0450]])
maxk=max((1,3))
#用于取前k个最大的值——即top k
 _, pred=a.topk(maxk,1,True,True)
 #这里的pred指的是索引
print(_)
tensor([[1.1596, 0.7042, 0.5264],
        [1.1776, 0.9683, 0.4469],
        [1.7596, 1.0520, 0.7166],
        [1.2592, 1.0450, 0.1266]])
print(pred)
tensor([[2, 0, 4],
        [5, 1, 2],
        [3, 0, 5],
        [2, 5, 4]])
_, pred=a.topk(1,1,True,True)
print(_)
tensor([[1.1596],
        [1.1776],
        [1.7596],
        [1.2592]])
print(pred)
tensor([[2],
        [5],
        [3],
        [2]])

top-1就是只看概率最大的那个结果,是否预测正确,将其作为top-1的结果。
top-5就是看概率最大的前五个结果,只要里面包含了预测正确的结果,就算预测正确,将其作为top-5的结果

你可能感兴趣的:(pytorch,深度学习,人工智能)