此教程的目标:

  • 更高层次地理解Pytorch的Tensor库以及神经网络。
  • 训练一个小的神经网络模型用于分类图像。

确保你安装了 torch 和 torchvision 包。
02-PyTorch 深度学习: 60 分钟极速入门1 - 图1

  • PyTorch 是什么
  • Autograd:自动求导
  • 神经网络
  • 训练分类器
  • 数据并行

1 张量tensor

  1. In [1]: import torch
  2. In [2]: x = torch.empty(3,4)
  3. In [3]: x
  4. Out[3]:
  5. tensor([[5.6753e-42, 0.0000e+00, 0.0000e+00, 0.0000e+00],
  6. [0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00],
  7. [0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00]])
  8. In [4]: x = torch.ones(3,4)
  9. In [5]: x
  10. Out[5]:
  11. tensor([[1., 1., 1., 1.],
  12. [1., 1., 1., 1.],
  13. [1., 1., 1., 1.]])
  14. In [54]: torch.zeros(2)
  15. Out[54]: tensor([0., 0.])
  16. In [55]: torch.zeros(2,)
  17. Out[55]: tensor([0., 0.])
  18. In [56]: torch.zeros(2,3)
  19. Out[56]:
  20. tensor([[0., 0., 0.],
  21. [0., 0., 0.]])
  22. In [57]: torch.zeros(2,3,4)
  23. Out[57]:
  24. tensor([[[0., 0., 0., 0.],
  25. [0., 0., 0., 0.],
  26. [0., 0., 0., 0.]],
  27. [[0., 0., 0., 0.],
  28. [0., 0., 0., 0.],
  29. [0., 0., 0., 0.]]])
  1. # 返回均值为0,方差为1的标准正态分布
  2. In [8]: x = torch.randn(3,)
  3. In [9]: x
  4. Out[9]: tensor([0.4476, 0.2597, 0.0523])
  5. In [10]: x.shape
  6. Out[10]: torch.Size([3])
  7. In [22]: x = torch.randn(3,1)
  8. In [23]: x
  9. Out[23]:
  10. tensor([[-0.9060],
  11. [ 2.0127],
  12. [-1.3605]])
  13. In [24]: x.shape
  14. Out[24]: torch.Size([3, 1])
  15. In [11]: x = torch.randn(3,2)
  16. In [12]: x
  17. Out[12]:
  18. tensor([[-0.7473, 1.0257],
  19. [ 0.3302, -0.3894],
  20. [ 1.1525, 0.3747]])
  21. In [13]: x.shape
  22. Out[13]: torch.Size([3, 2])
  23. In [14]: x = torch.randn(3,2,4)
  24. In [15]: x
  25. Out[15]:
  26. tensor([[[ 2.0151, 0.9684, 1.6057, 0.1693],
  27. [ 1.6014, -0.1547, 0.6339, -2.1830]],
  28. [[ 0.2804, -0.3243, -1.3168, 1.1731],
  29. [-0.1829, 0.5489, 0.1494, -2.0575]],
  30. [[-0.6438, -1.0181, 0.5926, -0.5505],
  31. [ 1.2672, 0.8542, 1.5096, 2.5186]]])
  32. In [16]: x.shape
  33. Out[16]: torch.Size([3, 2, 4])
  1. # 返回[0,1]之间的均匀分布
  2. In [33]: torch.rand(10)
  3. Out[33]:
  4. tensor([0.2389, 0.8907, 0.3929, 0.0315, 0.5598, 0.4148, 0.6898, 0.6691, 0.0761,
  5. 0.3793])
  6. In [34]: torch.rand(3,4)
  7. Out[34]:
  8. tensor([[0.0688, 0.6932, 0.1009, 0.1109],
  9. [0.7857, 0.9575, 0.7772, 0.1911],
  10. [0.8424, 0.4165, 0.3198, 0.5043]])
  11. In [35]: torch.rand(3,4,2)
  12. Out[35]:
  13. tensor([[[0.3173, 0.9806],
  14. [0.1815, 0.6252],
  15. [0.3163, 0.6357],
  16. [0.9688, 0.0951]],
  17. [[0.6719, 0.9924],
  18. [0.2468, 0.7327],
  19. [0.1184, 0.4472],
  20. [0.8086, 0.2959]],
  21. [[0.4796, 0.9292],
  22. [0.1021, 0.9367],
  23. [0.2053, 0.0738],
  24. [0.6674, 0.9440]]])
  25. In [36]: torch.rand(3,)
  26. Out[36]: tensor([0.1190, 0.8914, 0.4051])
  27. In [37]: torch.rand(3,1)
  28. Out[37]:
  29. tensor([[0.8033],
  30. [0.2413],
  31. [0.2629]])
  1. # randint
  2. In [41]: torch.randint(0,8,[3,3])
  3. Out[41]:
  4. tensor([[6, 4, 6],
  5. [4, 0, 1],
  6. [5, 5, 5]])
  7. In [42]: torch.randint(8,[3,3])
  8. Out[42]:
  9. tensor([[2, 2, 6],
  10. [6, 1, 7],
  11. [7, 7, 7]])
  12. In [43]: torch.randint(8,[3,1])
  13. Out[43]:
  14. tensor([[6],
  15. [1],
  16. [6]])
  17. In [44]: torch.randint(8,[3,])
  18. Out[44]: tensor([2, 0, 3])
  19. In [45]: torch.randint(8,[3,2,4])
  20. Out[45]:
  21. tensor([[[1, 6, 2, 7],
  22. [4, 7, 4, 4]],
  23. [[4, 2, 1, 4],
  24. [3, 7, 3, 7]],
  25. [[6, 5, 0, 5],
  26. [1, 0, 1, 3]]])
  1. # 直接从数据构造张量
  2. In [62]: x = torch.tensor(3)
  3. In [63]: x
  4. Out[63]: tensor(3)
  5. In [64]: x = torch.tensor(3,dtype=torch.float32)
  6. In [65]: x
  7. Out[65]: tensor(3.)
  8. In [66]: x = torch.tensor([3,4],dtype=torch.float32)
  9. In [67]: x
  10. Out[67]: tensor([3., 4.])
  11. In [68]: x.shape
  12. Out[68]: torch.Size([2])
  13. In [69]: x = torch.tensor([[3,4],[2,5]],dtype=torch.float32)
  14. In [70]: x
  15. Out[70]:
  16. tensor([[3., 4.],
  17. [2., 5.]])
  18. In [71]: x.shape
  19. Out[71]: torch.Size([2, 2])
  20. In [72]: torch.randn_like(x)
  21. Out[72]:
  22. tensor([[ 0.0315, 0.0971],
  23. [-0.7058, 0.5100]])
  1. # 加法
  2. In [73]: x = torch.randn(3,4)
  3. In [74]: x
  4. Out[74]:
  5. tensor([[-0.0512, -1.9237, -1.3809, 0.7449],
  6. [-1.5901, -2.0461, -0.0884, -0.4058],
  7. [-0.5473, 0.0627, 0.9264, -0.5887]])
  8. In [75]: y = torch.randn(3,4)
  9. In [76]: y
  10. Out[76]:
  11. tensor([[ 0.3731, -0.2898, 0.6289, 0.8557],
  12. [-0.3129, -0.7714, -0.7404, -1.4080],
  13. [-0.7252, 2.5395, -2.2563, -0.1399]])
  14. In [77]: torch.add(x,y)
  15. Out[77]:
  16. tensor([[ 0.3219, -2.2136, -0.7520, 1.6006],
  17. [-1.9030, -2.8175, -0.8287, -1.8138],
  18. [-1.2725, 2.6022, -1.3299, -0.7286]])
  19. # 加法:原位/原地操作(in-place)
  20. # adds x to y
  21. In [114]: y = torch.randn(3,4)
  22. In [115]: y
  23. Out[115]:
  24. tensor([[-1.1976, 1.4221, -0.0657, 0.9441],
  25. [-1.1427, 0.0568, 0.8195, 0.3546],
  26. [-0.9769, -0.7331, -0.4502, -0.0629]])
  27. In [116]: y.add_(x)
  28. Out[116]:
  29. tensor([[ 1.7456e-01, 1.9636e+00, -1.1081e+00, 3.4312e-01],
  30. [-1.0931e+00, -1.0881e+00, 2.9528e+00, 2.9883e-04],
  31. [-2.7004e-01, 4.3621e-01, -2.3812e-01, 3.0546e-01]])
  32. In [117]: y
  33. Out[117]:
  34. tensor([[ 1.7456e-01, 1.9636e+00, -1.1081e+00, 3.4312e-01],
  35. [-1.0931e+00, -1.0881e+00, 2.9528e+00, 2.9883e-04],
  36. [-2.7004e-01, 4.3621e-01, -2.3812e-01, 3.0546e-01]])

