1.Pooling Layers讲解:
最大池化有时也被称为下采样,对应的有上采样。注意ceil_mode参数的使用
2.代码实战:
import torch
from torch import nn
from torch.nn import MaxPool2dinput=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 Tudui(nn.Module):def __init__(self):super(Tudui,self).__init__()self.maxpool1=MaxPool2d(kernel_size=3,ceil_mode=True)def forward(self,input):output=self.maxpool1(input)return outputtudui=Tudui()
output=tudui(input)
print(output)
最大池化无法在长整型的数据上执行。生成tensor时可以使用dtype参数改变其数据类型,比如从长整型变为浮点型。
最大池化的作用:保留输入数据的特征并减小数据的规模。
import torch
import torchvision
from torch import nn
from torch.nn import MaxPool2d
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriterdataset = torchvision.datasets.CIFAR10("./data", train=False,transform=torchvision.transforms.ToTensor(), download=True)
dataloader = DataLoader(dataset, batch_size=64)class Tudui(nn.Module):def __init__(self):super(Tudui, self).__init__()self.maxpool1 = MaxPool2d(kernel_size=3, ceil_mode=True)def forward(self, input):output = self.maxpool1(input)return outputtudui = Tudui()writer = SummaryWriter("logs_maxpool")
step = 0for data in dataloader:imgs, targets = datawriter.add_images("input", imgs, step)output = tudui(imgs)writer.add_images("output",output, step)step = step + 1writer.close()