【PyTorch】教程:可视化数据,模型和训练过程

可视化数据、模型和训练过程

【目标】

  • 学习读入数据并转换
  • 建立 TensorBoard
  • 写入 TensorBoard
  • 使用 TensorBoard 检查模型架构
  • 使用 TensorBoard 创建可视化交互版本
    • 检查训练数据的几种方法
    • 跟踪训练中的模型性能
    • 训练后模型性能的评估

开始

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

## 转换
transform = transforms.Compose(
    [transforms.ToTensor(),
    transforms.Normalize((0.5), (0.5))]
)

## 数据集
trainset = torchvision.datasets.FashionMNIST(
    root = "../../datasets",
    download = True, 
    train = True, 
    transform = transform
)

testset = torchvision.datasets.FashionMNIST(
    root = "../../datasets",
    download = True,
    train = False,
    transform = transform
)

## dataloader
trainloader = torch.utils.data.DataLoader(trainset, batch_size = 4, shuffle = True)
testloader = torch.utils.data.DataLoader(testset, batch_size = 4, shuffle = True)

## 类别
classes = ('T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
        'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle Boot')


## 显示数据
def matplotlib_show(img, one_channel=False):
    if one_channel:
        img = img.mean(dim=0)
    
    img = img / 2 + 0.5
    npimg = img.numpy()
    
    if one_channel:
        plt.imshow(npimg, cmap='Greys')
    else:
        plt.imshow(np.transpose(npimg, (1, 2, 0)))


## 模型
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(1, 6, 5)
        self.pool1 = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.pool2 = nn.MaxPool2d(2, 2)
        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.pool1(F.relu(self.conv1(x)))
        x = self.pool2(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()


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

建立 TensorBoard

from torch.utils.tensorboard import SummaryWriter

writer = SummaryWriter("../runs/fashion_mnist_exp")

写入 TensorBoard

让我们将图像写入到 TensorBoard, 用 make_grid

dataiter = iter(trainloader)
images, labels = next(dataiter)

image_grid = torchvision.utils.make_grid(images)

matplotlib_show(image_grid, one_channel=True)

writer.add_image('images', image_grid)

jupyter notebook 可以支持 TensorBoard.
在这里插入图片描述

  • 运行完后,点击 启动TensorBoard 会话(也可以在命令行执行)
  • 如果是脚本文件的话,通过命令行执行 tensorboard --logdir=runsruns 为路径名

在这里插入图片描述

使用 TensorBoard 检查模型架构

TensorBoard 一个非常强的功能是可视化复杂的模型结构。

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

执行以上语句,并刷新 TensorBoard , 就可以看到多了一个 GRAPH

在这里插入图片描述

双击 Net 就可以展开网络结构;TensorBoard 有一个非常方便的功能就是在低维空间可视化高维数据。

在这里插入图片描述

添加一个 Projector 到 TensorBoard 中

可视化高维数据在低维空间的表达 add_embedding 方法。

在这里插入图片描述

跟踪模型训练

现在,我们将把运行 loss 记录到 TensorBoard ,并查看模型通过 plot_classes_preds 函数所做的预测。

def images_to_probs(net, images):
    '''
    Generates predictions and corresponding probabilities from a trained
    network and a list of images
    '''
    outputs = net(images)
    
    _, preds_tensor = torch.max(outputs, 1)
    preds = np.squeeze(preds_tensor.numpy())
    
    return preds, [F.softmax(el, dim=0)[i].item() for i, el in zip(preds, outputs)]
    

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_show(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
running_loss = 0.0
for epoch in range(10):  # 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')

在这里插入图片描述

在这里插入图片描述

模型评估

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)

def add_pr_curve_tensorboard(class_index, test_probs, test_label, global_step = 0):
    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 pr curves
for i in range(len(classes)):
    add_pr_curve_tensorboard(i, test_probs, test_label)

在这里插入图片描述

可以在上面的菜单栏中看到多了一个菜单 PR CURVES, 每个类别的 PR 曲线都不一样。

【参考】

VISUALIZING MODELS, DATA, AND TRAINING WITH TENSORBOARD

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黄金旺铺

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值