• pytorch初学笔记(十):神经网络基本结构之最大池化的使用


    目录

    一、最大池化:下采样

    1.1 参数介绍 

    1.2 公式

    二、最大池化的作用和目的

    三、代码实战

    3.1 题目要求

    3.2 池化的具体实现

    3.2.1 步骤

    3.2.2 报错及其原因 

    3.2.3 ceil_mode不同运行的结果不同

    3.2.4 完整代码

    3.3 tensorboard可视化


    一、最大池化:下采样

    官方文档:torch.nn — PyTorch 1.13 documentation

    1.1 参数介绍 

    Parameters:

    • kernel_size 池化核 (Union[intTuple[intint]]) – the size of the window to take a max over

    • stride (Union[intTuple[intint]]) – the stride of the window. Default value is kernel_size

    • padding (Union[intTuple[intint]]) – implicit zero padding to be added on both sides

    • dilation (Union[intTuple[intint]]) – a parameter that controls the stride of elements in the window

    • return_indices (bool) – if True, will return the max indices along with the outputs. Useful for torch.nn.MaxUnpool2d later

    • ceil_mode (bool) – when True, will use ceil instead of floor to compute the output shape,是否对结果进行保留,默认为FALSE

    注意: 

    1. stride的默认大小为池化核的大小 

    2. dilation:空洞卷积,如右图,进行卷积操作时会隔n个取一个。

     

      

    3. ceil_mode:ceil为向上取整,floor为向下取整。

    • ceil_mode=True,结果进行保留;
    • ceil_mode=False,结果不进行保留

    1.2 公式

    输入的input要求为四维或者三维,需要输入通道数以及长和宽。

            因此当我们自定义输入一个input矩阵时,需要再使用torch.reshape方法将其转变成(N, C, H, W)的维度。

     

    二、最大池化的作用和目的

    作用:最大限度的保留图片特征,同时减少数据量。加速训练速度。

    三、代码实战

    3.1 题目要求

    输入tensor矩阵为5*5,如下图所示,池化核为大小为3*3,经过池化后根据ceil_mode的不同应输出下图所示的两个矩阵,输出如下的采样结果。

     

    3.2 池化的具体实现

    3.2.1 步骤

    1. 输入tensor型变量input
    2. 按照池化函数所需的input尺寸reshape输入的大小: 
      input = torch.reshape(input, (-1,1, 5, 5))
    3. 自定义神经网络,完成池化操作 
    4. 实例化神经网络,输出结果

    3.2.2 报错及其原因 

    1. import torch
    2. from torch.nn import MaxPool2d
    3. #输入的矩阵
    4. input = torch.tensor([
    5. [1,2,0,3,1],
    6. [0,1,2,3,1],
    7. [1,2,1,0,0],
    8. [5,2,3,1,1],
    9. [2,1,0,1,1]
    10. ])
    11. input = torch.reshape(input,(1,5,5))
    12. print(input.shape)
    13. class Maweiyi(torch.nn.Module):
    14. def __init__(self):
    15. super(Maweiyi, self).__init__()
    16. # 设置池化
    17. self.maxpool1 = MaxPool2d(kernel_size=3,ceil_mode=False)
    18. def forward(self,input):
    19. output = self.maxpool1(input)
    20. return output
    21. maweiyi = Maweiyi()
    22. output = maweiyi(input)
    23. print(output)

    会出现如下报错:无法实现long型的数据。

    解决:需要修改input的类型,设置tensor的dtype=float32 。

    1. #输入的矩阵
    2. input = torch.tensor([
    3. [1,2,0,3,1],
    4. [0,1,2,3,1],
    5. [1,2,1,0,0],
    6. [5,2,3,1,1],
    7. [2,1,0,1,1]
    8. ],dtype=torch.float32)

     修改过后即可成功运行。

    3.2.3 ceil_mode不同运行的结果不同

    1. ceil_mode = True,保留最大采样过程中的所有结果,运行出的tensor大小为4*4

    self.maxpool1 = MaxPool2d(kernel_size=3,ceil_mode=True)

     

    2. ceil_mode = False,不保留最大采样过程中的所有结果,运行出的tensor大小为1*1

    self.maxpool1 = MaxPool2d(kernel_size=3,ceil_mode=False)

    3.2.4 完整代码

    1. import torch
    2. from torch.nn import MaxPool2d
    3. #输入的矩阵
    4. input = torch.tensor([
    5. [1,2,0,3,1],
    6. [0,1,2,3,1],
    7. [1,2,1,0,0],
    8. [5,2,3,1,1],
    9. [2,1,0,1,1]
    10. ],dtype=torch.float32)
    11. input = torch.reshape(input,(1,5,5))
    12. print(input.shape)
    13. class Maweiyi(torch.nn.Module):
    14. def __init__(self):
    15. super(Maweiyi, self).__init__()
    16. # 设置池化
    17. self.maxpool1 = MaxPool2d(kernel_size=3,ceil_mode=True)
    18. def forward(self,input):
    19. output = self.maxpool1(input)
    20. return output
    21. maweiyi = Maweiyi()
    22. output = maweiyi(input)
    23. print(output)

     

    3.3 tensorboard可视化

    1. import torch
    2. import torchvision.datasets
    3. from torch.nn import MaxPool2d
    4. from torch.utils.data import DataLoader
    5. dataset = torchvision.datasets.CIFAR10(root=".\CIFAR10",train=False,transform=torchvision.transforms.ToTensor(),download=True)
    6. dataloader = DataLoader(dataset,batch_size=64)
    7. from torch.utils.tensorboard import SummaryWriter
    8. input = torch.tensor([
    9. [1, 2, 0, 3, 1],
    10. [0, 1, 2, 3, 1],
    11. [1, 2, 1, 0, 0],
    12. [5, 2, 3, 1, 1],
    13. [2, 1, 0, 1, 1]
    14. ], dtype=torch.float32)
    15. input = torch.reshape(input, (-1,1, 5, 5))
    16. class Maweiyi(torch.nn.Module):
    17. def __init__(self):
    18. super(Maweiyi, self).__init__()
    19. self.maxPool1 = MaxPool2d(kernel_size=3,ceil_mode=True)
    20. def forward(self, input):
    21. output = self.maxPool1(input)
    22. return output
    23. writer = SummaryWriter("logs")
    24. step = 0
    25. maweiyi = Maweiyi()
    26. for data in dataloader:
    27. imgs,labels=data
    28. writer.add_images("inputs",imgs,step)
    29. output = maweiyi(imgs)
    30. writer.add_images("output",output,step)
    31. step+=1
    32. writer.close()

    输出如下所示:

    可以看到经过最大池化之后图片变为了马赛克形式,不太清晰,但是大体能保留原图像的特征。 

  • 相关阅读:
    Java高级之反射
    LeetCode-1710. 卡车上的最大单元数【自定义排序,贪心】
    明御安全网关任意文件上传漏洞复现
    什么是自动化测试,一文吃透自动化测试【实战总结/建议收藏】
    P2 B+树索引
    从零开始学docker(四)-安装mysql及主从配置(一)
    Java EE 用户删除和修改功能
    板凳---------unix网络编程卷1:第二章传输层:TCP、UDP 和 SCTP
    UVA 107 The Cat in the Hat
    CentOS 安装HTTP代理服务器 Squid
  • 原文地址:https://blog.csdn.net/weixin_45662399/article/details/127969936