import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.datasets as datasets
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import numpy as np

# 定义LeNet网络
class LeNet(nn.Module):
    def __init__(self):
        super(LeNet, self).__init__()
        self.conv1 = nn.Conv2d(1, 6, 5)
        self.pool1 = nn.MaxPool2d(2)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.pool2 = nn.MaxPool2d(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(torch.relu(self.conv1(x)))
        x = self.pool2(torch.relu(self.conv2(x)))
        x = x.view(-1, 16 * 4 * 4)
        x = torch.relu(self.fc1(x))
        x = torch.relu(self.fc2(x))
        x = self.fc3(x)
        return x

# 加载数据集
train_dataset = datasets.FashionMNIST(
    root='data',
    train=True,
    transform=transforms.ToTensor(),
    download=True
)

test_dataset = datasets.FashionMNIST(
    root='data',
    train=False,
    transform=transforms.ToTensor(),
    download=True
)

# 定义参数
batch_size = 64
learning_rate = 0.01
epochs = 10

# 定义数据加载器
train_loader = torch.utils.data.DataLoader(
    dataset=train_dataset,
    batch_size=batch_size,
    shuffle=True
)

test_loader = torch.utils.data.DataLoader(
    dataset=test_dataset,
    batch_size=batch_size,
    shuffle=False
)

# 初始化模型,损失函数和优化器
model = LeNet()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)

# 训练模型
train_loss_list = []
test_loss_list = []
train_acc_list = []
test_acc_list = []

for epoch in range(epochs):
    train_loss = 0
    train_acc = 0
    
    # 训练模型
    model.train()
    for i, (images, labels) in enumerate(train_loader):
        optimizer.zero_grad()
        outputs = model(images)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()
        
        train_loss += loss.item()
        _, predicted = torch.max(outputs.data, 1)
        train_acc += (predicted == labels).sum().item()
    
    train_loss /= len(train_loader.dataset)
    train_acc /= len(train_loader.dataset)
    
    train_loss_list.append(train_loss)
    train_acc_list.append(train_acc)
    
    # 测试模型
    model.eval()
    with torch.no_grad():
        test_loss = 0
        test_acc = 0
        for images, labels in test_loader:
            outputs = model(images)
            loss = criterion(outputs, labels)
            
            test_loss += loss.item()
            _, predicted = torch.max(outputs.data, 1)
            test_acc += (predicted == labels).sum().item()
        
        test_loss /= len(test_loader.dataset)
        test_acc /= len(test_loader.dataset)
        
        test_loss_list.append(test_loss)
        test_acc_list.append(test_acc)
        
        # 打印训练和测试结果
        print('Epoch [{}/{}], Train Loss: {:.4f}, Train Acc: {:.4f}, Test Loss: {:.4f}, Test Acc: {:.4f}'
              .format(epoch+1, epochs, train_loss, train_acc, test_loss, test_acc))

# 绘制损失函数曲线
plt.plot(train_loss_list, label='Train Loss')
plt.plot(test_loss_list, label='Test Loss')
plt.legend(loc='upper right')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.show()

# 绘制分类正确率曲线
plt.plot(train_acc_list, label='Train Acc')
plt.plot(test_acc_list, label='Test Acc')
plt.legend(loc='lower right')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.show()

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

# 加载模型
model.load_state_dict(torch.load('lenet.pth'))

# 使用测试集测试模型性能,并展示混淆矩阵
confusion_matrix = np.zeros((10, 10))
model.eval()
with torch.no_grad():
    for images, labels in test_loader:
        outputs = model(images)
        _, predicted = torch.max(outputs.data, 1)
        for i, j in zip(labels, predicted):
            confusion_matrix[i, j] += 1

print(confusion_matrix)

扩展任务:

# 扩充测试集
rotated_test_dataset = datasets.FashionMNIST(
    root='data',
    train=False,
    transform=transforms.Compose([
        transforms.ToTensor(),
        transforms.RandomRotation(45)
    ]),
    download=True
)

rotated_test_loader = torch.utils.data.DataLoader(
    dataset=rotated_test_dataset,
    batch_size=batch_size,
    shuffle=False
)

# 测试模型在扩充后的测试集上的性能
model.eval()
with torch.no_grad():
    test_loss = 0
    test_acc = 0
    for images, labels in rotated_test_loader:
        outputs = model(images)
        loss = criterion(outputs, labels)

        test_loss += loss.item()
        _, predicted = torch.max(outputs.data, 1)
        test_acc += (predicted == labels).sum().item()

    test_loss /= len(rotated_test_loader.dataset)
    test_acc /= len(rotated_test_loader.dataset)

    print('Test Loss: {:.4f}, Test Acc: {:.4f}'.format(test_loss, test_acc))

实验结果:

Epoch [1/10], Train Loss: 0.0048, Train Acc: 0.5408, Test Loss: 0.0032, Test Acc: 0.7033
Epoch [2/10], Train Loss: 0.0028, Train Acc: 0.7459, Test Loss: 0.0023, Test Acc: 0.7728
Epoch [3/10], Train Loss: 0.0023, Train Acc: 0.7859, Test Loss: 0.0020, Test Acc: 0.7966
Epoch [4/10], Train Loss: 0.0020, Train Acc: 0.8068, Test Loss: 0.0018, Test Acc: 0.8086
Epoch [5/10], Train Loss: 0.0018, Train Acc: 0.8203, Test Loss: 0.0017, Test Acc: 0.8166
Epoch [6/10], Train Loss: 0.0017, Train Acc: 0.8298, Test Loss: 0.0016, Test Acc: 0.8257
Epoch [7/10], Train Loss: 0.0016, Train Acc: 0.8373, Test Loss: 0.0015, Test Acc: 0.8334
Epoch [8/10], Train Loss: 0.0015, Train Acc: 0.8441, Test Loss: 0.0015, Test Acc: 0.8353
Epoch [9/10], Train Loss: 0.0015, Train Acc: 0.8496, Test Loss: 0.0014, Test Acc: 0.8419
Epoch [10/10], Train Loss: 0.0014, Train Acc: 0.8542, Test Loss: 0.0014, Test Acc: 0.8467
[[852.   1.  22.  38.   3.   0.  74.   0.  10.   0.]
 [  3. 981.   3.  10.   0.   0.   1.   0.   2.   0.]
 [ 14.   0. 742.  10. 110.   0. 122.   0.   2.   0.]
 [ 16.   5.  12. 901.  29.   0.  32.   0.   5.   0.]
 [  1.   1.  57.  29. 794.   0. 115.   0.   3.   0.]
 [  0.   0.   0.   1.   0. 938.   0.  37.   2.  22.]
 [ 86.   1.  61.  28.  67.   0. 743.   0.  14.   0.]
 [  0.   0.   0.   0.   0.  21.   0. 970.   1.   8.]
 [  4.   0.   4.   3.   3.   3.   8.   3. 972.   0.]
 [  0.   0.   0.   0.   0.  14.   0.  47.   0. 939.]]
Test Loss: 0.0015, Test Acc: 0.8347
``
优秀的程序员请你根据以下要求写出对应的python代码使用pytorch实现lenet网络。 使用实验7的 fashion mnist 对lenet进行训练和测试。优化算法采用sgd或adam。 torchoptimsgd 或 torchoptimadam。可复用多层感知器的相关代码 分别绘制训练和测试的损失函数曲线和分类正确率曲线 调节batchsize、学习率并依据测试损失曲

原文地址: http://www.cveoy.top/t/topic/eTc7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录