1、需要安装Pytorch依赖
2、官方文档conv2d
3、图片需要CIFAR10数据集
用卷积核覆盖在原始数据上,选择原始数据中被卷积核覆盖的最大值
选择卷积核覆盖时的最大值,ceil_mode控制卷积核超出原始数据后是否进行保留
kernel_size
设置卷积核大小的属性
stride
和conv2d中的stride一样,是控制移动步幅的属性,这里注意,conv2d默认值是1,但是MaxPool2d默认值是卷积核大小
padding
设置原始数据周围填充的属性
dilation:
表明给原始数据之间添加0的属性
ceil_mode
控制当卷积核超过原始图像时,是否对max进行保留
代码:
import torch
import torchvision
from torch.nn import Module,MaxPool2d
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
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)
print("前",input.shape) # torch.Size([5, 5]),不满足输入的条件,需要进行格式转换
input = torch.reshape(input,(-1,1,5,5))
print("后",input.shape) # 后 torch.Size([1, 1, 5, 5]) 一个bach_size,
class ConNet(Module):
def __init__(self):
super(ConNet, self).__init__()
# 池化层使用,设置卷积核为3*3,超出的部分保留数据
self.maxpool = MaxPool2d(kernel_size=3,ceil_mode=True)
def forward(self,input):
output = self.maxpool(input)
return output
# 实例化对象
Work = ConNet()
# 神经网络调用
output = Work(input)
print(output)
代码:
import torch
import torchvision
from torch.nn import Module,MaxPool2d
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
class ConNet(Module):
def __init__(self):
super(ConNet, self).__init__()
# 池化层使用,设置卷积核为3*3,超出的部分保留数据
self.maxpool = MaxPool2d(kernel_size=3,ceil_mode=True)
def forward(self,input):
output = self.maxpool(input)
return output
# 实例化对象
Work = ConNet()
# CIFAR10数据使用
dataset = torchvision.datasets.CIFAR10("./datasetvision",train=False,download=False,transform=torchvision.transforms.ToTensor())
# 数据加载
dataloader = DataLoader(dataset,batch_size=64)
writer = SummaryWriter("logs_MaxPool")
step = 0
for data in dataloader:
imgs,target = data
writer.add_images("input",imgs,step)
output = Work(imgs)
writer.add_images("output",output,step)
step = step + 1
writer.close()
代码:
import torch
import torchvision
from torch.nn import Module,MaxPool2d,Conv2d
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
class ConNet(Module):
def __init__(self):
super(ConNet, self).__init__()
# 池化层使用,设置卷积核为3*3,超出的部分保留数据
self.maxpool = MaxPool2d(kernel_size=3,ceil_mode=True)
self.conv2d = Conv2d(in_channels=3,out_channels=3,kernel_size=3,stride=1,padding=0)
def forward(self,input):
output = self.conv2d(input)
output = self.maxpool(output)
return output
# 实例化对象
Work = ConNet()
# CIFAR10数据使用
dataset = torchvision.datasets.CIFAR10("./datasetvision",train=False,download=False,transform=torchvision.transforms.ToTensor())
# 数据加载
dataloader = DataLoader(dataset,batch_size=64)
writer = SummaryWriter("logs_MaxPoolAndConv2d")
step = 0
for data in dataloader:
imgs,target = data
writer.add_images("input",imgs,step)
output = Work(imgs)
writer.add_images("output",output,step)
step = step + 1
writer.close()