此教程的目标:
- 更高层次地理解Pytorch的Tensor库以及神经网络。
- 训练一个小的神经网络模型用于分类图像。
确保你安装了 torch 和 torchvision 包。
- PyTorch 是什么
- Autograd:自动求导
- 神经网络
- 训练分类器
- 数据并行
1 张量tensor
In [1]: import torchIn [2]: x = torch.empty(3,4)In [3]: xOut[3]:tensor([[5.6753e-42, 0.0000e+00, 0.0000e+00, 0.0000e+00],[0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00],[0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00]])In [4]: x = torch.ones(3,4)In [5]: xOut[5]:tensor([[1., 1., 1., 1.],[1., 1., 1., 1.],[1., 1., 1., 1.]])In [54]: torch.zeros(2)Out[54]: tensor([0., 0.])In [55]: torch.zeros(2,)Out[55]: tensor([0., 0.])In [56]: torch.zeros(2,3)Out[56]:tensor([[0., 0., 0.],[0., 0., 0.]])In [57]: torch.zeros(2,3,4)Out[57]:tensor([[[0., 0., 0., 0.],[0., 0., 0., 0.],[0., 0., 0., 0.]],[[0., 0., 0., 0.],[0., 0., 0., 0.],[0., 0., 0., 0.]]])
# 返回均值为0,方差为1的标准正态分布In [8]: x = torch.randn(3,)In [9]: xOut[9]: tensor([0.4476, 0.2597, 0.0523])In [10]: x.shapeOut[10]: torch.Size([3])In [22]: x = torch.randn(3,1)In [23]: xOut[23]:tensor([[-0.9060],[ 2.0127],[-1.3605]])In [24]: x.shapeOut[24]: torch.Size([3, 1])In [11]: x = torch.randn(3,2)In [12]: xOut[12]:tensor([[-0.7473, 1.0257],[ 0.3302, -0.3894],[ 1.1525, 0.3747]])In [13]: x.shapeOut[13]: torch.Size([3, 2])In [14]: x = torch.randn(3,2,4)In [15]: xOut[15]:tensor([[[ 2.0151, 0.9684, 1.6057, 0.1693],[ 1.6014, -0.1547, 0.6339, -2.1830]],[[ 0.2804, -0.3243, -1.3168, 1.1731],[-0.1829, 0.5489, 0.1494, -2.0575]],[[-0.6438, -1.0181, 0.5926, -0.5505],[ 1.2672, 0.8542, 1.5096, 2.5186]]])In [16]: x.shapeOut[16]: torch.Size([3, 2, 4])
# 返回[0,1]之间的均匀分布In [33]: torch.rand(10)Out[33]:tensor([0.2389, 0.8907, 0.3929, 0.0315, 0.5598, 0.4148, 0.6898, 0.6691, 0.0761,0.3793])In [34]: torch.rand(3,4)Out[34]:tensor([[0.0688, 0.6932, 0.1009, 0.1109],[0.7857, 0.9575, 0.7772, 0.1911],[0.8424, 0.4165, 0.3198, 0.5043]])In [35]: torch.rand(3,4,2)Out[35]:tensor([[[0.3173, 0.9806],[0.1815, 0.6252],[0.3163, 0.6357],[0.9688, 0.0951]],[[0.6719, 0.9924],[0.2468, 0.7327],[0.1184, 0.4472],[0.8086, 0.2959]],[[0.4796, 0.9292],[0.1021, 0.9367],[0.2053, 0.0738],[0.6674, 0.9440]]])In [36]: torch.rand(3,)Out[36]: tensor([0.1190, 0.8914, 0.4051])In [37]: torch.rand(3,1)Out[37]:tensor([[0.8033],[0.2413],[0.2629]])
# randintIn [41]: torch.randint(0,8,[3,3])Out[41]:tensor([[6, 4, 6],[4, 0, 1],[5, 5, 5]])In [42]: torch.randint(8,[3,3])Out[42]:tensor([[2, 2, 6],[6, 1, 7],[7, 7, 7]])In [43]: torch.randint(8,[3,1])Out[43]:tensor([[6],[1],[6]])In [44]: torch.randint(8,[3,])Out[44]: tensor([2, 0, 3])In [45]: torch.randint(8,[3,2,4])Out[45]:tensor([[[1, 6, 2, 7],[4, 7, 4, 4]],[[4, 2, 1, 4],[3, 7, 3, 7]],[[6, 5, 0, 5],[1, 0, 1, 3]]])
# 直接从数据构造张量In [62]: x = torch.tensor(3)In [63]: xOut[63]: tensor(3)In [64]: x = torch.tensor(3,dtype=torch.float32)In [65]: xOut[65]: tensor(3.)In [66]: x = torch.tensor([3,4],dtype=torch.float32)In [67]: xOut[67]: tensor([3., 4.])In [68]: x.shapeOut[68]: torch.Size([2])In [69]: x = torch.tensor([[3,4],[2,5]],dtype=torch.float32)In [70]: xOut[70]:tensor([[3., 4.],[2., 5.]])In [71]: x.shapeOut[71]: torch.Size([2, 2])In [72]: torch.randn_like(x)Out[72]:tensor([[ 0.0315, 0.0971],[-0.7058, 0.5100]])
# 加法In [73]: x = torch.randn(3,4)In [74]: xOut[74]:tensor([[-0.0512, -1.9237, -1.3809, 0.7449],[-1.5901, -2.0461, -0.0884, -0.4058],[-0.5473, 0.0627, 0.9264, -0.5887]])In [75]: y = torch.randn(3,4)In [76]: yOut[76]:tensor([[ 0.3731, -0.2898, 0.6289, 0.8557],[-0.3129, -0.7714, -0.7404, -1.4080],[-0.7252, 2.5395, -2.2563, -0.1399]])In [77]: torch.add(x,y)Out[77]:tensor([[ 0.3219, -2.2136, -0.7520, 1.6006],[-1.9030, -2.8175, -0.8287, -1.8138],[-1.2725, 2.6022, -1.3299, -0.7286]])# 加法:原位/原地操作(in-place)# adds x to yIn [114]: y = torch.randn(3,4)In [115]: yOut[115]:tensor([[-1.1976, 1.4221, -0.0657, 0.9441],[-1.1427, 0.0568, 0.8195, 0.3546],[-0.9769, -0.7331, -0.4502, -0.0629]])In [116]: y.add_(x)Out[116]:tensor([[ 1.7456e-01, 1.9636e+00, -1.1081e+00, 3.4312e-01],[-1.0931e+00, -1.0881e+00, 2.9528e+00, 2.9883e-04],[-2.7004e-01, 4.3621e-01, -2.3812e-01, 3.0546e-01]])In [117]: yOut[117]:tensor([[ 1.7456e-01, 1.9636e+00, -1.1081e+00, 3.4312e-01],[-1.0931e+00, -1.0881e+00, 2.9528e+00, 2.9883e-04],[-2.7004e-01, 4.3621e-01, -2.3812e-01, 3.0546e-01]])
任何一个in-place改变张量的操作后面都固定一个
_。例如x.copy_(y)、x.t_()将更改x
# 改变形状In [123]: yOut[123]:tensor([[ 1.7456e-01, 1.9636e+00, -1.1081e+00, 3.4312e-01],[-1.0931e+00, -1.0881e+00, 2.9528e+00, 2.9883e-04],[-2.7004e-01, 4.3621e-01, -2.3812e-01, 3.0546e-01]])In [124]: y.reshape(2,6)Out[124]:tensor([[ 1.7456e-01, 1.9636e+00, -1.1081e+00, 3.4312e-01, -1.0931e+00,-1.0881e+00],[ 2.9528e+00, 2.9883e-04, -2.7004e-01, 4.3621e-01, -2.3812e-01,3.0546e-01]])In [125]: y.view(2,6)Out[125]:tensor([[ 1.7456e-01, 1.9636e+00, -1.1081e+00, 3.4312e-01, -1.0931e+00,-1.0881e+00],[ 2.9528e+00, 2.9883e-04, -2.7004e-01, 4.3621e-01, -2.3812e-01,3.0546e-01]])In [126]: yOut[126]:tensor([[ 1.7456e-01, 1.9636e+00, -1.1081e+00, 3.4312e-01],[-1.0931e+00, -1.0881e+00, 2.9528e+00, 2.9883e-04],[-2.7004e-01, 4.3621e-01, -2.3812e-01, 3.0546e-01]])In [127]: y.view(-1,3)Out[127]:tensor([[ 1.7456e-01, 1.9636e+00, -1.1081e+00],[ 3.4312e-01, -1.0931e+00, -1.0881e+00],[ 2.9528e+00, 2.9883e-04, -2.7004e-01],[ 4.3621e-01, -2.3812e-01, 3.0546e-01]])
# 将torch的Tensor转化为NumPy数组In [128]: a = torch.ones(2,3)In [129]: aOut[129]:tensor([[1., 1., 1.],[1., 1., 1.]])In [130]: type(a)Out[130]: torch.TensorIn [131]: b = a.numpy()In [132]: bOut[132]:array([[1., 1., 1.],[1., 1., 1.]], dtype=float32)In [133]: type(b)Out[133]: numpy.ndarray
# 将NumPy数组转化为Torch张量# CPU上的所有张量(CharTensor除外)都支持转换为NumPy以及由NumPy转换回来。In [136]: import numpy as npIn [137]: a = np.ones(5)In [138]: b = torch.from_numpy(a)In [139]: aOut[139]: array([1., 1., 1., 1., 1.])In [140]: bOut[140]: tensor([1., 1., 1., 1., 1.], dtype=torch.float64)
# CUDA上的张量# 张量可以使用.to方法移动到任何设备(device)上import torchx = torch.tensor(1.0445)if torch.cuda.is_available():device = torch.device("cuda") # a CUDA device objecty = torch.ones_like(x, device=device) # 直接在GPU上创建tensorx = x.to(device) # 或者使用`.to("cuda")`方法z = x + yprint(z)print(z.to("cpu", torch.double)) # `.to`也能在移动时改变dtype
2 Autograd:自动求导
PyTorch中,所有神经网络的核心是autograd包。先简单介绍一下这个包,然后训练我们的第一个的神经网络。autograd包为张量上的所有操作提供了自动求导机制。它是一个在运行时定义(define-by-run)的框架,这意味着反向传播是根据代码如何运行来决定的,并且每次迭代可以是不同的.
torch.Tensor是这个包的核心类。如果设置它的属性.requires_grad为True,那么它将会追踪对于该张量的所有操作。当完成计算后可以通过调用.backward(),来自动计算所有的梯度。这个张量的所有梯度将会自动累加到.grad属性.要阻止一个张量被跟踪历史,可以调用.detach()方法将其与计算历史分离,并阻止它未来的计算记录被跟踪。为了防止跟踪历史记录(和使用内存),可以将代码块包装在with torch.no_grad():中。在评估模型时特别有用,因为模型可能具有requires_grad = True的可训练的参数,但是我们不需要在此过程中对他们进行梯度计算。对于autograd的实现非常重要:
Function。Tensor和Function互相连接生成了一个非循环图,它编码了完整的计算历史。每个张量都有一个.grad_fn属性,它引用了一个创建了这个Tensor的Function(除非这个张量是用户手动创建的,即这个张量的grad_fn是None)。如果需要计算导数,可以在Tensor上调用.backward()。如果Tensor是一个标量(即它包含一个元素的数据),则不需要为backward()指定任何参数,但是如果它有更多的元素,则需要指定一个gradient参数,它是形状匹配的张量。
张量:torch.tensor
tensor(data, dtype=None, device=None, requires_grad=False) -> Tensor
import torch# 创建一个张量并设置requires_grad=True用来追踪其计算历史x = torch.ones(2,2,requires_grad=True)xtensor([[1., 1.],[1., 1.]], requires_grad=True)# 张量做计算y = x + 2ytensor([[3., 3.],[3., 3.]], grad_fn=<AddBackward>)# y是计算结果,具有grad_fn属性y.grad_fn<AddBackward at 0x7f59643c7a90>z = y*y*3ztensor([[27., 27.],[27., 27.]], grad_fn=<MulBackward>)out = z.mean()outtensor(27., grad_fn=<MeanBackward1>)print(out.shape)print(out.size())torch.Size([])torch.Size([])
梯度
# 链式求导法则:out对x=1的情况下求导x.gradtensor([[4.5000, 4.5000],[4.5000, 4.5000]])

在这种情况下,y不再是标量。torch.autograd不能直接计算完整的雅可比矩阵,但是如果我们只想要雅可比向量积,只需将这个向量作为参数传给backward
v = torch.tensor([0.1, 1.0, 0.0001], dtype=torch.float)y.backward(v)print(x.grad)tensor([ 51.2000, 512.0000, 0.0512])
实际中,为了防止跟踪历史记录(和使用内存),可以将代码块包装在with torch.no_grad():中。在评估模型时特别有用,因为模型可能具有requires_grad = True的可训练的参数,但是我们不需要在此过程中对他们进行梯度计算。也可以通过将代码块包装在 with torch.no_grad(): 中,来阻止autograd跟踪设置了 **.requires_grad=True** 的张量的历史记录。
**
print(x.requires_grad)print((x ** 2).requires_grad)with torch.no_grad():print((x ** 2).requires_grad)TrueTrueFalse
3 神经网络
可以使用torch.nn包来构建神经网络。前面介绍了autograd,nn**包依赖于autograd包来定义模型并对它们求导。一个nn.Module包含各个层和一个forward(input)方法**,该方法返回output。
例如,下面这个神经网络可以对数字进行分类:
这是一个简单的前馈神经网络(feed-forward network)。它接受一个输入,然后将它送入下一层,一层接一层的传递,最后给出输出。
一个神经网络的典型训练过程如下:
- 定义包含一些可学习参数(或者叫权重)的神经网络
- 在输入数据集上迭代
- 通过网络处理输入
- 计算损失(输出和正确答案的距离)
- 将梯度反向传播给网络的参数
- 更新网络的权重,一般使用一个简单的规则:
weight = weight - learning_rate * gradient
我们只需要定义 forward 函数,backward函数会在使用autograd时自动定义,backward函数用来计算导数。
可以在 forward 函数中使用任何针对张量的操作和计算。
一个模型的可学习参数可以通过net.parameters()返回。
定义网络
import torchimport torch.nn as nnimport torch.nn.functional as Fclass Net(nn.Module):def __init__(self):super(Net, self).__init__()# 输入图像channel:1;输出channel:6;5x5卷积核self.conv1 = nn.Conv2d(1, 6, 5)self.conv2 = nn.Conv2d(6, 16, 5)# an affine operation: y = Wx + bself.fc1 = nn.Linear(16 * 5 * 5, 120)self.fc2 = nn.Linear(120, 84)self.fc3 = nn.Linear(84, 10)def forward(self, x):# 2x2 Max poolingx = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))# If the size is a square you can only specify a single numberx = F.max_pool2d(F.relu(self.conv2(x)), 2)x = x.view(-1, self.num_flat_features(x))x = F.relu(self.fc1(x))x = F.relu(self.fc2(x))x = self.fc3(x)return xdef num_flat_features(self, x):size = x.size()[1:] # 除去批大小维度的其余维度num_features = 1for s in size:num_features *= sreturn num_featuresnet = Net()print(net)# 一个模型的可学习参数可以通过net.parameters()返回params = list(net.parameters())print(len(params))print(params[0].size()) # conv1's .weight# 这个网络(LeNet)的期待输入是32x32,如果使用MNIST数据集来训练这个网络,要把图片大小重新调整到32x32input = torch.randn(1, 1, 32, 32)out = net(input)print(out)# 清零所有参数的梯度缓存,然后进行随机梯度的反向传播net.zero_grad()out.backward(torch.randn(1, 10))
输出:
Net((conv1): Conv2d(1, 6, kernel_size=(5, 5), stride=(1, 1))(conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))(fc1): Linear(in_features=400, out_features=120, bias=True)(fc2): Linear(in_features=120, out_features=84, bias=True)(fc3): Linear(in_features=84, out_features=10, bias=True))10torch.Size([6, 1, 5, 5])tensor([[-0.1501, 0.1201, 0.0528, -0.1485, -0.0332, -0.0235, -0.0992, 0.0264,0.0179, -0.0556]], grad_fn=<ThAddmmBackward>)
print(net.parameters)
输出:
<bound method Module.parameters of Net((conv1): Conv2d(1, 6, kernel_size=(5, 5), stride=(1, 1))(conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))(fc1): Linear(in_features=400, out_features=120, bias=True)(fc2): Linear(in_features=120, out_features=84, bias=True)(fc3): Linear(in_features=84, out_features=10, bias=True))>
可视化模型框架——方法一
pip install tensorboardX
demo.py
import torchimport torchvision.utils as vutilsimport numpy as npimport torchvision.models as modelsfrom torchvision import datasetsfrom tensorboardX import SummaryWriterresnet18 = models.resnet18(False)writer = SummaryWriter()sample_rate = 44100freqs = [262, 294, 330, 349, 392, 440, 440, 440, 440, 440, 440]for n_iter in range(100):dummy_s1 = torch.rand(1)dummy_s2 = torch.rand(1)# data grouping by `slash`writer.add_scalar('data/scalar1', dummy_s1[0], n_iter)writer.add_scalar('data/scalar2', dummy_s2[0], n_iter)writer.add_scalars('data/scalar_group', {'xsinx': n_iter * np.sin(n_iter),'xcosx': n_iter * np.cos(n_iter),'arctanx': np.arctan(n_iter)}, n_iter)dummy_img = torch.rand(32, 3, 64, 64) # output from networkif n_iter % 10 == 0:x = vutils.make_grid(dummy_img, normalize=True, scale_each=True)writer.add_image('Image', x, n_iter)dummy_audio = torch.zeros(sample_rate * 2)for i in range(x.size(0)):# amplitude of sound should in [-1, 1]dummy_audio[i] = np.cos(freqs[n_iter // 10] * np.pi * float(i) / float(sample_rate))writer.add_audio('myAudio', dummy_audio, n_iter, sample_rate=sample_rate)writer.add_text('Text', 'text logged at step:' + str(n_iter), n_iter)for name, param in resnet18.named_parameters():writer.add_histogram(name, param.clone().cpu().data.numpy(), n_iter)# needs tensorboard 0.4RC or laterwriter.add_pr_curve('xoxo', np.random.randint(2, size=100), np.random.rand(100), n_iter)dataset = datasets.MNIST('mnist', train=False, download=True)images = dataset.test_data[:100].float()label = dataset.test_labels[:100]features = images.view(100, 784)writer.add_embedding(features, metadata=label, label_img=images.unsqueeze(1))# export scalar data to JSON for external processingwriter.export_scalars_to_json("./all_scalars.json")writer.close()
d:\git\pytorch$ lltotal 76drwxr-xr-x 1 Administrator 197121 0 1月 26 13:06 ./drwxr-xr-x 1 Administrator 197121 0 1月 26 09:18 ../drwxr-xr-x 1 Administrator 197121 0 1月 26 13:47 .idea/-rw-r--r-- 1 Administrator 197121 13774 1月 26 13:06 all_scalars.json-rw-r--r-- 1 Administrator 197121 2103 1月 26 13:01 demo.py-rw-r--r-- 1 Administrator 197121 2200 1月 26 12:16 Digraph.gv-rw-r--r-- 1 Administrator 197121 32970 1月 26 12:16 Digraph.gv.pdfdrwxr-xr-x 1 Administrator 197121 0 1月 26 13:02 mnist/drwxr-xr-x 1 Administrator 197121 0 1月 26 13:02 runs/-rw-r--r-- 1 Administrator 197121 2102 1月 26 13:06 test.pyd:\git\pytorch$ tensorboard --logdir runsc:\anaconda\lib\site-packages\h5py\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.from ._conv import register_converters as _register_convertersTensorBoard 1.12.2 at http://7125messi:6006 (Press CTRL+C to quit)

可视化模型框架——方法二
pip install git+https://github.com/szagoruyko/pytorchviz
——A small package to create visualizations of PyTorch execution graphs
from torchviz import make_dotg=make_dot(net(torch.randn(1, 1, 32, 32)),params=dict(net.named_parameters()))g.view()
会生成一个PDF文件
torch.Tensor`` - 一个多维数组,支持诸如``backward()等的自动求导操作,同时也保存了张量的梯度。nn.Module - 神经网络模块。是一种方便封装参数的方式,具有将参数移动到GPU、导出、加载等功能。nn.Parameter`` - 张量的一种,当它作为一个属性分配给一个``Module``时,它会被自动注册为一个参数。autograd.Function`` - 实现了自动求导前向和反向传播的定义,每个``Tensor``至少创建一个``Function``节点,该节点连接到创建``Tensor``的函数并对其历史进行编码。
损失函数
一个损失函数接受一对(output, target)作为输入,计算一个值来估计网络的输出和目标值相差多少。
nn包中有很多不同的损失函数。``nn.MSELoss``是比较简单的一种,它计算输出和目标的均方误差(mean-squared error)。
output = net(input)target = torch.randn(10) # a dummy target, for exampletarget = target.view(1, -1) # make it the same shape as outputcriterion = nn.MSELoss()loss = criterion(output, target)print(loss)
输出:
tensor(1.0263, grad_fn=<MseLossBackward>)
如果使用loss的.grad_fn属性跟踪反向传播过程,会看到计算图如下:
input -> conv2d -> relu -> maxpool2d -> conv2d -> relu -> maxpool2d-> view -> linear -> relu -> linear -> relu -> linear-> MSELoss-> loss
我们调用loss.backward(),整张图开始关于loss微分,图中所有设置了requires_grad=True的张量的.grad属性累积着梯度张量。为了说明这一点,让我们向后跟踪几步:
print(loss.grad_fn) # MSELossprint(loss.grad_fn.next_functions[0][0]) # Linearprint(loss.grad_fn.next_functions[0][0].next_functions[0][0]) # ReLU
输出:
<MseLossBackward object at 0x000002396E9BA518><AddmmBackward object at 0x000002396C8F22B0><AccumulateGrad object at 0x000002396C8F22B0>
反向传播
我们只需要调用loss.backward()来反向传播权重。我们需要清零现有的梯度,否则梯度将会与已有的梯度累加。
现在,我们将调用loss.backward(),并查看conv1层的偏置(bias)在反向传播前后的梯度。
net.zero_grad() # 清零所有参数(parameter)的梯度缓存print('conv1.bias.grad before backward')print(net.conv1.bias.grad)loss.backward()print('conv1.bias.grad after backward')print(net.conv1.bias.grad)
输出:
conv1.bias.grad before backwardtensor([0., 0., 0., 0., 0., 0.])conv1.bias.grad after backwardtensor([-0.0037, -0.0204, 0.0316, -0.0079, 0.0027, -0.0034])
更新权重
最简单的更新规则是随机梯度下降法(SGD):weight = weight - learning_rate * gradient
我们可以使用简单的python代码来实现:
learning_rate = 0.01for f in net.parameters():f.data.sub_(f.grad.data * learning_rate)
然而,在使用神经网络时,可能希望使用各种不同的更新规则,如SGD、Nesterov-SGD、Adam、RMSProp等。为此,我们构建了一个较小的包torch.optim,它实现了所有的这些方法。使用它很简单:
import torch.optim as optim# 创建优化器(optimizer)optimizer = optim.SGD(net.parameters(), lr=0.01)# 在训练的迭代中:optimizer.zero_grad() # 清零梯度缓存output = net(input)loss = criterion(output, target)loss.backward()optimizer.step() # 更新参数
4 训练分类器
通常来说,当必须处理图像、文本、音频或视频数据时,可以使用python标准库将数据加载到numpy数组里。然后将这个数组转化成torch.*Tensor。
- 对于图片,有Pillow,OpenCV等包可以使用
- 对于音频,有scipy和librosa等包可以使用
- 对于文本,不管是原生python的或者是基于Cython的文本,可以使用NLTK和SpaCy
特别对于视觉方面,我们创建了一个包,名字叫torchvision,其中包含了针对Imagenet、CIFAR10、MNIST等常用数据集的数据加载器(data loaders),还有对图片数据变形的操作,即torchvision.datasets和torch.utils.data.DataLoader。
这提供了极大的便利,可以避免编写样板代码。
在这个教程中,我们将使用CIFAR10数据集,它有如下的分类:“飞机”,“汽车”,“鸟”,“猫”,“鹿”,“狗”,“青蛙”,“马”,“船”,“卡车”等。在CIFAR-10里面的图片数据大小是3x32x32,即三通道彩色图,图片大小是32x32像素。

训练一个图片分类器
我们将按顺序做以下步骤:
- 通过
torchvision加载CIFAR10里面的训练和测试数据集,并对数据进行标准化 - 定义卷积神经网络
- 定义损失函数
- 利用训练数据训练网络
- 利用测试数据测试网络
使用Jupyter
1.加载并标准化CIFAR10
# 使用torchvision加载CIFAR10import torchimport torchvisionfrom torchvision import transforms# torchvision数据集加载完后的输出是范围在[0, 1]之间的PILImage# 我们将其标准化为范围在[-1, 1]之间的张量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')
Downloading https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz to ./data/cifar-10-python.tar.gz
Files already downloaded and verified
import matplotlib.pyplot as pltimport numpy as np# 输出图像的函数def imshow(img):img = img / 2 + 0.5 # unnormalizenpimg = img.numpy()plt.imshow(np.transpose(npimg, (1, 2, 0)))plt.show()# 随机得到一些训练图片dataiter = iter(trainloader)images, labels = dataiter.next()# 显示图片imshow(torchvision.utils.make_grid(images))# 打印图片标签print(' '.join('%5s' % classes[labels[j]] for j in range(4)))

deer cat cat ship
2.定义卷积神经网络
import torch.nn as nnimport 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.定义损失函数和优化器
# 使用分类的交叉熵损失和随机梯度下降(使用momentum)import torch.optim as optimcriterion = nn.CrossEntropyLoss()optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
4.训练网络
遍历我们的数据迭代器,并且输入“喂”给网络和优化函数
for epoch in range(2): # loop over the dataset multiple timesrunning_loss = 0.0for i, data in enumerate(trainloader, 0):# get the inputsinputs, 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')
输出结果:
[1, 2000] loss: 2.245[1, 4000] loss: 1.885[1, 6000] loss: 1.714[1, 8000] loss: 1.612[1, 10000] loss: 1.571[1, 12000] loss: 1.491[2, 2000] loss: 1.400[2, 4000] loss: 1.390[2, 6000] loss: 1.360[2, 8000] loss: 1.321[2, 10000] loss: 1.331[2, 12000] loss: 1.300Finished Training
5.使用测试数据测试网络
# 显示测试集中的图像dataiter = iter(testloader)images, labels = dataiter.next()# 输出图片imshow(torchvision.utils.make_grid(images))print('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4)))

