第 7 章 · 梯度与初始化
Understanding Deep Learning — Gradients and initialization
Chapter 6 introduced iterative optimization algorithms. These are general-purpose methods for finding the minimum of a function. In the context of neural networks, they find parameters that minimize the loss so that the model accurately predicts the training outputs from the inputs. The basic approach is to choose initial parameters randomly and then make a series of small changes that decrease the loss on average. Each change is based on the gradient of the loss with respect to the parameters at the current position.
This chapter discusses two issues that are specific to neural networks.
First, we consider how to calculate the gradients efficiently. This is a serious challenge since the largest models at the time of writing have ∼1012 parameters, and the gradient needs to be computed for every parameter at every iteration of the training algorithm. Second, we consider how to initialize the parameters. If this is not done carefully, the initial losses and their gradients can be extremely large or small. In either case, this impedes the training process.
第 6 章介绍了迭代优化算法。这些是用于寻找函数最小值的通用方法。在神经网络的背景下,它们寻找最小化损失的参数,使模型能够从输入准确预测训练输出。基本方法是随机选择初始参数,然后进行一系列平均降低损失的小幅调整。每次调整都基于当前参数位置处损失对参数的梯度。
本章讨论神经网络特有的两个问题。首先,我们考虑如何高效地计算梯度。这是一个严峻的挑战,因为在本书撰写时,最大的模型拥有 ∼1012 个参数,并且在训练算法的每次迭代中都需要为每个参数计算梯度。其次,我们考虑如何初始化参数。如果初始化不谨慎,初始损失及其梯度可能极大或极小。无论哪种情况,这都会阻碍训练过程。
Consider a network f[ x , ϕ] with multivariate input x, parameters ϕ, and three hidden layers h 1, h 2, and h 3:
where the function a[•] applies the activation function separately to every element of the input. The model parameters ϕ={β0, Ω 0, β1, Ω 1, β2, Ω 2, β3, Ω 3} consist of the bias vectors βk and weight matrices Ω k between every layer (figure 7.1).
考虑一个网络 f[ x ϕ],其多元输入为 x,参数为 ϕ,以及三个隐藏层 h 1,、 h 2, 和 h 3:
其中,函数 a[•] 对输入的每个元素分别应用激活函数。模型参数 ϕ={β0, Ω 0, β1, Ω 1, β2, Ω 2, β3, Ω 3} 由各层之间的偏差向量 βk 和权重矩阵 Ω k 组成(图 7.1)。
We also have individual loss terms ℓi, which return the negative log-likelihood of the ground truth label yi given the model prediction f[ x i, ϕ] for training input x i. For example, this might be the least squares loss ℓi=( f[ x i, ϕ] −yi)2. The total loss is the sum of these terms over the training data:
我们还有各个损失项 ℓi,其回报为真值标签 yi 在模型预测 f[ x i, ϕ] 对应训练输入 x i 下的负对数似然。例如,这可以是最小二乘损失 ℓi= (f[ x i, ϕ] −yi) 2。总损失是这些项在训练数据上的总和:
The most commonly used optimization algorithm for training neural networks is stochastic gradient descent (SGD), which updates the parameters as:
训练神经网络最常用的优化算法是随机梯度下降(SGD),其参数更新方式为:

where α is the learning rate, and Bt contains the batch indices at iteration t. To compute this update, we need to calculate the derivatives: for the parameters{βk, Ω k} at every layer k∈{0, 1,..., K} and for each index i in
其中 α 是学习率, Bt 包含第 t 次迭代中的批次索引。要计算此更新,我们需要计算导数:对于每一层 k∈{0, 1,..., K} 的参数{βk, Ω k},以及每个索引 i 所在的
the batch. The first part of this chapter describes the backpropagation algorithm, which computes these derivatives efficiently.
In the second part of the chapter, we consider how to initialize the network parameters before we commence training. We describe methods to choose the initial weights Ω k and biases βk so that training is stable.
批次。本章第一部分介绍了反向传播算法,该算法能够高效计算这些导数。
在本章的第二部分,我们考虑如何在开始训练之前初始化网络参数。我们介绍如何选择初始权重 Ω k 和偏差 βk,以确保训练稳定。
The derivatives of the loss tell us how the loss changes when we make a small change to the parameters. Optimization algorithms exploit this information to manipulate the parameters so that the loss becomes smaller. The backpropagation algorithm computes these derivatives. The mathematical details are somewhat involved, so we first make two observations that provide some intuition.
Observation 1:
Each weight (element of Ω k) multiplies the activation at a source hidden unit and adds the result to a destination hidden unit in the next layer. It follows that the effect of any small change to the weight is amplified or attenuated by the activation at the source hidden unit. Hence, we run the network for each data example in the batch and store the activations of all the hidden units. This is known as the forward pass (figure 7.1). The stored activations will subsequently be used to compute the gradients.
Observation 2: A small change in a bias or weight causes a ripple effect of changes through the subsequent network. The change modifies the value of its destination hidden
损失的导数告诉我们,当对参数进行微小改变时,损失如何变化。优化算法利用这些信息来调整参数,使损失变得更小。反向传播算法计算这些导数。数学细节较为复杂,因此我们先提出两个观察,以提供一些直观理解。
观察 1: 每个权重(Ω k 中的元素)乘以源隐藏单元的激活值,并将结果加到下一层的目标隐藏单元。因此,对权重的任何微小改变所产生的影响,都会被源隐藏单元的激活值放大或衰减。于是,我们对批次中的每个数据样本运行网络,并存储所有隐藏单元的激活值。这被称为前向传播(图 7.1)。随后,这些存储的激活值将用于计算梯度。观察 2:偏差或权重的微小变化会在后续网络中引发连锁变化。该变化会修改其目标隐藏
unit. This, in turn, changes the values of the hidden units in the subsequent layer, which will change the hidden units in the layer after that, and so on, until a change is made to the model output and, finally, the loss.
单元。这反过来会改变后续层中隐藏单元的值,进而改变再后一层中的隐藏单元,依此类推,直到模型输出发生变化,并最终影响损失。

