Pytorch最大值最小值函数:torch.max()、torch.min()

torch.max()函数原型:

torch.max(input, dim, keepdim=False, *, out=None)

input:输入的Tensor

dim:将要在哪一个维度上进行比较

keepdim:是否保留维度信息,默认False。为True时,返回值将增加一个与dim相同的维度

        当只传入input时,则在整个input中寻找最大值,只返回最大值,不返回索引。

input = torch.tensor([[6, 2, 7], [8, 1, 3], [4, 5, 9]])
print(input)
values = torch.max(input)
print(values)

tensor([[6, 2, 7],
        [8, 1, 3],
        [4, 5, 9]])
tensor(9)

        当传入dim时,将返回dim对应维度上的最大值与对应的dim维度的索引。若input为一个二维的Tensor,那么dim=0时将在列上寻找最大值,并返回对应行的索引;dim=1时将在行上寻找最大值,并返回对应列的索引。

# dim=0 在列上寻找最大值 返回对应行的索引
input = torch.tensor([[6, 2, 7], [8, 1, 3], [4, 5, 9]])
print(input)
values, indices = torch.max(input, dim=0)
print(values)
print(indices)

output:
tensor([[6, 2, 7],
        [8, 1, 3],
        [4, 5, 9]])
tensor([8, 5, 9])
tensor([1, 2, 2])
# dim=1 在行上寻找最大值 返回对应列的索引
input = torch.tensor([[6, 2, 7], [8, 1, 3], [4, 5, 9]])
print(input)
values, indices = torch.max(input, dim=1)
print(values)
print(indices)

output:
tensor([[6, 2, 7],
        [8, 1, 3],
        [4, 5, 9]])
tensor([7, 8, 9])
tensor([2, 0, 2])

        当传入keepdim时,则会保留维度的信息。以input为二维的Tensor举例。若dim=0,keepdim=True,将返回每列上的最大值,与对应行的索引,值与索引的格式保留了列的维度信息。可以看到当keepdim=False时,返回的值与索引的shape为3;keepdim=True时,返回的值与索引的shape为[1, 3],列的维度信息被保留下来。

# dim=0 keepdim=True 返回值保留列维度信息
input = torch.tensor([[6, 2, 7], [8, 1, 3], [4, 5, 9]])
print(input)
values, indices = torch.max(input, dim=0, keepdim=True)
print(values)
print(indices)

output:
tensor([[6, 2, 7],
        [8, 1, 3],
        [4, 5, 9]])
tensor([[8, 5, 9]])
tensor([[1, 2, 2]])
# dim=1 keepdim=True 返回值保留了行维度信息
input = torch.tensor([[6, 2, 7], [8, 1, 3], [4, 5, 9]])
print(input)
values, indices = torch.max(input, dim=1, keepdim=True)
print(values)
print(indices)

output:
tensor([[6, 2, 7],
        [8, 1, 3],
        [4, 5, 9]])
tensor([[7],
        [8],
        [9]])
tensor([[2],
        [0],
        [2]])

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值