python
复制代码
import torch
from torch import nn
# 最大汇聚层和平均汇聚层
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]])
print(pool2d(X, (2, 2)))
#(3 - 2 + 0 + 1) / 1 * (3 - 2 + 0 + 1) / 1
"""
tensor([[4., 5.],
[7., 8.]])
"""
print(pool2d(X, (2, 2), 'avg'))
"""
tensor([[2., 3.],
[5., 6.]])
"""
# 填充和步幅
X = torch.arange(16, dtype=torch.float32).reshape((1, 1, 4, 4))
#默认情况下,深度学习框架中的步幅与汇聚窗口的大小相同
#如果我们使用形状为(3, 3)的汇聚窗口,
#那么默认情况下,我们得到的步幅形状为(3, 3)。
pool2d = nn.MaxPool2d(3)
# (4 - 3 + 0 + 3) / 3 * (4 - 3 + 0 + 3) / 3
print(pool2d(X))
# 输入张量的大小是 4x4,而池化窗口是 3x3,
# 并且步幅也是 3,导致只能提取一个 3x3 的窗口
#tensor([[[[10.]]]])
# 手动设定填充和步幅
pool2d = nn.MaxPool2d(3, padding=1, stride=2)
# (4 - 3 + 2 + 2) / 2 * (4 - 3 + 2 + 2) / 2
print(pool2d(X))
"""
tensor([[[[ 5., 7.],
[13., 15.]]]])
"""
pool2d = nn.MaxPool2d((2, 3), padding=(0, 1), stride=(2, 3))
# (4 - 2 + 0 + 2) / 2 * (4 - 3 + 2 + 3) / 3
print(pool2d(X))
"""
tensor([[[[ 5., 7.],
[13., 15.]]]])
"""
# 多个通道
# torch.cat 函数用于在指定的维度上拼接张量
#构建具有2个通道的输入
X = torch.cat((X, X + 1), 1)
print(X)
print(X.shape)
"""
tensor([[[[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[12., 13., 14., 15.]],
[[ 1., 2., 3., 4.],
[ 5., 6., 7., 8.],
[ 9., 10., 11., 12.],
[13., 14., 15., 16.]]]])
torch.Size([1, 2, 4, 4])
"""
pool2d = nn.MaxPool2d(3, padding=1, stride=2)
# (4 - 3 + 2 + 2) / 2 * (4 - 3 + 2 + 2) / 2
# print(pool2d(X))
"""
tensor([[[[ 5., 7.],
[13., 15.]],
[[ 6., 8.],
[14., 16.]]]])
"""