任何一个in-place改变张量的操作后面都固定一个_。例如x.copy_(y)、x.t_()将更改x

  1. # 改变形状
  2. In [123]: y
  3. Out[123]:
  4. tensor([[ 1.7456e-01, 1.9636e+00, -1.1081e+00, 3.4312e-01],
  5. [-1.0931e+00, -1.0881e+00, 2.9528e+00, 2.9883e-04],
  6. [-2.7004e-01, 4.3621e-01, -2.3812e-01, 3.0546e-01]])
  7. In [124]: y.reshape(2,6)
  8. Out[124]:
  9. tensor([[ 1.7456e-01, 1.9636e+00, -1.1081e+00, 3.4312e-01, -1.0931e+00,
  10. -1.0881e+00],
  11. [ 2.9528e+00, 2.9883e-04, -2.7004e-01, 4.3621e-01, -2.3812e-01,
  12. 3.0546e-01]])
  13. In [125]: y.view(2,6)
  14. Out[125]:
  15. tensor([[ 1.7456e-01, 1.9636e+00, -1.1081e+00, 3.4312e-01, -1.0931e+00,
  16. -1.0881e+00],
  17. [ 2.9528e+00, 2.9883e-04, -2.7004e-01, 4.3621e-01, -2.3812e-01,
  18. 3.0546e-01]])
  19. In [126]: y
  20. Out[126]:
  21. tensor([[ 1.7456e-01, 1.9636e+00, -1.1081e+00, 3.4312e-01],
  22. [-1.0931e+00, -1.0881e+00, 2.9528e+00, 2.9883e-04],
  23. [-2.7004e-01, 4.3621e-01, -2.3812e-01, 3.0546e-01]])
  24. In [127]: y.view(-1,3)
  25. Out[127]:
  26. tensor([[ 1.7456e-01, 1.9636e+00, -1.1081e+00],
  27. [ 3.4312e-01, -1.0931e+00, -1.0881e+00],
  28. [ 2.9528e+00, 2.9883e-04, -2.7004e-01],
  29. [ 4.3621e-01, -2.3812e-01, 3.0546e-01]])
  1. # 将torch的Tensor转化为NumPy数组
  2. In [128]: a = torch.ones(2,3)
  3. In [129]: a
  4. Out[129]:
  5. tensor([[1., 1., 1.],
  6. [1., 1., 1.]])
  7. In [130]: type(a)
  8. Out[130]: torch.Tensor
  9. In [131]: b = a.numpy()
  10. In [132]: b
  11. Out[132]:
  12. array([[1., 1., 1.],
  13. [1., 1., 1.]], dtype=float32)
  14. In [133]: type(b)
  15. Out[133]: numpy.ndarray
  1. # 将NumPy数组转化为Torch张量
  2. # CPU上的所有张量(CharTensor除外)都支持转换为NumPy以及由NumPy转换回来。
  3. In [136]: import numpy as np
  4. In [137]: a = np.ones(5)
  5. In [138]: b = torch.from_numpy(a)
  6. In [139]: a
  7. Out[139]: array([1., 1., 1., 1., 1.])
  8. In [140]: b
  9. Out[140]: tensor([1., 1., 1., 1., 1.], dtype=torch.float64)
  1. # CUDA上的张量
  2. # 张量可以使用.to方法移动到任何设备(device)上
  3. import torch
  4. x = torch.tensor(1.0445)
  5. if torch.cuda.is_available():
  6. device = torch.device("cuda") # a CUDA device object
  7. y = torch.ones_like(x, device=device) # 直接在GPU上创建tensor
  8. x = x.to(device) # 或者使用`.to("cuda")`方法
  9. z = x + y
  10. print(z)
  11. 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

  1. tensor(data, dtype=None, device=None, requires_grad=False) -> Tensor
  1. import torch
  2. # 创建一个张量并设置requires_grad=True用来追踪其计算历史
  3. x = torch.ones(2,2,requires_grad=True)
  4. x
  5. tensor([[1., 1.],
  6. [1., 1.]], requires_grad=True)
  7. # 张量做计算
  8. y = x + 2
  9. y
  10. tensor([[3., 3.],
  11. [3., 3.]], grad_fn=<AddBackward>)
  12. # y是计算结果,具有grad_fn属性
  13. y.grad_fn
  14. <AddBackward at 0x7f59643c7a90>
  15. z = y*y*3
  16. z
  17. tensor([[27., 27.],
  18. [27., 27.]], grad_fn=<MulBackward>)
  19. out = z.mean()
  20. out
  21. tensor(27., grad_fn=<MeanBackward1>)
  22. print(out.shape)
  23. print(out.size())
  24. torch.Size([])
  25. torch.Size([])

