import 模块

  1. from __future__ import print_function

future 看做是一个 Python 专门存放新特性的模块
import print_function 之后,在 Python2.x 中也需要使用 Python3.xprint() 来输出

  1. import torch
  2. import torchvision
  3. import torch.nn as nn
  4. import torch.nn.functional as F
  5. import torch.optim as optim
  6. import matplotlib.pyplot as plt
  7. import numpy as np
  8. from torchvision import datasets, transforms
  9. from torch.utils.data import Dataset, DataLoader
  • 引入 root package
  • The torchvision package consists of popular datasets, model architectures, and common image transformations for computer vision
    • torchvision.datasets : MNIST, CIFAR, etc.
    • torchvision.transforms : torchvision.transforms are common image transformations. They can be chained together using torchvision.transforms.Compose(transforms).
  • torch.nn 神经网络工具箱(layer是由class定义) : Conv2d, MaxPool2d, etc.
  • torch.nn.functionaltorch.nn 相似,但它的layer由def定义。
  • 引入 optimizer
  • 引入绘图模块
  • 引入 numpy 模块
  • 引入图片转换模块
  • 引入数据模块

torch.utils.data.Dataset 是数据集的抽象类,所有的 torchvision.datasets 都是 torch.utils.data.Dataset 的子类。

torch.nn.functional是确定不变的运算公式,如果模型有可学习的参数,最好使用torch.nn中nn.Module对应的相关layer。比如Relu其实没有可学习的参数,只是进行一个运算而已,所以使用的就是functional中的relu函数,而卷积层和全连接层都有可学习的参数,所以用的是nn.Module中的类。

数据处理

  1. batch_size = 4
  2. epoch_size = 3
  1. # 对数据进行预处理
  2. transform = transforms.Compose(
  3. [transforms.ToTensor(), # range [0, 255] -> [0.0,1.0]
  4. transforms.Normalize((0.5, 0.5, 0.5), # 以均值和标准差进行标准化(C=3)
  5. (0.5, 0.5, 0.5))])
  6. trainset = datasets.CIFAR10(root='./data/cifar10', # 相对目录
  7. train=True, # True 则为训练集
  8. download=True, # 目录中数据集不存在则下载
  9. transform=transform)
  10. trainloader = DataLoader(trainset,
  11. batch_size=batch_size,
  12. shuffle=True, # 将数据打乱
  13. num_workers=0) # 进程数
  14. testset = datasets.CIFAR10(root='./data/cifar10',
  15. train=False,
  16. download=True,
  17. transform=transform)
  18. testloader = DataLoader(testset,
  19. batch_size=batch_size,
  20. shuffle=False,
  21. num_workers=0)
  22. classes = ('plane', 'car', 'bird', 'cat',
  23. 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
  1. Files already downloaded and verified
  2. Files already downloaded and verified

torchvision.transforms 中的函数

  • Resize:把给定的图片resize到given size
  • Normalize:Normalized an tensor image with mean and standard deviation
  • ToTensor:convert a PIL image to tensor (HWC) in range [0,255] to a torch.Tensor(CHW) in the range [0.0,1.0]
  • ToPILImage: convert a tensor to PIL image
  • Scale:目前已经不用了,推荐用Resize
  • CenterCrop:在图片的中间区域进行裁剪
  • RandomCrop:在一个随机的位置进行裁剪
  • RandomHorizontalFlip:以0.5的概率水平翻转给定的PIL图像
  • RandomVerticalFlip:以0.5的概率竖直翻转给定的PIL图像
  • RandomResizedCrop:将PIL图像裁剪成任意大小和纵横比
  • Grayscale:将图像转换为灰度图像
  • RandomGrayscale:将图像以一定的概率转换为灰度图像
  • FiceCrop:把图像裁剪为四个角和一个中心
  • TenCrop
  • Pad:填充
  • ColorJitter:随机改变图像的亮度对比度和饱和度
  1. def imshow(img):
  2. img = img / 2 + 0.5 # 去标准化
  3. npimg = img.numpy() # 将torch.FloatTensor 转换为numpy
  4. # plt.axis("off") # 不显示坐标尺寸
  5. plt.imshow(np.transpose(npimg, (1, 2, 0))) # 进行转置
  6. plt.show() # 显示图片
  7. # get some random training images
  8. dataiter = iter(trainloader)
  9. images, labels = dataiter.next()
  10. # show images
  11. imshow(torchvision.utils.make_grid(images))
  12. # print labels
  13. print(' '.join('%11s' % classes[labels[j]] for j in range(batch_size)))

output_10_0.png

  1. bird frog horse truck

错误:

  1. [Errno 32] Broken pipe

原因:

  1. trainloader = DataLoader(trainset,
  2. batch_size=batch_size,
  3. shuffle=True, # 将数据打乱
  4. num_workers=2) # 进程数

方法:

设置 num_workers = 0

numpy.transpose 说明

如果 x = np.arange(24).reshape((2, 3, 4))(维度/通道为 2,行数为 3,列数为 4),
x 按照某一顺序进行转置(numpy.transpose):

  • np.transpose(x, (2, 0, 1)) : shape(2,3,4) -> shape(4,2,3)
  • np.transpose(x, (0, 1, 2)) : shape(2,3,4) -> shape(2,3,4)

查看列表的维度

np.array(images).shape #(batch_size, C, H, W)
(4, 3, 32, 32)

定义网络结构

  1. class Net(nn.Module): # nn.Module 是所有神经网络的基类,自定义的网络应该继承自它
  2. def __init__(self):
  3. super(Net, self).__init__()
  4. self.conv1 = nn.Conv2d(3, 6, 5)
  5. self.pool = nn.MaxPool2d(2, 2)
  6. self.conv2 = nn.Conv2d(6, 16, 5)
  7. self.fc1 = nn.Linear(16 * 5 * 5, 120)
  8. self.fc2 = nn.Linear(120, 84)
  9. self.fc3 = nn.Linear(84, 10)
  10. def forward(self, x):
  11. x = self.pool(F.relu(self.conv1(x)))
  12. x = self.pool(F.relu(self.conv2(x)))
  13. x = x.view(-1, 16 * 5 * 5)
  14. x = F.relu(self.fc1(x))
  15. x = F.relu(self.fc2(x))
  16. x = self.fc3(x)
  17. return x
  1. device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
  2. net = Net().to(device)
  1. # 定义损失函数和优化器
  2. criterion = nn.CrossEntropyLoss() # 交叉熵损失
  3. optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9) # SGD with momentum

