用pytorch训练模型并用tensorboardX记录loss曲线,acc曲线,给出代码演示
时间: 2023-08-10 15:17:44 浏览: 169
好的,下面是一个简单的用PyTorch训练模型并用tensorboardX记录loss曲线和acc曲线的代码演示:
```python
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.tensorboard import SummaryWriter
from torchvision import datasets, transforms
# 定义模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.conv2_drop = nn.Dropout2d()
self.fc1 = nn.Linear(320, 50)
self.fc2 = nn.Linear(50, 10)
def forward(self, x):
x = nn.functional.relu(nn.functional.max_pool2d(self.conv1(x), 2))
x = nn.functional.relu(nn.functional.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
x = x.view(-1, 320)
x = nn.functional.relu(self.fc1(x))
x = nn.functional.dropout(x, training=self.training)
x = self.fc2(x)
return nn.functional.log_softmax(x, dim=1)
# 加载数据集
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)
# 定义训练函数
def train(model, device, train_loader, optimizer, criterion, epoch, writer):
model.train()
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()
writer.add_scalar('train_loss', loss.item(), epoch * len(train_loader) + batch_idx)
# 定义测试函数
def test(model, device, test_loader, criterion, epoch, writer):
model.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in test_loader:
data, target = data.to(device), target.to(device)
output = model(data)
test_loss += criterion(output, target).item() * len(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
test_loss /= len(test_loader.dataset)
accuracy = correct / len(test_loader.dataset)
writer.add_scalar('test_loss', test_loss, epoch)
writer.add_scalar('test_accuracy', accuracy, epoch)
# 初始化模型、优化器、损失函数、设备和tensorboard writer
model = Net().to('cuda')
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)
criterion = nn.CrossEntropyLoss()
device = 'cuda'
writer = SummaryWriter()
# 训练和测试模型
for epoch in range(1, 11):
train(model, device, train_loader, optimizer, criterion, epoch, writer)
test(model, device, test_loader, criterion, epoch, writer)
writer.close()
```
运行上述代码后,就可以在tensorboard中看到train_loss、test_loss和test_accuracy的曲线了。
阅读全文