梯度

  1. # 链式求导法则:out对x=1的情况下求导
  2. x.grad
  3. tensor([[4.5000, 4.5000],
  4. [4.5000, 4.5000]])

02-PyTorch 深度学习: 60 分钟极速入门1 - 图2
在这种情况下,y不再是标量。torch.autograd不能直接计算完整的雅可比矩阵,但是如果我们只想要雅可比向量积,只需将这个向量作为参数传给backward

  1. v = torch.tensor([0.1, 1.0, 0.0001], dtype=torch.float)
  2. y.backward(v)
  3. print(x.grad)
  4. tensor([ 51.2000, 512.0000, 0.0512])

实际中,为了防止跟踪历史记录(和使用内存),可以将代码块包装在with torch.no_grad():中。在评估模型时特别有用,因为模型可能具有requires_grad = True的可训练的参数,但是我们不需要在此过程中对他们进行梯度计算。也可以通过将代码块包装在 with torch.no_grad(): 中,来阻止autograd跟踪设置了 **.requires_grad=True** 的张量的历史记录。
**

  1. print(x.requires_grad)
  2. print((x ** 2).requires_grad)
  3. with torch.no_grad():
  4. print((x ** 2).requires_grad)
  5. True
  6. True
  7. False

3 神经网络

可以使用torch.nn包来构建神经网络。前面介绍了autograd,nn**包依赖于autograd包来定义模型并对它们求导。一个nn.Module包含各个层和一个forward(input)方法**,该方法返回output。

