目的:保留数据特征,减少数据量 一般常用的是nn.MaxPool2d ,来看看它的参数 参数 dilation(空洞卷积)的解释 ceil_mode的解释:如果=True,就要保留这六个数 咱们来实现一下!
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)
input = torch.reshape(input, (-1, 1, 5, 5))
print(input.shape)
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.maxpool1 = MaxPool2d(kernel_size=3, ceil_mode=True)
def forward(self, input):
output = self.maxpool1(input)
return output
model = Model()
output = model(input)
print(output)
输出结果为
D:\Anaconda3\envs\pytorch\python.exe D:/研究生/代码尝试/nn_maxpool.py
torch.Size([1, 1, 5, 5])
tensor([[[[2., 3.],
[5., 1.]]]])
进程已结束,退出代码为 0
以CIFAR数据集为例,来看看结果吧!
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())
dataloader = DataLoader(dataset, batch_size=64)
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.maxpool1 = MaxPool2d(kernel_size=3, ceil_mode=True)
def forward(self, input):
output = self.maxpool1(input)
return output
model = Model()
writer = SummaryWriter("logs_maxpool")
step = 0
for data in dataloader:
imgs, targets = data
writer.add_images("input", imgs, step)
output = model(imgs)
writer.add_images("output", output, step)
step = step + 1
writer.close()
输出 可以发现,经过maxpool层,图片变得更模糊了,但是都保留了一定特征,所以maxpool的作用为减小数据量的同时保留部分特征~
|