使用PyTh实现LeNet网络。 使用已下载好的本地Fashion MNIST 对LeNet进行训练和测试。优化算法采用SGD或Adam。 torch.optim.SGD 或 torch.optim.Adam。可复用多层感知器的相关代码 分别绘制训练和测试的损失函数曲线和分类正确率曲线 调节BatchSize、学习率,并依据测试损失曲线的拐点确定最佳模型,保存该模型。 使用测试集测试所保存模型的性能,以混淆矩阵展示。 扩展任务:以旋转的方式扩充测试集,在前述最佳模型上测试扩充
时间: 2023-06-15 12:05:09 浏览: 162
以下是实现LeNet网络的代码,使用了PyTorch框架和Fashion MNIST数据集进行训练和测试。其中优化算法采用了Adam。
```python
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
# 定义LeNet网络
class LeNet(nn.Module):
def __init__(self):
super(LeNet, self).__init__()
self.conv1 = nn.Conv2d(1, 6, kernel_size=5)
self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv2 = nn.Conv2d(6, 16, kernel_size=5)
self.pool2 = nn.MaxPool2d(kernel_size=2, stride=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
# 定义训练函数
def train(model, train_loader, optimizer, criterion):
model.train()
train_loss = 0
correct = 0
total = 0
for inputs, targets in train_loader:
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
train_loss += loss.item()
_, predicted = outputs.max(1)
total += targets.size(0)
correct += predicted.eq(targets).sum().item()
return train_loss / len(train_loader), correct / total
# 定义测试函数
def test(model, test_loader, criterion):
model.eval()
test_loss = 0
correct = 0
total = 0
with torch.no_grad():
for inputs, targets in test_loader:
outputs = model(inputs)
loss = criterion(outputs, targets)
test_loss += loss.item()
_, predicted = outputs.max(1)
total += targets.size(0)
correct += predicted.eq(targets).sum().item()
return test_loss / len(test_loader), correct / total
# 数据集处理
train_transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
test_transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
train_set = datasets.FashionMNIST(root='./data', train=True, download=True, transform=train_transform)
test_set = datasets.FashionMNIST(root='./data', train=False, download=True, transform=test_transform)
# 参数设置
batch_size = 64
lr = 0.001
num_epochs = 30
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# 数据加载
train_loader = DataLoader(train_set, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_set, batch_size=batch_size, shuffle=False)
# 模型、损失函数、优化器定义
model = LeNet().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=lr)
# 训练和测试
train_losses = []
train_accs = []
test_losses = []
test_accs = []
best_test_loss = float('inf')
for epoch in range(num_epochs):
train_loss, train_acc = train(model, train_loader, optimizer, criterion)
test_loss, test_acc = test(model, test_loader, criterion)
train_losses.append(train_loss)
train_accs.append(train_acc)
test_losses.append(test_loss)
test_accs.append(test_acc)
print('Epoch [{}/{}] - Train Loss: {:.4f}, Train Acc: {:.4f}, Test Loss: {:.4f}, Test Acc: {:.4f}'.format(
epoch+1, num_epochs, train_loss, train_acc, test_loss, test_acc))
if test_loss < best_test_loss:
best_test_loss = test_loss
torch.save(model.state_dict(), 'best_model.pth')
# 扩展任务:旋转测试集
test_set_rotate = datasets.FashionMNIST(root='./data', train=False, download=True, transform=transforms.Compose([
transforms.RandomRotation(90),
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
]))
test_loader_rotate = DataLoader(test_set_rotate, batch_size=batch_size, shuffle=False)
# 加载最佳模型
model.load_state_dict(torch.load('best_model.pth'))
# 在旋转的测试集上测试模型性能
confusion_matrix = torch.zeros(10, 10)
with torch.no_grad():
for inputs, targets in test_loader_rotate:
inputs, targets = inputs.to(device), targets.to(device)
outputs = model(inputs)
_, predicted = outputs.max(1)
for i in range(targets.size(0)):
confusion_matrix[targets[i]][predicted[i]] += 1
print('Confusion Matrix:')
print(confusion_matrix)
```
可以通过调节BatchSize、学习率等参数,得到不同的训练和测试结果。在训练过程中,我们记录了训练和测试的损失函数曲线和分类正确率曲线,来观察模型的训练和测试过程。
```python
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.plot(train_losses, label='train')
plt.plot(test_losses, label='test')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.subplot(1, 2, 2)
plt.plot(train_accs, label='train')
plt.plot(test_accs, label='test')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.show()
```
最后,我们保存了在测试集上表现最好的模型,并在扩展任务中使用旋转的测试集来测试该模型的性能,得到了混淆矩阵。
阅读全文