通道维度上的Pytorch最大池化

jjjwad0x  于 2023-06-29  发布在  其他
关注(0)|答案(3)|浏览(108)

我试图用Pytorch构建一个cnn,在maxpooling中遇到了困难。我参加了斯坦福大学大学举办的CS231 N。正如我回忆的那样,maxpooling可以用作维度推导步骤,例如,我有这个(1,20,height,width)输入到max_pool2d(假设我的batch_size为1)。如果我使用(1,1)kernel,我想得到这样的输出:(1,1,高度,宽度),这意味着内核应该在通道尺寸上滑动。然而,在检查了pytorch文档之后,它说内核在高度和宽度上滑动。感谢Pytorch论坛上的@ImgPrcSng,他告诉我使用max_pool3d,结果运行得很好。但是在conv 2d层的输出和max_pool3d层的输入之间仍然存在整形操作。所以很难聚合成一个nn.Sequential,所以我想知道有没有另一种方法来做到这一点?

gorkyyrv

gorkyyrv1#

像这样的工作吗?

from torch.nn import MaxPool1d
import torch.nn.functional as F

class ChannelPool(MaxPool1d):
    def forward(self, input):
        n, c, w, h = input.size()
        input = input.view(n, c, w * h).permute(0, 2, 1)
        pooled = F.max_pool1d(
            input,
            self.kernel_size,
            self.stride,
            self.padding,
            self.dilation,
            self.ceil_mode,
            self.return_indices,
        )
        _, _, c = pooled.size()
        pooled = pooled.permute(0, 2, 1)
        return pooled.view(n, c, w, h)

或者,使用einops

from torch.nn import MaxPool1d
import torch.nn.functional as F
from einops import rearrange

class ChannelPool(MaxPool1d):
    def forward(self, input):
        n, c, w, h = input.size()
        pool = lambda x: F.max_pool1d(
            x,
            self.kernel_size,
            self.stride,
            self.padding,
            self.dilation,
            self.ceil_mode,
            self.return_indices,
        )
        return rearrange(
            pool(rearrange(input, "n c w h -> n (w h) c")),
            "n (w h) c -> n c w h",
            n=n,
            w=w,
            h=h,
        )
omvjsjqw

omvjsjqw2#

要在所有通道上的每个坐标中最大化池,只需使用来自EINOP的layer

from einops.layers.torch import Reduce

max_pooling_layer = Reduce('b c h w -> b 1 h w', 'max')

层可以在您的模型中作为任何其他 Torch 模块使用

oxcyiej7

oxcyiej73#

我不知道为什么其他的答案都这么复杂。在整个通道维度上的最大池化以获得仅具有1个通道声音的输出,相当于在该维度上取最大值:

torch.amax(left_images, dim=1, keepdim=True)

相关问题