visualizing
PyTorch integrates with TensorBoard, a tool designed for visualizing the results of neural network training runs.
In this tutorial, we’ll learn how to:
- 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
1. Get the datasets
我们以CIFAR-10 tutorial中的模板代码开始
# 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)))
2. Define the model
(We’ll define a similar model architecture from that tutorial, making only minor modifications to account for the fact that the images are now one channel instead of three and 28x28 instead of 32x32:)图像现在是一个通道而不是三个,并且是28x28而不是32x32:
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# input shape (1, 28, 28)
self.conv1 = nn.Conv2d(1, 6, 5) # in_channels, out_channels, kernel_size
# 28 - 5 + 1 = 24
# =>(6 * 24 *24)
self.pool = nn.MaxPool2d(2, 2) # 在 2x2 空间里向下采样, output shape (6, 12, 12)
self.conv2 = nn.Conv2d(6, 16, 5)
# =>(16 * 8 * 8)
self.fc1 = nn.Linear(16 * 4 * 4, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
# (1*28*28)
x = self.pool(F.relu(self.conv1(x)))# =>(6*12*12)
x = self.pool(F.relu(self.conv2(x)))# =>(16 * 4 * 4)
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()