Hence, to know how changing a parameter modifies the loss, we also need to know how changes to every subsequent hidden layer will, in turn, modify their successor. These same quantities are required when considering other parameters in the same or earlier layers. It follows that we can calculate them once and reuse them. For example, consider computing the effect of a small change in weights that feed into hidden layers h 3, h 2, and h 1, respectively: • To calculate how a small change in a weight or bias feeding into hidden layer h 3 modifies the loss, we need to know (i) how a change in layer h 3 changes the model
output f, and (ii) how a change in this output changes the loss ℓ (figure 7.2a). • To calculate how a small change in a weight or bias feeding into hidden layer h 2 modifies the loss, we need to know (i) how a change in layer h 2 affects h 3, (ii) how h 3
changes the model output, and (iii) how this output changes the loss (figure 7.2b). • To calculate how a small change in a weight or bias feeding into hidden layer h 1 modifies the loss, we need to know (i) how a change in layer h 1 affects layer h 2, (ii) how a change in layer h 2 affects layer h 3, (iii) how layer h 3 changes the model
因此,要了解改变一个参数如何影响损失,我们还需要了解对每个后续隐藏层的改动如何依次影响其后继层。在考虑同一层或更早层中的其他参数时,也需要这些相同的量。因此我们可以计算一次并重复使用它们。例如,考虑计算分别馈入隐藏层 h 3,、 h 2, 和 h 1, 的权重发生微小变化的影响: • 为了计算一个馈入隐藏层 h 1 的权重或偏差的微小变化如何改变损失,我们需要知道 (i) 层 h 1 的变化如何影响层 h 2, (ii) 层 h 2 的变化如何影响层 h 3, (iii) 层 h 3 如
output, and (iv) how the model output changes the loss (figure 7.2c).
As we move backward through the network, we see that most of the terms we need were already calculated in the previous step, so we do not need to re-compute them. Proceeding backward through the network in this way to compute the derivatives is known as the backward pass.
何改变模型输出,以及 (iv) 模型输出如何改变损失(图 7.2c)。
当我们在神经网络中向后推进时,会发现所需的大多数项已经在上一步计算过,因此无需重新计算。以这种方式在神经网络中向后推进来计算导数,称为反向传播。

The ideas behind backpropagation are relatively easy to understand. However, the derivation requires matrix calculus because the bias and weight terms are vectors and matrices, respectively. To help grasp the underlying mechanics, the following section derives backpropagation for a simpler toy model with scalar parameters. We then apply the same approach to a deep neural network in section 7.4.
反向传播背后的思想相对容易理解。然而,其推导需要矩阵微积分,因为偏差项和权重项分别是向量和矩阵。为了帮助理解其底层机制,下一节将针对一个具有标量参数的更简单玩具模型推导反向传播。随后,我们将在第 7.4 节中把相同方法应用于深层神经网络。
Consider a model f[x, ϕ] with eight scalar parameters ϕ = {β0, ω0, β1, ω1, β2, ω2, β3, ω3} that consists of a composition of the functions sin[•], exp[•], and cos[•]:

