import torch
from torch import nn
from d2l import torch as d2l
# 实现池化层的正向传播
def pool2d(x,pool_size,mode='max'):
# 获取窗口大小
p_h,p_w=pool_size
# 获取偏移量
y=torch.zeros((x.shape[0]-p_h+1,x.shape[1]-p_w+1))
for i in range(y.shape[0]):
for j in range(y.shape[1]):
if mode=='max':
y[i,j]=x[i:i+p_h,j:j+p_w].max()
elif mode=='avg':
y[i,j]=x[i:i+p_h,j:j+p_w].mean()
return y
X = torch.tensor([[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]])
pool2d(X, (2, 2))
pool2d(X,(2,2),'avg')
# 通道是1批量大小是1,4x4矩阵
x=torch.arange(16,dtype=torch.float32).reshape((1,1,4,4))
print(x)
# 深度学习框架中的步幅与池化窗口的大小相同,每次池化没有相同的部分
# 3x3的窗口
pool2d = nn.MaxPool2d(3)
pool2d(x)
# 填充步幅可以手动设定
pool2d = nn.MaxPool2d(3,padding=1,stride=2)
pool2d(x)
# 设定一个任意大小的矩形池化窗口,并分别设定填充和步幅的高度和宽度
pool2d = nn.MaxPool2d((2,3),padding=(1,1),stride=(2,3))
pool2d(x)
# 池化在每个输入通道上单独运算
x=torch.cat((x,x+1),1)
print(x)
pool2d = nn.MaxPool2d(3,padding=1,stride=2)
pool2d(x)
标签:池化层,nn,torch,shape,MaxPool2d,pytorch,池化,pool2d From: https://www.cnblogs.com/jinbb/p/17609397.html