PyTorch深度学习60分钟入门与实战(三)神经网络

痛定思痛。 2022-03-28 14:56 528阅读 0赞

原文:github link,最新版会首先更新在github上
有误的地方拜托大家指出~

神经网络

可以使用torch.nn包来构建神经网络.

我们以及介绍了autogradnn包依赖于autograd包来定义模型并对它们求导。一个nn.Module包含各个层和一个forward(input)方法,该方法返回output

例如,下面这个神经网络可以对数字进行分类:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Ck5zMPUh-1588513930096)(assets/mnist.png)]

这是一个简单的前馈神经网络(feed-forward network)。它接受一个输入,然后将它送入下一层,一层接一层的传递,最后给出输出。

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

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

定义网络

让我们定义这样一个网络:

  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. # 1 input image channel, 6 output channels, 5x5 square convolution
  8. # kernel
  9. self.conv1 = nn.Conv2d(1, 6, 5)
  10. self.conv2 = nn.Conv2d(6, 16, 5)
  11. # an affine operation: y = Wx + b
  12. self.fc1 = nn.Linear(16 * 5 * 5, 120)
  13. self.fc2 = nn.Linear(120, 84)
  14. self.fc3 = nn.Linear(84, 10)
  15. def forward(self, x):
  16. # Max pooling over a (2, 2) window
  17. x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
  18. # If the size is a square you can only specify a single number
  19. x = F.max_pool2d(F.relu(self.conv2(x)), 2)
  20. x = x.view(-1, self.num_flat_features(x))
  21. x = F.relu(self.fc1(x))
  22. x = F.relu(self.fc2(x))
  23. x = self.fc3(x)
  24. return x
  25. def num_flat_features(self, x):
  26. size = x.size()[1:] # all dimensions except the batch dimension
  27. num_features = 1
  28. for s in size:
  29. num_features *= s
  30. return num_features
  31. net = Net()
  32. print(net)

输出:

  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. )

我们只需要定义 forward 函数,backward函数会在使用autograd时自动定义,backward函数用来计算导数。可以在 forward 函数中使用任何针对张量的操作和计算。

一个模型的可学习参数可以通过net.parameters()返回

  1. params = list(net.parameters())
  2. print(len(params))
  3. print(params[0].size()) # conv1's .weight

输出:

  1. 10
  2. torch.Size([6, 1, 5, 5])

让我们尝试一个随机的32x32的输入。注意,这个网络(LeNet)的期待输入是32x32。如果使用MNIST数据集来训练这个网络,要把图片大小重新调整到32x32。

  1. input = torch.randn(1, 1, 32, 32)
  2. out = net(input)
  3. print(out)

输出:

  1. tensor([[ 0.0399, -0.0856, 0.0668, 0.0915, 0.0453, -0.0680, -0.1024, 0.0493,
  2. -0.1043, -0.1267]], grad_fn=<AddmmBackward>)

清零所有参数的梯度缓存,然后进行随机梯度的反向传播:

  1. net.zero_grad()
  2. out.backward(torch.randn(1, 10))

注意:

torch.nn只支持小批量处理(mini-batches)。整个torch.nn包只支持小批量样本的输入,不支持单个样本。

比如,nn.Conv2d 接受一个4维的张量,即nSamples x nChannels x Height x Width

如果是一个单独的样本,只需要使用input.unsqueeze(0)来添加一个“假的”批大小维度。

在继续之前,让我们回顾一下到目前为止看到的所有类。

复习:

  • torch.Tensor - A multi-dimensional array with support for autograd operations like backward(). Also holds the gradient w.r.t. the tensor.
  • nn.Module - Neural network module. Convenient way of encapsulating parameters, with helpers for moving them to GPU, exporting, loading, etc.
  • nn.Parameter - A kind of Tensor, that is automatically registered as a parameter when assigned as an attribute to a Module.
  • autograd.Function - Implements forward and backward definitions of an autograd operation. Every Tensor operation, creates at least a single Function node, that connects to functions that created a Tensor and encodes its history.

目前为止,我们讨论了:

  • 定义一个神经网络
  • 处理输入调用backward

还剩下:

  • 计算损失
  • 更新网络权重

损失函数

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

译者注: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 0x7f94c821fdd8>
  2. <AddmmBackward object at 0x7f94c821f6a0>
  3. <AccumulateGrad object at 0x7f94c821f6a0>

反向传播

我们只需要调用loss.backward()来反向传播权重。我们需要清零现有的梯度,否则梯度将会与已有的梯度累加。

现在,我们将调用loss.backward(),并查看conv1层的偏置(bias)在反向传播前后的梯度。

  1. net.zero_grad() # zeroes the gradient buffers of all parameters
  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.0084, 0.0019, -0.0179, -0.0212, 0.0067, -0.0096])

现在,我们已经见到了如何使用损失函数。

稍后阅读

神经网络包包含了各种模块和损失函数,这些模块和损失函数构成了深度神经网络的构建模块。完整的文档列表见这里。

现在唯一要学习的是:

  • 更新网络的权重

更新权重

最简单的更新规则是随机梯度下降法(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. # create your optimizer
  3. optimizer = optim.SGD(net.parameters(), lr=0.01)
  4. # in your training loop:
  5. optimizer.zero_grad() # zero the gradient buffers
  6. output = net(input)
  7. loss = criterion(output, target)
  8. loss.backward()
  9. optimizer.step() # Does the update

注意:
观察梯度缓存区是如何使用optimizer.zero_grad()手动清零的。这是因为梯度是累加的,正如前面反向传播章节叙述的那样。

发表评论

表情:
评论列表 (有 0 条评论,528人围观)

还没有评论,来说两句吧...

相关阅读

    相关 神经网络深度学习

    1 神经网络与深度学习 1.3 神经网络基础之Python与向量化   上节课我们主要介绍了逻辑回归,以输出概率的形式来处理二分类问题。我们介绍了逻辑回归的Cost