在pytorch中有两种方式torch.nn.MaxPool2d和torch.nn.functional.max_pool2d,具体区别见【Pytorch】由torch.nn.MaxPool2d和torch.nn.functional.max_pool2d理解类模块与函数之间的差别
1、定义输入
input = torch.tensor([[1, 2, 0, 3, 1],
[0, 1, 2, 3, 1],
[1, 2, 1, 0, 0],
[5, 2, 3, 1, 1],
[2, 1, 0, 1, 1]], dtype=torch.float32)
2、reshape输入
# [ batch_size, channels, height, width ]
input = torch.reshape(input, (-1, 1, 5, 5))
3、MaxPool2d最大池化
maxpool1 = MaxPool2d(kernel_size=2)
output = maxpool1(input)
4、输出
print(output)
代码:
import torch
from torch.nn import MaxPool2d
input = torch.tensor([[1, 2, 0, 3, 1],
[0, 1, 2, 3, 1],
[1, 2, 1, 0, 0],
[5, 2, 3, 1, 1],
[2, 1, 0, 1, 1]], dtype=torch.float32)
input = torch.reshape(input, (-1, 1, 5, 5))
maxpool1 = MaxPool2d(kernel_size=2)
output = maxpool1(input)
print(output)