备注
点击此处下载完整示例代码
神经网络 ¶
创建于:2025 年 4 月 1 日 | 最后更新:2025 年 4 月 1 日 | 最后验证:2024 年 11 月 5 日
神经网络可以使用 torch.nn
包构建。
现在,你已经对 autograd
有了一个大致的了解, nn
依赖于 autograd
来定义模型并区分它们。一个 nn.Module
包含层,以及一个 forward(input)
方法,该方法返回 output
。
例如,看看这个用于分类数字图像的网络:

卷积神经网络 ¶
它是一个简单的前馈网络。它接收输入,然后一层层地通过它,最后给出输出。
神经网络的典型训练过程如下:
定义具有一些可学习参数(或权重)的神经网络
遍历输入数据集
将输入通过网络处理
计算损失(输出与正确结果之间的差距)
将梯度反向传播到网络的参数中
更新网络的权重,通常使用简单的更新规则:
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)
您只需定义 forward
函数,而 backward
函数(计算梯度的地方)将自动为您定义,使用 autograd
函数中的任何 Tensor 操作即可。
模型的可学习参数由 net.parameters()
返回
params = list(net.parameters())
print(len(params))
print(params[0].size()) # conv1's .weight
让我们尝试一个随机的 32x32 输入。注意:此网络(LeNet)的预期输入大小为 32x32。要在 MNIST 数据集上使用此网络,请将数据集中的图像调整大小为 32x32。
input = torch.randn(1, 1, 32, 32)
out = net(input)
print(out)
将所有参数的梯度缓冲区清零,并使用随机梯度进行反向传播:
net.zero_grad()
out.backward(torch.randn(1, 10))
备注
torch.nn
仅支持小批量。整个 torch.nn
包仅支持样本的小批量输入,而不是单个样本。
例如, nn.Conv2d
将接收一个 4D 张量 nSamples x nChannels x Height x Width
。
如果只有一个样本,只需使用 input.unsqueeze(0)
添加一个假的批次维度即可。
在继续之前,让我们回顾一下你迄今为止所看到的全部类。
- 回顾:
torch.Tensor
- 支持自动微分操作的多元数组。也包含相对于张量的梯度。nn.Module
- 神经网络模块。方便封装参数,并提供将参数移动到 GPU、导出、加载等辅助工具。nn.Parameter
- 一种 Tensor,当作为模块的属性赋值时,会自动注册为参数。autograd.Function
- 实现自动微分操作的正向和反向定义。每个Tensor
操作至少创建一个Function
节点,该节点连接到创建Tensor
的函数,并编码其历史记录。
- 到目前为止,我们已经涵盖了:
定义神经网络
处理输入和调用反向传播
- 还剩下:
计算损失
更新网络的权重
损失函数 ¶
损失函数接收一个(输出,目标)输入对,并计算一个值,该值估计输出与目标之间的距离。
在 nn 包下有几种不同的损失函数。一个简单的损失函数是: 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)
现在,如果您沿着 loss
的反向方向追踪,使用其 .grad_fn
属性,您将看到一个计算图,其外观如下:
input -> conv2d -> relu -> maxpool2d -> conv2d -> relu -> maxpool2d
-> flatten -> linear -> relu -> linear -> relu -> linear
-> MSELoss
-> loss
因此,当我们调用 loss.backward()
时,整个图相对于神经网络参数进行微分,并且图中所有具有 requires_grad=True
的 Tensors 的 .grad
Tensor 都会累积梯度。
为了说明,让我们跟随几个反向步骤:
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
反向传播
要反向传播错误,我们只需做的是 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)
现在,我们已经看到了如何使用损失函数。
标记为稍后阅读:
神经网络包包含各种模块和损失函数,这些是深度神经网络的基本构建块。完整的列表和文档在这里。
剩下的唯一要学习的就是:
更新网络的权重
更新权重
实践中最简单的更新规则是随机梯度下降(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.000 秒)