pytorch: torch.max() 使用与理解

在使用 pytorch 进行训练时,会使用使用到改行代码:
predict = torch.max(outputs.data, 1)[1]
其中 output 为模型的输出,该函数主要用来求 tensor 的最大值。

每次看到都不太理解 torch.max() 的使用,为了下次看到或者写道时不会忘记,特意详细了解其用法。
torch.max(input:tensor, dim:index)
该函数有两个输入:
inputs: tensor,第一个参数为一个张量
dim: index,第二个参数为一个整数[-2-1],dim=0表示计算每列的最大值,dim=1表示每行的最大值
如:

import torch

output = torch.tensor([[1, 23], [3, 45]])
predict = torch.max(output, dim=0)
print(predict)
predict = torch.max(output, dim=1)
print(predict)

输出为:
torch.return_types.max(
values=tensor([3, 4, 5]),
indices=tensor([1, 1, 1]))

torch.return_types.max(
values=tensor([3, 5]),
indices=tensor([2, 2]))

输出返回最大值以及对应的索引值。因此,predict = torch.max(outputs.data, 1)[1] 是计算模型中每个类别的最大值并返回其索引值,即该类别的标签值。

  • 18
    点赞
  • 71
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值