第 6 章 · 拟合模型
Understanding Deep Learning — Fitting models
Chapters 3 and 4 described shallow and deep neural networks. These represent families of piecewise linear functions, where the parameters determine the particular function. Chapter 5 introduced the loss — a single number representing the mismatch between the network predictions and the ground truth for a training set.
The loss depends on the network parameters, and this chapter considers how to find the parameter values that minimize this loss. This is known as learning the network’s parameters or simply as training or fitting the model. The process is to choose initial parameter values and then iterate the following two steps: (i) compute the derivatives (gradients) of the loss with respect to the parameters, and (ii) adjust the parameters based on the gradients to decrease the loss. After many iterations, we hope to reach the overall minimum of the loss function.
This chapter tackles the second of these steps; we consider algorithms that adjust the parameters to decrease the loss. Chapter 7 discusses how to initialize the parameters and compute the gradients for neural networks.
第 3 章和第 4 章描述了浅层和深层神经网络。它们表示分段线性函数族,其中参数决定特定函数。第 5 章介绍了损失 —— 一个表示网络预测值与训练集真值之间差异的单一数值。
损失取决于网络参数,本章考虑如何找到使该损失最小的参数值。这被称为学习网络的参数,或简称为训练或拟合模型。该过程是选择初始参数值,然后迭代以下两个步骤: (i) 计算损失关于参数的导数(梯度), (ii) 根据梯度调整参数以降低损失。经过多次迭代后,我们希望达到损失函数的全局最小值。
本章处理这些步骤中的第二步;我们考虑调整参数以降低损失的算法。第 7 章讨论如何初始化神经网络的参数并计算梯度。
To fit a model, we need a training set{ x i, y i} of input/output pairs. We seek parameters ϕ for the model f[ x i, ϕ] that map the inputs x i to the outputs y i as closely as possible. To this end, we define a loss function L[ϕ] that returns a single number that quantifies the mismatch in this mapping. The goal of an optimization algorithm is to find parameters ˆϕ that minimize the loss:
There are many families of optimization algorithms, but the standard methods for training neural networks are iterative. These algorithms initialize the parameters heuristically and then adjust them repeatedly in such a way that the loss decreases.
要拟合模型,我们需要一个训练集 { x i, y i},它由输入 / 输出对组成。我们寻找模型的参数 ϕ,使 f[ x i, ϕ] 尽可能准确地将输入 x i 映射到输出 y i。为此,我们定义一个损失函数 L[ϕ],其回报是一个单一数值,用于量化该映射中的不匹配。优化算法的目标是找到使损失最小的参数 ϕ:
有许多优化算法家族,但训练神经网络的标准方法是迭代式的。这些算法以启发式方式初始化参数,然后反复调整参数,使损失减小。
The simplest method in this class is gradient descent. This starts with initial parameters ϕ = [ϕ0, ϕ1,..., ϕN]T and iterates two steps:
Step 1.
Compute the derivatives of the loss with respect to the parameters:
这一类中最简单的方法是梯度下降。它从初始参数 ϕ = [ϕ0, ϕ1,..., ϕN]T 开始,并迭代两个步骤:
步骤 1。计算损失相对于参数的导数:
Step 2.
Update the parameters according to the rule:
步骤 2。按照以下规则更新参数:

