nn.MaxPool1d

函数

class torch.nn.MaxPool1d(kernel_size, stride=None, padding=0, dilation=1, return_indices=False, ceil_mode=False)

参数

kernel_size(int or tuple) - max pooling的窗口大小

stride(int or tuple, optional) - max pooling的窗口移动的步长。默认值是kernel_size

padding(int or tuple, optional) - 输入的每一条边补充0的层数

dilation(int or tuple, optional) – 一个控制窗口中元素步幅的参数

return_indices - 如果等于True,会返回输出最大值的序号,对于上采样操作会有帮助

ceil_mode - 如果等于True,计算输出信号大小的时候,会使用向上取整,代替默认的向下取整的操作

例子

举个例子,构建一个卷积核大小为1x3,步长为2的池化

import torch
import torch.nn as nn
from torch.autograd import Variable

m = nn.MaxPool1d(3, stride=2)
input = Variable(torch.randn(2, 4, 5))
output = m(input)

print(input)
print(output)
tensor([[[ 1.0000, -0.2401, -1.1694,  0.3162,  0.5495],
         [-0.0668, -0.1455, -0.6538,  0.7396, -1.2040],
         [ 1.9750,  0.9449,  0.6117,  0.9990, -0.8750],
         [ 0.5644, -0.2105,  0.1103,  1.2369,  0.3041]],

        [[-0.6587,  0.5686, -0.4883,  1.4393,  2.0761],
         [ 0.7883,  0.9219,  3.0924,  0.0957,  0.3198],
         [ 1.3996,  0.7220,  0.8044,  1.4365, -0.9084],
         [ 0.8209,  0.6308,  1.7780, -0.2451, -0.7157]]])
  
 tensor([[[ 1.0000,  0.5495],
         [-0.0668,  0.7396],
         [ 1.9750,  0.9990],
         [ 0.5644,  1.2369]],

        [[ 0.5686,  2.0761],
         [ 3.0924,  3.0924],
         [ 1.3996,  1.4365],
         [ 1.7780,  1.7780]]])

计算过程

在这里插入图片描述
1x3的池化层首先在图中红色区域的3个数中,选出最大的数字1,然后移动2个步长,在图中绿色区域的3个数中选择处最大的数字0.549。接着下移1行,用同样的方式操作

nn.MaxPool2d

函数

class torch.nn.MaxPool2d(kernel_size, stride=None, padding=0, dilation=1, return_indices=False, ceil_mode=False)

参数

参数:

kernel_size(int or tuple) - max pooling的窗口大小

stride(int or tuple, optional) - max pooling的窗口移动的步长。默认值是kernel_size

padding(int or tuple, optional) - 输入的每一条边补充0的层数
dilation(int or tuple, optional) – 一个控制窗口中元素步幅的参数

return_indices - 如果等于True,会返回输出最大值的序号,对于上采样操作会有帮助

ceil_mode - 如果等于True,计算输出信号大小的时候,会使用向上取整,代替默认的向下取整的操作

例子

举个例子,构建一个卷积核大小为1x3,步长为2的池化层

import torch
import torch.nn as nn
from torch.autograd import Variable

m = nn.MaxPool2d(3, stride=2)
input = Variable(torch.randn(2, 4, 5))
output = m(input)

print(input)
print(output)

tensor([[[ 1.0000, -0.2401, -1.1694,  0.3162,  0.5495],
         [-0.0668, -0.1455, -0.6538,  0.7396, -1.2040],
         [ 1.9750,  0.9449,  0.6117,  0.9990, -0.8750],
         [ 0.5644, -0.2105,  0.1103,  1.2369,  0.3041]],

        [[-0.6587,  0.5686, -0.4883,  1.4393,  2.0761],
         [ 0.7883,  0.9219,  3.0924,  0.0957,  0.3198],
         [ 1.3996,  0.7220,  0.8044,  1.4365, -0.9084],
         [ 0.8209,  0.6308,  1.7780, -0.2451, -0.7157]]])
  
tensor([[[1.9750, 0.9990]],

        [[3.0924, 3.0924]]])

计算过程

在这里插入图片描述

3x3的池化层首先在图中红色区域的9个数中,选出最大的数字1.9750, 然后移动2个步长,在图中绿色区域的9个数中选择处最大的数字0.9990。接着下移2行,发现3x3的池化层超出边界,那就跳到下一个4x5的输入层,接着重复上一个4x5的输入层操作