cifar100图像分类实验训练集和测试集loss和acc曲线绘制源码
时间: 2023-09-04 11:10:48 浏览: 131
以下是使用PyTorch绘制cifar100图像分类实验训练集和测试集loss和acc曲线的示例代码:
```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
# 定义超参数
batch_size = 128
lr = 0.1
momentum = 0.9
weight_decay = 1e-4
epochs = 50
# 加载数据集
train_transform = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.5071, 0.4867, 0.4408), (0.2675, 0.2565, 0.2761))
])
test_transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5071, 0.4867, 0.4408), (0.2675, 0.2565, 0.2761))
])
train_set = torchvision.datasets.CIFAR100(root='./data', train=True, download=True, transform=train_transform)
train_loader = torch.utils.data.DataLoader(train_set, batch_size=batch_size, shuffle=True, num_workers=2)
test_set = torchvision.datasets.CIFAR100(root='./data', train=False, download=True, transform=test_transform)
test_loader = torch.utils.data.DataLoader(test_set, batch_size=batch_size, shuffle=False, num_workers=2)
# 定义模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 64, 3, padding=1)
self.bn1 = nn.BatchNorm2d(64)
self.relu1 = nn.ReLU(inplace=True)
self.conv2 = nn.Conv2d(64, 128, 3, padding=1)
self.bn2 = nn.BatchNorm2d(128)
self.relu2 = nn.ReLU(inplace=True)
self.conv3 = nn.Conv2d(128, 256, 3, padding=1)
self.bn3 = nn.BatchNorm2d(256)
self.relu3 = nn.ReLU(inplace=True)
self.fc = nn.Linear(256 * 8 * 8, 100)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu1(x)
x = self.conv2(x)
x = self.bn2(x)
x = self.relu2(x)
x = self.conv3(x)
x = self.bn3(x)
x = self.relu3(x)
x = x.view(-1, 256 * 8 * 8)
x = self.fc(x)
return x
# 定义损失函数和优化器
net = Net()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=lr, momentum=momentum, weight_decay=weight_decay)
# 训练模型
train_loss_list = []
train_acc_list = []
test_loss_list = []
test_acc_list = []
for epoch in range(epochs):
train_loss = 0
train_acc = 0
net.train()
for i, (inputs, labels) in enumerate(train_loader):
optimizer.zero_grad()
outputs = net(inputs)
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)
test_loss = 0
test_acc = 0
net.eval()
with torch.no_grad():
for inputs, labels in test_loader:
outputs = net(inputs)
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 [%d/%d], Train Loss: %.4f, Train Acc: %.4f, Test Loss: %.4f, Test Acc: %.4f'
% (epoch+1, epochs, train_loss, train_acc, test_loss, test_acc))
# 绘制loss和acc曲线
plt.plot(range(epochs), train_loss_list, label='train')
plt.plot(range(epochs), test_loss_list, label='test')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()
plt.plot(range(epochs), train_acc_list, label='train')
plt.plot(range(epochs), test_acc_list, label='test')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.show()
```
运行该代码,即可绘制出cifar100图像分类实验训练集和测试集loss和acc曲线。
阅读全文