从model模型中获取每一轮的accurac和loss训练数据,并绘制图形。 参考输出如下:
时间: 2024-02-15 10:01:33 浏览: 76
好的,可以使用PyTorch中的`nn.Module`来创建模型,并使用`nn.CrossEntropyLoss`作为损失函数。在训练过程中,我们可以使用PyTorch提供的`nn.utils`来计算每个epoch的平均loss和accuracy,并绘制图形。以下是一个示例代码:
```python
import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as data
import torchvision.datasets as datasets
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
# 定义模型
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.fc1 = nn.Linear(784, 512)
self.fc2 = nn.Linear(512, 10)
def forward(self, x):
x = x.view(-1, 784)
x = self.fc1(x)
x = nn.functional.relu(x)
x = self.fc2(x)
return x
# 加载数据集
train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transforms.ToTensor())
train_loader = data.DataLoader(train_dataset, batch_size=64, shuffle=True)
# 定义模型、损失函数、优化器
model = MyModel()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)
# 训练模型
epochs = 10
loss_list = []
acc_list = []
for epoch in range(epochs):
running_loss = 0.0
running_corrects = 0
for inputs, labels in train_loader:
optimizer.zero_grad()
outputs = model(inputs)
_, preds = torch.max(outputs, 1)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item() * inputs.size(0)
running_corrects += torch.sum(preds == labels.data)
epoch_loss = running_loss / len(train_dataset)
epoch_acc = running_corrects.double() / len(train_dataset)
loss_list.append(epoch_loss)
acc_list.append(epoch_acc)
print('Epoch [{}/{}], Loss: {:.4f}, Acc: {:.4f}'.format(epoch+1, epochs, epoch_loss, epoch_acc))
# 绘制loss和accuracy图像
plt.plot(range(epochs), loss_list)
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.title('Training Loss')
plt.show()
plt.plot(range(epochs), acc_list)
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.title('Training Accuracy')
plt.show()
```
输出结果可能类似于:
```
Epoch [1/10], Loss: 1.3121, Acc: 0.6596
Epoch [2/10], Loss: 0.6635, Acc: 0.8314
Epoch [3/10], Loss: 0.5197, Acc: 0.8645
Epoch [4/10], Loss: 0.4566, Acc: 0.8807
Epoch [5/10], Loss: 0.4193, Acc: 0.8903
Epoch [6/10], Loss: 0.3947, Acc: 0.8964
Epoch [7/10], Loss: 0.3774, Acc: 0.9013
Epoch [8/10], Loss: 0.3637, Acc: 0.9049
Epoch [9/10], Loss: 0.3524, Acc: 0.9084
Epoch [10/10], Loss: 0.3429, Acc: 0.9112
```
并且会弹出两个图形窗口,分别显示训练loss和accuracy的变化趋势。
阅读全文