目录
在训练神经网络时,最常用的算法是反向传播。 在该算法中,参数(模型权重)根据损失函数相对于给定参数的梯度进行调整。
为了计算这些梯度,PyTorch 有一个名为 torch.autograd 的内置微分引擎。 它支持任何计算图的梯度自动计算。
考虑最简单的一层神经网络,输入 x、参数 w 和 b,以及一些损失函数。 它可以通过以下方式在 PyTorch 中定义:
import torch
x = torch.ones(5) # input tensor
y = torch.zeros(3) # expected output
w = torch.randn(5, 3, requires_grad=True)
b = torch.randn(3, requires_grad=True)
z = torch.matmul(x, w)+b
loss = torch.nn.functional.binary_cross_entropy_with_logits(z, y)
张量、函数和计算图
此代码定义了以下计算图:
在这个网络中,w 和 b 是我们需要优化的参数。 因此,我们需要能够计算损失函数相对于这些变量的梯度。 为此,我们设置了这些张量的 requires_grad 属性。
注:可以在创建张量时设置 requires_grad 的值,或者稍后使用 x.requires_grad_(True) 方法设置。
我们应用张量以构建计算图的函数实际上是类 Function 的对象。 这个对象知道如何计算正向的函数,以及如何在反向传播步骤中计算它的导数。 对反向传播函数的引用存储在张量的 grad_fn 属性中。
print(f"Gradient function for z = {z.grad_fn}")
print(f"Gradient function for loss = {loss.grad_fn}")
out:
Gradient function for z = <AddBackward0 object at 0x7fae23d0b210>
Gradient function for loss = <BinaryCrossEntropyWithLogitsBackward0 object at 0x7fae23d7de90>
计算梯度
为了计算这些导数,我们调用 loss.backward(),然后从 w.grad 和 b.grad 中检索值。
loss.backward()
print(w.grad)
print(b.grad)
out:
tensor([[0.2920, 0.3199, 0.2709],
[0.2920, 0.3199, 0.2709],
[0.2920, 0.3199, 0.2709],
[0.2920, 0.3199, 0.2709],
[0.2920, 0.3199, 0.2709]])
tensor([0.2920, 0.3199, 0.2709])
我们只能获取计算图叶节点的 grad 属性,其中 requires_grad 属性设置为 True。 对于我们图中的所有其他节点,梯度将不可用。
出于性能原因,我们只能在给定的图上使用一次后向执行梯度计算。 如果我们需要对同一个图进行多次反向调用,我们需要将 retain_graph=True 传递给反向调用。
禁用梯度跟踪
默认情况下,所有 requires_grad=True 的张量都在跟踪它们的计算历史并支持梯度计算。 但是,在某些情况下我们不需要这样做,例如,当我们训练了模型并且只想将其应用于某些输入数据时,即我们只想通过网络进行前向计算。 我们可以通过用 torch.no_grad() 块使计算代码停止跟踪:
z = torch.matmul(x, w)+b
print(z.requires_grad)
with torch.no_grad():
z = torch.matmul(x, w)+b
print(z.requires_grad)
out:
True
False
Another way to achieve the same result is to use the detach()
method on the tensor:
z = torch.matmul(x, w)+b
z_det = z.detach()
print(z_det.requires_grad)
out:
False
禁用梯度跟踪的原因如下:
- 将神经网络中的某些参数标记为冻结参数。 这是微调预训练网络的一个非常常见的场景
- 只进行前向传递时加快计算速度,因为在不跟踪梯度的张量上进行计算会更有效。
参考
官方文档:Automatic Differentiation with torch.autograd — PyTorch Tutorials 1.11.0+cu102 documentation