transformers做cifar10图像分类任务保存loss曲线和准确率曲线并保存模型pytorch
时间: 2024-02-11 22:09:21 浏览: 96
好的,我可以为您提供一些关于使用 PyTorch 进行 CIFAR-10 图像分类任务的代码,并保存模型和绘制 loss 曲线和准确率曲线。以下是示例代码:
```python
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
# 定义 CNN 模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
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(nn.functional.relu(self.conv1(x)))
x = self.pool(nn.functional.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = nn.functional.relu(self.fc1(x))
x = nn.functional.relu(self.fc2(x))
x = self.fc3(x)
return x
# 定义训练超参数
LR = 0.001
EPOCHS = 10
BATCH_SIZE = 128
# 加载数据集
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=BATCH_SIZE,
shuffle=True, num_workers=2)
testset = torchvision.datasets.CIFAR10(root='./data', train=False,
download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=BATCH_SIZE,
shuffle=False, num_workers=2)
classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
# 初始化模型、损失函数和优化器
net = Net()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=LR, momentum=0.9)
# 训练模型
loss_list = []
accuracy_list = []
for epoch in range(EPOCHS):
running_loss = 0.0
total = 0
correct = 0
for i, data in enumerate(trainloader, 0):
inputs, labels = data
optimizer.zero_grad()
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
# 记录 loss 和 accuracy
loss_list.append(running_loss / len(trainloader))
accuracy_list.append(correct / total)
print('Epoch %d, loss: %.3f, accuracy: %.3f' % (epoch + 1, running_loss / len(trainloader), correct / total))
print('Finished Training')
# 保存模型
PATH = './cifar_net.pth'
torch.save(net.state_dict(), PATH)
# 绘制 loss 曲线和准确率曲线
plt.plot(loss_list)
plt.title('Training Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.show()
plt.plot(accuracy_list)
plt.title('Training Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.show()
```
以上代码使用了一个简单的 CNN 模型来进行 CIFAR-10 图像分类任务,并记录了每个 epoch 的 loss 和 accuracy,最后保存了训练好的模型,并绘制了 loss 曲线和准确率曲线。您可以根据自己的需要对代码进行修改和扩展。
阅读全文