where the positive scalar α determines the magnitude of the change.
The first step computes the gradient of the loss function at the current position. This determines the uphill direction of the loss function. The second step moves a small distance αdownhill (hence the negative sign). The parameter α may be fixed (in which case, we call it a learning rate), or we may perform a line search where we try several
其中,正标量 α 决定变化的大小。第一步计算损失函数在当前点的梯度。这决定了损失函数的上坡方向。第二步沿下坡方向移动一小段距离 α (因此有负号)。参数 α 可以固定(在这种情况下
values of α to find the one that most decreases the loss.
At the minimum of the loss function, the surface must be flat (or we could improve further by going downhill). Hence, the gradient will be zero, and the parameters will stop changing. In practice, we monitor the gradient magnitude and terminate the algorithm when it becomes too small.
在损失函数的最小值处,曲面必须是平坦的(否则我们仍可通过沿下坡方向继续改进)。因此,梯度将为零,参数也将停止变化。在实践中,我们监测梯度幅值,并在其变得过小时终止算法。
Consider applying gradient descent to the 1D linear regression model from chapter 2. The model f[x, ϕ] maps a scalar input x to a scalar output y and has parameters ϕ = [ϕ0, ϕ1]T, which represent the y-intercept and the slope:
Given a dataset{xi, yi} containing I input/output pairs, we choose the least squares loss function:
考虑将梯度下降应用于第 2 章中的一维线性回归模型。模型 f[x, ϕ] 将标量输入 x 映射为标量输出 y,并具有参数 ϕ = [ϕ0, ϕ1]T,它们分别表示 y 轴截距和斜率:
给定数据集 {xi, yi},其中包含 I 个输入 / 输出对,我们选择最小二乘损失函数:
where the term ℓi=(ϕ0 + ϕ1xi −yi)2 is the individual contribution to the loss from the ith training example.
The derivative of the loss function with respect to the parameters can be decomposed into the sum of the derivatives of the individual contributions:
其中,项 ℓi= (ϕ0 + ϕ1xi −yi) 2 是第 ith 个训练样本对损失的单独贡献。
损失函数对参数的导数可分解为各个单独贡献的导数之和:


where these are given by: Figure 6.1 shows the progression of this algorithm as we iteratively compute the derivatives according to equations 6.6 and 6.7 and then update the parameters using the
其中,这些导数由下式给出:图 6.1 展示了当我们迭代计算时,该算法的进展根据公式 6.6 和 6.7 计算导数,然后使用公式 6.3 中的规则更新参数。在本例中,我们使用了线搜索过程来寻找在每次迭代中使损失下降最多的 α 的值。
rule in equation 6.3. In this case, we have used a line search procedure to find the value of α that decreases the loss the most at each iteration.
Loss functions for linear regression problems (figure 6.1c) always have a single welldefined global minimum. More formally, they are convex, which means that every chord
(line segment between two points on the surface) lies above the function and does not intersect it. Convexity implies that wherever we initialize the parameters, we are bound to reach the minimum if we keep walking downhill; the training procedure can’t fail.
线性回归问题的损失函数(图 6.1c)总是只有一个明确定义的全局最小值。更正式地说,它们是凸的,这意味着每条弦(曲面上两点之间的线段)位于函数上方且不与函数相交。凸性意味着,无论我们在何处初始化参数,只要持续沿下坡方向移动,就一定能到达最小值;训练过程不会失败。
Unfortunately, loss functions for most nonlinear models, including both shallow and deep networks, are non-convex.
Visualizing neural network loss functions is challenging due to the number of parameters. Hence, we first explore a simpler nonlinear model with two parameters to gain insight into the properties of non-convex loss functions: This Gabormodel maps scalar input x to scalar output y and consists of a sinusoidal
component (creating an oscillatory function) multiplied by a negative exponential component (causing the amplitude to decrease as we move from the center). It has two parameters ϕ=[ϕ0, ϕ1]T, where ϕ0∈R determines the mean position of the function and ϕ1∈R+ stretches or squeezes it along the x-axis (figure 6.2).
不幸的是,大多数非线性模型(包括浅层网络和深层网络)的损失函数都是非凸的。由于参数数量众多,可视化神经网络的损失函数具有挑战性。因此,我们首先探索一个具有两个参数的更简单的非线性模型,以深入了解非凸损失函数的性质:这个加博尔模型将标量输入 x 映射为标量输出 y,包含一个正弦分量(形成振荡函数)乘以一个负指数分量(使振幅随着我们离开中心而减小)。它有两个参数 ϕ=[ϕ0, ϕ1]T,其中 ϕ0∈R 决定函数的平均位置, ϕ1∈R+ 沿 x 轴拉伸或压缩它(图 6.2)。
Consider a training set of I examples{xi, yi} (figure 6.3). The least squares loss function for I training examples is defined as:
考虑一个包含 I 个样本的训练集 {xi, yi}(图 6.3)。针对 I 个训练样本的最小二乘损失函数定义为:
Once more, the goal is to find the parameters ˆϕ that minimize this loss.
ˆ 再一次,目标是找到使该损失最小化的参数 ϕ。
![图 6.2 Gabor 模型。该非线性模型将标量输入 x 映射为标量输出 y,并具有参数 ϕ=[ϕ0, ϕ1]T。它描述一个正弦函数,其振幅随距其中心距离的增加](/learning/udl/ch6/figures/ch6_p05_f0.webp)

Figure 6.4 depicts the loss function associated with the Gabor model for this dataset. There are numerous local minima (cyan circles). Here the gradient is zero, and the loss increases if we move in any direction, but we are not at the overall minimum of the function. The point with the lowest loss is known as the global minimum and is depicted by the gray circle.
图 6.4 展示了该数据集对应的 Gabor 模型的损失函数。存在许多局部最小值(青色圆圈)。此处梯度为零,并且向任意方向移动都会使损失增加,
但我们并不处于函数的整体最小值处。损失最低的点称为全局最小值,由灰色圆圈表示。
If we start in a random position and use gradient descent to go downhill, there is no guarantee that we will wind up at the global minimum and find the best parameters (figure 6.5a). It’s equally or even more likely that the algorithm will terminate in one of the local minima. Furthermore, there is no way of knowing whether there is a better solution elsewhere.
如果我们从随机位置出发,并使用梯度下降下山,就无法保证我们最终会达到全局最小值并找到最佳参数(图 6.5a)。算法终止于某个局部最小值的可能性同样大,甚至更大。此外,我们无法知道别处是否存在更好的解。
In addition, the loss function contains saddle points (e.g., the blue cross in figure 6.4). Here, the gradient is zero, but the function increases in some directions and decreases in others. If the current parameters are not exactly at the saddle point, then gradient descent can escape by moving downhill. However, the surface near the saddle point is flat, so it’s hard to be sure that training hasn’t converged; if we terminate the algorithm when the gradient is small, we may erroneously stop near a saddle point.
此外,损失函数包含鞍点(例如,图 6.4 中的蓝色十字)。在这里,梯度为零,但函数在某些方向上增加,在另一些方向上减小。如果当前参数并不恰好位于鞍点,则梯度下降可以通过沿下坡方向移动而逃离。然而,鞍点附近的曲面是平坦的,因此很难确定训练尚未收敛;如果我们在梯度较小时终止算法,就可能会错误地在鞍点附近停止。


The Gabor model has two parameters, so we could find the global minimum by either (i) exhaustively searching the parameter space or (ii) repeatedly starting gradient descent from different positions and choosing the result with the lowest loss. However, neural network models can have millions of parameters, so neither approach is practical. In short, using gradient descent to find the global optimum of a high-dimensional loss function is challenging. We can find a minimum, but there is no way to tell whether this
is the global minimum or even a good one. One of the main problems is that the final destination of a gradient descent algorithm is entirely determined by the starting point. Stochastic gradient descent (SGD) attempts to remedy this problem by adding some noise to the gradient at each step. The solution
Gabor 模型有两个参数,因此我们可以通过两种方式找到全局最小值: (i) 穷举搜索参数空间,或 (ii) 从不同位置反复启动梯度下降,并选择损失最低的结果。然而,神经网络模型可能拥有数百万个参数,因此这两种方法都不实用。简而言之,使用梯度下降来寻找高维损失函数的全局最优具有挑战性。我们可以找到一个最小值,但无法判断这

still moves downhill on average, but at any given iteration, the direction chosen is not necessarily in the steepest downhill direction. Indeed, it might not be downhill at all. The SGD algorithm has the possibility of moving temporarily uphill and hence jumping from one “valley” of the loss function to another (figure 6.5b).
是全局最小值,甚至是一个好的最小值。
主要问题之一是梯度下降算法的最终落点完全由起始点决定。随机梯度下降(SGD)试图通过在每个步骤中向梯度添加一些噪声来补救这一问题。该解平均而言仍会沿下坡方向移动,但在任意一次迭代中,所选方向不一定是最陡下坡方向。事实上,它可能根本不在下坡方向。 SGD 算法有可能暂时向上移动,从而从一个损失函数的“谷”跳到另一个“谷”(图 6.5b)。
The mechanism for introducing randomness is simple. At each iteration, the algorithm chooses a random subset of the training data and computes the gradient from these examples alone. This subset is known as a minibatch or batch for short. The update rule for the model parameters ϕt at iteration t is hence:
引入随机性的机制很简单。在每次迭代中,算法随机选择训练数据的一个子集,并仅根据这些样本计算梯度。该子集称为小批量或批量(简称)。因此,模型参数 ϕt 在第 t 次迭代的更新规则为:

where Bt is a set containing the indices of the input/output pairs in the current batch and, as before, ℓi is the loss due to the ith pair. The term α is the learning rate, and together with the gradient magnitude, determines the distance moved at each iteration. The learning rate is chosen at the start of the procedure and does not depend on the local properties of the function. The batches are usually drawn from the dataset without replacement. The algorithm works through the training examples until it has used all the data, at which point it
其中, Bt 是包含当前批量中输入 / 输出对索引的集合,并且如前所述, ℓi 是由 ith 对产生的损失。项 α 是学习率,它与梯度大小共同决定每次迭代的移动距离。学习率在过程开始时选定,并不依赖于函数的局部性质。
starts sampling from the full training dataset again. A single pass through the entire training dataset is referred to as an epoch. A batch may be as small as a single example or as large as the whole dataset. The latter case is called full-batch gradient descent and is identical to regular (non-stochastic) gradient descent.
An alternative interpretation of SGD is that it computes the gradient of a different loss function at each iteration; the loss function depends on both the model and the training data and hence will differ for each randomly selected batch.
In this view, SGD performs deterministic gradient descent on a constantly changing loss function (figure 6.6). However, despite this variability, the expected loss and expected gradients at any point remain the same as for gradient descent.
再次开始从完整训练数据集中采样。遍历整个训练数据集一次被称为一个轮次。一个批量可以小到单个样本,也可以大到整个数据集。后一种情况称为全批量梯度下降,与常规(非随机)梯度下降相同。
SGD 的另一种解释是,它在每次迭代时都计算不同损失函数的梯度;损失函数同时取决于模型和训练数据,因此每个随机选择的批次都会有所不同。在这种观点下, SGD 在一个不断变化的损失函数上执行确定性的梯度下降(图 6.6)。然而,尽管存在这种变化,任意一点的期望损失和期望梯度仍与梯度下降相同。
SGD has several attractive features. First, although it adds noise to the trajectory, it still improves the fit to a subset of the data at each iteration. Hence, the updates tend to be sensible even if they are not optimal. Second, because it draws training examples without replacement and iterates through the dataset, the training examples all still contribute equally. Third, it is less computationally expensive to compute the gradient
SGD 有几个吸引人的特征。首先,虽然它会给轨迹添加噪声,但在每次迭代时仍会改善对数据子集的拟合。因此,即使更新并非最优,它们也往往合理。其次,由于它在不放回的情况下抽取训练样本并遍历数据集,所有训练样本仍然同等贡献。第三,计算梯度的计算成本更低
from just a subset of the training data. Fourth, it can (in principle) escape local minima. Fifth, it reduces the chances of getting stuck near saddle points; it is likely that at least some of the possible batches will have a significant gradient at any point on the loss function. Finally, there is some evidence that SGD finds parameters for neural networks that cause them to generalize well to new data in practice (see section 9.2).
SGD does not necessarily “converge” in the traditional sense. However, the hope is that when we are close to the global minimum, all the data points will be well described by the model. Consequently, the gradient will be small, whichever batch is chosen, and the parameters will cease to change much. In practice, SGD is often applied with a learningrateschedule. The learning rate α starts at a high value and is decreased by a constant factor every N epochs. The logic is that in the early stages of training, we want the algorithm to explore the parameter space, jumping from valley to valley to find a sensible region. In later stages, we are roughly in the right place and are more concerned with fine-tuning the parameters, so we decrease α to make smaller changes.
仅从训练数据的一个子集。第四,它(原则上)可以逃离局部极小值。第五,它降低了在鞍点附近卡住的几率;在损失函数的任意一点上,至少某些可能的批次很可能具有显著梯度。最后,有证据表明, SGD 能找到使神经网络在实践中对新数据泛化良好的参数(见 9.2 节)。
SGD 并不一定在传统意义上“收敛”。然而,我们希望当接近全局最小值时,模型能够很好地描述所有数据点。因此,无论选择哪个批次,梯度都会很小,参数也不再大幅变化。在实践中, SGD 通常采用学习率调度。学习率 α 从一个较高值开始,并且每 N 个 epoch 按固定倍数降低。其逻辑是,在训练早期,我们希望算法探索参数空间,在山谷之间跳跃,以找到一个合理的区域。在后期,我们大致处于合适的位置,更关心微调参数,因此降低 α 以进行更小的改变。
A common modification to stochastic gradient descent is to add a momentum term. We update the parameters with a weighted combination of the gradient computed from the current batch and the direction moved in the previous step:
随机梯度下降的一种常见改进是添加一个动量项。我们使用当前批次计算得到的梯度与上一步移动方向的加权组合来更新参数:

where m t is the momentum (which drives the update at iteration t), β∈[0, 1) controls the degree to which the gradient is smoothed over time, and α is the learning rate.
The recursive formulation of the momentum calculation means that the gradient step is an infinite weighted sum of all the previous gradients, where the weights get smaller as we move back in time. The effective learning rate increases if all these gradients
其中 m t 是动量(它驱动第 t 次迭代中的更新), β∈[0, 1)控制梯度随时间平滑的程度,而 α 是学习率。动量计算的递归公式意味着,梯度步长是所有先前梯度的无穷加权和,其中权重随着我们向过去回溯而变小。有效学习率就会增加,如果所有这些梯度
are aligned over multiple iterations but decreases if the gradient direction repeatedly changes as the terms in the sum cancel out. The overall effect is a smoother trajectory and reduced oscillatory behavior in valleys (figure 6.7).
在多次迭代中保持一致,但如果梯度方向反复变化,导致求和项相互抵消,有效学习率就会下降。总体效果是轨迹更平滑,并减少了山谷中的振荡行为(图 6.7)。
The momentum term can be considered a coarse prediction of where the SGD algorithm will move next. Nesterov accelerated momentum (figure 6.8) computes the gradients at
动量项可被视为对 SGD 算法去向的粗略预测
下一步将移动到的位置。 Nesterov 加速动量(图 6.8)在此预测点而非当前点计算梯度:
this predicted point rather than at the current point:


where now the gradients are evaluated at ϕt −αβ · m t. One way to think about this is that the gradient term now corrects the path provided by momentum alone.
此时,梯度在 ϕt −αβ · m t 处求值。一种理解方式是,现在梯度项会修正仅由动量提供的路径。

Gradient descent with a fixed step size has the following undesirable property: it makes large adjustments to parameters associated with large gradients (where perhaps we should be more cautious) and small adjustments to parameters associated with small gradients (where perhaps we should explore further).
When the gradient of the loss surface is much steeper in one direction than another, it is difficult to choose a learning rate that (i) makes good progress in both directions and (ii) is stable (figures 6.9a–b).
固定步长的梯度下降具有如下不理想性质:它会对与大梯度相关的参数进行大幅调整(也许我们应当更加谨慎),并对与小梯度相关的参数进行小幅调整(也许我们应当进一步探索)。当损失曲面在一个方向上的梯度比另一个方向陡峭得多时,很难选择一个学习率,使其(i)在两个方向上都取得良好进展,并且(ii)保持稳定(图 6.9a–b)。
A straightforward approach is to normalize the gradients so that we move a fixed distance (governed by the learning rate) in each direction. To do this, we first measure the gradient m t+1 and the pointwise squared gradient v t+1:
一种直接的方法是对梯度进行归一化,使我们在每个方向上移动固定距离(由学习率控制)。为此,我们首先计算梯度 m t+1 和逐点平方梯度 v t+1:

Then we apply the update rule:
然后我们应用更新规则:

where the square root and division are both pointwise, α is the learning rate, and ϵ is a small constant that prevents division by zero when the gradient magnitude is zero. The term v t+1 is the squared gradient, and the positive root of this is used to normalize the gradient itself, so all that remains is the sign in each coordinate direction. The result is that the algorithm moves a fixed distance α along each coordinate, where the direction is determined by whichever way is downhill (figure 6.9c). This simple algorithm makes good progress in both directions but will not converge unless it happens to land exactly at the minimum. Instead, it will bounce back and forth around the minimum.
Adaptive moment estimation, or Adam, takes this idea and adds momentum to both the estimate of the gradient and the squared gradient:
其中平方根和除法均为逐元素运算, α 为学习率, ϵ 是一个小常数,用于在梯度幅值为零时防止除以零。项 v t+1 是梯度平方,取其正平方根用于对梯度本身进行归一化,因此每个坐标方向上只剩下符号。结果是算法沿每个坐标移动固定距离 α,方向由下坡方向决定(图 6.9c)。这种简单算法在两个方向上都取得良好进展,但除非恰好落在最小值处,否则不会收敛;相反,它会在最小值附近来回振荡。
自适应矩估计,即 Adam,沿用这一思想,并在梯度估计和梯度平方估计中都添加动量:


where β and γ are the momentum coefficients for the two statistics.
Using momentum is equivalent to taking a weighted average over the history of each of these statistics. At the start of the procedure, all the previous measurements are effectively zero, resulting in unrealistically small estimates. Consequently, we modify these statistics using the rule:
其中 β 和 γ 是这两个统计量的动量系数。
使用动量相当于对每个统计量的历史进行加权平均。在过程开始时,所有先前的测量值实际上都为零,导致估计值小得不切实际。因此,我们使用以下规则修改这些统计量:


Since β and γ are in the range[0, 1), the terms with exponents t+1 become smaller with each time step, the denominators become closer to one, and this modification has a diminishing effect.
Finally, we update the parameters as before, but with the modified terms: The result is an algorithm that can converge to the overall minimum and makes good progress in every direction in the parameter space. Note that Adam is usually used in a
由于 β 和 γ 位于范围 [0, 1) 内,带指数 t+1 的项会随着每个时间步变小,分母逐渐接近 1,因此这一修改的影响会逐渐减弱。
最后,我们像之前一样更新参数,但使用修改后的项:其结果是一种能够收敛到全局最小值并产生良好


stochastic setting where the gradients and their squares are computed from mini-batches:

and so the trajectory is noisy in practice.
As we shall see in chapter 7, the gradient magnitudes of neural network parameters can depend on their depth in the network. Adam helps compensate for this tendency and balances out changes across the different layers. In practice, Adam also has the advantage of being less sensitive to the initial learning rate because it avoids situations like those in figures 6.9a–b, so it doesn’t need complex learning rate schedules.
因此在实践中,轨迹会带有噪声。
正如我们在第 7 章将看到的,神经网络参数的梯度大小可能取决于其在网络中的深度。 Adam 有助于补偿这种趋势,并平衡不同层之间的变化。在实践中, Adam 还有一个优势,即对初始学习率不太敏感,因为它避免了图 6.9a–b 中的情况,因此不需要复杂的学习率调度。
The choices of learning algorithm, batch size, learning rate schedule, and momentum coefficients are all considered hyperparameters of the training algorithm; these directly affect the final model performance but are distinct from the model parameters. Choosing these can be more art than science, and it’s common to train many models with different hyperparameters and choose the best one. This is known as hyperparameter search. We return to this issue in chapter 8.
学习算法、批量大小、学习率调度和动量系数的选择都被视为训练算法的超参数;这些选择直接影响最终模型性能,但不同于模型参数。选择这些参数更像是一门艺术而非科学,通常会使用不同的超参数训练许多模型,然后选择最佳模型。这被称为超参数搜索。我们在第 8 章将回到这个问题。
This chapter discussed model training. This problem was framed as finding parameters ϕ that corresponded to the minimum of a loss function L[ϕ]. The gradient descent method measures the gradient of the loss function for the current parameters (i.e., how the loss changes when we make a small change to the parameters). Then it moves the parameters in the direction that decreases the loss fastest. This is repeated until convergence.
For nonlinear functions, the loss function may have both local minima (where gradient descent gets trapped) and saddle points (where gradient descent may appear to have converged but has not). Stochastic gradient descent helps mitigate these problems. 1 At each iteration, we use a different random subset of the data (a batch) to compute the gradient. This adds noise to the process and helps prevent the algorithm from getting trapped in a sub-optimal region of parameter space. Each iteration is also computationally cheaper since it only uses a subset of the data. We saw that adding a momentum term makes convergence more efficient. Finally, we introduced the Adam algorithm.
The ideas in this chapter apply to optimizing any model. The next chapter tackles two aspects of training specific to neural networks. First, we address how to compute the gradients of the loss with respect to the parameters of a neural network. This is accomplished using the famous backpropagation algorithm. Second, we discuss how to initialize the network parameters before optimization begins. Without careful initialization, the gradients used by the optimization can become extremely large or extremely small, which can hinder the training process.
本章讨论了模型训练。该问题被表述为寻找参数 ϕ,使其对应于损失函数 L[ϕ] 的最小值。梯度下降方法测量当前参数下损失函数的梯度(即当我们对参数进行微小改变时损失如何变化)。然后,它沿使损失下降最快的方向移动参数。重复这一过程,直到收敛。
对于非线性函数,损失函数可能同时存在局部极小值(梯度下降会陷入其中)和鞍点(梯度下降可能看似收敛但并未收敛)。随机梯度下降有助于缓解这些问题。 1 在每次迭代中,我们使用数据的不同随机子集(一个批次)来计算梯度。这为过程增加了噪声,有助于防止算法陷入参数空间中的次优区域。由于每次迭代仅使用数据的一个子集,其计算成本也更低。我们了解到,加入动量项可以使收敛更高效。最后,我们介绍了 Adam 算法。
本章中的思想适用于优化任何模型。下一章将探讨神经网络特有的两个训练方面。首先,我们讨论如何计算损失相对于神经网络参数的梯度。这可以通过著名的反向传播算法实现。其次,我们讨论在优化开始之前如何初始化网络参数。如果没有仔细初始化,优化所使用的梯度可能变得极大或极小,从而阻碍训练过程。
Optimization algorithms:
Convexity, minima, and saddle points:
Line search:
Beyond gradient descent:
Properties of SGD:
Momentum:
Adaptive training algorithms:
![图 6.10 使用夹逼法进行线搜索。 a) 当前解位于位置 a (橙色点),我们希望在区域 [a, d] (灰色阴影区域)内搜索。我们在搜索区域内部定义两个点](/learning/udl/ch6/figures/ch6_p19_f0.webp)
SGD vs. Adam:
Exhaustive search:

