使用TensorBoard可视化模型、数据和训练过程¶
创建日期: 2019年8月8日 | 最后更新日期: 2022年10月18日 | 最后验证日期: 2024年11月5日
在60分钟快速入门中,
我们向您展示如何加载数据,
将数据输入到我们定义为nn.Module子类的模型中,
在训练数据上训练该模型,并在测试数据上进行测试。
为了了解训练过程,我们在模型训练时打印出一些统计数据,
以判断训练是否在进展。
然而,我们可以做得更好:PyTorch集成了
TensorBoard,这是一种用于可视化神经网络训练结果的工具。本教程展示了它的一些功能,
使用可以通过torchvision.datasets读入PyTorch的
Fashion-MNIST数据集。
在本教程中,我们将学习如何:
Read in data and with appropriate transforms (nearly identical to the prior tutorial).
Set up TensorBoard.
Write to TensorBoard.
Inspect a model architecture using TensorBoard.
Use TensorBoard to create interactive versions of the visualizations we created in last tutorial, with less code
特别是在第5点上,我们将看到:
A couple of ways to inspect our training data
How to track our model’s performance as it trains
How to assess our model’s performance once it is trained.
我们将从与CIFAR-10 教程中类似的样板代码开始:
# imports
import matplotlib.pyplot as plt
import numpy as np
import torch
import torchvision
import torchvision.transforms as transforms
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
# transforms
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,))])
# datasets
trainset = torchvision.datasets.FashionMNIST('./data',
download=True,
train=True,
transform=transform)
testset = torchvision.datasets.FashionMNIST('./data',
download=True,
train=False,
transform=transform)
# dataloaders
trainloader = torch.utils.data.DataLoader(trainset, batch_size=4,
shuffle=True, num_workers=2)
testloader = torch.utils.data.DataLoader(testset, batch_size=4,
shuffle=False, num_workers=2)
# constant for classes
classes = ('T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle Boot')
# helper function to show an image
# (used in the `plot_classes_preds` function below)
def matplotlib_imshow(img, one_channel=False):
if one_channel:
img = img.mean(dim=0)
img = img / 2 + 0.5 # unnormalize
npimg = img.numpy()
if one_channel:
plt.imshow(npimg, cmap="Greys")
else:
plt.imshow(np.transpose(npimg, (1, 2, 0)))
我们将定义一个与教程类似的模型架构,仅对图像现在是一通道而不是三通道以及尺寸为28x28而不是32x32的情况进行轻微修改:
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 4 * 4, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 4 * 4)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
net = Net()
我们将会定义之前相同的 optimizer 和 criterion:
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
1. TensorBoard 设置¶
现在我们将设置TensorBoard,从torch.utils导入tensorboard并定义一个
SummaryWriter,这是我们向TensorBoard写入信息的关键对象。
from torch.utils.tensorboard import SummaryWriter
# default `log_dir` is "runs" - we'll be more specific here
writer = SummaryWriter('runs/fashion_mnist_experiment_1')
请注意,单独这一行代码会创建一个 runs/fashion_mnist_experiment_1
文件夹。
2. 写入 TensorBoard¶
现在让我们将一张图片写入我们的TensorBoard - 具体来说,是一个网格 - 使用 make_grid。
# get some random training images
dataiter = iter(trainloader)
images, labels = next(dataiter)
# create grid of images
img_grid = torchvision.utils.make_grid(images)
# show images
matplotlib_imshow(img_grid, one_channel=True)
# write to tensorboard
writer.add_image('four_fashion_mnist_images', img_grid)
现在运行中
tensorboard --logdir=runs
从命令行输入并导航到 http://localhost:6006 应该显示以下内容。
现在你已经学会了如何使用TensorBoard!然而,这个例子可以在Jupyter Notebook中完成——TensorBoard真正出色的地方在于创建交互式可视化。我们将在教程的末尾覆盖其中一个交互式可视化示例,并涵盖更多的示例。
3. 使用 TensorBoard 检查模型 ¶
TensorBoard 的一个优势是能够可视化复杂的模型结构。让我们来可视化我们构建的模型。
writer.add_graph(net, images)
writer.close()
现在刷新 TensorBoard 后,你应该会看到一个名为“Graphs”的标签页,如下所示:
双击“Net”即可查看其展开情况,看到模型中各个操作的详细视图。
TensorBoard 具有一个非常实用的功能,可以将高维数据,例如图像数据,在低维空间中进行可视化;我们接下来将介绍这一功能。
4. 在 TensorBoard 中添加一个“投影器”¶
我们可以使用 add_embedding 方法可视化高维数据的低维表示
# helper function
def select_n_random(data, labels, n=100):
'''
Selects n random datapoints and their corresponding labels from a dataset
'''
assert len(data) == len(labels)
perm = torch.randperm(len(data))
return data[perm][:n], labels[perm][:n]
# select random images and their target indices
images, labels = select_n_random(trainset.data, trainset.targets)
# get the class labels for each image
class_labels = [classes[lab] for lab in labels]
# log embeddings
features = images.view(-1, 28 * 28)
writer.add_embedding(features,
metadata=class_labels,
label_img=images.unsqueeze(1))
writer.close()
现在在 TensorBoard 的“Projector”标签页中,你可以看到这些 100 张图像——每张图像都是 784 维的——被投影到三维空间中。此外,这个功能是互动的:你可以点击并拖动来旋转三维投影。最后,为了使可视化更易于查看,可以尝试选择左上角的“颜色:标签”,同时启用“夜间模式”,因为这些图像的背景是白色,所以开启夜间模式会使图像更容易看清。
现在我们已经彻底检查了数据,让我们展示一下 TensorBoard 如何使跟踪模型训练和评估更加清晰,从训练开始。
5. 使用TensorBoard跟踪模型训练¶
在之前的示例中,我们只是在每2000次迭代时打印了模型的运行损失。
现在,我们将使用plot_classes_preds函数将运行损失记录到TensorBoard,并查看模型正在做出的预测。
# helper functions
def images_to_probs(net, images):
'''
Generates predictions and corresponding probabilities from a trained
network and a list of images
'''
output = net(images)
# convert output probabilities to predicted class
_, preds_tensor = torch.max(output, 1)
preds = np.squeeze(preds_tensor.numpy())
return preds, [F.softmax(el, dim=0)[i].item() for i, el in zip(preds, output)]
def plot_classes_preds(net, images, labels):
'''
Generates matplotlib Figure using a trained network, along with images
and labels from a batch, that shows the network's top prediction along
with its probability, alongside the actual label, coloring this
information based on whether the prediction was correct or not.
Uses the "images_to_probs" function.
'''
preds, probs = images_to_probs(net, images)
# plot the images in the batch, along with predicted and true labels
fig = plt.figure(figsize=(12, 48))
for idx in np.arange(4):
ax = fig.add_subplot(1, 4, idx+1, xticks=[], yticks=[])
matplotlib_imshow(images[idx], one_channel=True)
ax.set_title("{0}, {1:.1f}%\n(label: {2})".format(
classes[preds[idx]],
probs[idx] * 100.0,
classes[labels[idx]]),
color=("green" if preds[idx]==labels[idx].item() else "red"))
return fig
最后,让我们使用之前的教程中的相同模型训练代码进行训练,但每1000个批次将结果写入TensorBoard,而不是打印到控制台;这通过使用 add_scalar 函数完成。
此外,在训练过程中,我们会生成一张图片,展示模型在该批次中包含的四张图片上的预测结果与实际结果的对比。
running_loss = 0.0
for epoch in range(1): # loop over the dataset multiple times
for i, data in enumerate(trainloader, 0):
# get the inputs; data is a list of [inputs, labels]
inputs, labels = data
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if i % 1000 == 999: # every 1000 mini-batches...
# ...log the running loss
writer.add_scalar('training loss',
running_loss / 1000,
epoch * len(trainloader) + i)
# ...log a Matplotlib Figure showing the model's predictions on a
# random mini-batch
writer.add_figure('predictions vs. actuals',
plot_classes_preds(net, inputs, labels),
global_step=epoch * len(trainloader) + i)
running_loss = 0.0
print('Finished Training')
你现在可以查看标量选项卡,查看在训练的15,000次迭代中绘制的运行损失:
此外,在训练过程中,我们还可以查看模型在任意批次上的预测结果。在“Images”标签页中,向下滚动“预测与实际值”的可视化图表即可看到这一点;这表明,在仅仅3000次训练迭代之后,模型就已经能够区分出诸如衬衫、运动鞋和外套等视觉上明显不同的类别,尽管它后来在训练中的信心更强。
在之前的教程中,我们查看了模型训练后的每个类别的准确率;在这里,我们将使用TensorBoard绘制每个类别的精确率-召回率曲线(这里有很好的解释)。
6. 使用TensorBoard评估训练好的模型¶
# 1. gets the probability predictions in a test_size x num_classes Tensor
# 2. gets the preds in a test_size Tensor
# takes ~10 seconds to run
class_probs = []
class_label = []
with torch.no_grad():
for data in testloader:
images, labels = data
output = net(images)
class_probs_batch = [F.softmax(el, dim=0) for el in output]
class_probs.append(class_probs_batch)
class_label.append(labels)
test_probs = torch.cat([torch.stack(batch) for batch in class_probs])
test_label = torch.cat(class_label)
# helper function
def add_pr_curve_tensorboard(class_index, test_probs, test_label, global_step=0):
'''
Takes in a "class_index" from 0 to 9 and plots the corresponding
precision-recall curve
'''
tensorboard_truth = test_label == class_index
tensorboard_probs = test_probs[:, class_index]
writer.add_pr_curve(classes[class_index],
tensorboard_truth,
tensorboard_probs,
global_step=global_step)
writer.close()
# plot all the pr curves
for i in range(len(classes)):
add_pr_curve_tensorboard(i, test_probs, test_label)
你现在会看到一个“PR 曲线”标签页,其中包含了每个类别的精确召回曲线。你可以随意浏览;你会发现有些类别模型的“曲线下的面积”接近 100%,而在其他类别中,这个面积较低。
这便是对TensorBoard及其与PyTorch集成的一个简介。 当然,你可以在Jupyter Notebook中完成TensorBoard的所有功能,但使用TensorBoard时,默认会获得交互式的可视化效果。