介绍

pip install matplotlib

1.导入相关库

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

2.定义 LeNet-5 网络结构

# reshape输入为28*28的图像
class Reshape(nn.Module):
    def forward(self, x):
        return x.view(-1, 1, 28, 28)


# 定义网络
net = nn.Sequential(Reshape(), nn.Conv2d(1, 6, kernel_size=5, padding=2), nn.Sigmoid(),
                    nn.AvgPool2d(kernel_size=2, stride=2),
                    nn.Conv2d(6, 16, kernel_size=5), nn.Sigmoid(),
                    nn.AvgPool2d(kernel_size=2, stride=2),
                    nn.Flatten(),
                    nn.Linear(16*5*5, 120), nn.Sigmoid(),
                    nn.Linear(120, 84), nn.Sigmoid(),
                    nn.Linear(84, 10))

3.下载并配置数据集和加载器

# 下载并配置数据集
train_dataset = datasets.MNIST(root='./dataset', train=True,
                               transform=transforms.ToTensor(), download=True)
test_dataset = datasets.MNIST(root='./dataset', train=False,
                              transform=transforms.ToTensor(), download=True)

# 配置数据加载器
batch_size = 64
train_loader = DataLoader(dataset=train_dataset,
                          batch_size=batch_size, shuffle=True)
test_loader = DataLoader(dataset=test_dataset,
                         batch_size=batch_size, shuffle=True)

4.定义损失函数和优化器

# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(net.parameters())

5.定义训练函数并训练和保存模型

def train(epochs):
    # 训练模型
    for epoch in range(epochs):
        for i, (images, labels) in enumerate(train_loader):
            outputs = net(images)
            loss = criterion(outputs, labels)
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()

            if i % 50 == 0:
                print(
                    f'Epoch: {epoch + 1}, Step: {i + 1}, Loss: {loss.item():.4f}')

        correct = 0
        total = 0
        for images, labels in test_loader:
            outputs = net(images)
            _, predicted = torch.max(outputs.data, 1)
            total += labels.size(0)
            correct += (predicted == labels).sum().item()

        print(f'Accuracy: {correct / total * 100:.2f}%')

    # 保存模型
    torch.save(net.state_dict(),
               f"./model/LeNet_Epoch{epochs}_Accuracy{correct / total * 100:.2f}%.pth") 


train(epochs=5)

6.可视化展示

def show_predict():
    # 预测结果图像可视化
    loader = DataLoader(dataset=test_dataset, batch_size=1, shuffle=True)
    plt.figure(figsize=(8, 8))
    for i in range(9):
        (images, labels) = next(iter(loader))
        outputs = net(images)
        _, predicted = torch.max(outputs.data, 1)
        title = f"Predicted: {predicted[0]}, True: {labels[0]}"
        plt.subplot(3, 3, i + 1)
        plt.imshow(images[0].squeeze(), cmap="gray")
        plt.title(title)
        plt.xticks([])
        plt.yticks([])
    plt.show()

show_predict()

7.预测图


8.加载现有模型(可选)

# 加载保存的模型
net.load_state_dict(torch.load("./model/LeNet_Epoch10_Accuracy98.42%.pth"))
11-04 06:42