💻 PyTorch池化实现
import torch
import torch.nn as nn
maxpool = nn.MaxPool2d(
kernel_size=2,
stride=2,
padding=0
)
avgpool = nn.AvgPool2d(
kernel_size=2,
stride=2
)
x = torch.randn(1, 64, 56, 56)
out = maxpool(x)
print(out.shape)
pool_custom = nn.MaxPool2d(kernel_size=3, stride=1, padding=1)
🌟 全局池化与自适应池化
global_avg = nn.AdaptiveAvgPool2d((1, 1))
x = torch.randn(1, 512, 7, 7)
out = global_avg(x)
print(out.shape)
adaptive_pool = nn.AdaptiveAvgPool2d((1, 1))
adaptive_pool = nn.AdaptiveAvgPool2d((2, 2))
adaptive_pool = nn.AdaptiveAvgPool2d((7, 7))
x1 = torch.randn(1, 64, 28, 28)
x2 = torch.randn(1, 64, 32, 32)
adaptive = nn.AdaptiveAvgPool2d((7, 7))
print(adaptive(x1).shape)
print(adaptive(x2).shape)
🏗️ 池化层在网络中的应用
class SimpleCNN(nn.Module):
def __init__(self, num_classes=10):
super().__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 64, 3, padding=1),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.MaxPool2d(2),
nn.Conv2d(64, 128, 3, padding=1),
nn.BatchNorm2d(128),
nn.ReLU(),
nn.MaxPool2d(2),
nn.Conv2d(128, 256, 3, padding=1),
nn.BatchNorm2d(256),
nn.ReLU(),
nn.MaxPool2d(2),
)
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.classifier = nn.Linear(256, num_classes)
def forward(self, x):
x = self.features(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.classifier(x)
return x