where, as usual, xi is the ith training input, and yi is the ith training output. You can think of this as a simple neural network with one input, one output, one hidden unit at each layer, and different activation functions sin[•], exp[•], and cos[•] between each layer.
We aim to compute the derivatives:
Of course, we could find expressions for these derivatives by hand and compute them directly. However, some of these expressions are quite complex. For example:
当然,我们可以手动求出这些导数的表达式并直接计算。然而,其中一些表达式相当复杂。例如:反向传播算法是一种高效的方法,可一次性计算所有这些导数。它包括(i)前向传播,在此过程中我们计算并存储一系列中间值和网络的输出,以及(ii)反向传播,在此过程中
Such expressions are awkward to derive and code without mistakes and do not exploit the inherent redundancy; notice that the three exponential terms are the same. The backpropagation algorithm is an efficient method for computing all of these derivatives at once. It consists of (i) a forward pass, in which we compute and store a series of intermediate values and the network output, and (ii) a backward pass, in which
we calculate the derivatives of each parameter, starting at the end of the network, and reusing previous calculations as we move toward the start.
Forward pass:

We treat the computation of the loss as a series of calculations:
We compute and store the values of the intermediate variables fk and hk (figure 7.3).
我们从网络末端开始计算每个参数的导数,并在向起始端移动时复用先前的计算。
前向传播:我们将损失的计算视为一系列计算:我们计算并存储中间变量 fk 和 hk 的值 (图 7.3

Backward pass #1:
We now compute the derivatives of ℓi with respect to these intermediate variables, but in reverse order: The left-hand side asks how ℓi changes when h3 changes. The right-hand side says we can decompose this into (i) how f3 changes when h3 changes and (ii) how ℓi changes when f3 changes. In the original equations, h3 changes f3, which changes ℓi, and the derivatives
反向传播 #1:我们现在计算 ℓi 对这些中间变量的导数,但按相反顺序:左侧问的是 ℓi 如何随 h3 变化。右侧表示我们可以将其分解为 (i) f3 如何随 h3 变化以及 (ii) ℓi 如何随 f3 变化。在原始方程中, h3 改变 f3,而 f3 又改变 ℓi,并且各导数
represent the effects of this chain. Notice that we already computed the second of these derivatives, and the other is the derivative of β3 +ω3 ·h3 with respect to h3, which is ω3.
We continue in this way, computing the derivatives of the output with respect to these intermediate quantities (figure 7.4): In each case, we have already computed the quantities in the brackets in the previous
我们继续以这种方式计算输出关于这些中间量的导数(图 7.4):在每种情况下,我们已计算过括号中的量,在上一

step, and the last term has a simple expression. These equations embody Observation 2 from the previous section (figure 7.2); we can reuse the previously computed derivatives if we calculate them in reverse order.
Backward pass #2:
步骤中,且最后一项具有简单表达式。这些方程体现了上一节中的观察 2 (图 7.2);如果我们按相反顺序计算,就可以复用先前计算出的导数。
Finally, we consider how the loss ℓi changes when we change the parameters{βk} and{ωk}. Once more, we apply the chain rule (figure 7.5):
In each case, the second term on the right-hand side was computed in equation 7.13. When k> 0, we have fk= βk + ωk · hk, so:
反向传播 #2:最后,我们考虑当我们改变参数 {βk} 和 {ωk} 时,损失 ℓi 如何变化。我们再次应用链式法则(图 7.5):

This is consistent with Observation 1 from the previous section; the effect of a change in the weight ωk is proportional to the value of the source variable hk (which was stored in the forward pass). The final derivatives from the term f0= β0 + ω0 · xi are: Backpropagation is both simpler and more efficient than computing the derivatives individually, as in equation 7.8. 1
这与上一节中的观察 1 一致;权重 ωk 的变化所产生的影响与源变量 hk 的值成正比(该值在前向传播中已被存储)。由项 f0= β0 + ω0 · xi 得到的最终导数为:反向传播比逐个计算导数更简单且更高效,如公式 7.8 所示。 1
Now we repeat this process for a three-layer network (figure 7.1). The intuition and much of the algebra are identical. The main differences are that intermediate variables f k, h k are vectors, the biases βk are vectors, the weights Ω k are matrices, and we are using ReLU functions rather than simple algebraic functions like cos[•].
Forward pass:
We write the network as a series of sequential calculations:
现在,我们对三层网络重复这一过程(图 7.1)。直观理解和大部分代数推导都相同。主要区别在于:中间变量 f k, h k 是向量,偏差 βk 是向量,权重 Ω k 是矩阵,并且我们使用的是 ReLU 函数,而不是像 cos[•] 这样的简单代数函数。
前向传播:我们将网络写成一系列顺序计算:
where f k−1 represents the pre-activations at the kth hidden layer (i.e., the values before the ReLU function a[•]) and h k contains the activations at the kth hidden layer (i.e., after the ReLU function). The term l[ f 3, yi] represents the loss function (e.g., least squares or binary cross-entropy loss). In the forward pass, we work through these calculations and store all the intermediate quantities.
其中 f k−1 表示 kth 隐藏层的预激活值(即 ReLU 函数 a[•] 之前的值),而 h k 包含 kth 隐藏层的激活值(即 ReLU 函数之后的值)。项 l[ f 3, yi] 表示损失函数(例如最小二乘或二元交叉熵损失)。在前向传播中,我们依次执行这些计算并存储所有中间量。
Backward pass #1: Now let’s consider how the loss changes when the pre-activations f 0, f 1, f 2 change. Applying the chain rule, the expression for the derivative of the loss ℓi
with respect to f 2 is:
关于 f 2 的导数为:
The three terms on the right-hand side have sizes D3×D3, D3×Df, and Df×1, respectively, where D3 is the number of hidden units in the third layer, and Df is the dimensionality of the model output f 3.
Similarly, we can compute how the loss changes when we change f 1 and f 0: Note that in each case, the term in brackets was computed in the previous step. By
右侧三项的大小分别为 D3×D3、 D3×Df 和 Df×1,其中 D3 是第三层中隐藏单元的数量, Df 是模型输出 f 3 的维度。
类似地,我们可以计算当改变 f 1 和 f 0 时损失如何变化:请注意,在每种情况下,方括号中的项都已在上一步中计算过。通过

working backward through the network, we can reuse the previous computations. Moreover, the terms themselves are simple. Working backward through the right-
沿网络反向进行,我们可以复用先前的计算。此外,这些项本身很简单。沿右侧反向进行 -
hand side of equation 7.18, we have: • The derivative ∂ℓi/∂ f 3 of the loss ℓi with respect to the network output f 3 will
depend on the loss function but usually has a simple form.
• The derivative ∂ f 3/∂ h 3 of the network output with respect to hidden layer h 3 is: If you are unfamiliar with matrix calculus, this result is not obvious. It is explored
方程 7.18 的右侧,我们得到:
• 损失 ∂ℓi/∂ f 3 关于网络输出 f 3 的导数 ℓi 取决于损失函数,但通常形式简单。
• 导数 ∂ f 3/∂ h 3,即网络输出关于隐藏层 h 3 的导数,为:如果你不熟悉矩阵微积分,这一结果并不显然。它被探讨

in problem 7.6. • The derivative ∂ h 3/∂ f 2 of the output h 3 of the activation function with respect to its input f 2 will depend on the activation function. It will be a diagonal matrix since each activation only depends on the corresponding pre-activation. For ReLU functions, the diagonal terms are zero everywhere f 2 is less than zero and one otherwise (figure 7.6). Rather than multiply by this matrix, we extract the diagonal
terms as a vector I[ f 2> 0] and pointwise multiply, which is more efficient. The terms on the right-hand side of equations 7.19 and 7.20 have similar forms. As we progress back through the network, we alternately (i) multiply by the transpose of the weight matrices Ω T
在问题 7.6 中。 • 输出 h 3 关于其输入 f 2 的导数 ∂ h 3/∂ f 2 取决于激活函数。由于每个激活值仅依赖于对应的预激活值,因此它将是一个对角矩阵。对于 ReLU 函数,当 f 2 小于零时,对角元素处处为零,以及 1公式 7.19 和 7.20 右侧的各项具有相似的形式。当我们沿网络反向传播时,我们交替地(i)乘以权重矩阵 Ω T
k and (ii) threshold based on the inputs f k−1 to the hidden layer. These inputs were stored during the forward pass.
Backward pass #2:
Now that we know how to compute ∂ℓi/∂ f k, we can focus on calculating the derivatives of the loss with respect to the weights and biases. To calculate the derivatives of the loss with respect to the biases βk, we again use the chain rule:
k 的转置,并(ii)根据到隐藏层的输入 f k−1 进行阈值处理。这些输入在前向传播期间被存储。
反向传播 #2:既然我们已经知道如何计算 ∂ℓi/∂ f k,就可以专注于计算损失关于权重和偏差的导数。为了计算损失关于偏差 βk 的导数,我们再次使用链式法则:
which we already calculated in equations 7.18 and 7.19.
这已在公式 7.18 和 7.19 中计算过。
Similarly, the derivative for the weights matrix Ω k, is given by: Again, the progression from line two to line three is not obvious and is explored in
problem 7.9. However, the result makes sense. The final line is a matrix of the same size as Ω k. It depends linearly on h k, which was multiplied by Ω k in the original expression. This is also consistent with the initial intuition that the derivative of the weights in Ω k will be proportional to the values of the hidden units h k that they multiply. Recall that we already computed these during the forward pass.
类似地,权重矩阵 Ω k 的导数由下式给出:
同样,从第二行到第三行的推导并不显然,将在问题 7.9。然而,该结果是合理的。最后一行是一个与 Ω k 大小相同的矩阵。它线性依赖于 h k,而后者在原始表达式中与 Ω k 相乘。这也与最初的直觉一致: Ω k 中权重的导数将与它们所乘的隐藏单元 h k 的值成比例。请记住,我们在前向传播过程中已经计算了这些值。
We now briefly summarize the final backpropagation algorithm. Consider a deep neural network f[ x i, ϕ] that takes input x i, has K hidden layers with ReLU activations, and individual loss term ℓi= l[ f[ x i, ϕ], y i]. The goal of backpropagation is to compute the derivatives ∂ℓi/∂βk and ∂ℓi/∂ Ω k with respect to the biases βk and weights Ω k.
Forward pass:
We compute and store the following quantities:
我们现在简要总结最终的反向传播算法。考虑一个深层神经网络 f[ x i, ϕ],它以 x i 为输入,具有 K 个采用 ReLU 激活的隐藏层,以及单个损失项 ℓi= l[ f[ x i, ϕ], y i]。反向传播的目标是计算导数 ∂ℓi/∂βk 和 ∂ℓi/∂ Ω k,即关于偏差 βk 和权重 Ω k 的导数。
前向传播:我们计算并存储以下量:
Backward pass:
We start with the derivative ∂ℓi/∂ f K of the loss function ℓi with respect to the network output f K and work backward through the network:
反向传播:我们从导数 ∂ℓi/∂ f K 开始,即损失函数 ℓi 关于网络输出 f K 的导数,并沿网络反向计算:

where ⊙ denotes pointwise multiplication, and I[ f k−1>0] is a vector containing ones where f k−1 is greater than zero and zeros elsewhere. Finally, we compute the derivatives with respect to the first set of biases and weights: We calculate these derivatives for every training example in the batch and sum them
其中 ⊙ 表示逐元素乘法,而 I[ f k−1>0] 是一个向量,其中在 f k−1 大于零的位置为 1,其余位置为 0。最后,我们计算关于第一组偏差和权重的导数:我们对批次中的每个训练样本计算这些导数并求和
together to retrieve the gradient for the SGD update. Note that the backpropagation algorithm is extremely efficient; the most demanding computational step in both the forward and backward pass is matrix multiplication (by Ω
and Ω T, respectively) which only requires additions and multiplications. However, it is not memory efficient; the intermediate values in the forward pass must all be stored, and this can limit the size of the model we can train.
一起获取用于 SGD 更新的梯度。请注意,反向传播算法极其高效;在前向和反向传播中,计算量最大的步骤都是矩阵乘法(分别通过 Ω 和 Ω T 进行),而这只需要加法和乘法。然而,它并不节省内存;前
向传播中的所有中间值都必须存储,这可能会限制我们可以训练的模型规模。
Although it’s important to understand the backpropagation algorithm, it’s unlikely that you will need to code it in practice. Modern deep learning frameworks such as PyTorch
and TensorFlow calculate the derivatives automatically, given the model specification. This is known as algorithmic differentiation.
Each functional component (linear transform, ReLU activation, loss function) in the framework knows how to compute its own derivative. For example, the PyTorch ReLU function z out= relu[ z in] knows how to compute the derivative of its output z out with respect to its input z in. Similarly, a linear function z out=β+ Ωz in knows how to compute the derivatives of the output z out with respect to the input z in and with respect to the parameters β and Ω. The algorithmic differentiation framework also knows the sequence of operations in the network and thus has all the information required to perform the forward and backward passes. These frameworks exploit the massive parallelism of modern graphics processing units (GPUs). Computations such as matrix multiplication (which features in both the forward and backward pass) are naturally amenable to parallelization. Moreover, it’s possible to
虽然理解反向传播算法很重要,但在实践中你不太可能需要自己编写代码。诸如 PyTorch 等现代深度学习框架
和 TensorFlow 会在给定模型规范的情况下自动计算导数。这被称为算法微分。
框架中的每个功能组件(线性变换、 ReLU 激活、损失函数)都知道如何计算自身的导数。例如, PyTorch 的 ReLU 函数 z out= relu[ z in] 知道如何计算其输出 z out 相对于其输入 z in 的导数。类似地,线性函数 z out=β+ Ωz in 知道如何计算输出 z out 相对于输入 z in 以及相对于参数 β 和 Ω 的导数。算法微分框架也知道网络中的操作序列,因此拥有执行前向传播和反向传播所需的全部信息。这些框架利用了现代图形处理单元(GPU)的大规模并行性。诸如矩阵乘法(在前向传播和反向传播中均出现)这样的计算天然适合并行化。此外,还可以
perform the forward and backward passes for the entire batch in parallel if the model and intermediate results in the forward pass do not exceed the available memory.
Since the training algorithm now processes the entire batch in parallel, the input becomes a multi-dimensional tensor. In this context, a tensor can be considered the generalization of a matrix to arbitrary dimensions. Hence, a vector is a 1D tensor, a matrix is a 2D tensor, and a 3D tensor is a 3D grid of numbers. Until now, the training data have been 1D, so the input for backpropagation would be a 2D tensor where the first dimension indexes the batch element and the second indexes the data dimension. In subsequent chapters, we will encounter more complex structured input data.
For example, in models where the input is an RGB image, the original data examples are 3D (height × width × channel). Here, the input to the learning framework would be a 4D tensor, where the extra dimension indexes the batch element.
由于训练算法现在并行处理整个批次,输入变成了多维张量。在此语境下,张量可以被视为矩阵向任意维度的泛化。因此,向量是一维张量,矩阵是二维张量,三维张量是三维数字网格。到目前为止,训练数据一直是一维的,因此反向传播的输入会是二维张量,其中第一维度索引批次元素,第二维度索引数据维度。在后续章节中,我们会遇到结构更复杂的输入数据。例如,在输入为 RGB 图像的模型中,原始数据样本是三维的(高度 × 宽度 × 通道)。这里,学习框架的输入会是四维张量,其中额外维度索引批次元素。
We have described backpropagation in a deep neural network that is naturally sequential; we calculate the intermediate quantities f 0, h 1, f 1, h 2..., f k in turn. However, models need not be restricted to sequential computation.
Later in this book, we will meet models with branching structures. For example, we might take the values in a hidden layer and process them through two different sub-networks before recombining.
我们已经在天然按顺序计算的深层神经网络中描述了反向传播;我们依次计算中间量 f 0, h 1, f 1, h 2..., f k。然而,模型不必局限于顺序计算。本书后面,我们会遇到具有分支结构的模型。例如,我们可以取隐藏层中的值,将它们通过两个不同的子网络处理,然后再合并。
Fortunately, the ideas of backpropagation still hold if the computational graph is acyclic. Modern algorithmic differentiation frameworks such as PyTorch and TensorFlow can handle arbitrary acyclic computational graphs.
幸运的是,如果计算图是无环的,反向传播的思想仍然成立。现代算法微分框架(如 PyTorch 和 TensorFlow)可以处理任意无环计算图。
The backpropagation algorithm computes the derivatives that are used by stochastic gradient descent and Adam to train the model. We now address how to initialize the parameters before we start training. To see why this is crucial, consider that during the forward pass, each set of pre-activations f k is computed as:
反向传播算法计算随机梯度下降和 Adam 用于训练模型的导数。我们现在讨论如何在开始训练之前初始化参数。为了理解这为何至关重要,考虑在前向传播过程中,每一组预激活值 f k 计算如下:
where a[•] applies the ReLU functions and Ω k and βk are the weights and biases, respectively. Imagine that we initialize all the biases to zero and the elements of Ω k according to a normal distribution with mean zero and variance σ2. Consider two scenarios: • If the variance σ2 is very small (e.g., 10−5), then each element of βk + Ω k h k will be a weighted sum of h k where the weights are very small; the result will likely have a smaller magnitude than the input. In addition, the ReLU function clips values less than zero, so the range of h k will be half that of f k−1. Consequently, the magnitudes of the pre-activations at the hidden layers will get smaller and smaller
as we progress through the network. • If the variance σ2 is very large (e.g., 105), then each element of βk + Ω k h k will be a weighted sum of h k where the weights are very large; the result is likely to have a much larger magnitude than the input. The ReLU function halves the range of the inputs, but if σ2 is large enough, the magnitudes of the pre-activations will still
其中, a[•] 应用 ReLU 函数, Ω k 和 βk 分别为权重和偏差。设想我们将所有偏差初始化为零,并按照均值为零、方差为 σ2 的正态分布初始化 Ω k 的元素。考虑两种情况: • 如果方差 σ2 非常小(例如 10−5),那么 βk + Ω k h k 的每个元素都将是 h k 的加权和,其中权重非常小;结果很可能比输入的幅度更小。此外, ReLU 函数会截断小于零的值,因此 h k 的取值范围将是 f k−1 取值范围的一半。因此,随着我们在网络中逐
层推进,隐藏层中预激活值的幅度会越来越小。 • 如果方差 σ2 非常大(例如 10 5),那么 βk + Ω k h k 的每个元素都将是 h k 的加权和,其中权重非常大;结果很可能比输入的幅度大得多。 ReLU 函数会使输入的取值范围减半,但如果 σ2 足够大,预激活值的幅度仍会随着我们在网络中逐层推进而变
get larger as we progress through the network.
In these two situations, the values at the pre-activations can become so small or so large that they cannot be represented with finite precision floating point arithmetic.
Even if the forward pass is tractable, the same logic applies to the backward pass. Each gradient update (equation 7.25) consists of multiplying by Ω T. If the values of Ω are not initialized sensibly, then the gradient magnitudes may decrease or increase uncontrollably during the backward pass. These cases are known as the vanishing gradient problem and the exploding gradient problem, respectively. In the former case, updates to the model become vanishingly small. In the latter case, they become unstable.
得更大。
在这两种情况下,预激活值可能变得过小或过大,以至于无法用有限精度浮点运算表示。
即使前向传播是可处理的,同样的逻辑也适用于反向传播。每次梯度更新(公式 7.25)都涉及乘以 Ω T。如果 Ω 的值没有合理初始化,那么梯度幅度可能在反向传播过程中不可控地减小或增大。这些情况分别称为梯度消失问题和梯度爆炸问题。在前一种情况下,对模型的更新会变得极其微小;在后一种情况下,它们会变得不稳定。
We now present a mathematical version of the same argument. Consider the computation between adjacent pre-activations f and f ′ with dimensions Dh and Dh′, respectively:
我们现在给出同一论证的数学版本。考虑相邻预激活值 f 与 f ′ 之间的计算,其维度分别为 Dh 和 Dh′:
where h represents the activations, Ω and β represent the weights and biases, and a[•] is the activation function. Assume the pre-activations fj in the input layer f have variance σ2 f. Consider initializing the biases βi to zero and the weights Ωij as normally distributed with mean zero and variance σ2
其中, h 表示激活值, Ω 和 β 表示权重和偏差, a[•] 是激活函数。假设输入层 f 中的预激活值 fj 具有方差 σ2 f。考虑将偏差 βi 初始化为零,并将权重 Ω ij 初始化为服从均值为零、方差为 σ2

Now we derive expressions for the mean and variance of the pre-activations f ′ in the subsequent layer. The expectation (mean) E[f′ i] of the intermediate values f ′
i is: where Dh is the dimensionality of the input layer h. We have used the rules for manipu- lating expectations, and we have assumed that the distributions over the hidden units hj
Ω 的正态分布。现在,我们推导后续层中预激活值 f ′ 的均值和方差表达式。这反过来意味着,如果我们希望后续预激活值 f ′ 的方差 σ2 f′ 与前向传播过程中原始预激活值 f 的方差 σ2
and the network weights Ωij are independent between the second and third lines. Using this result, we see that the variance σ2 f′ of the pre-activations f ′
i is: where we have used the variance identity σ2=E[(z −E[z])2]=E[z2] −E[z]2. We have assumed once more that the distributions of the weights Ωij and the hidden units hj are
independent between lines three and four. Assuming that the distribution of pre-activations fj at the previous layer is symmetric about zero, half of these pre-activations will be clipped by the ReLU function, and the second moment E[h2 j] will be half the variance σ2
f of fj (see problem 7.14): This, in turn, implies that if we want the variance σ2 f′ of the subsequent pre-activations f ′ to be the same as the variance σ2
f of the original pre-activations f during the forward pass, we should set:

where Dh is the dimension of the original layer to which the weights were applied. This is known as He initialization.
f 相同,则应设置:
其中 Dh 是应用权重时原始层的维度。这被称为 He 初始化。
A similar argument establishes how the variance of the gradients ∂l/∂fk changes during the backward pass. During the backward pass, we multiply by the transpose Ω T of the weight matrix (equation 7.25), so the equivalent expression becomes:
类似的论证阐明了梯度 ∂l/∂fk 的方差在反向传播过程中如何变化。在反向传播过程中,我们乘以权重矩阵的转置 Ω T (公式 7.25),因此等效表达式变为:
where Dh′ is the dimension of the layer that the weights feed into.
其中 Dh′ 是权重所馈入的层的维度。
If the weight matrix Ω is not square (i.e., there are different numbers of hidden units in the two adjacent layers, so Dh and Dh′ differ), then it is not possible to choose the variance to satisfy both equations 7.32 and 7.33 simultaneously. One possible compromise is to use the mean(Dh + Dh′)/2 as a proxy for the number of terms, which gives: Figure 7.7 shows empirically that both the variance of the hidden units in the forward
如果权重矩阵 Ω 不是方阵(即相邻两层中的隐藏单元数量不同,因此 Dh 和 Dh′ 不同),则无法选择方差以同时满足公式 7.32 和 7.33。一种可能的折中方案是使用均值 (Dh + Dh′) /2 作为项数的代理,从而得到:图 7.7 实证表明,前向传播中隐藏单元的方差以及
pass and the variance of the gradients in the backward pass remain stable when the parameters are initialized appropriately.
传播,并且当参数被适当初始化时,反向传播中的梯度方差保持稳定。
The primary focus of this book is scientific; this is not a guide for implementing deep learning models. Nonetheless, in figure 7.8, we present PyTorch code that implements the ideas explored in this book so far. The code defines a neural network and initializes
本书的重点是科学性的;这不是一本实现深度学习模型的指南。尽管如此,在图 7.8 中,我们展示了实现本书迄今所探讨理念的 PyTorch 代码。该代码定义了一个神经网络并初始化
the weights. It creates random input and output datasets and defines a least squares loss function. The model is trained from the data using SGD with momentum in batches of size 10 over 100 epochs. The learning rate starts at 0.01 and halves every 10 epochs.
The takeaway is that although the underlying ideas in deep learning are quite complex, implementation is relatively simple. For example, all of the details of the backpropagation are hidden in the single line of code: loss.backward().
权重。它创建随机输入和输出数据集,并定义一个最小二乘损失函数。模型通过带动量的 SGD,以批量大小 10 在数据上训练 100 轮。学习率从 0.01 开始,每 10 轮减半一次。
要点是,尽管深度学习的基本思想相当复杂,但实现相对简单。例如,反向传播的所有细节都隐藏在一行代码中: loss.backward()。
The previous chapter introduced stochastic gradient descent (SGD), an iterative optimization algorithm that aims to find the minimum of a function. In the context of neural networks, this algorithm finds the parameters that minimize the loss function. SGD relies on the gradient of the loss function with respect to the parameters, which must be initialized before optimization. This chapter has addressed these two problems for deep neural networks. The gradients must be evaluated for a very large number of parameters, for each member of the batch, and at each SGD iteration. It is hence imperative that the gradient
Figure 7.8 Sample code for training two-layer network on random data.
上一章介绍了随机梯度下降(SGD),这是一种迭代优化算法,旨在寻找函数的最小值。在神经网络中,该算法寻找使损失函数最小化的参数。 SGD 依赖于损失函数相对于参数的梯度,这些参数必须在优化之前初始化。本章针对深层神经网络解决了这两个问题。梯度必须针对大量参数、批次中的每个样本以及每次 SGD 迭代进行计算。因此,梯度必须
图 7.8 在随机数据上训练两层网络的示例代码。
computation is efficient, and to this end, the backpropagation algorithm was introduced. Careful parameter initialization is also critical.
The magnitudes of the hidden unit activations can either decrease or increase exponentially in the forward pass. The same is true of the gradient magnitudes in the backward pass, where these behaviors are known as the vanishing gradient and exploding gradient problems. Both impede training but can be avoided with appropriate initialization.
We’ve now defined the model and the loss function, and we can train a model for a given task. The next chapter discusses how to measure the model performance.
计算是高效的,为此引入了反向传播算法。谨慎的参数初始化也至关重要。在前向传播中,隐藏单元激活值的大小可能指数级减小或增大。在反向传播中,梯度大小也是如此,这些现象分别被称为梯度消失和梯度爆炸问题。二者都会阻碍训练,但可以通过适当的初始化避免。
我们现在已经定义了模型和损失函数,并且可以为一个 g 给定任务。下一章讨论了如何衡量模型性能。
Backpropagation:
Initialization:
Reducing memory requirements:
Distributed training:
Figure 7.9 Computational graph for problem 7.12 and problem 7.13. Adapted from Domke (2010). and rect[z] = Discuss why these functions are problematic for neural network training with gradient-based optimization methods. Problem 7.9 ∗ Consider a loss function ℓ[ f ], where f = β + Ωh. We want to find how the loss ℓ changes when we change Ω, which we’ll express with a matrix that contains the derivative ∂ℓ/∂Ωij at the ith row and jth column. Find an expression for ∂fi/∂Ωij and, using the chain rule, show that: Problem 7.10 ∗ Derive the equations for the backward pass of the backpropagation algorithm for a network that uses leaky ReLU activations, which are defined as: where α is a small positive constant (typically 0.1). Problem 7.11 Consider training a network with fifty layers using gradient checkpointing. Assume that we store the pre-activations at every tenth hidden layer during the forward pass. Explain how to compute the derivatives in this situation. Problem 7.12 ∗ This problem explores computing derivatives on general acyclic computational graphs. Consider the function: We can break this down into a series of intermediate computations so that:
图 7.9 问题 7.12 和问题 7.13 的计算图。改编自 Domke (2010)。 and rect[z] = 讨论这些函数为何会给基于梯度优化方法的神经网络训练带来问题。问题 7. 9 ∗ 考虑一个损失函数 ℓ[ f ],,其中 f = β + Ωh。我们想要找到损失 ℓ 在改变 Ω 时如何变化,我们将用一个矩阵来表示它,该矩阵包含第 ith 行、第 jth 列处的导数 ∂ℓ/∂ Ω ij。求出 ∂fi/∂ Ω ij 的表达式,并使用链式法则证明:问题 7. 10 ∗ 推导使用 Leaky ReLU 激活函数的网络的反向传播算法的反向传播方程,其定义如下:其中 α 是一个小的正数(通常为 0.1)。问题 7.11 考虑使用梯度检查点训练一个五十层的网络。假设在前向传播过程中,我们在每第十个隐藏层存储预激活值。解释在这种情况下如何计算导数。问题 7。 12 ∗ 本题探讨在一般无环计算图上计算导数。考虑函数: