绘制训练集准确度曲线和失函数曲线pytorch代码30轮次
时间: 2023-05-11 20:05:48 浏览: 241
以下是绘制训练集准确度曲线和损失函数曲线的 PyTorch 代码,共计 30 轮次:
```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(10, 5)
self.fc2 = nn.Linear(5, 2)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = self.fc2(x)
return x
# 定义训练函数
def train(model, optimizer, criterion, train_loader, device):
model.train()
train_loss = 0
correct = 0
total = 0
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device)
optimizer.zero_grad()
output = model(data)
loss = criterion(output, target)
loss.backward()
optimizer.step()
train_loss += loss.item()
_, predicted = output.max(1)
total += target.size(0)
correct += predicted.eq(target).sum().item()
train_acc = 100. * correct / total
train_loss /= len(train_loader.dataset)
return train_acc, train_loss
# 定义测试函数
def test(model, criterion, test_loader, device):
model.eval()
test_loss = 0
correct = 0
total = 0
with torch.no_grad():
for batch_idx, (data, target) in enumerate(test_loader):
data, target = data.to(device), target.to(device)
output = model(data)
loss = criterion(output, target)
test_loss += loss.item()
_, predicted = output.max(1)
total += target.size(0)
correct += predicted.eq(target).sum().item()
test_acc = 100. * correct / total
test_loss /= len(test_loader.dataset)
return test_acc, test_loss
# 加载数据集
train_loader = torch.utils.data.DataLoader(
torch.randn(1000, 10), batch_size=32, shuffle=True)
test_loader = torch.utils.data.DataLoader(
torch.randn(100, 10), batch_size=32, shuffle=True)
# 定义超参数
lr = 0.01
momentum = 0.9
epochs = 30
# 初始化模型、优化器和损失函数
model = Net().to("cuda")
optimizer = optim.SGD(model.parameters(), lr=lr, momentum=momentum)
criterion = nn.CrossEntropyLoss()
# 记录训练过程中的准确度和损失函数
train_acc_list = []
train_loss_list = []
test_acc_list = []
test_loss_list = []
# 开始训练
for epoch in range(1, epochs + 1):
train_acc, train_loss = train(model, optimizer, criterion, train_loader, "cuda")
test_acc, test_loss = test(model, criterion, test_loader, "cuda")
train_acc_list.append(train_acc)
train_loss_list.append(train_loss)
test_acc_list.append(test_acc)
test_loss_list.append(test_loss)
print(f"Epoch {epoch}: Train Acc: {train_acc:.2f}%, Train Loss: {train_loss:.4f}, Test Acc: {test_acc:.2f}%, Test Loss: {test_loss:.4f}")
# 绘制训练集准确度曲线和损失函数曲线
plt.plot(range(1, epochs + 1), train_acc_list, label="Train Acc")
plt.plot(range(1, epochs + 1), train_loss_list, label="Train Loss")
plt.plot(range(1, epochs + 1), test_acc_list, label="Test Acc")
plt.plot(range(1, epochs + 1), test_loss_list, label="Test Loss")
plt.legend()
plt.show()
```
希望这个代码能够帮到你!
阅读全文