1.读取数据并进行适当的转换。
#导入库
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
import matplotlib.pyplot as plt
import numpy as np
#加载数据集
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5), (0.5))
])
trainset = torchvision.datasets.FashionMNIST(root = './data', train = True, transform = transform, download = True)
testset = torchvision.datasets.FashionMNIST(root = './data', train = False, transform = transform, download = True)
trainloader = torch.utils.data.DataLoader(dataset = trainset, shuffle = True, batch_size = 4, num_workers = 2)
testloader = torch.utils.data.DataLoader(dataset = testset, shuffle = False, batch_size = 4, num_workers = 2)
classes = ('T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle Boot')
2.定义辅助函数-图像显示
def imshow(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)))
3.定义神经网络
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()
4.定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr = 0.001, momentum = 0.9)
5.设置Tensorboard
from torch.utils.tensorboard import SummaryWriter
writer = SummaryWriter('runs/fashion_mnist_experiment_1')
6.写入Tensorboard
dataiter = iter(trainloader)
images, labels = dataiter.next()
img_grid = torchvision.utils.make_grid(images)
imshow(img_grid, one_channel = True)
writer.add_image('four_fashion_mnist_images', img_grid)
7.在jupyter notebook中显示tensorboard
%reload_ext tensorboard
%tensorboard --logdir=./runs --port=6006
图像无法显示,且提示端口被占用时,需要删除.tensorbard-info文件夹中的所有文件。