一、用法
torch.nn.MaxPool2d
torch.nn.MaxPool2d(kernel_size, stride=None, padding=0, dilation=1, return_indices=False, ceil_mode=False)
- kernel_size:池化窗口的大小,可以是整数或元组。
- stride:步幅,默认为与 kernel_size 相同,决定窗口移动的距离。
- padding:每个边缘的填充大小,默认为0。
- dilation:控制池化窗口元素之间的间隔,默认是1。
- return_indices:如果为 True,返回最大值的索引(默认值为 True)。
- ceil_mode:如果为 False ,则当kernel 超过二维 tensor 时,不保留值(默认值为 False)。
二、代码举例1
import torch
import torchvision
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=float)
# maxpool 的 input 需要是四维
input = torch.reshape(input,(1,1,5,5))
class Mary(nn.Module):
def __init__(self):
super(Mary,self).__init__()
self.maxpool1 = MaxPool2d(kernel_size=3,ceil_mode=True)
def forward(self,x):
x = self.maxpool1(x)
return x
Yorelee = Mary()
output = Yorelee(input)
print(output)
输出:
tensor([[[[2., 3.],
[5., 1.]]]], dtype=torch.float64)
三、代码举例2
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("datasets",False,torchvision.transforms.ToTensor(),download=True)
dataloader = DataLoader(dataset,64)
class Mary(nn.Module):
def __init__(self):
super(Mary,self).__init__()
self.maxpool1 = MaxPool2d(kernel_size=3,ceil_mode=True)
def forward(self,x):
x = self.maxpool1(x)
return x
Yorelee = Mary()
writer = SummaryWriter("logs")
step = 0
for data in dataloader:
img,target = data
writer.add_images("input",img,step)
output = Yorelee(img)
writer.add_images("output",output,step)
step += 1
writer.close()
输出: