Shortcuts

神经网络

Created On: Mar 24, 2017 | Last Updated: May 06, 2024 | Last Verified: Nov 05, 2024

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

现在你已经了解 autograd 的一些知识,nn 依赖于 autograd 来定义模型并为它们求导。一个 nn.Module 包含层,以及返回 output 的方法 forward(input)

例如,看看这个用于数字图像分类的网络:

convnet

convnet

这是一个简单的前馈网络。它接收输入,将其逐层传递,最终生成输出。

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

  • 定义具有一些可学习参数(或权重)的神经网络

  • 遍历输入的数据集

  • 通过网络处理输入

  • 计算损失(输出与正确结果的距离)

  • 将梯度反向传播到网络的参数中

  • 通常使用简单的更新规则更新网络的权重:weight = weight - learning_rate * gradient

定义网络

我们定义这个网络:

import torch
import torch.nn as nn
import torch.nn.functional as F


class Net(nn.Module):

    def __init__(self):
        super(Net, self).__init__()
        # 1 input image channel, 6 output channels, 5x5 square convolution
        # kernel
        self.conv1 = nn.Conv2d(1, 6, 5)
        self.conv2 = nn.Conv2d(6, 16, 5)
        # an affine operation: y = Wx + b
        self.fc1 = nn.Linear(16 * 5 * 5, 120)  # 5*5 from image dimension
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, input):
        # Convolution layer C1: 1 input image channel, 6 output channels,
        # 5x5 square convolution, it uses RELU activation function, and
        # outputs a Tensor with size (N, 6, 28, 28), where N is the size of the batch
        c1 = F.relu(self.conv1(input))
        # Subsampling layer S2: 2x2 grid, purely functional,
        # this layer does not have any parameter, and outputs a (N, 6, 14, 14) Tensor
        s2 = F.max_pool2d(c1, (2, 2))
        # Convolution layer C3: 6 input channels, 16 output channels,
        # 5x5 square convolution, it uses RELU activation function, and
        # outputs a (N, 16, 10, 10) Tensor
        c3 = F.relu(self.conv2(s2))
        # Subsampling layer S4: 2x2 grid, purely functional,
        # this layer does not have any parameter, and outputs a (N, 16, 5, 5) Tensor
        s4 = F.max_pool2d(c3, 2)
        # Flatten operation: purely functional, outputs a (N, 400) Tensor
        s4 = torch.flatten(s4, 1)
        # Fully connected layer F5: (N, 400) Tensor input,
        # and outputs a (N, 120) Tensor, it uses RELU activation function
        f5 = F.relu(self.fc1(s4))
        # Fully connected layer F6: (N, 120) Tensor input,
        # and outputs a (N, 84) Tensor, it uses RELU activation function
        f6 = F.relu(self.fc2(f5))
        # Gaussian layer OUTPUT: (N, 84) Tensor input, and
        # outputs a (N, 10) Tensor
        output = self.fc3(f6)
        return output


net = Net()
print(net)
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)
)

你只需定义 forward 函数,而 backward 函数(计算梯度)由 autograd 自动定义。你可以在 forward 函数中使用任何 Tensor 操作。

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

params = list(net.parameters())
print(len(params))
print(params[0].size())  # conv1's .weight
10
torch.Size([6, 1, 5, 5])

试试一个随机的 32x32 输入。注意:这个网络(LeNet)的预期输入大小是 32x32。要在 MNIST 数据集上使用这个网络,请将数据集中的图像重设为 32x32。

input = torch.randn(1, 1, 32, 32)
out = net(input)
print(out)
tensor([[ 0.0801, -0.0641, -0.0555,  0.0810,  0.1203, -0.0141, -0.0435, -0.0457,
          0.0446, -0.0002]], grad_fn=<AddmmBackward0>)

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

备注

torch.nn 仅支持小批量操作。整个 torch.nn 包仅支持作为小批量样本的输入,而不是单个样本。

例如,nn.Conv2d 将接收一个形状为 nSamples x nChannels x Height x Width 的 4D 张量。

如果你有单个样本,只需使用 input.unsqueeze(0) 添加一个伪批量维度。

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

回顾:
  • torch.Tensor - 一个支持自动微分操作(如 backward())的*多维数组*,同时*持有与该张量相关的梯度*。

  • nn.Module - 神经网络模块。一种封装参数的方便方式,带有移动到GPU、导出、加载等的辅助功能。

  • nn.Parameter - 一种特殊的Tensor,当分配为``Module``的属性时,会自动注册为一个参数

  • autograd.Function - 实现了*autograd操作的前向和后向定义*。每个``Tensor``操作至少创建一个``Function``节点,这些节点连接到创建``Tensor``的函数并*记录它的历史*。

到目前为止,我们覆盖了:
  • 定义神经网络

  • 处理输入并调用反向传播

仍待学习:
  • 计算损失

  • 更新网络的权重

损失函数

损失函数接收(output, target)这一对输入,并计算一个值,估计输出距离目标有多远。

在nn包中有许多不同的`损失函数 <https://pytorch.org/docs/nn.html#loss-functions>`_。一个简单的损失函数是:nn.MSELoss,它计算输出与目标之间的均方误差。

例如:

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

loss = criterion(output, target)
print(loss)
tensor(1.2783, grad_fn=<MseLossBackward0>)

现在,如果你沿着``loss``的反向方向,使用它的``.grad_fn``属性,你会看到一个计算图,如下所示:

input -> conv2d -> relu -> maxpool2d -> conv2d -> relu -> maxpool2d
      -> flatten -> linear -> relu -> linear -> relu -> linear
      -> MSELoss
      -> loss

因此,当我们调用``loss.backward()``时,整个图相对于神经网络参数进行微分,并且图中特定拥有``requires_grad=True``的所有Tensor都会累积它们的``.grad``参数。

为了说明,我们回溯几个步骤:

print(loss.grad_fn)  # MSELoss
print(loss.grad_fn.next_functions[0][0])  # Linear
print(loss.grad_fn.next_functions[0][0].next_functions[0][0])  # ReLU
<MseLossBackward0 object at 0x7f057cf21840>
<AddmmBackward0 object at 0x7f057cf200a0>
<AccumulateGrad object at 0x7f057cf20070>

反向传播

为了反向传播误差,我们只需调用``loss.backward()``。但你需要清除现有的梯度,否则梯度将会累积到现有的梯度。

现在我们将调用``loss.backward()``,看一下conv1的偏置梯度在反向传播之前和之后的变化。

net.zero_grad()     # zeroes the gradient buffers of all parameters

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 backward
None
conv1.bias.grad after backward
tensor([-0.0002, -0.0109, -0.0011,  0.0098,  0.0024,  0.0026])

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

稍后阅读:

神经网络包包含了各种模块和损失函数,这些模块构成了深度神经网络的基本构建块。完整的文档和列表在`这里 <https://pytorch.org/docs/nn>`_。

我们剩下要学习的唯一内容是:

  • 更新网络的权重

更新权重

实践中最简单的更新规则是随机梯度下降(SGD):

weight = weight - learning_rate * gradient

我们可以用简单的Python代码来实现:

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

然而,当你使用神经网络时,你可能希望使用各种更新规则,例如SGD,Nesterov-SGD,Adam,RMSProp等。为了实现这一点,我们创建了一个小型包``torch.optim``,它实现了所有这些方法。使用它非常简单:

import torch.optim as optim

# create your optimizer
optimizer = optim.SGD(net.parameters(), lr=0.01)

# in your training loop:
optimizer.zero_grad()   # zero the gradient buffers
output = net(input)
loss = criterion(output, target)
loss.backward()
optimizer.step()    # Does the update

备注

注意如何必须手动使用``optimizer.zero_grad()``清除梯度缓冲区。这是因为梯度会累积,如`反向传播`_部分所解释的那样。

脚本的总运行时间: ( 0 分钟 0.387 秒)

画廊由 Sphinx-Gallery 生成

文档

访问 PyTorch 的详细开发者文档

查看文档

教程

获取针对初学者和高级开发人员的深入教程

查看教程

资源

查找开发资源并获得问题的解答

查看资源