Figure 6.11 Three 1D loss functions for problem 6.6. (i) Plot y against x for this model for different values of ϕ0 and ϕ1 and explain the qualitative meaning of each parameter. (ii) What is a suitable loss function for this model? (iii) Compute the derivatives of this loss function with respect to the parameters. (iv) Generate ten data points from a normal distribution with mean -1 and standard deviation 1 and assign them the label y=0. Generate another ten data points from a normal distribution with mean 1 and standard deviation 1 and assign these the label y=1. Plot the loss as a heatmap in terms of the two parameters ϕ0 and ϕ1. (v) Is this loss function convex? How could you prove this? Problem 6.5 ∗ Compute the derivatives of the least squares loss with respect to the ten parameters of the simple neural network model introduced in equation 3.1: Think carefully about what the derivative of the ReLU function a[•] will be. Problem 6.6 Which of the functions in figure 6.11 is convex? Justify your answer. Characterize each of the points 1–7 as (i) a local minimum, (ii) the global minimum, or (iii) neither. Problem 6.7 ∗ The gradient descent trajectory for path 1 in figure 6.5a oscillates back and forth inefficiently as it moves down the valley toward the minimum. It’s also notable that it turns at right angles to the previous direction at each step. Provide a qualitative explanation for these phenomena. Propose a solution that might help prevent this behavior. Problem 6.8 ∗ Can (non-stochastic) gradient descent with a fixed learning rate escape local minima? Problem 6.9 We run the stochastic gradient descent algorithm for 1,000 iterations on a dataset of size 100 with a batch size of 20. For how many epochs did we train the model? Problem 6.10 Show that the momentum term m t (equation 6.11) is an infinite weighted sum of the gradients at the previous iterations and derive an expression for the coefficients (weights) of that sum. Problem 6.11 What dimensions will the Hessian have if the model has one million parameters?
图 6.11 问题 6.6 的三个一维损失函数。 (i) 对于该模型,绘制不同 ϕ0 和 ϕ1 取值下的 y 对 x 的曲线,并解释每个参数的定性含义。 (ii) 该模型适合使用哪种损失函数? (iii) 计算该损失函数对各个参数的导数。 (iv) 从均值为 -1、标准差为 1 的正态分布生成十个数据点,并为其分配标签 y=0。再从均值为 1、标准差为 1 的正态分布生成另外十个数据点,并为其分配标签 y=1。将损失关于两个参数 ϕ0 和 ϕ1 绘制成热力图。 (v) 该损失函数是凸函数吗?如何证明? P 问题 6. 5 ∗ 计算最小二乘损失函数关于这十个参 e 数的导数,这些参数来自公式 3.1 中引入的简单神经网络模型:请仔细思考 ReLU 函数 a[•] 的导数会是什么。问题 6.6 图 6.11 中的哪些函数是凸函数?请说明你的答案。将点 1–7 分别判定为 (i) 局部最小值、 (ii) 全局最小值,或 (iii) 两者都不是。问题 6。 7 ∗ 图 6.5a 中路径 1 的梯度下降轨迹在沿山谷向最小值移动时来回振荡,效率低下。值得注意的是,它在每一步都与前一步方向垂直转向。请对这些现象给出定性解释。提出一个可能有助于防止这种行为的方法。问题 6。 8 ∗ 使用固定学习率的(非随机)梯度下降能否逃离局部最小值? 问题 6.9 我们在大小为 100 的数据集上以批量大小 20 运行随机梯度下降算法 1,000 次迭代。模型训练了多少轮? 问题 6.10 证明动量项 m t (公式 6.11)是先前各次迭代梯度的无穷加权和,并推导该和的系数(权重)表达式。问题 6.11 如果模型有一百万个参数,黑塞矩阵的维度是多少?