使用torch.max函数计算一批特征图中每个通道的最大值

一、函数介绍

torch.max(input, dim, keepdim=False) 函数返回一个张量中所有元素的最大值。具体参数解释如下:

  • input (Tensor) – the input tensor.(输入张量)

  • dim (int) – the dimension to reduce.(在哪个维度上求张量的最大值)

  • keepdim (bool) – whether the output tensor has retained or not. Default: False.(是否保持输出结果的维度与输入张量的维度一样,默认为False)

二、代码实例

1.在只有Input参数的情况下,torch.tensor(Input)返回该张量中所有元素的最大值。

import torch
a = torch.tensor([[1,2,3],[4,5,6]])
print(torch.max(a))
b = torch.Tensor([[[[  1,   2,   3],
                    [  4,   8,   6],
                    [  7,   5,   9]],

                   [[ 10,  11,  18],
                    [ 13,  14,  15],
                    [ 16,  17,  12]]],


                  [[[ 70,  20,  10],
                    [ 40,  50,  60],
                    [ 10,  80,  90]],

                   [[ 70,  170,  90],
                    [100, 110, 120],
                    [160, 80, 180]]]])
print(torch.max(b))

在这里插入图片描述

2.在指定某个维度dim,且keepdim参数为True的情况下,torch.max()函数仅对该维度下的数据进行最大值求解,且求解结果的维度与输入张量的维度保持一致。如下所示,张量a是一个4维张量,由于keepdim参数为True,因此torch.max的结果也是4维,若keepdim参数为False,则torch.max的结果就会变成3维。

import torch
a = torch.Tensor([[[[  1,   2,   3],
                    [  4,   8,   6],
                    [  7,   5,   9]],

                   [[ 10,  11,  18],
                    [ 13,  14,  15],
                    [ 16,  17,  12]]],


                  [[[ 70,  20,  10],
                    [ 40,  50,  60],
                    [ 10,  80,  90]],

                   [[ 70,  170,  90],
                    [100, 110, 120],
                    [160, 80, 180]]]])
print(a.shape) # torch.Size([2, 2, 3, 3])
print()

b = torch.max(a,dim=2,keepdim=True)[0] 
# 这里torch.max()返回的是最大值及最大值在指定维度上的索引
# 因此,如果我们只是想获取最大值的话,就在torch.max()后面加个[0]
print(b)
print(b.shape) # torch.Size([2, 2, 1, 3])
print()

b = torch.max(b,dim=3,keepdim=True)[0]
print(b)
print(b.shape) # torch.Size([2, 2, 1, 1])

在这里插入图片描述

如果你仔细看最后这个例子,就会发现,张量a其实可以看作一批图像的特征图,而经过两次torch.max后,就可以得到这一批图像的特征图中每个通道的最大值。如果我们想得到一批特征图中每个通道的最大值,从而进行一些操作(比如特征图的归一化),那么就可以这么做。

当你跌入谷底时,只要不放弃,怎么走,都会是上坡路。共勉!

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

信小海

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值