训练

  1. import os
  2. if os.path.exists('./model/learn0.pt'):
  3. net.load_state_dict(torch.load('./model/learn0.pt'))
  4. net.eval()
  5. else:
  6. for epoch in range(epoch_size): # loop over the dataset multiple times
  7. running_loss = 0.0
  8. for i, data in enumerate(trainloader, 0):
  9. # get the inputs; data is a list of [inputs, labels]
  10. inputs, labels = inputs, labels = data[0].to(device), data[1].to(device)
  11. # zero the parameter gradients
  12. optimizer.zero_grad()
  13. # forward + backward + optimize
  14. outputs = net(inputs)
  15. loss = criterion(outputs, labels)
  16. loss.backward()
  17. optimizer.step()
  18. # print statistics
  19. running_loss += loss.item()
  20. if i % 2000 == 1999: # print every 2000 mini-batches
  21. print('[%d, %5d] loss: %.3f' %
  22. (epoch + 1, i + 1, running_loss / 2000))
  23. running_loss = 0.0
  24. print('Finished Training')
  1. # tensorboard
  2. from torch.autograd import Variable
  3. from tensorboardX import SummaryWriter
  4. dumpy_input = Variable(torch.rand(1,3 ,32 ,32 ))
  5. with SummaryWriter('runs/learn-0/') as W:
  6. W.add_graph(net,(dumpy_input,))
  7. import torch
  8. import torchvision
  9. from tensorboardX import SummaryWriter
  10. from torchvision import datasets, transforms
  11. # Writer will output to ./runs/ directory by default
  12. writer = SummaryWriter('runs/unimportant/')
  13. transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])
  14. trainset = datasets.MNIST('mnist_train', train=True, download=True, transform=transform)
  15. trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)
  16. model = torchvision.models.resnet50(False)
  17. # Have ResNet model take in grayscale rather than RGB
  18. model.conv1 = torch.nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3, bias=False)
  19. images, labels = next(iter(trainloader))
  20. grid = torchvision.utils.make_grid(images)
  21. writer.add_image('images', grid, 0)
  22. writer.add_graph(model, images)
  23. writer.close()