GroundTruth: cat ship ship plane
# (1)看看神经网络认为上面的例子是啥outputs = net(images)# 输出是10个类别的量值,一个类的值越高,网络就越认为这个图像属于这个特定的类# 让我们得到最高量值的下标/索引_, predicted = torch.max(outputs, 1)print('Predicted: ', ' '.join('%5s' % classes[predicted[j]] for j in range(4)))
Predicted: cat ship ship ship
In [ ]:
# (2)看看网络在整个数据集上表现的怎么样correct = 0total = 0with 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))
Accuracy of the network on the 10000 test images: 55 %
这比随机选取(即从10个类中随机选择一个类,正确率是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]))
Accuracy of plane : 52 %
Accuracy of car : 66 %
Accuracy of bird : 43 %
Accuracy of cat : 26 %
Accuracy of deer : 39 %
Accuracy of dog : 50 %
Accuracy of frog : 73 %
Accuracy of horse : 57 %
Accuracy of ship : 84 %
Accuracy of truck : 58 %
6.在GPU上训练
与将一个张量传递给GPU一样,可以这样将神经网络转移到GPU上。如果我们有cuda可用的话,让我们首先定义第一个设备为可见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)
输出:cuda:0
然后这些方法将递归遍历所有模块,并将它们的参数和缓冲区转换为CUDA张量
请记住,我们不得不将输入和目标在每一步都送入GPU
net.to(device)inputs, labels = inputs.to(device), labels.to(device)
