以pytorch官网文档为学习教案
在卷积层stride默认为1,在池化层stride默认为kernal_size大小
对于Docs > torch.nn > MaxPool2d中的
ceil_mode – when True, will use ceil instead of floor to compute the output shape参数
当为True时,保留,为False舍去
根据其需要的input与output格式,进行reshape
import torch
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]])
input = torch.reshape(input, [-1, 1, 5, 5])
print(input.shape)
D:\anaconda\python.exe C:/Users/ASUS/Desktop/tudui/nn_maxpool.py
torch.Size([1, 1, 5, 5])
Process finished with exit code 0
import torch
from torch import nn
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) # 因为MaxPool2d要求long浮点输入
input = torch.reshape(input, [-1, 1, 5, 5])
print(input.shape)
class Lixinyu(nn.Module):
def __init__(self):
super(Lixinyu,self).__init__()
self.maxpool1 = MaxPool2d(kernel_size=3, ceil_mode=True)
def forward(self, input):
output = self.maxpool1(input)
return output
lixinyu = Lixinyu()
output = lixinyu(input)
print(output)
D:\anaconda\python.exe C:/Users/ASUS/Desktop/tudui/nn_maxpool.py
D:\anaconda\lib\site-packages\torch\nn\functional.py:780: UserWarning: Note that order of the arguments: ceil_mode and return_indices will changeto match the args list in nn.MaxPool2d in a future release.
warnings.warn("Note that order of the arguments: ceil_mode and return_indices will change"
torch.Size([1, 1, 5, 5])
tensor([[[[2., 3.],
[5., 1.]]]])
Process finished with exit code 0
最终
import torch
import torchvision
from torch import nn
from torch.nn import MaxPool2d
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
dataset = torchvision.datasets.CIFAR10("./dataset", train=False, transform=torchvision.transforms.ToTensor(), download=True)
dataloader = DataLoader(dataset, batch_size=64)
class Lixinyu(nn.Module):
def __init__(self):
super(Lixinyu, self).__init__()
self.maxpool1 = MaxPool2d(kernel_size=3, ceil_mode=True)
def forward(self, input):
output = self.maxpool1(input)
return output
lixinyu = Lixinyu()
writer = SummaryWriter("p19")
step = 0
for data in dataloader:
imgs, targets = data
writer.add_images("input", imgs, step)
output = lixinyu(imgs)
writer.add_images("output", output, step)
step += 1
writer.close()