torch.max()语法、用法以及例子

torch.max()用法

torch.max(input, dim, keepdim=False, out=None) -> (Tensor, LongTensor)

按维度dim 返回最大值以及最大值的索引。

1.torch..max(input)

此时返回一个input的最大值。

例子:
import torch
logist = torch.tensor([[-0.1661,  -0.3044]])
a = torch.max(logist) 
print('------a value: {}'.format(a))

输出:
------a value: -0.16609999537467957

2.torch..max(input, dim)

dim = 0 表示按列求最大值,并返回最大值的索引
dim = 1 表示按行求最大值,并返回最大值的索引

例子:

import torch
logist = torch.tensor([[-0.1661,  -0.3044]])
a = torch.max(logist, 1) # a 中包含两个内容:现在最大值,然后是最大值的索引
print('------a value: {}'.format(a))
predict = torch.max(logist, 1)[0] # 返回一个tensor
print('-----predict [0] : {}'.format(predict))
predict = torch.max(logist, 1)[1].cpu().numpy() # 返回一个数组
print('-----predict [1]: {}'.format(predict))
输出:
------a value: torch.return_types.max(
values=tensor([-0.1661]),
indices=tensor([0]))
-----predict [0] : tensor([-0.1661])
-----predict [1]: [0]

注意:当tensor是N*M,其中N和M大于1,返回的最大值是一个数组,索引是该维度下最大值的索引。比如0,1,2,这种数值。

例子:

import torch
logist = torch.tensor([[-0.1661,  -0.3044],[-0.2661,  0.4044]])
a = torch.max(logist, 1) # 按行取最大值,a 中包含两个内容:现在最大值,然后是最大值的索引
print('------a value: {}'.format(a))
predict = torch.max(logist, 1)[0] # 返回一个tensor
print('-----predict [0] : {}'.format(predict))
predict = torch.max(logist, 1)[1].cpu().numpy() # 返回一个数组
print('-----predict [1]: {}'.format(predict))
输出:
------a value: torch.return_types.max(
values=tensor([-0.1661,  0.4044]),
indices=tensor([0, 1]))
-----predict [0] : tensor([-0.1661,  0.4044])
-----predict [1]: [0 1]

记住:

torch.max()[0], 只返回最大值的每个数

troch.max()[1], 只返回最大值的每个索引

torch.max()[1].data 只返回variable中的数据部分(去掉Variable containing:)

torch.max()[1].data.numpy() 把数据转化成numpy ndarry

torch.max()[1].data.numpy().squeeze() 把数据条目中维度为1 的删除掉

torch.max(tensor1,tensor2) element-wise 比较tensor1 和tensor2 中的元素,返回较大的那个值

参考:https://blog.csdn.net/weixin_43635550/article/details/100534904

 

 

 

 

  • 13
    点赞
  • 49
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值