官方解释:
torch.
max
(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor)
Returns a namedtuple (values, indices)
where values
is the maximum value of each row of the input
tensor in the given dimension dim
. And indices
is the index location of each maximum value found (argmax).
If keepdim
is True
, the output tensors are of the same size as input
except in the dimension dim
where they are of size 1. Otherwise, dim
is squeezed (see torch.squeeze()), resulting in the output tensors having 1 fewer dimension than input
.
大意:在指定的维数取最大值,返回结果和序号。
对于输入为一或者二维的向量,很好理解。对于高维的向量a,shape为(2,3,4),torch.max(a,1) 代表的表示遍历i∈[0,1],j∈[0,3],取(i,:,j)这几个数的最大值,形成新的张量的size为(2,4),如果keepdim=True,则形成的张量为(2,1,4)。
torch.max(a,2),代表的表示遍历i∈[0,1],j∈[0,2],取(i,j,:)这几个数的最大值。
import torch
a = torch.randn(2, 3,4)
print(a)
c=torch.max(a,1)
d=torch.max(a,2)
print(c[0].shape)
print(c)
print(d[0].shape)
print(d)
tensor([[[ 0.8346, -0.6632, 1.0924, 2.3951],
[ 0.8407, 0.3949, -0.3020, -1.7022],
[ 2.7546, 0.5894, 1.9637, -1.0159]],
[[-1.3591, -0.8133, 0.4478, 0.1800],
[ 0.0949, -0.3733, 0.4843, -0.9781],
[ 0.0283, -0.9105, -1.2899, 2.9471]]])
torch.Size([2, 4])
torch.return_types.max(
values=tensor([[ 2.7546, 0.5894, 1.9637, 2.3951],
[ 0.0949, -0.3733, 0.4843, 2.9471]]),
indices=tensor([[2, 2, 2, 0],
[1, 1, 1, 2]]))
torch.Size([2, 3])
torch.return_types.max(
values=tensor([[2.3951, 0.8407, 2.7546],
[0.4478, 0.4843, 2.9471]]),
indices=tensor([[3, 0, 0],
[2, 2, 3]]))