Pytorch 60分钟入门之(四) TRAINING A CLASSIFIER 训练一个分类器
目录
- TRAINING A CLASSIFIER 训练一个分类器
- 数据呢?
- Training an image classifier 训练一个图像分类器
- 1. 载入和归一化CIFAR10
- 2. Define a Convolutional Neural Network 定义一个卷积神经网络
- 3. Define a Loss function and optimizer 定义一个loss函数和优化器
- 4. Train the network 训练网络
- 5. Test the network on the test data 用测试数据测试网络
- Training on GPU GPU上训练
- Training on multiple GPUs 在多GPU上训练.
- Where do I go next? 下面做什么?
TRAINING A CLASSIFIER 训练一个分类器
就这样. 你已经知道怎样定义神经网络, 计算loss和更新网络权重.
现在你可能会想:
数据呢?
一般, 当处理图片, 文本, 音频或者视频数据时, 你可以使用标准的python包,将数据载入为numpy array. 然后你可以将array转化为torch.*Tensor
.
对于图片, Pillow, OpenCV之类的包较为有用.
对于音频, 可以用scipy和librosa
对于文本, 基于原生Python或Cython的载入功能, NLTK和SpaCy之类的较为有用.
特别对于视觉(vision), 我们创建了一个包叫torchvision
. 它有常用datasets(如ImageNet, CIFAR10, MNIST等)的数据载入工具(data loader)和图片转换工具, 也就是torchvision.datasets
和torch.utils.data.DataLoader
.
用起来很方便.
这个教程里. 我们用CIFAR10数据库. 有 ‘airplane’, ‘automobile’, ‘bird’, ‘cat’, ‘deer’, ‘dog’, ‘frog’, ‘horse’, ‘ship’, ‘truck’十个类别的图片. 图片3x32x32. 也就是3通道, 32x32大小.
Training an image classifier 训练一个图像分类器
步骤:
- 用
torchvision
载入和归一化训练和测试数据, - 定义卷积神经网络(CNN)
- 定义loss函数
- 训练
- 测试
1. 载入和归一化CIFAR10
使用torchvision
, 很简单.
import torch
import torchvision
import torchvision.transforms as transforms
torchvision
的输出是PILImage, 范围[0,1]. 我们将其转化为归一化到[-1, 1]范围的Tensor
.
注意:
如果在Windows上出现BrokenPipeError
, 将torch.utils.data.DataLoader()
的num_worker
置为0.
transform = transforms.Compose([transforms.ToTensor(),transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])trainset = torchvision.datasets.CIFAR10(root='./data', train=True,download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=4,shuffle=True, num_workers=2)testset = torchvision.datasets.CIFAR10(root='./data', train=False,download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=4,shuffle=False, num_workers=2)classes = ('plane', 'car', 'bird', 'cat','deer', 'dog', 'frog', 'horse', 'ship', 'truck')
Out:
Downloading https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz to ./data/cifar-10-python.tar.gz
Extracting ./data/cifar-10-python.tar.gz to ./data
Files already downloaded and verified
让我们看看训练数据什么样.
import matplotlib.pyplot as plt
import numpy as np# functions to show an imagedef imshow(img):img = img / 2 + 0.5 # unnormalizenpimg = img.numpy()plt.imshow(np.transpose(npimg, (1, 2, 0)))plt.show()# get some random training images
dataiter = iter(trainloader)
images, labels = dataiter.next()# show images
imshow(torchvision.utils.make_grid(images))
# print labels
print(' '.join('%5s' % classes[labels[j]] for j in range(4)))
../../_images/sphx_glr_cifar10_tutorial_001.png
Out:
dog bird ship dog
2. Define a Convolutional Neural Network 定义一个卷积神经网络
将之前定义的网络拷贝过来, 修改为接收3通道图片(之前的接收单通道).
import torch.nn as nn
import torch.nn.functional as Fclass Net(nn.Module):def __init__(self):super(Net, self).__init__()self.conv1 = nn.Conv2d(3, 6, 5)self.pool = nn.MaxPool2d(2, 2)self.conv2 = nn.Conv2d(6, 16, 5)self.fc1 = nn.Linear(16 * 5 * 5, 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 * 5 * 5)x = F.relu(self.fc1(x))x = F.relu(self.fc2(x))x = self.fc3(x)return xnet = Net()
3. Define a Loss function and optimizer 定义一个loss函数和优化器
用分类交叉熵和带动量(momentum)的SGD.
import torch.optim as optimcriterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
4. Train the network 训练网络
有意思的地方来了. 我们简单地在数据迭代器(data iterator)上循环遍历, 将输入喂给网络并优化.
for epoch in range(2): # loop over the dataset multiple timesrunning_loss = 0.0for i, data in enumerate(trainloader, 0):# get the inputs; data is a list of [inputs, labels]inputs, labels = data# zero the parameter gradientsoptimizer.zero_grad()# forward + backward + optimizeoutputs = net(inputs)loss = criterion(outputs, labels)loss.backward()optimizer.step()# print statisticsrunning_loss += loss.item()if i % 2000 == 1999: # print every 2000 mini-batchesprint('[%d, %5d] loss: %.3f' %(epoch + 1, i + 1, running_loss / 2000))running_loss = 0.0print('Finished Training')
Out:
[1, 2000] loss: 2.235
[1, 4000] loss: 1.902
[1, 6000] loss: 1.674
[1, 8000] loss: 1.571
[1, 10000] loss: 1.529
[1, 12000] loss: 1.478
[2, 2000] loss: 1.389
[2, 4000] loss: 1.391
[2, 6000] loss: 1.359
[2, 8000] loss: 1.335
[2, 10000] loss: 1.330
[2, 12000] loss: 1.289
Finished Training
保存训练好的模型:
PATH = './cifar_net.pth'
torch.save(net.state_dict(), PATH)
这里有更多的保存模型的细节.
5. Test the network on the test data 用测试数据测试网络
我们已经训练了两轮了, 我们看看网络是否学到东西了.
我们将模型输出的结果和真实结果(ground-truth)作比较. 如果预测是正确的, 我们将这个sample加到正确预测的list中.
dataiter = iter(testloader)
images, labels = dataiter.next()
# print images
imshow(torchvision.utils.make_grid(images))
print('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4)))
Out:
GroundTruth: cat ship ship plane
然后, 重新载入保存的模型(注意: 保存和重新载入模型不是必要的, 我们这里只是为了说明怎样做):
net = Net()
net.load_state_dict(torch.load(PATH))
好, 我们来看看模型分类结果如何:
outputs = net(images)
输出是10类的置信度(energy). 某一类的置信度越高, 网络认为图片是此类的可能性越大. 所以, 我们来获取最高的置信度:
_, predicted = torch.max(outputs, 1)print('Predicted: ', ' '.join('%5s' % classes[predicted[j]]for j in range(4)))
Out:
Predicted: cat ship ship ship
结果还不错, 我们来看看整个数据集上的表现:
correct = 0
total = 0
with torch.no_grad():for data in testloader:images, labels = dataoutputs = net(images)_, predicted = torch.max(outputs.data, 1)total += labels.size(0)correct += (predicted == labels).sum().item()print('Accuracy of the network on the 10000 test images: %d %%' % (100 * correct / total))
Out:
Accuracy of the network on the 10000 test images: 53 %
看起来比随机猜测要好. 随机猜测正确率是10%. 看来网络确实学到了东西.
看看哪些类表现好, 哪些类表现不好:
class_correct = list(0. for i in range(10))
class_total = list(0. for i in range(10))
with torch.no_grad():for data in testloader:images, labels = dataoutputs = net(images)_, predicted = torch.max(outputs, 1)c = (predicted == labels).squeeze()for i in range(4):label = labels[i]class_correct[label] += c[i].item()class_total[label] += 1for i in range(10):print('Accuracy of %5s : %2d %%' % (classes[i], 100 * class_correct[i] / class_total[i]))
Out:
Accuracy of plane : 56 %
Accuracy of car : 74 %
Accuracy of bird : 30 %
Accuracy of cat : 29 %
Accuracy of deer : 57 %
Accuracy of dog : 37 %
Accuracy of frog : 73 %
Accuracy of horse : 62 %
Accuracy of ship : 56 %
Accuracy of truck : 53 %
好了, 接下来做什么呢?
怎样在GPU上跑神经网络呢?
Training on GPU GPU上训练
正如将Tensor
转到GPU上一样, 你可以将网络转到GPU上.
如果CUDA有效的话, 将device定义为第一个可用的cuda设备.
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")# Assuming that we are on a CUDA machine, this should print a CUDA device:print(device)
Out:
cuda:0
剩下的部分, 我们认为device就是CUDA device.
然后这些方法将会递归地遍历我们的模型部件(module)并将他们的参数和buffer转为CUDA tensor:
net.to(device)
记住, 你必须要在每一步中将输入图像和目标输出都转到GPU上:
inputs, labels = data[0].to(device), data[1].to(device)
为什么我们有看到很大的速度提升? 因为你的模型太小了.
练习: 尝试增大网络宽度(第一个nn.Conv2d
的第二个参数, 第二个nn.Conv2d
的第一个参数, 两者要相等), 看看提速效果如何.
目标达成:
- 在高层(high level)上理解Pytorch Tensor库和神经网络.
- 训练一个分类图片的小神经网络.
Training on multiple GPUs 在多GPU上训练.
如果你想用多块GPU训练, 请看: Data Parallelism.
Where do I go next? 下面做什么?
- 训练网络玩游戏
- 在imagenet上训练ResNet
- 使用生成对抗网络GAN训练人脸生成器
- 使用循环LSTM网络训练词级语言模型
- 更多例子
- 更多教程
- 论坛讨论
- Slack交流
Total running time of the script: ( 3 minutes 29.428 seconds)
Pytorch 60分钟入门之(四) TRAINING A CLASSIFIER 训练一个分类器相关推荐
- PyTorch 60 分钟入门教程中的一些疑惑
PyTorch 60 分钟入门教程中的一些疑惑 自动微分 参考: PyTorch 60 分钟入门教程. 自动微分 y.data.norm()指的是y的范数,举一个例子 假设x是[1.,2.,3.],则 ...
- PyTorch基础教程学习笔记(八):训练一个分类器
数据应该怎么办呢? 通常来说,当必须处理图像.文本.音频或视频数据时,可以使用python标准库将数据加载到numpy数组里.然后将这个数组转化成torch.*Tensor. 对于图片,有Pillow ...
- 【深度学习】翻译:60分钟入门PyTorch(四)——训练一个分类器
前言 原文翻译自:Deep Learning with PyTorch: A 60 Minute Blitz 翻译:林不清(https://www.zhihu.com/people/lu-guo-92 ...
- TRAINING A CLASSIFIER训练分类器(pytorch官网60分钟闪电战第四节)
Training an image classifier训练图像分类器 本节没有写在GPU和多个GPU上训练的代码,主要写了训练图像分类器,分为5个步骤 文章目录 一.Loading and norm ...
- 可下载:60分钟入门PyTorch(中文翻译全集)
来源:机器学习初学者本文约9500字,建议阅读20分钟官网教程翻译:60分钟入门PyTorch(全集) 前言 原文翻译自:Deep Learning with PyTorch: A 60 Minute ...
- 【深度学习】翻译:60分钟入门PyTorch(三)——神经网络
前言 原文翻译自:Deep Learning with PyTorch: A 60 Minute Blitz 翻译:林不清(https://www.zhihu.com/people/lu-guo-92 ...
- (翻译)60分钟入门深度学习工具-PyTorch
60分钟入门深度学习工具-PyTorch 作者:Soumith Chintala 原文翻译自: https://pytorch.org/tutorials/beginner/deep_learning ...
- 【转载】PYTORCH整理:60分钟入门
PYTORCH整理:60分钟入门 官方地址:Deep Learning with PyTorch: A 60 Minute Blitz,感谢作者: Soumith Chintala 转载出处:Gaus ...
- 60分钟入门深度学习工具PyTorch
「免费学习 60+ 节公开课:投票页面,点击讲师头像」 作者 | Soumith Chintala 中文翻译.注释制作 | 黄海广 配置环境:PyTorch 1.3,python 3.7, 主机:显卡 ...
最新文章
- VMware Workstation 9下基于Ubuntu 12.10服务器版本的Hadoop集群的配置
- java poi 更新excel_在Java Apache POI中更新现有的Excel文件
- django-web聊天
- spring boot 入门-使用spring boot构建简单应用
- cocos2d 走动椭圆
- 缓存和数据库一致性问题,看这篇就够了
- oracle exp调过坏块,无备份坏块处理(跳过方式)
- (转)利用AIR的ServerSocket类让 AIR 做socket服务器
- linux安装windows常用中文字体库
- 【微课堂】汽车软件工程解决方案(现场实录)
- plc应用与c语言编程区别,PLC编程与应用入门基础知识
- 图像匹配论文与方法超全整理
- couchbase java view_基于Java的Couchbase使用入门
- 基于vue+element的时间、农历、和日历的选择
- git恢复某个文件到上一个提交版本
- 网卡驱动卸载后一直安装失败的问题成功解决
- Mac苹果电脑怎样安装Python
- 小A是大四的学生,还有半年就要毕业了
- 【C语言】控制台窗口图形界面编程(八):键盘事件
- 笨办法学习python3 ex3