简单手动实现pytorch中的MaxPooling层

简单手动实现pytorch中的MaxPooling层

本来想去看一下pytorch中的MaxPooling层的源码,结果没有找到具体过程,于是自己实现了一下,代码如下。

import torch
import torch.nn as nn


class MyMaxPool2D(nn.Module):
    def __init__(self, kernel_size=(2, 2), stride=2):
        super(MyMaxPool2D, self).__init__()
        self.stride = stride
        self.kernel_size = kernel_size
        self.w_height = kernel_size[0]
        self.w_width = kernel_size[1]


    def forward(self, x):
        in_height = x.size(0)
        in_width = x.size(1)

        out_height = int((in_height - self.w_height) / self.stride) + 1
        out_width = int((in_width - self.w_width) / self.stride) + 1

        out = torch.zeros((out_height, out_width))

        for i in range(out_height):
            for j in range(out_width):
                start_i = i * self.stride
                start_j = j * self.stride
                end_i = start_i + self.w_height
                end_j = start_j + self.w_width
                out[i, j] = torch.max(x[start_i: end_i, start_j: end_j])
        return out



if __name__ == "__main__":
    # myMaxPool2d
    print("="*10 + "MyMaxPool2D" + "="*10)
    x = torch.randn((6,8), requires_grad=True)
    mypool = MyMaxPool2D()
    y = mypool(x)
    c = torch.mean(y)
    c.backward()

    print(x.size(), x.dtype)
    print(y.size())
    print(x.grad)

    # nn.MaxPool2d
    print("=" * 10 + "nn.MaxPool2d" + "=" * 10)
    x2 = x.detach().view(1,1,6,8)
    x2.requires_grad=True
    mypool = nn.MaxPool2d((2,2),2)
    y2 = mypool(x2)
    c2 = torch.mean(y2)
    c2.backward()

    print(x2.size(), x2.dtype)
    print(y2.size())
    print(x2.grad)

刚开始还担心是否需要自己实现MaxPooling反向传播过程,后来发现pytorch的自动求导cover了torch.max()函数的反向求导功能,所以就不用自己实现了。

输出结果:

MyMaxPool2D
torch.Size([6, 8]) torch.float32
torch.Size([3, 4])
tensor([[0.0833, 0.0000, 0.0000, 0.0833, 0.0000, 0.0000, 0.0000, 0.0833],
[0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0833, 0.0000, 0.0000],
[0.0000, 0.0833, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
[0.0000, 0.0000, 0.0833, 0.0000, 0.0000, 0.0833, 0.0833, 0.0000],
[0.0000, 0.0000, 0.0833, 0.0000, 0.0000, 0.0000, 0.0833, 0.0000],
[0.0833, 0.0000, 0.0000, 0.0000, 0.0000, 0.0833, 0.0000, 0.0000]])
nn.MaxPool2d
torch.Size([1, 1, 6, 8]) torch.float32
torch.Size([1, 1, 3, 4])
tensor([[[[0.0833, 0.0000, 0.0000, 0.0833, 0.0000, 0.0000, 0.0000, 0.0833],
[0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0833, 0.0000, 0.0000],
[0.0000, 0.0833, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
[0.0000, 0.0000, 0.0833, 0.0000, 0.0000, 0.0833, 0.0833, 0.0000],
[0.0000, 0.0000, 0.0833, 0.0000, 0.0000, 0.0000, 0.0833, 0.0000],
[0.0833, 0.0000, 0.0000, 0.0000, 0.0000, 0.0833, 0.0000, 0.0000]]]])

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值