目录

使用 TensorBoard 可视化模型、数据和训练

创建时间: Aug 08, 2019 |上次更新时间:2022 年 10 月 18 日 |上次验证: Nov 05, 2024

60 分钟闪电战中, 我们向您展示如何加载数据, 通过我们定义为 的子类 的模型馈送它, 在训练数据上训练此模型,并在测试数据上对其进行测试。 为了查看发生了什么,我们打印出一些统计数据作为模型 正在进行培训,以了解培训是否在进行。 但是,我们可以做得更好:PyTorch 与 TensorBoard,一种旨在可视化神经 网络训练运行。本教程说明了它的一些 功能,使用 Fashion-MNIST 数据集,该数据集可以使用 torchvision.datasets 读入 PyTorch。nn.Module

在本教程中,我们将学习如何:

  1. 读入数据并使用适当的转换(与前面的教程几乎相同)。

  2. 设置 TensorBoard。

  3. 写入 TensorBoard。

  4. 使用 TensorBoard 检查模型架构。

  5. 使用 TensorBoard 创建我们在上一个教程中创建的可视化的交互式版本,使用更少的代码

具体来说,在第 #5 点,我们将看到:

  • 检查训练数据的几种方法

  • 如何在训练时跟踪模型的性能

  • 如何评估模型在训练后的性能。

我们将从与 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()

我们将定义相同的 和 之前的内容:optimizercriterion

criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)

1. TensorBoard 设置

现在,我们将设置 TensorBoard,从 导入并定义一个 ,用于将信息写入 TensorBoard 的关键对象。tensorboardtorch.utilsSummaryWriter

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 应该会显示以下内容。

../_static/img/tensorboard_first_view.png

现在您知道如何使用 TensorBoard!但是,此示例可能是 在 Jupyter Notebook 中完成 - TensorBoard 真正擅长的地方在于 创建交互式可视化。我们接下来将介绍其中之一, 以及本教程结束时的更多内容。

3. 使用 TensorBoard 检查模型

TensorBoard 的优势之一是它能够可视化复杂模型 结构。让我们可视化我们构建的模型。

writer.add_graph(net, images)
writer.close()

现在,在刷新 TensorBoard 时,您应该会看到一个“Graphs”选项卡,该选项卡 如下所示:

../_static/img/tensorboard_model_viz.png

继续并双击“Net”以查看它展开,看到一个 构成模型的各个操作的详细视图。

TensorBoard 有一个非常方便的功能,用于可视化高维 数据,例如低维空间中的图像数据;我们将介绍这一点 下一个。

4. 向 TensorBoard 添加“投影仪”

我们可以可视化 higher 的 lower 维度表示 通过 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 维的 - 投影成三个 维度空间。此外,这是交互式的:您可以单击 并拖动以旋转三维投影。最后,一对 使可视化效果更易于查看的提示:选择 “color: label” ,以及启用“夜间模式”,这将使 由于背景为白色,因此更容易看到图像:

../_static/img/tensorboard_projector.png

现在我们已经彻底检查了我们的数据,让我们展示一下 TensorBoard 如何 可以让跟踪模型训练和评估更清晰,从 训练。

5. 使用 TensorBoard 跟踪模型训练

在前面的示例中,我们简单地打印了模型的 running loss 每 2000 次迭代。现在,我们将 Running Loss 记录为 TensorBoard 以及模型的预测视图 making 的plot_classes_preds

# 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 次训练迭代中:

../_static/img/tensorboard_scalar_runs.png

此外,我们可以查看模型对 在整个学习过程中的任意批次。查看 “Images” 选项卡并滚动 在 “Predictions vs. actuals” 可视化下查看此内容; 这向我们表明,例如,在仅仅 3000 次训练迭代之后, 该模型已经能够区分视觉上不同的 衬衫、运动鞋和外套等类,尽管它不像 在以后的训练中变得自信:

../_static/img/tensorboard_images.png

在前面的教程中,我们查看了模型 受过训练;在这里,我们将使用 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 Curves” 选项卡 曲线。去四处逛逛;您将在 某些类模型具有近 100% 的“曲线下面积”, 而在其他 S 上,这个区域较低:

../_static/img/tensorboard_pr_curves.png

这就是 TensorBoard 和 PyTorch 与它集成的介绍。 当然,您可以在 Jupyter 中执行 TensorBoard 执行的所有操作 Notebook 的 Notebook 中,但使用 TensorBoard,您可以获得交互式的视觉效果 默认情况下。

文档

访问 PyTorch 的全面开发人员文档

查看文档

教程

获取面向初学者和高级开发人员的深入教程

查看教程

资源

查找开发资源并解答您的问题

查看资源