例如,下面这个神经网络可以对数字进行分类:
02-PyTorch 深度学习: 60 分钟极速入门1 - 图3
这是一个简单的前馈神经网络(feed-forward network)。它接受一个输入,然后将它送入下一层,一层接一层的传递,最后给出输出。

一个神经网络的典型训练过程如下:

  • 定义包含一些可学习参数(或者叫权重)的神经网络
  • 在输入数据集上迭代
  • 通过网络处理输入
  • 计算损失(输出和正确答案的距离)
  • 将梯度反向传播给网络的参数
  • 更新网络的权重,一般使用一个简单的规则:weight = weight - learning_rate * gradient

我们只需要定义 forward 函数,backward函数会在使用autograd时自动定义,backward函数用来计算导数。
可以在 forward 函数中使用任何针对张量的操作和计算。
一个模型的可学习参数可以通过net.parameters()返回。

定义网络

  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. class Net(nn.Module):
  5. def __init__(self):
  6. super(Net, self).__init__()
  7. # 输入图像channel:1;输出channel:6;5x5卷积核
  8. self.conv1 = nn.Conv2d(1, 6, 5)
  9. self.conv2 = nn.Conv2d(6, 16, 5)
  10. # an affine operation: y = Wx + b
  11. self.fc1 = nn.Linear(16 * 5 * 5, 120)
  12. self.fc2 = nn.Linear(120, 84)
  13. self.fc3 = nn.Linear(84, 10)
  14. def forward(self, x):
  15. # 2x2 Max pooling
  16. x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
  17. # If the size is a square you can only specify a single number
  18. x = F.max_pool2d(F.relu(self.conv2(x)), 2)
  19. x = x.view(-1, self.num_flat_features(x))
  20. x = F.relu(self.fc1(x))
  21. x = F.relu(self.fc2(x))
  22. x = self.fc3(x)
  23. return x
  24. def num_flat_features(self, x):
  25. size = x.size()[1:] # 除去批大小维度的其余维度
  26. num_features = 1
  27. for s in size:
  28. num_features *= s
  29. return num_features
  30. net = Net()
  31. print(net)
  32. # 一个模型的可学习参数可以通过net.parameters()返回
  33. params = list(net.parameters())
  34. print(len(params))
  35. print(params[0].size()) # conv1's .weight
  36. # 这个网络(LeNet)的期待输入是32x32,如果使用MNIST数据集来训练这个网络,要把图片大小重新调整到32x32
  37. input = torch.randn(1, 1, 32, 32)
  38. out = net(input)
  39. print(out)
  40. # 清零所有参数的梯度缓存,然后进行随机梯度的反向传播
  41. net.zero_grad()
  42. out.backward(torch.randn(1, 10))

