torch.max()函数 ==> 返回该维度的最大值以及该维度最大值对应的索引

本文介绍了PyTorch中torch.max()函数的基础和深度用法。基础用法显示如何返回一个张量的最大值,而深度用法则展示了如何按维度返回最大值及其索引。通过实例解释了torch.max(a, 0)和torch.max(a, 1)分别如何返回列和行的最大值及索引。这对于理解和操作张量在神经网络中的最大值计算至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天在学习TTSR的过程总遇到了一行代码,我发现max()函数竟然可以返回两个值,于是我决定重新学习一下这个函数

R_lv3_star, R_lv3_star_arg = torch.max(R_lv3, dim=1) #[N, H*W]  hi


 1、基础用法:

首先是 torch.max()的基础用法,输入一个张量,返回一个确定的最大值

torch.max(input) → Tensor

Example:

>>> a = torch.randn(1, 3)
>>> a
tensor([[ 0.6763,  0.7445, -2.2369]])
>>> torch.max(a)
tensor(0.7445)

 2、深度用法:

torch.max(inputdimkeepdim=False*out=None)

按维度dim 返回最大值,并且返回索引。

Parameters

  • input (Tensor) – the input tensor.

  • dim (int) – the dimension to reduce.

  • keepdim (bool) – whether the output tensor has dim retained or not. Default: False.

Keyword Arguments

out (tupleoptional) – the result tuple of two output tensors (max, max_indices),返回的最大值和索引各是一个tensor,分别表示该维度的最大值,以及该维度最大值的索引,一起构成元组(Tensor, LongTensor)

Example:

torch.max(a,0)返回每一列中最大值的那个元素,且返回索引(返回最大元素在这一列的行索引)。返回的最大值和索引各是一个tensor,一起构成元组(Tensor, LongTensor)

a = torch.randn(4, 4)
print(a)
print(torch.max(a,0))


tensor([[ 0.7439,  2.2739, -2.7576, -0.0676],
        [-0.7755, -0.6696,  0.3009, -1.4939],
        [-0.9244,  2.7325,  1.7982,  1.2904],
        [-0.9091, -0.1857, -1.3392, -1.2928]])
torch.return_types.max(
values=tensor([0.7439, 2.7325, 1.7982, 1.2904]),
indices=tensor([0, 2, 2, 2]))

torch.max(a,1)返回每一行中最大值的那个元素,且返回其索引(返回最大元素在这一行的列索引)

>>> a = torch.randn(4, 4)
>>> a
tensor([[-1.2360, -0.2942, -0.1222,  0.8475],
        [ 1.1949, -1.1127, -2.2379, -0.6702],
        [ 1.5717, -0.9207,  0.1297, -1.8768],
        [-0.6172,  1.0036, -0.6060, -0.2432]])
>>> torch.max(a, 1)
torch.return_types.max(values=tensor([0.8475, 1.1949, 1.5717, 1.0036]), indices=tensor([3, 0, 0, 1]))

Pytorch笔记torch.max() - 知乎

torch.max — PyTorch 1.10 documentation

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Pengsen Ma

太谢谢了

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值