Task 01
替换平均池化(AvgPool)为最大池化(MaxPool),并输出结果。
代码
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
# --------------------- 1. 定义 LeNet 网络 ---------------------
class LeNet(nn.Module):
def __init__(self, use_maxpool=True):
super(LeNet, self).__init__()
# 卷积层
self.conv1 = nn.Conv2d(1, 6, kernel_size=5, padding=2) # 28x28 -> 28x28
self.conv2 = nn.Conv2d(6, 16, kernel_size=5) # 14x14 -> 10x10
# 选择池化方式(默认使用 MaxPool)
self.pool = nn.MaxPool2d(kernel_size=2, stride=2) if use_maxpool else nn.AvgPool2d(kernel_size=2, stride=2)
# 全连接层
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = self.pool(torch.relu(self.conv1(x))) # 第一层卷积 + ReLU + 池化
x = self.pool(torch.relu(self.conv2(x))) # 第二层卷积 + ReLU + 池化
x = torch.flatten(x, 1) # 展平
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
x = self.fc3(x) # 最终输出 10 维
return x
# --------------------- 2. 载入 MNIST 数据集 ---------------------
mnist_data_path = "D:/603/pythonProject/data/MNIST/"
transform = transforms.Compose([
transforms.Grayscale(),
transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,)) # 归一化到 [-1, 1]
])
# 加载训练和测试数据
trainset = torchvision.datasets.MNIST(root=mnist_data_path, train=True, download=False, transform=transform)
testset = torchvision.datasets.MNIST(root=mnist_data_path, train=False, download=False, transform=transform)
train_loader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)
test_loader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=False)
# --------------------- 3. 训练模型 ---------------------
def train_model(model, train_loader, epochs=5, learning_rate=0.001):
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
for epoch in range(epochs):
model.train()
running_loss = 0.0
for images, labels in train_loader:
images, labels = images.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
print(f"Epoch {epoch + 1}, Loss: {running_loss / len(train_loader):.4f}")
# --------------------- 4. 评估模型 ---------------------
def evaluate_model(model, test_loader):
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
model.eval()
correct, total = 0, 0
with torch.no_grad():
for images, labels in test_loader:
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print(f"Test Accuracy: {100 * correct / total:.2f}%")
# --------------------- 5. 运行实验 ---------------------
# 训练并评估使用平均池化的 LeNet
print("\nTraining LeNet with Average Pooling...")
lenet_avg = LeNet(use_maxpool=False)
train_model(lenet_avg, train_loader, epochs=5, learning_rate=0.001)
print("\nEvaluating LeNet with Average Pooling...")
evaluate_model(lenet_avg, test_loader)
# 训练并评估使用最大池化的 LeNet
print("\nTraining LeNet with Max Pooling...")
lenet_max = LeNet(use_maxpool=True)
train_model(lenet_max, train_loader, epochs=5, learning_rate=0.001)
print("\nEvaluating LeNet with Max Pooling...")
evaluate_model(lenet_max, test_loader)