输出:

  1. Net(
  2. (conv1): Conv2d(1, 6, kernel_size=(5, 5), stride=(1, 1))
  3. (conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))
  4. (fc1): Linear(in_features=400, out_features=120, bias=True)
  5. (fc2): Linear(in_features=120, out_features=84, bias=True)
  6. (fc3): Linear(in_features=84, out_features=10, bias=True)
  7. )
  8. 10
  9. torch.Size([6, 1, 5, 5])
  10. tensor([[-0.1501, 0.1201, 0.0528, -0.1485, -0.0332, -0.0235, -0.0992, 0.0264,
  11. 0.0179, -0.0556]], grad_fn=<ThAddmmBackward>)
  1. print(net.parameters)

输出:

  1. <bound method Module.parameters of Net(
  2. (conv1): Conv2d(1, 6, kernel_size=(5, 5), stride=(1, 1))
  3. (conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))
  4. (fc1): Linear(in_features=400, out_features=120, bias=True)
  5. (fc2): Linear(in_features=120, out_features=84, bias=True)
  6. (fc3): Linear(in_features=84, out_features=10, bias=True)
  7. )>

可视化模型框架——方法一

pip install tensorboardX

demo.py

  1. import torch
  2. import torchvision.utils as vutils
  3. import numpy as np
  4. import torchvision.models as models
  5. from torchvision import datasets
  6. from tensorboardX import SummaryWriter
  7. resnet18 = models.resnet18(False)
  8. writer = SummaryWriter()
  9. sample_rate = 44100
  10. freqs = [262, 294, 330, 349, 392, 440, 440, 440, 440, 440, 440]
  11. for n_iter in range(100):
  12. dummy_s1 = torch.rand(1)
  13. dummy_s2 = torch.rand(1)
  14. # data grouping by `slash`
  15. writer.add_scalar('data/scalar1', dummy_s1[0], n_iter)
  16. writer.add_scalar('data/scalar2', dummy_s2[0], n_iter)
  17. writer.add_scalars('data/scalar_group', {'xsinx': n_iter * np.sin(n_iter),
  18. 'xcosx': n_iter * np.cos(n_iter),
  19. 'arctanx': np.arctan(n_iter)}, n_iter)
  20. dummy_img = torch.rand(32, 3, 64, 64) # output from network
  21. if n_iter % 10 == 0:
  22. x = vutils.make_grid(dummy_img, normalize=True, scale_each=True)
  23. writer.add_image('Image', x, n_iter)
  24. dummy_audio = torch.zeros(sample_rate * 2)
  25. for i in range(x.size(0)):
  26. # amplitude of sound should in [-1, 1]
  27. dummy_audio[i] = np.cos(freqs[n_iter // 10] * np.pi * float(i) / float(sample_rate))
  28. writer.add_audio('myAudio', dummy_audio, n_iter, sample_rate=sample_rate)
  29. writer.add_text('Text', 'text logged at step:' + str(n_iter), n_iter)
  30. for name, param in resnet18.named_parameters():
  31. writer.add_histogram(name, param.clone().cpu().data.numpy(), n_iter)
  32. # needs tensorboard 0.4RC or later
  33. writer.add_pr_curve('xoxo', np.random.randint(2, size=100), np.random.rand(100), n_iter)
  34. dataset = datasets.MNIST('mnist', train=False, download=True)
  35. images = dataset.test_data[:100].float()
  36. label = dataset.test_labels[:100]
  37. features = images.view(100, 784)
  38. writer.add_embedding(features, metadata=label, label_img=images.unsqueeze(1))
  39. # export scalar data to JSON for external processing
  40. writer.export_scalars_to_json("./all_scalars.json")
  41. writer.close()
  1. d:\git\pytorch
  2. $ ll
  3. total 76
  4. drwxr-xr-x 1 Administrator 197121 0 1月 26 13:06 ./
  5. drwxr-xr-x 1 Administrator 197121 0 1月 26 09:18 ../
  6. drwxr-xr-x 1 Administrator 197121 0 1月 26 13:47 .idea/
  7. -rw-r--r-- 1 Administrator 197121 13774 1月 26 13:06 all_scalars.json
  8. -rw-r--r-- 1 Administrator 197121 2103 1月 26 13:01 demo.py
  9. -rw-r--r-- 1 Administrator 197121 2200 1月 26 12:16 Digraph.gv
  10. -rw-r--r-- 1 Administrator 197121 32970 1月 26 12:16 Digraph.gv.pdf
  11. drwxr-xr-x 1 Administrator 197121 0 1月 26 13:02 mnist/
  12. drwxr-xr-x 1 Administrator 197121 0 1月 26 13:02 runs/
  13. -rw-r--r-- 1 Administrator 197121 2102 1月 26 13:06 test.py
  14. d:\git\pytorch
  15. $ tensorboard --logdir runs
  16. c:\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`.
  17. from ._conv import register_converters as _register_converters
  18. TensorBoard 1.12.2 at http://7125messi:6006 (Press CTRL+C to quit)

image.png

可视化模型框架——方法二

pip install git+https://github.com/szagoruyko/pytorchviz
——A small package to create visualizations of PyTorch execution graphs

  1. from torchviz import make_dot
  2. g=make_dot(net(torch.randn(1, 1, 32, 32)),params=dict(net.named_parameters()))
  3. g.view()

会生成一个PDF文件
image.png

torch.Tensor`` - 一个多维数组,支持诸如``backward()等的自动求导操作,同时也保存了张量的梯度。
nn.Module - 神经网络模块。是一种方便封装参数的方式,具有将参数移动到GPU、导出、加载等功能。
nn.Parameter`` - 张量的一种,当它作为一个属性分配给一个``Module``时,它会被自动注册为一个参数。
autograd.Function`` - 实现了自动求导前向和反向传播的定义,每个``Tensor``至少创建一个``Function``节点,该节点连接到创建``Tensor``的函数并对其历史进行编码。

损失函数

一个损失函数接受一对(output, target)作为输入,计算一个值来估计网络的输出和目标值相差多少。

nn包中有很多不同的损失函数。``nn.MSELoss``是比较简单的一种,它计算输出和目标的均方误差(mean-squared error)。

  1. output = net(input)
  2. target = torch.randn(10) # a dummy target, for example
  3. target = target.view(1, -1) # make it the same shape as output
  4. criterion = nn.MSELoss()
  5. loss = criterion(output, target)
  6. print(loss)

输出:

  1. tensor(1.0263, grad_fn=<MseLossBackward>)

如果使用loss的.grad_fn属性跟踪反向传播过程,会看到计算图如下:

  1. input -> conv2d -> relu -> maxpool2d -> conv2d -> relu -> maxpool2d
  2. -> view -> linear -> relu -> linear -> relu -> linear
  3. -> MSELoss
  4. -> loss

我们调用loss.backward(),整张图开始关于loss微分,图中所有设置了requires_grad=True的张量的.grad属性累积着梯度张量。为了说明这一点,让我们向后跟踪几步:

  1. print(loss.grad_fn) # MSELoss
  2. print(loss.grad_fn.next_functions[0][0]) # Linear
  3. print(loss.grad_fn.next_functions[0][0].next_functions[0][0]) # ReLU

输出:

  1. <MseLossBackward object at 0x000002396E9BA518>
  2. <AddmmBackward object at 0x000002396C8F22B0>
  3. <AccumulateGrad object at 0x000002396C8F22B0>

反向传播

我们只需要调用loss.backward()来反向传播权重。我们需要清零现有的梯度,否则梯度将会与已有的梯度累加。
现在,我们将调用loss.backward(),并查看conv1层的偏置(bias)在反向传播前后的梯度。

  1. net.zero_grad() # 清零所有参数(parameter)的梯度缓存
  2. print('conv1.bias.grad before backward')
  3. print(net.conv1.bias.grad)
  4. loss.backward()
  5. print('conv1.bias.grad after backward')
  6. print(net.conv1.bias.grad)

输出:

  1. conv1.bias.grad before backward
  2. tensor([0., 0., 0., 0., 0., 0.])
  3. conv1.bias.grad after backward
  4. tensor([-0.0037, -0.0204, 0.0316, -0.0079, 0.0027, -0.0034])

更新权重

最简单的更新规则是随机梯度下降法(SGD):
weight = weight - learning_rate * gradient
我们可以使用简单的python代码来实现:

  1. learning_rate = 0.01
  2. for f in net.parameters():
  3. f.data.sub_(f.grad.data * learning_rate)

然而,在使用神经网络时,可能希望使用各种不同的更新规则,如SGD、Nesterov-SGD、Adam、RMSProp等。为此,我们构建了一个较小的包torch.optim,它实现了所有的这些方法。使用它很简单:

  1. import torch.optim as optim
  2. # 创建优化器(optimizer)
  3. optimizer = optim.SGD(net.parameters(), lr=0.01)
  4. # 在训练的迭代中:
  5. optimizer.zero_grad() # 清零梯度缓存
  6. output = net(input)
  7. loss = criterion(output, target)
  8. loss.backward()
  9. 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像素。

02-PyTorch 深度学习: 60 分钟极速入门1 - 图6

训练一个图片分类器

我们将按顺序做以下步骤:

  1. 通过torchvision加载CIFAR10里面的训练和测试数据集,并对数据进行标准化
  2. 定义卷积神经网络
  3. 定义损失函数
  4. 利用训练数据训练网络
  5. 利用测试数据测试网络

使用Jupyter

1.加载并标准化CIFAR10

  1. # 使用torchvision加载CIFAR10
  2. import torch
  3. import torchvision
  4. from torchvision import transforms
  5. # torchvision数据集加载完后的输出是范围在[0, 1]之间的PILImage
  6. # 我们将其标准化为范围在[-1, 1]之间的张量
  7. transform = transforms.Compose(
  8. [transforms.ToTensor(),
  9. transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
  10. trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
  11. trainloader = torch.utils.data.DataLoader(trainset, batch_size=4, shuffle=True, num_workers=2)
  12. testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)
  13. testloader = torch.utils.data.DataLoader(testset, batch_size=4, shuffle=False, num_workers=2)
  14. classes = ('plane', 'car', 'bird', 'cat',
  15. '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

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. # 输出图像的函数
  4. def imshow(img):
  5. img = img / 2 + 0.5 # unnormalize
  6. npimg = img.numpy()
  7. plt.imshow(np.transpose(npimg, (1, 2, 0)))
  8. plt.show()
  9. # 随机得到一些训练图片
  10. dataiter = iter(trainloader)
  11. images, labels = dataiter.next()
  12. # 显示图片
  13. imshow(torchvision.utils.make_grid(images))
  14. # 打印图片标签
  15. print(' '.join('%5s' % classes[labels[j]] for j in range(4)))

image.png
deer cat cat ship

2.定义卷积神经网络


  1. import torch.nn as nn
  2. import torch.nn.functional as F
  3. class Net(nn.Module):
  4. def __init__(self):
  5. super(Net, self).__init__()
  6. self.conv1 = nn.Conv2d(3, 6, 5)
  7. self.pool = nn.MaxPool2d(2, 2)
  8. self.conv2 = nn.Conv2d(6, 16, 5)
  9. self.fc1 = nn.Linear(16 * 5 * 5, 120)
  10. self.fc2 = nn.Linear(120, 84)
  11. self.fc3 = nn.Linear(84, 10)
  12. def forward(self, x):
  13. x = self.pool(F.relu(self.conv1(x)))
  14. x = self.pool(F.relu(self.conv2(x)))
  15. x = x.view(-1, 16 * 5 * 5)
  16. x = F.relu(self.fc1(x))
  17. x = F.relu(self.fc2(x))
  18. x = self.fc3(x)
  19. return x
  20. net = Net()

3.定义损失函数和优化器


  1. # 使用分类的交叉熵损失和随机梯度下降(使用momentum)
  2. import torch.optim as optim
  3. criterion = nn.CrossEntropyLoss()
  4. optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)

4.训练网络

遍历我们的数据迭代器,并且输入“喂”给网络和优化函数

  1. for epoch in range(2): # loop over the dataset multiple times
  2. running_loss = 0.0
  3. for i, data in enumerate(trainloader, 0):
  4. # get the inputs
  5. inputs, labels = data
  6. # zero the parameter gradients
  7. optimizer.zero_grad()
  8. # forward + backward + optimize
  9. outputs = net(inputs)
  10. loss = criterion(outputs, labels)
  11. loss.backward()
  12. optimizer.step()
  13. # print statistics
  14. running_loss += loss.item()
  15. if i % 2000 == 1999: # print every 2000 mini-batches
  16. print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 2000))
  17. running_loss = 0.0
  18. print('Finished Training')

输出结果:

  1. [1, 2000] loss: 2.245
  2. [1, 4000] loss: 1.885
  3. [1, 6000] loss: 1.714
  4. [1, 8000] loss: 1.612
  5. [1, 10000] loss: 1.571
  6. [1, 12000] loss: 1.491
  7. [2, 2000] loss: 1.400
  8. [2, 4000] loss: 1.390
  9. [2, 6000] loss: 1.360
  10. [2, 8000] loss: 1.321
  11. [2, 10000] loss: 1.331
  12. [2, 12000] loss: 1.300
  13. Finished Training

5.使用测试数据测试网络

  1. # 显示测试集中的图像
  2. dataiter = iter(testloader)
  3. images, labels = dataiter.next()
  4. # 输出图片
  5. imshow(torchvision.utils.make_grid(images))
  6. print('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4)))

image.png
GroundTruth: cat ship ship plane

  1. # (1)看看神经网络认为上面的例子是啥
  2. outputs = net(images)
  3. # 输出是10个类别的量值,一个类的值越高,网络就越认为这个图像属于这个特定的类
  4. # 让我们得到最高量值的下标/索引
  5. _, predicted = torch.max(outputs, 1)
  6. print('Predicted: ', ' '.join('%5s' % classes[predicted[j]] for j in range(4)))

Predicted: cat ship ship ship
In [ ]:

  1. # (2)看看网络在整个数据集上表现的怎么样
  2. correct = 0
  3. total = 0
  4. with torch.no_grad():
  5. for data in testloader:
  6. images, labels = data
  7. outputs = net(images)
  8. _, predicted = torch.max(outputs.data, 1)
  9. total += labels.size(0)
  10. correct += (predicted == labels).sum().item()
  11. 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%)要好很多。看来网络确实学到了一些东西。
那么哪些是表现好的类呢?哪些是表现的差的类呢?

  1. class_correct = list(0. for i in range(10))
  2. class_total = list(0. for i in range(10))
  3. with torch.no_grad():
  4. for data in testloader:
  5. images, labels = data
  6. outputs = net(images)
  7. _, predicted = torch.max(outputs, 1)
  8. c = (predicted == labels).squeeze()
  9. for i in range(4):
  10. label = labels[i]
  11. class_correct[label] += c[i].item()
  12. class_total[label] += 1
  13. for i in range(10):
  14. 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设备:

  1. device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
  2. # Assuming that we are on a CUDA machine, this should print a CUDA device:
  3. print(device)

输出:cuda:0

然后这些方法将递归遍历所有模块,并将它们的参数和缓冲区转换为CUDA张量
请记住,我们不得不将输入和目标在每一步都送入GPU

  1. net.to(device)
  2. inputs, labels = inputs.to(device), labels.to(device)