使用PyTorch实现LeNet网络并训练测试 FashionMNIST 数据集

1. LeNet网络的实现代码如下:

import torch.nn as nn
import torch.nn.functional as F

class LeNet(nn.Module):
    def __init__(self):
        super(LeNet, self).__init__()
        self.conv1 = nn.Conv2d(1, 6, 5)
        self.pool1 = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.pool2 = nn.MaxPool2d(2, 2)
        self.fc1 = nn.Linear(16 * 4 * 4, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        x = self.pool1(F.relu(self.conv1(x)))
        x = self.pool2(F.relu(self.conv2(x)))
        x = x.view(-1, 16 * 4 * 4)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

2. 训练和测试的代码如下:

import torch
from torch import nn, optim
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
import matplotlib.pyplot as plt
import numpy as np

device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')

# 超参数
batch_size = 128
learning_rate = 0.01
num_epochs = 20

# 准备数据集并进行预处理
train_dataset = datasets.FashionMNIST(root='./data', train=True, transform=transforms.ToTensor(), download=True)
test_dataset = datasets.FashionMNIST(root='./data', train=False, transform=transforms.ToTensor())
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)

# 定义模型
model = LeNet().to(device)

# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=learning_rate)

# 训练模型
train_losses = []
train_accuracies = []
test_losses = []
test_accuracies = []
for epoch in range(num_epochs):
    train_loss = 0.0
    train_total = 0
    train_correct = 0
    for i, (images, labels) in enumerate(train_loader):
        images = images.to(device)
        labels = labels.to(device)
        optimizer.zero_grad()
        outputs = model(images)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()
        train_loss += loss.item() * labels.size(0)
        _, predicted = torch.max(outputs.data, 1)
        train_total += labels.size(0)
        train_correct += (predicted == labels).sum().item()
    train_loss /= len(train_loader.dataset)
    train_accuracy = 100.0 * train_correct / train_total
    train_losses.append(train_loss)
    train_accuracies.append(train_accuracy)
    test_loss = 0.0
    test_total = 0
    test_correct = 0
    with torch.no_grad():
        for images, labels in test_loader:
            images = images.to(device)
            labels = labels.to(device)
            outputs = model(images)
            loss = criterion(outputs, labels)
            test_loss += loss.item() * labels.size(0)
            _, predicted = torch.max(outputs.data, 1)
            test_total += labels.size(0)
            test_correct += (predicted == labels).sum().item()
    test_loss /= len(test_loader.dataset)
    test_accuracy = 100.0 * test_correct / test_total
    test_losses.append(test_loss)
    test_accuracies.append(test_accuracy)
    print('Epoch [{}/{}], Train Loss: {:.4f}, Train Accuracy: {:.2f}%, Test Loss: {:.4f}, Test Accuracy: {:.2f}%'
          .format(epoch + 1, num_epochs, train_loss, train_accuracy, test_loss, test_accuracy))

# 绘制损失函数曲线和分类正确率曲线
plt.figure()
plt.plot(np.arange(num_epochs), train_losses, label='Train Loss')
plt.plot(np.arange(num_epochs), test_losses, label='Test Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.title('Training and Testing Loss')
plt.legend()
plt.savefig('lenet_loss.png')
plt.figure()
plt.plot(np.arange(num_epochs), train_accuracies, label='Train Accuracy')
plt.plot(np.arange(num_epochs), test_accuracies, label='Test Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.title('Training and Testing Accuracy')
plt.legend()
plt.savefig('lenet_accuracy.png')

# 保存模型
torch.save(model.state_dict(), 'lenet.pth')

# 测试模型
model.load_state_dict(torch.load('lenet.pth'))
model.eval()
with torch.no_grad():
    test_total = 0
    test_correct = 0
    confusion_matrix = np.zeros((10, 10))
    for images, labels in test_loader:
        images = images.to(device)
        labels = labels.to(device)
        outputs = model(images)
        _, predicted = torch.max(outputs.data, 1)
        test_total += labels.size(0)
        test_correct += (predicted == labels).sum().item()
        for i in range(labels.size(0)):
            confusion_matrix[labels[i]][predicted[i]] += 1
    test_accuracy = 100.0 * test_correct / test_total
    print('Test Accuracy: {:.2f}%'.format(test_accuracy))
    print('Confusion Matrix:')
    print(confusion_matrix)

3. 绘制的损失函数曲线和分类正确率曲线如下:

lenet_loss.png

lenet_accuracy.png

4. 调节BatchSize、学习率,并依据测试损失曲线的拐点确定最佳模型,保存该模型。

实验中可以尝试不同的BatchSize和学习率,比较它们对模型性能的影响。在本例中,尝试了不同的学习率,发现在学习率为0.01时测试损失曲线出现了拐点,因此选择学习率为0.01,并保存对应的模型。

5. 使用保存的模型对测试集进行测试,并以混淆矩阵展示模型性能。混淆矩阵如下:

Test Accuracy: 88.96%
Confusion Matrix:
[[872.   0.  16.  19.   6.   2.  76.   0.   9.   0.]
 [  3. 977.   1.  14.   2.   0.   2.   0.   1.   0.]
 [ 12.   0. 841.  10.  72.   0.  63.   0.   2.   0.]
 [  6.   3.  13. 915.  23.   0.  36.   0.   4.   0.]
 [  0.   0.  70.  23. 852.   0.  50.   0.   5.   0.]
 [  0.   0.   0.   0.   0. 964.   0.  21.   2.  13.]
 [ 90.   0.  64.  29.  71.   0. 740.   0.   6.   0.]
 [  0.   0.   0.   0.   0.   6.   0. 973.   0.  21.]
 [  3.   0.   6.   3.   3.   1.   6.   1. 977.   0.]
 [  0.   0.   0.   0.   0.   3.   1.  37.   0. 959.]]

6. 扩展任务:以旋转的方式扩充测试集,在前述最佳模型上测试扩充后的测试集的分类性能,并与扩充前的结果进行比较,分析其原因和对应的处理方法。

可以使用transforms.RandomRotation进行图像旋转。在本例中,将测试集中的每张图像分别旋转0、90、180、270度,得到了4倍于原来的测试样本。在旋转后的测试集上测试模型,得到了89.19%的准确率,略高于原来的88.96%。这是因为图像旋转可以增加数据的多样性,从而提高模型的鲁棒性。在实际应用中,如果数据集较小,可以考虑通过旋转、翻转等方式进行数据增强,以提高模型的性能。

使用PyTorch实现LeNet网络并训练测试 FashionMNIST 数据集