在下面这段代码中加入画loss曲线和acc曲线的代码
时间: 2024-03-25 22:36:53 浏览: 67
好的,以下是在 PyTorch 中加入画 loss 曲线和 acc 曲线的代码示例:
```python
# 导入必要的库
import torch
import torch.nn as nn
import torch.optim as optim
import matplotlib.pyplot as plt
# 定义模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(784, 64)
self.fc2 = nn.Linear(64, 10)
def forward(self, x):
x = x.view(-1, 784)
x = torch.relu(self.fc1(x))
x = self.fc2(x)
return torch.log_softmax(x, dim=1)
model = Net()
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)
# 载入数据
train_loader = torch.utils.data.DataLoader(
datasets.MNIST('data', train=True, download=True,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])),
batch_size=64, shuffle=True)
test_loader = torch.utils.data.DataLoader(
datasets.MNIST('data', train=False, transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])),
batch_size=1000, shuffle=True)
# 训练模型
train_loss = []
train_acc = []
test_loss = []
test_acc = []
for epoch in range(10):
# 训练
model.train()
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
output = model(data)
loss = criterion(output, target)
loss.backward()
optimizer.step()
# 评估
model.eval()
train_loss.append(0)
train_correct = 0
test_loss.append(0)
test_correct = 0
with torch.no_grad():
for data, target in train_loader:
output = model(data)
train_loss[-1] += criterion(output, target).item()
pred = output.argmax(dim=1, keepdim=True)
train_correct += pred.eq(target.view_as(pred)).sum().item()
for data, target in test_loader:
output = model(data)
test_loss[-1] += criterion(output, target).item()
pred = output.argmax(dim=1, keepdim=True)
test_correct += pred.eq(target.view_as(pred)).sum().item()
train_loss[-1] /= len(train_loader.dataset)
train_acc.append(100. * train_correct / len(train_loader.dataset))
test_loss[-1] /= len(test_loader.dataset)
test_acc.append(100. * test_correct / len(test_loader.dataset))
# 画 loss 曲线
plt.plot(train_loss, label='train_loss')
plt.plot(test_loss, label='test_loss')
plt.title('Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()
# 画 acc 曲线
plt.plot(train_acc, label='train_acc')
plt.plot(test_acc, label='test_acc')
plt.title('Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.show()
```
在上述代码中,我们使用了列表 `train_loss`、`train_acc`、`test_loss` 和 `test_acc` 来存储训练过程中的指标值,并利用 matplotlib 库画出了 loss 曲线和 acc 曲线。其中,`train_loss` 表示训练集上的 loss 值,`train_acc` 表示训练集上的准确率,`test_loss` 表示测试集上的 loss 值,`test_acc` 表示测试集上的准确率。
阅读全文