测试

  1. # 测试集准备
  2. dataiter = iter(testloader)
  3. images, labels = dataiter.next()
  4. # print images
  5. print('GroundTruth:')
  6. imshow(torchvision.utils.make_grid(images))
  7. print(' '.join('%11s' % classes[labels[j]] for j in range(4)))
  8. # 测试一次
  9. outputs = net(images.to(device))
  10. _, predicted = torch.max(outputs, 1)
  11. print('Predicted:\n', ' '.join('%11s' % classes[predicted[j]]
  12. for j in range(4)))
  13. # 在整个测试集上测试
  14. correct = 0
  15. total = 0
  16. with torch.no_grad(): # 不进行梯度计算,减小了内存的占用,一般此时不进行BP的计算
  17. for data in testloader:
  18. images, labels = data[0].to(device),data[1].to(device)
  19. outputs = net(images)
  20. _, predicted = torch.max(outputs.data, 1)
  21. total += labels.size(0)
  22. correct += (predicted == labels).sum().item()
  23. print('Accuracy of the network on the %d test images: %d %%' % (batch_size*len(testloader),
  24. 100 * correct / total))
  1. GroundTruth:

output_21_1.png

  1. cat ship ship plane
  2. Predicted:
  3. cat ship ship plane
  4. Accuracy of the network on the 10000 test images: 57 %
  1. # 模型对各个class分类的表现
  2. class_correct = list(0. for i in range(10))
  3. class_total = list(0. for i in range(10))
  4. with torch.no_grad():
  5. for data in testloader:
  6. images, labels = data[0].to(device), data[1].to(device)
  7. outputs = net(images)
  8. _, predicted = torch.max(outputs, 1) # _ 表示不重要,可直接取[1]赋值
  9. c = (predicted == labels).squeeze()
  10. for i in range(4):
  11. label = labels[i]
  12. class_correct[label] += c[i].item()
  13. class_total[label] += 1
  14. for i in range(10):
  15. print('Accuracy of %5s : %2d %%' % (
  16. classes[i], 100 * class_correct[i] / class_total[i]))
  1. Accuracy of plane : 62 %
  2. Accuracy of car : 68 %
  3. Accuracy of bird : 51 %
  4. Accuracy of cat : 39 %
  5. Accuracy of deer : 51 %
  6. Accuracy of dog : 40 %
  7. Accuracy of frog : 62 %
  8. Accuracy of horse : 52 %
  9. Accuracy of ship : 80 %
  10. Accuracy of truck : 62 %

可视化

BUG

  • 必须先安装软件 graphviz 整个流程才可以继续下去
  • 安装软件 -> 添加环境变量 -> pip install package
  • 因为需要添加环境变量,所以添加完之后要关闭打开 notebook 的 cmd 窗口,重新启动才能 work。
  1. import tensorwatch as tw
  2. # from torchviz import make_dot
  3. tw.draw_model(net.to('cpu'),[1,3,32,32])

output_25_0.svg

模型保存与读取

  1. # 模型保存
  2. torch.save(net.state_dict(),'./model/learn0.pt')
  1. # 模型读取
  2. model = Net().to('cuda')
  3. model.load_state_dict(torch.load('./model/learn0.pt'))
  4. model.eval()

变量测试

  1. # 测试 python
  2. # help(torch.no_grad)
  3. # print(torch.cuda.device_count())
  4. print(net.parameters())
  1. # 测试 shell
  2. !nvidia-smi

格式转换

  1. # !jupyter nbconvert --to html --template full learn.ipynb
  2. # !jupyter nbconvert --to markdown learn.ipynb
  3. !jupyter nbconvert --to html --template full learn-0.ipynb
  4. !jupyter nbconvert --to markdown learn-0.ipynb