使用 TensorBoard 可視化模型、資料和訓練¶
建立於:2019 年 8 月 8 日 | 最後更新:2022 年 10 月 18 日 | 最後驗證:2024 年 11 月 05 日
在 60 分鐘速成課程中,我們向您展示如何載入資料,將其輸入到我們定義為 nn.Module
子類別的模型中,在訓練資料上訓練此模型,並在測試資料上測試它。為了了解正在發生的事情,我們在模型訓練時印出一些統計數據,以了解訓練是否正在進行。 然而,我們可以做得更好:PyTorch 與 TensorBoard 整合,TensorBoard 是一種設計用於可視化神經網路訓練運行的結果的工具。 本教學說明了它的一些功能,使用 Fashion-MNIST 資料集,可以使用 torchvision.datasets 讀取到 PyTorch 中。
在本教學中,我們將學習如何
讀取資料並使用適當的轉換 (幾乎與之前的教學相同)。
設定 TensorBoard。
寫入 TensorBoard。
使用 TensorBoard 檢查模型架構。
使用 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()
我們將定義與之前相同的 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¶
現在讓我們使用 make_grid 將圖像(特別是網格)寫入我們的 TensorBoard。
# 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
從命令列執行,然後導航到 https://127.0.0.1:6006 應該會顯示以下內容。

現在您知道如何使用 TensorBoard 了! 然而,這個例子可以在 Jupyter Notebook 中完成 - TensorBoard 真正擅長的是創建互動式可視化。 我們將在接下來介紹其中一個,並在本教學結束時介紹更多。
3. 使用 TensorBoard 檢查模型¶
TensorBoard 的優勢之一是它能夠可視化複雜的模型結構。 讓我們可視化我們建立的模型。
writer.add_graph(net, images)
writer.close()
現在重新整理 TensorBoard 後,您應該會看到一個「Graphs」標籤,如下所示

繼續並雙擊「Net」以展開它,查看構成模型的個別操作的詳細檢視。
TensorBoard 有一個非常方便的功能,可以將高維資料(例如影像資料)可視化為較低的維度空間; 我們將在接下來介紹這一點。
4. 在 TensorBoard 中加入「投影器」(Projector)¶
我們可以透過 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」,以及啟用「夜間模式」,這會讓圖片更容易觀看,因為它們的背景是白色的。

現在我們已經徹底檢查了我們的資料,讓我們展示 TensorBoard 如何讓追蹤模型訓練和評估更加清晰,從訓練開始。
5. 使用 TensorBoard 追蹤模型訓練¶
在先前的範例中,我們只是每 2000 次迭代印出模型的 running loss。 現在,我們將改為將 running loss 記錄到 TensorBoard 中,並透過 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')
你現在可以查看 scalars 標籤,以查看在 15,000 次訓練迭代中繪製的 running loss。

此外,我們可以查看模型在整個學習過程中對任意批次所做的預測。 請參閱「Images」標籤,並在「predictions vs. actuals」可視化下方滾動以查看此內容; 這向我們表明,例如,僅經過 3000 次訓練迭代後,模型已經能夠區分視覺上不同的類別,例如襯衫、運動鞋和外套,儘管它不像稍後在訓練中那樣有信心。

在先前的教學課程中,我們在模型訓練完成後查看了每個類別的準確度; 在這裡,我們將使用 TensorBoard 繪製每個類別的精確度-召回率曲線(很好的解釋 here)。
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% 的「曲線下面積」,而在其他類別上,這個面積較小。

這就是 TensorBoard 和 PyTorch 與其整合的介紹。 當然,你可以在你的 Jupyter Notebook 中完成 TensorBoard 所做的一切,但使用 TensorBoard,你將獲得預設為互動式的視覺效果。