PyTorch 使用 TensorBoard 可視化模型,數(shù)據(jù)和訓(xùn)練

2020-09-16 11:45 更新

原文: PyTorch 使用 TensorBoard 可視化模型,數(shù)據(jù)和訓(xùn)練

校驗(yàn)者:yearing1017

60 分鐘閃電戰(zhàn)中,我們向您展示了如何加載數(shù)據(jù),如何向定義為nn.Module子類的模型提供數(shù)據(jù),如何在訓(xùn)練數(shù)據(jù)上訓(xùn)練該模型,以及在測(cè)試數(shù)據(jù)上對(duì)其進(jìn)行測(cè)試。 為了了解發(fā)生的情況,我們?cè)谀P陀?xùn)練期間打印一些統(tǒng)計(jì)信息,以了解訓(xùn)練是否在進(jìn)行中。 但是,我們可以做得更好:PyTorch 與 TensorBoard 集成,該工具旨在可視化神經(jīng)網(wǎng)絡(luò)訓(xùn)練運(yùn)行的結(jié)果。 本教程使用 Fashion-MNIST 數(shù)據(jù)集說明了其某些功能,可以使用 torchvision.datasets 將其讀取到 PyTorch 中。

在本教程中,我們將學(xué)習(xí)如何:

  1. 讀取數(shù)據(jù)并進(jìn)行適當(dāng)?shù)霓D(zhuǎn)換(與先前的教程幾乎相同)。
    2. 設(shè)置 TensorBoard。
    3. 寫入 TensorBoard。
    4. 使用 TensorBoard 檢查模型架構(gòu)。
    5. 使用 TensorBoard 來創(chuàng)建我們?cè)谏弦粋€(gè)教程中創(chuàng)建的可視化的替代版本,代碼量更少。

具體來說,在第 5 點(diǎn),我們將看到:

  • 有兩種檢查訓(xùn)練數(shù)據(jù)的方法
    - 在訓(xùn)練模型時(shí)如何追蹤其性能
    - 在訓(xùn)練完成后如何評(píng)估模型的性能。

我們將從 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)))

我們將在該教程中定義一個(gè)類似的模型架構(gòu),僅需進(jìn)行少量修改即可說明以下事實(shí):圖像現(xiàn)在是一個(gè)通道而不是三個(gè)通道,是 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 設(shè)置

現(xiàn)在,我們將設(shè)置 TensorBoard,從torch.utils導(dǎo)入tensorboard并定義SummaryWriter,這是將信息寫入 TensorBoard 的關(guān)鍵對(duì)象。

from torch.utils.tensorboard import SummaryWriter


## default `log_dir` is "runs" - we'll be more specific here
writer = SummaryWriter('runs/fashion_mnist_experiment_1')

請(qǐng)注意,僅此行會(huì)創(chuàng)建一個(gè)runs/fashion_mnist_experiment_1文件夾。

2.寫入 TensorBoard

現(xiàn)在,使用 make_grid 將圖像寫入到 TensorBoard 中,具體來說就是網(wǎng)格。

## get some random training images
dataiter = iter(trainloader)
images, labels = dataiter.next()


## 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)

現(xiàn)在運(yùn)行

tensorboard --logdir=runs

應(yīng)該顯示以下內(nèi)容。

intermediate/../../_static/img/tensorboard_first_view.png

現(xiàn)在您知道如何使用 TensorBoard 了! 但是,此示例可以在 Jupyter Notebook 中完成-TensorBoard 真正擅長(zhǎng)的地方是創(chuàng)建交互式可視化。 接下來,我們將介紹其中之一,并在本教程結(jié)束時(shí)介紹更多內(nèi)容。

3.使用 TensorBoard 檢查模型

TensorBoard 的優(yōu)勢(shì)之一是其可視化復(fù)雜模型結(jié)構(gòu)的能力。 讓我們可視化我們構(gòu)建的模型。

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

現(xiàn)在刷新 TensorBoard 后,您應(yīng)該會(huì)看到一個(gè)“ Graphs”標(biāo)簽,如下所示:

intermediate/../../_static/img/tensorboard_model_viz.png

繼續(xù)并雙擊“ Net”以展開它,查看組成模型的各個(gè)操作的詳細(xì)視圖。

TensorBoard 具有非常方便的功能,可在低維空間中可視化高維數(shù)據(jù),例如圖像數(shù)據(jù); 接下來我們將介紹。

4.在 TensorBoard 中添加一個(gè)“投影儀”

我們可以通過 add_embedding 方法可視化高維數(shù)據(jù)的低維表示

## 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()

現(xiàn)在,在 TensorBoard 的“投影儀”選項(xiàng)卡中,您可以看到這 100 張圖像-每個(gè)圖像 784 維-向下投影到三維空間中。 此外,這是交互式的:您可以單擊并拖動(dòng)以旋轉(zhuǎn)三維投影。 最后,有兩個(gè)技巧可以使可視化效果更容易看到:在左上方選擇“顏色:標(biāo)簽”,并啟用“夜間模式”,這將使圖像更容易看到,因?yàn)樗鼈兊谋尘笆前咨模?/p>

intermediate/../../_static/img/tensorboard_projector.png

現(xiàn)在我們已經(jīng)徹底檢查了我們的數(shù)據(jù),接下來讓我們展示TensorBoard 如何從訓(xùn)練開始就可以使跟蹤模型的訓(xùn)練和評(píng)估更加清晰。

5.使用 TensorBoard 跟蹤模型訓(xùn)練

在前面的示例中,我們僅每 2000 次迭代打印該模型的運(yùn)行損失。 現(xiàn)在,我們將運(yùn)行損失記錄到 TensorBoard 中,并通過plot_classes_preds函數(shù)查看模型所做的預(yù)測(cè)。

## 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

最后,讓我們使用與之前教程相同的模型訓(xùn)練代碼來訓(xùn)練模型,但是每 1000 批將結(jié)果寫入 TensorBoard,而不是打印到控制臺(tái)。 這是通過 add_scalar 函數(shù)完成的。

此外,在訓(xùn)練過程中,我們將生成一幅圖像,顯示該批次中包含的四幅圖像的模型預(yù)測(cè)與實(shí)際結(jié)果。

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')

現(xiàn)在,您可以查看“標(biāo)量”選項(xiàng)卡,以查看在 15,000 次訓(xùn)練迭代中繪制的運(yùn)行損失:

intermediate/../../_static/img/tensorboard_scalar_runs.png

此外,我們可以查看整個(gè)學(xué)習(xí)過程中模型在任意批次上所做的預(yù)測(cè)。 查看“圖像”選項(xiàng)卡,然后在“預(yù)測(cè)與實(shí)際”可視化條件下向下滾動(dòng)以查看此內(nèi)容; 這向我們表明,例如,僅經(jīng)過 3000 次訓(xùn)練迭代,該模型就能夠區(qū)分出視覺上截然不同的類,例如襯衫,運(yùn)動(dòng)鞋和外套,盡管它并沒有像后來的訓(xùn)練那樣有信心:

intermediate/../../_static/img/tensorboard_images.png

在之前的教程中,我們研究了模型訓(xùn)練后的每類準(zhǔn)確性; 在這里,我們將使用 TensorBoard 繪制每個(gè)類的精度回召曲線。

6.使用 TensorBoard 評(píng)估經(jīng)過訓(xùn)練的模型

## 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_preds = []
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_preds_batch = torch.max(output, 1)


        class_probs.append(class_probs_batch)
        class_preds.append(class_preds_batch)


test_probs = torch.cat([torch.stack(batch) for batch in class_probs])
test_preds = torch.cat(class_preds)


## helper function
def add_pr_curve_tensorboard(class_index, test_probs, test_preds, global_step=0):
    '''
    Takes in a "class_index" from 0 to 9 and plots the corresponding
    precision-recall curve
    '''
    tensorboard_preds = test_preds == class_index
    tensorboard_probs = test_probs[:, class_index]


    writer.add_pr_curve(classes[class_index],
                        tensorboard_preds,
                        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_preds)

現(xiàn)在,您將看到一個(gè)“ PR Curves”選項(xiàng)卡,其中包含每個(gè)類別的精度回召曲線。 繼續(xù)戳一下; 您會(huì)發(fā)現(xiàn)在某些類別中,模型的“曲線下面積”接近 100%,而在另一些類別中,該面積更低:

intermediate/../../_static/img/tensorboard_pr_curves.png

這是 TensorBoard 和 PyTorch 與之集成的介紹。 當(dāng)然,您可以在 Jupyter Notebook 中完成 TensorBoard 所做的所有操作,但是使用 TensorBoard,默認(rèn)情況下,您還可以獲得交互式視覺效果。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)