学习资料 理解深度学习 第 8 章 · 衡量性能
学 习 资 料 · 中 英 对 照

第 8 章 · 衡量性能

Understanding Deep Learning — Measuring performance

性能测量
Measuring performance

Previous chapters described neural network models, loss functions, and training algorithms. This chapter considers how to measure the performance of the trained models. With sufficient capacity (i.e., number of hidden units), a neural network model will often perform perfectly on the training data. However, this does not necessarily mean it will generalize well to new test data.

We will see that the test errors have three distinct causes and that their relative contributions depend on (i) the inherent uncertainty in the task, (ii) the amount of training data, and (iii) the choice of model. The latter dependency raises the issue of hyperparameter search. We discuss how to select both the model hyperparameters (e.g., the number of hidden layers and the number of hidden units in each) and the learning algorithm hyperparameters (e.g., the learning rate and batch size).

前面章节介绍了神经网络模型、损失函数和训练算法。本章讨论如何衡量训练好的模型的性能。如果容量足够(即隐藏单元数量足够),神经网络模型通常会在训练数据上表现完美。然而,这并不一定意味着它会很好地泛化到新的测试数据。

我们会看到,测试误差有三个不同的成因,且它们的相对贡献取决于(i)任务固有的不确定性,(ii)训练数据的数量,以及(iii)模型的选择。后一种依赖关系引出了超参数搜索的问题。我们讨论如何选择模型超参数(例如隐藏层的数量以及每层隐藏单元的数量)和学习算法超参数(例如学习率和批量大小)。

8.1 训练一个简单模型
8.1 Training a simple model

We explore model performance using the MNIST-1D dataset (figure 8.1).

This consists of ten classes y∈{0, 1,..., 9}, representing the digits 0–9. The data are derived from 1D templates for each of the digits. Each data example x is created by randomly transforming one of these templates and adding noise. The full training dataset{ x i, yi} consists of I =4000 training examples, each consisting of Di =40 dimensions representing the horizontal offset at 40 positions. The ten classes are drawn uniformly during data generation, so there are ∼400 examples of each class.

We use a network with Di= 40 inputs and Do= 10 outputs which are passed through a softmax function to produce class probabilities (see section 5.5). The network has two hidden layers with D = 100 hidden units each. It is trained using stochastic gradient descent with batch size 100 and learning rate 0.1 for 6000 steps (150 epochs) with a multiclass cross-entropy loss (equation 5.24). Figure 8.2 shows that the training error decreases as training proceeds. The training data are classified perfectly after about 4000 steps. The training loss also decreases, eventually approaching zero. However, this doesn’t imply that the classifier is perfect; the model might have mem-

我们使用 MNIST-1D 数据集(图 8.1)来探索模型性能。该数据集包含十个类别 y∈{0, 1,..., 9},分别代表数字 0–9。这些数据源自每个数字的一维模板。每个数据示例 x 都是通过对其中一个模板进行随机变换并添加噪声而生成的。完整训练数据集 { x i, yi} 包含 I =4000 个训练示例,每个示例包含 Di =40 个维度,表示 40 个位置上的水平偏移。在数据生成过程中,十个类别是均匀抽取的,因此每个类别有 ∼400 个示例。

我们使用一个具有 Di= 40 个输入和 Do= 10 个输出的网络,这些输出经过 Softmax 函数以产生类别概率(见第 5.5 节)。该网络有两个隐藏层,每层有 D = 100 个隐藏单元。我们使用随机梯度下降进行训练,批量大小为 100,学习率为 0.1,共训练 6000 步(150 轮),并采用多分类交叉熵损失(公式 5.24)。图 8.2 显示,训练误差随着训练进行而下降。大约 4000 步后,训练数据被完全正确分类。训练损失也随之下降,最终趋近于零。然而,这并不意味着分类器是完美的;模型可能已经记忆 -

图 8.1 MNIST-1D。 a) 10 个类别 y∈{0,..., 9} 的模板,基于数字 0–9。 b) 训练样本 x 由随机变换模板并 c) 添加噪声生
图 8.1 MNIST-1D。 a) 10 个类别 y∈{0,..., 9} 的模板,基于数字 0–9。 b) 训练样本 x 由随机变换模板并 c) 添加噪声生成。 d) 随后在 40 个垂直位置对变换后模板的水平偏移进行采样。改编自 (Greydanus, 2020)Figure 8.1 MNIST-1D. a) Templates for 10 classes y∈{0,..., 9}, based on digits 0–9. b) Training examples x are created by randomly transforming a template and c) adding noise. d) The horizontal offset of the transformed template is then sampled at 40 vertical positions. Adapted from (Greydanus, 2020)
图 8.2 MNIST-1D 结果。 a) 分类误差百分比随训练步数的变化。训练集误差降至零,但测试误差不会降至 ∼40% 以下。该模型不能很好地泛化到新的测试
图 8.2 MNIST-1D 结果。 a) 分类误差百分比随训练步数的变化。训练集误差降至零,但测试误差不会降至 ∼40% 以下。该模型不能很好地泛化到新的测试数据。 b) 损失随训练步数的变化。训练损失稳定地趋近于零。测试损失起初下降,随后由于模型对其(错误)预测越来越自信而上升。Figure 8.2 MNIST-1D results. a) Percent classification error as a function of the training step. The training set errors decrease to zero, but the test errors do not drop below ∼40%. This model doesn’t generalize well to new test data. b) Loss as a function of the training step. The training loss decreases steadily toward zero. The test loss decreases at first but subsequently increases as the model becomes increasingly confident about its (wrong) predictions.
图 8.3 回归函数。黑色实线显示真值函数。要生成  I 训练样本  {xi, yi},输入空间 x∈[0, 1] 被划分为 I 个等分区间,每个区间内从均匀分
图 8.3 回归函数。黑色实线显示真值函数。要生成 I 训练样本 {xi, yi},输入空间 x∈[0, 1] 被划分为 I 个等分区间,每个区间内从均匀分布中抽取一个样本 xi。对应的值 yi 通过在 xi 处评估函数并添加高斯噪声生成(灰色区域显示 ±2 个标准差)。测试数据的生成方式相同。Figure 8.3 Regression function. black line shows ground truth function. To generate I training examples {xi, yi}, the input space x∈[0, 1] is divided into I equal segments and one sample xi is drawn from a uniform distribution within each segment. ing value yi is created by evaluating the function at xi and adding Gaussian noise (gray region shows ±2 standard deviations). the same way.

orized the training set but be unable to predict new examples. To estimate the true performance, we need a separate testset of input/output pairs{ x i, yi}. To this end, we generate 1000 more examples using the same process. Figure 8.2a also shows the errors for this test data as a function of the training step. These decrease as training proceeds, but only to around 40%. This is better than the chance error rate of 90% but far worse than for the training set; the model has not generalized well to the test data. The test loss (figure 8.2b) decreases for the first 1500 training steps but then increases again. At this point, the test error rate is fairly constant; the model makes the same mistakes but with increasing confidence. This decreases the probability of the correct

记住了训练集,但无法预测新样本。要估计真实性能,我们需要一个单独的测试集,由输入 / 输出对 { x i, yi} 组成。为此,我们使用相同过程再生成 1000 个样本。图 8.2a 还显示了该测试数据的误差随训练步数的变化。这些误差随着训练进行而下降,但仅降至约 40%。这优于 90% 的随机误差率,但远差于训练集;模型未能很好地泛化到测试数据。测试损失(图 8.2b)在前 1500 个训练步骤中下降,但随后上升再次上升。此时,测试误差率相当恒定;模型犯同样的错误,但置信度不断增加。这降

answers and thus increases the negative log-likelihood. This increasing confidence is a side-effect of the softmax function; the pre-softmax activations are driven to increasingly extreme values to make the probability of the training data approach one (see figure 5.10).

低了正确答案的概率,从而增加了负对数似然。这种置信度增加是 Softmax 函数的副作用; Softmax 之前的激活值被推向越来越极端的值,以使训练数据的概率趋近于 1 (见图 5.10)。

8.2 误差来源
8.2 Sources of error

We now consider the sources of the errors that occur when a model fails to generalize. To make this easier to visualize, we revert to a 1D least squares regression problem where we know exactly how the ground truth data were generated. Figure 8.3 shows a quasisinusoidal function; both training and test data are generated by sampling input values in the range[0, 1], passing them through this function, and adding Gaussian noise with a fixed variance. We fit a simplified shallow neural net to this data (figure 8.4). The weights and biases that connect the input layer to the hidden layer are chosen so that the “joints” of the function are evenly spaced across the interval. If there are D hidden units, then these joints will be at 0, 1/D, 2/D,..., (D−1)/D. This model can represent any piecewise linear function with D equally sized regions in the range[0, 1]. As well as being easy to understand, this model also has the advantage that it can be fit in closed form without the need for stochastic optimization algorithms (see problem 8.3). Consequently, we can guarantee to find the global minimum of the loss function during training.

我们现在考虑模型无法泛化时产生的误差来源。为了更直观地可视化,我们回到一个一维最小二乘回归问题,其中我们确切知道真值数据是如何生成的。图 8.3 显示了一个准正弦函数;训练数据和测试数据均通过在范围 [0, 1], 内对输入值进行采样、将其通过该函数并添加具有固定方差的高斯噪声来生成。我们用数据拟合了一个简化的浅层神经网络(图 8.4)。连接输入层与隐藏层的权重和偏差被选择为使函数的“折点”在整个区间上均匀分布。如果有 D 个隐藏单元,则这些折点将位于 0 , 1/D, 2/D,..., (D−1) /D。该模型可以表示在 [0, 1] 范围内具有 D 个等大小区域的任意分段线性函数。该模型不仅易于理解,而且还有一个优点:可以以闭式形式拟合,无需随机优化算法(见习题 8.3)。因此,我们可以

保证在训练过程中找到损失函数的全局最小值。

图 8.4 具有三个隐藏单元的简化神经网络。 a) 输入层与隐藏层之间的权重和偏差是固定的(虚线箭头)。 b–d) 选择它们,使得隐藏单元激活的斜率为 1,且其
图 8.4 具有三个隐藏单元的简化神经网络。 a) 输入层与隐藏层之间的权重和偏差是固定的(虚线箭头)。 b–d) 选择它们,使得隐藏单元激活的斜率为 1,且其拐点在区间内等距分布,分别位于 x=0、 x=1/3 和 x=2/3。修改其余参数 ϕ = {β, ω1, ω2, ω3} 可以在 x∈[0, 1] 上创建任意以 1/3 和 2/3 为拐点的分段线性函数。 e–g) 三个参数 ϕ 取值不同的示例函数。Figure 8.4 Simplified neural network with three hidden units. a) The weights and biases between the input and hidden layer are fixed (dashed arrows). b–d) They are chosen so that the hidden unit activations have slope one, and their joints are equally spaced across the interval, with joints at x=0, x=1/3, and x=2/3, respectively. Modifying the remaining parameters ϕ = {β, ω1, ω2, ω3} can create any piecewise linear function over x∈[0, 1] with joints at 1/3 and 2/3. Three example functions with different values of the parameters ϕ. e–g)
图 8.5 测试误差的来源。 a) 噪声。数据生成过程存在噪声,因此即使模型完全复现了真实的底层函数(黑线),测试数据中的噪声(灰点)也意味着仍会存在一定误差(
图 8.5 测试误差的来源。 a) 噪声。数据生成过程存在噪声,因此即使模型完全复现了真实的底层函数(黑线),测试数据中的噪声(灰点)也意味着仍会存在一定误差(灰色区域表示两个标准差)。 b) 偏差。即使使用最佳可能的参数,三区域模型(青色线)也无法完全拟合真实函数(黑线)。这种偏差是另一个误差来源(灰色区域表示带符号误差)。 c) 方差。在实践中,我们只有有限的含噪训练数据(橙色点)。在拟合模型时,我们得到的并不是 (b) 面板中最佳可能的函数,而是一个略有不同的函数(青色线),它反映了训练数据的特殊性。这提供了另一个误差来源(灰色区域表示两个标准差)。图 8.6 展示了该区域的计算方式。Figure 8.5 Sources of test error. a) Noise. Data generation is noisy, so even if the model exactly replicates the true underlying function (black line), the noise in the test data (gray points) means that some error will remain (gray region represents two standard deviations). b) Bias. Even with the best possible parameters, the three-region model (cyan line) cannot exactly fit the true function (black line). This bias is another source of error (gray regions represent signed error). Variance. In practice, we have limited noisy training data (orange points). When we fit the model, we don’t recover the best possible function from panel (b) but a slightly different function (cyan line) that reflects idiosyncrasies of the training data. This provides an additional source of error (gray region represents two standard deviations). Figure 8.6 shows how this region was calculated.
8.2.1 噪声、偏差和方差
8.2.1 Noise, bias, and variance

There are three possible sources of error, which are known as noise, bias, and variance respectively (figure 8.5): Noise

The data generation process includes the addition of noise, so there are multiple possible valid outputs y for each input x (figure 8.5a). This source of error is insurmountable for the test data. Note that it does not necessarily limit the training performance; we will likely never see the same input x twice during training, so it is still possible to fit the training data perfectly.

错误有三个可能的来源,分别称为噪声、偏差和方差(图 8.5):

噪声数据生成过程包含噪声的加入,因此对于每个输入 x,都存在多个可能的有效输出 y (图 8.5a)。对于测试数据而言,这一误差来源是无法克服的。注意,这并不一定限制训练性能;在训练过程中我们很可能不会再次看到相同的输入 x,因此仍然有可能完美拟合训练数据。

Noise may arise because there is a genuine stochastic element to the data generation process, because some of the data are mislabeled, or because there are further explanatory variables that were not observed.

In rare cases, noise may be absent; for example, a network might approximate a function that is deterministic but requires significant computation to evaluate.

However, noise is usually a fundamental limitation on the possible test performance. Bias

噪声的产生可能是因为数据生成过程本身具有真正的随机成分,可能是因为部分数据的标签有误,也可能是因为存在未被观测到的其他解释变量。在少数情况下,噪声可能不存在;例如,网络可能近似一个确定性的函数,但该函数需要大量计算才能求值。然而,噪声通常是测试性能可能达到的根本限制。

A second potential source of error may occur because the model is not flexible enough to fit the true function perfectly. For example, the three-region neural network model cannot exactly describe the quasi-sinusoidal function, even when the parameters are chosen optimally (figure 8.5b). This is known as bias. Variance

We have limited training examples, and there is no way to distinguish systematic changes in the underlying function from noise in the underlying data. When we fit a model, we do not get the closest possible approximation to the true underlying function. Indeed, for different training datasets, the result will be slightly different each time. This additional source of variability in the fitted function is termed variance (figure 8.5c). In practice, there might also be additional variance due to the stochastic learning algorithm, which does not necessarily converge to the same solution each time.

偏差第二个潜在误差来源可能源于模型不够灵活,无法完美拟合真实函数。例如,即使参数选择最优,三区域神经网络模型也无法精确描述准正弦函数(图 8.5b)。这被称为偏差。

方差我们只有有限的训练样本,无法区分底层函数的系统性变化与底层数据中的噪声。当我们拟合模型时,得到的并非对真实底层函数最接近的可能近似。事实上,对于不同的训练数据集,每次得到的结果都会略有不同。拟合函数中这种额外的变异性来源称为方差(图 8.5c)。在实践中,由于随机学习算法不一定每次收敛到相同解,可能还会产生额外的方差。

8.2.2 测试误差的数学表述
8.2.2 Mathematical formulation of test error

We now make the notions of noise, bias, and variance mathematically precise. Consider a 1D regression problem where the data generation process has additive noise with variance σ2 (e.g., figure 8.3); we can observe different outputs y for the same input x, so for

我们现在对噪声、偏差和方差的概念作出数学上精确的界定。考虑一个一维回归问题,其中数据生成过程具有方差 σ2 的加性噪声(例如图 8.3);我们可以观察到不同的输出 y 对应同一个输入 x,因此对于

each x, there is a distribution Pr(y|x) with expected value (mean) µ[x]:

每个 x,都存在一个分布 Pr(y|x) 其期望值(均值) µ[x]:

and fixed noise σ2= Ey that we are considering the output y at a given input position x.

Now consider a least squares loss between the model prediction f[x, ϕ] at position x and the observed value y[x] at that position:

现在考虑位置 x 处的模型预测 f[x, ϕ] 与该位置处的观测值 y[x] 之间的最小二乘损失:

where we have both added and subtracted the mean µ[x] of the underlying function in the second line and have expanded out the squared term in the third line.

The underlying function is stochastic, so this loss depends on the particular y[x] we observe. The expected loss is: where we have made use of the rules for manipulating expectations. In the second line, we have distributed the expectation operator and removed it from terms with no dependence on y[x], and in the third line, we note that the second term is zero since Ey[y[x]] = µ[x] by definition. Finally, in the fourth line, we have substituted in the definition of the

其中我们在第二行对底层函数的均值 µ[x] 同时进行了加减,并在第三行展开了平方项。

底层函数是随机的,因此该损失取决于我们观察到的特定 y[x]。期望损失为:其中我们利用了期望运算规则。在第二行,我们已对期望算子进行分配,并将其从与 y[x] 无关的项中移出,在第三行中,我们注意到第二项为零,因为根据定义 Ey[y[x]] = µ[x]。最后,在第四行中,我们已代入定义

noise σ2. We can see that the expected loss has been broken down into two terms; the first term is the squared deviation between the model and the true function mean, and the second term is the noise.

噪声 σ2。我们可以看到,期望损失已被分解为两项;第一项是模型与真实函数均值之间的平方偏差,第二项是噪声。

The first term can be further partitioned into bias and variance. The parameters ϕ of the model f[x, ϕ] depend on the training dataset D= {xi, yi}, so more properly, we should write f [x, ϕ[D]].

The training dataset is a random sample from the data generation process; with a different sample of training data, we would learn different parameter values. The expected model output f µ[x] with respect to all possible datasets D is hence:

where we have simplified using similar steps as for equation 8.3. Finally, we substitute this result into equation 8.3:

第一项可以进一步分解为偏差和方差。模型 f[x, ϕ] 的参数 ϕ 依赖于训练数据集 D= {xi, yi},因此更准确地说,我们应写成 f [x, ϕ[D]]。训练数据集是从数据生成过程中抽取的随机样本;如果训练数据样本不同,我们将学到不同的参数值。因此,相对于所有可能数据集 D 的期望模型输出 f µ[x] 为:其中,我们采用了与公式 8.3 类似的步骤进行简化。最后,我们将该结果代入公式 8.3:

This equation says that the expected loss after considering the uncertainty in the training data D and the test data y consists of three additive components.

The variance is uncertainty in the fitted model due to the particular training dataset we sample. The bias is the systematic deviation of the model from the mean of the function we are modeling. The noise is the inherent uncertainty in the true mapping from input to output. These three sources of error will be present for any task. They combine additively for regression tasks with a least squares loss. However, their interaction can be more complex for other types of problems.

该等式表明,在考虑训练数据 D 和测试数据 y 中的不确定性之后,期望损失由三个相加的组成部分构成。方差是由于我们所采样的特定训练数据集而导致的拟合模型中的不确定性。偏差是模型相对于我们所建模的函数的均值的系统性偏离。噪声是输入到输出的真实映射中固有的不确定性。这三种误差来源在任何任务中都会存在。对于采用最小二乘损失的回归任务,它们以相加的方式组合。然而,对于其他类型的问题,它们之间的相互作用可能更加复杂。

8.3 降低误差
8.3 Reducing error

In the previous section, we saw that test error results from three sources: noise, bias, and variance. The noise component is insurmountable; there is nothing we can do to circumvent this, and it represents a fundamental limit on expected model performance. However, it is possible to reduce the other two terms.

在上一节中,我们看到测试误差源于三个因素:噪声、偏差和方差。噪声分量是无法克服的;我们对此无能为力,它构成了模型期望性能的根本限制。不过,降低另外两项是可能的。

8.3.1 减少方差
8.3.1 Reducing variance

Recall that the variance results from limited noisy training data.

Fitting the model to two different training sets results in slightly different parameters. It follows we can reduce the variance by increasing the quantity of training data. This averages out the inherent noise and ensures that the input space is well sampled.

Figure 8.6 shows the effect of training with 6, 10, and 100 samples. For each dataset size, we show the best-fitting model for three training datasets. With only six samples, the fitted function is quite different each time: the variance is significant. As we increase the number of samples, the fitted models become very similar, and the variance reduces. In general, adding training data almost always improves test performance.

回想一下,方差源于有限的含噪训练数据。将模型拟合到两个不同的训练集会产生略有不同的参数。因此,我们可以通过增加训练数据的数量来降低方差。这会平均掉固有噪声,并确保输入空间得到充分采样。

图 8.6 展示了分别使用 6 个、 10 个和 100 个样本进行训练时的效果。对于每个数据集大小,我们都展示了三个训练数据集的最佳拟合模型。当仅有六个样本时,每次拟合得到的函数都差异很大:方差显著。随着样本数量增加,拟合模型变得非常相似,方差也随之减小。总体而言,增加训练数据几乎总能提升测试性能。

8.3.2 减少偏差
8.3.2 Reducing bias

The bias term results from the inability of the model to describe the true underlying function. This suggests that we can reduce this error by making the model more flexible. This is usually done by increasing the model capacity. For neural networks, this means adding more hidden units and/or hidden layers.

In the simplified model, adding capacity corresponds to adding more hidden units so that the interval[0, 1] is divided into more linear regions. Figures 8.7a–c show that (unsurprisingly) this does indeed reduce the bias; as we increase the number of linear regions to ten, the model becomes flexible enough to fit the true function closely.

偏差项源于模型无法描述真实的底层函数。这表明我们可以通过使模型更灵活来减少这种误差。通常的做法是增加模型容量。对于神经网络,这意味着添加更多隐藏单元和 / 或隐藏层。

在简化模型中,增加容量对应于添加更多隐藏单元,从而将区间 [0, 1] 划分为更多线性区域。图 8.7a–c 显示,(不出所料)这确实减少了偏差;当我们将线性区域的数量增加到十个时,模型变得足够灵活,能够紧密拟合真实函数。

8.3.3 偏差 - 方差权衡
8.3.3 Bias-variance trade-off

However, figures 8.7d–f show an unexpected side-effect of increasing the model capacity. For a fixed-size training dataset, the variance term typically increases as the model capacity increases.

Consequently, increasing the model capacity does not necessarily reduce the test error. This is known as the bias-variance trade-off.

然而,图 8.7d–f 显示了增加模型容量的一个意外副作用。对于固定大小的训练数据集,方差项通常随着模型容量的增加而增加。因此,增加模型容量并不一定会降低测试误差。这被称为偏差 - 方差权衡。

Figure 8.8 explores this phenomenon. In panels a–c), we fit the simplified three-region model to three different datasets of fifteen points. Although the datasets differ, the final model is much the same; the noise in the dataset roughly averages out in each linear region. In panels d–f), we fit a model with ten regions to the same three datasets. This model has more flexibility, but this is disadvantageous; the model certainly fits the data better, and the training error will be lower, but much of the extra descriptive power is devoted to modeling the noise. This phenomenon is known as overfitting. We’ve seen that as we add capacity to the model, the bias decreases, but the variance increases for a fixed-size training dataset. This suggests that there is an optimal capacity where the bias is not too large and the variance is still relatively small. Figure 8.9 shows how these terms vary numerically for the toy model as we increase the capacity, using the data from figure 8.8. For regression models, the total expected error is the sum of the bias and the variance, and this sum is minimized when the model capacity is four

图 8.8 探讨了这一现象。在面板 a–c) 中,我们将简化的三区域模型拟合到三个不同的十五点数据集。尽管数据集不同,最终模型却大致相同;数据集中的噪声在每个线性区域中大致平均化。在面板 d–f) 中,我们将具有十个区域的模型拟合到同样的三个数据集。这个模型具有更高的灵活性,但这反而不利;模型无疑更好地拟合了数据,训练误差会更低,但许多额外的描述能力被用于建模噪声。这一现象被称为过拟合。我们已经看到,随着向模型增加容量,偏差会减小,但对于固定大小的训练数据集,方差会增大。这表明存在一个最优容量,此时偏差不会太大,方差仍然相对较小。图 8.9 展示了随着容量增加,这些项在玩具模型中的数值变化,使用图 8.8 中的数据。对于回归模型,总期望误差是偏差与方差之和,当模型容量为四时

(i.e., with four hidden units and four linear regions in the range of the data).

(即在数据范围内具有四个隐藏单元和四个线性区域),该和达到最小。

图 8.6 通过增加训练数据来降低方差。 a–c) 对三个不同的随机抽样数据集(每个包含六个点)拟合三区域模型。每次拟合得到的模型都相当不同。 d) 我们重复此
图 8.6 通过增加训练数据来降低方差。 a–c) 对三个不同的随机抽样数据集(每个包含六个点)拟合三区域模型。每次拟合得到的模型都相当不同。 d) 我们重复此实验多次,并绘制模型预测的均值(青色线)以及模型预测的方差(灰色区域表示两个标准差)。 e–h) 我们进行同样的实验,但这次使用大小为十的数据集。预测方差降低了。 i–l) 我们使用大小为 100 的数据集重复此实验。此时拟合的模型始终相似,方差也很小。Figure 8.6 Reducing variance by increasing training data. a–c) The three-region model fitted to three different randomly sampled datasets of six points. fitted model is quite different each time. d) We repeat this experiment many times and plot the mean model predictions (cyan line) and the variance of the model predictions (gray area shows two standard deviations). e–h) We do the same experiment, but this time with datasets of size ten. The variance of the predictions is reduced. i–l) We repeat this experiment with datasets of size 100. Now the fitted model is always similar, and the variance is small. The
图 8.7 偏差和方差作为模型容量的函数。 a–c) 随着我们增加玩具模型的隐藏单元数量,线性区域数量增加,模型能够更紧密地拟合真实函数;偏差(灰色区域)减小。
图 8.7 偏差和方差作为模型容量的函数。 a–c) 随着我们增加玩具模型的隐藏单元数量,线性区域数量增加,模型能够更紧密地拟合真实函数;偏差(灰色区域)减小。 d–f) 不幸的是,增加模型容量会带来增加方差项(灰色区域)的副作用。这被称为偏差 - 方差权衡。Figure 8.7 Bias and variance as a function of model capacity. a–c) As we increase the number of hidden units of the toy model, the number of linear regions increases, and the model becomes able to fit the true function closely; the bias (gray region) decreases. d–f) Unfortunately, increasing the model capacity has the side-effect of increasing the variance term (gray region). This is known as the bias-variance trade-off.
8.4 双下降
8.4 Double descent

In the previous section, we examined the bias-variance trade-off as we increased the capacity of a model. Let’s now return to the MNIST-1D dataset and see whether this happens in practice. We use 10,000 training examples, test with another 5,000 examples and examine the training and test performance as we increase the capacity (number of parameters) in the model. We train the model with Adam and a step size of 0.005 using a full batch of 10,000 examples for 4000 steps.

在上一节中,我们考察了随着模型容量增加而产生的偏差 - 方差权衡。让我们现在回到 MNIST-1D 数据集,看看这种情况在实践中是否会发生。我们使用 10,000 个训练样本,用另外 5,000 个样本进行测试,并考察随着模型容量(参数数量)增加时的训练和测试性能。我们使用 Adam 和优化步长 0.005,以 10,000 个样本的全批量训练 4000 步。

Figure 8.10a shows the training and test error for a neural network with two hidden layers as the number of hidden units increases. The training error decreases as the capacity grows and quickly becomes close to zero. The vertical dashed line represents the capacity where the model has the same number of parameters as there are training examples, but the model memorizes the dataset before this point. The test error decreases as we add model capacity but does not increase as predicted by the bias-variance trade-off curve; it keeps decreasing. In figure 8.10b, we repeat this experiment, but this time, we randomize 15% of the

图 8.10a 展示了具有两个隐藏层的神经网络在隐藏单元数量增加时的训练误差和测试误差。训练误差随着模型容量增长而下降,并迅速接近零。垂直虚线表示模型参数数量与训练样本数量相同的容量,但模型在此之前已经记住了数据集。测试误差随着我们增加模型容量而下降,但并没有像偏差 - 方差权衡曲线所预测的那样上升;它持续下降。在图 8.10b 中,我们重复这一实验,但这一次,我们随机化 15% 的

图 8.8 过拟合。 a–c) 将具有三个区域的模型拟合到三个各含 15 个点的数据集上。三种情况的结果相似(即方差较低)。 d–f) 将具有十个区域的模型拟合
图 8.8 过拟合。 a–c) 将具有三个区域的模型拟合到三个各含 15 个点的数据集上。三种情况的结果相似(即方差较低)。 d–f) 将具有十个区域的模型拟合到相同的数据集上。额外的灵活性并不一定能产生更好的预测。虽然这三个模型各自对训练数据的描述更好,但它们不一定更接近真实底层函数(黑色曲线)。相反,它们过拟合数据并描述噪声,且方差(拟合曲线之间的差异)更大。Figure 8.8 Overfitting. a–c) A model with three regions is fit to three different datasets of fifteen points each. The result is similar in all three cases (i.e., the variance is low). d–f) A model with ten regions is fit to the same datasets. The additional flexibility does not necessarily produce better predictions. While these three models each describe the training data better, they are not necessarily closer to the true underlying function (black curve). Instead, they overfit the data and describe the noise, and the variance (difference between fitted curves) is larger.
图 8.9 偏差 - 方差权衡。在简化模型中,使用来自图 8.8 的训练数据,将方程 8.7 的偏差和方差项绘制为模型容量(数据范围内的隐藏单元数 / 线性区域
图 8.9 偏差 - 方差权衡。在简化模型中,使用来自图 8.8 的训练数据,将方程 8.7 的偏差和方差项绘制为模型容量(数据范围内的隐藏单元数 / 线性区域数)的函数。随着容量增加,偏差(橙色实线)减小,但方差(青色实线)增加。当容量为 4 时,这两项之和(灰色虚线)最小。Figure 8.9 Bias-variance trade-off. The bias and variance terms from equation 8.7 are plotted as a function of the model capacity (number of hidden units / linear regions in range of data) in the simplified model using training data from figure 8.8. As the capacity increases, the bias (solid orange line) decreases, but the variance (solid cyan line) increases. The sum of these two terms (dashed gray line) is minimized when the capacity is four.

training labels. Once more, the training error decreases to zero. This time, there is more randomness, and the model requires almost as many parameters as there are data points to memorize the data. The test error does show the typical bias-variance trade-off as we increase the capacity to the point where the model fits the training data exactly. However, then it does something unexpected; it starts to decrease again. Indeed, if we add enough capacity, the test loss reduces to below the minimal level that we achieved in the first part of the curve.

This phenomenon is known as double descent. For some datasets like MNIST, it is present with the original data (figure 8.10c). For others, like MNIST-1D and CIFAR-100 (figure 8.10d), it emerges or becomes more prominent when we add noise to the labels. The first part of the curve is referred to as the classical or under-parameterized regime,

训练标签。再次,训练误差降至零。这一次随机性更强,模型需要几乎与数据点数量一样多的参数来记忆数据。当我们增加容量直到模型完全拟合训练数据时,测试误差确实呈现出典型的偏差 - 方差权衡。然而,随后它出现了一个意外现象:开始再次下降。事实上,如果增加足够的容量,测试损失会降至我们在曲线第一部分中达到的最低水平以下。

and the second part as the modern or over-parameterized regime. The central part where the error increases is termed the critical regime.

曲线的第一部分被称为经典或欠参数化区间,第二部分被称为现代或过参数化区间。误差上升的中间部分被称为临界区间。

8.4.1 解释
8.4.1 Explanation

The discovery of double descent is recent, unexpected, and somewhat puzzling. It results from an interaction of two phenomena. First, the test performance becomes temporarily worse when the model has just enough capacity to memorize the data. Second, the test performance continues to improve with capacity even when this exceeds the point where the training data are all classified correctly. The first phenomenon is exactly as predicted by the bias-variance trade-off. The second phenomenon is more confusing; it’s unclear why performance should be better in the over-parameterized regime, given that there are now not even enough training data points to constrain the model parameters uniquely. To understand why performance continues to improve as we add more parameters, note that once the model has enough capacity to drive the training loss to near zero, the model fits the training data almost perfectly. This implies that further capacity

双下降的发现是近期的、出乎意料的,并且有些令人困惑。它源于两种现象之间的相互作用。首先,当模型恰好具有足以记忆数据的容量时,测试性能会暂时变差。其次,即使容量超过了训练数据全部被正确分类的点,测试性能仍会随着容量继续提升。第一种现象正是偏差 - 方差权衡所预测的。第二种现象更令人困惑;目前甚至没有足够的训练数据点来唯一地约束模型参数,因此不清楚为什么在过参数化区域中性能应该更好。

cannot help the model fit the training data any better; any change must occur between the training points. The tendency of a model to prioritize one solution over another between data points is known as its inductive bias.

The model’s behavior between data points is critical because, in high-dimensional space, the training data are extremely sparse. The MNIST-1D dataset has 40 dimensions, and we trained with 10,000 examples. If this seems like plenty of data, consider what would happen if we quantized each input dimension into 10 bins. There would be 1040 bins in total, constrained by only 104 examples. Even with this coarse quantization, there will only be one data point in every 1036 bins! The tendency of the volume of high-dimensional space to overwhelm the number of training points is termed the curse of dimensionality.

无法帮助模型更好地拟合训练数据;任何变化都必须发生在训练点之间。模型在数据点之间优先选择某个解而非另一个解的倾向,称为其归纳式偏差。

模型在数据点之间的行为至关重要,因为在高维空间中,训练数据极其稀疏。 MNIST-1D 数据集有 40 个维度,我们使用了 10,000 个样本进行训练。如果这看起来数据量很多,请考虑将每个输入维度量化为 10 个区间。总共会有 1040 个区间,但仅有 104 个样本对其加以约束。即使采用这种粗略的量化方式,每 1036 个区间中也只会有一个数据点!高维空间中体积远超训练点数量的趋势被称为维度灾难。

The implication is that problems in high dimensions might look more like figure 8.11a; there are small regions of the input space where we observe data with significant gaps between them. The putative explanation for double descent is that as we add capacity to the model, it interpolates between the nearest data points increasingly smoothly. In the absence of information about what happens between the training points, assuming smoothness is sensible and will probably generalize reasonably to new data.

这意味着,高维问题可能更像图 8.11a;在输入空间中存在一些小区域,我们能在其中观察到数据,但区域之间有明显的间隔。双下降的推测性解释是,随着模型容量增加,模型会以越来越平滑的方式在最近的数据点之间进行插值。在没有关于训练点之间发生何种情况的信息时,假设平滑性是合理的,并且可能会对新数据产生相当好的泛化。

图 8.10 双下降。 a) MNIST-1D 上具有两个隐藏层的网络的训练误差和测试误差,其中我们增加每层隐藏单元的数量(从而增加参数数量)。当参数数量接近训
图 8.10 双下降。 a) MNIST-1D 上具有两个隐藏层的网络的训练误差和测试误差,其中我们增加每层隐藏单元的数量(从而增加参数数量)。当参数数量接近训练样本数量时,训练误差降至零(垂直虚线)。测试误差没有表现出预期的偏差 - 方差权衡,即使模型已经记住了数据集,仍继续下降。 b) 使用噪声更大的训练数据重复同一实验。同样,训练误差降至零,尽管现在几乎需要与训练点数量一样多的参数才能记住数据集。测试误差表现出预测的偏差 / 方差权衡;随着容量增加而下降,但当我们接近训练数据被完全记住的点时再次上升。然而,随后它再次下降,并最终达到更好的性能水平。这被称为双下降。取决于损失函数、模型以及数据中的噪声量,双下降模式在许多数据集中会以不同程度出现。 c) 来自 Belkin 等人(2019)的浅层神经网络在 MNIST (无标签噪声)上的结果。 d) 来自 Nakkiran 等人(2021)的 ResNet18 网络在 CIFAR-100 上的结果(见第 11 章)。详见原始论文。Figure 8.10 Double descent. a) Training and test error on MNIST-1D for a two-hidden layer network as we increase the number of hidden units (and hence parameters) in each layer. The training error decreases to zero as the number of parameters approaches the number of training examples (vertical dashed line). The test error does not show the expected bias-variance trade-off but continues to decrease even after the model has memorized the dataset. b) The same experiment is repeated with noisier training data. Again, the training error reduces to zero, although it now takes almost as many parameters as training points to memorize the dataset. The test error shows the predicted bias/variance trade-off; it decreases as the capacity increases but then increases again as we near the point where the training data is exactly memorized. However, it subsequently decreases again and ultimately reaches a better performance level. This is known as double descent. Depending on the loss function, the model, and the amount of noise in the data, the double descent pattern can be seen to a greater or lesser degree across many datasets. c) Results on MNIST (without label noise) with shallow neural network from Belkin et al. (2019). d) Results on CIFAR-100 with ResNet18 network (see chapter 11) from Nakkiran et al. (2021). papers for details. See original

This argument is plausible. It’s certainly true that as we add more capacity to the model, it will have the capability to create smoother functions. Figures 8.11b–f show the smoothest possible functions that still pass through the data points as we increase the number of hidden units. When the number of parameters is very close to the number of training data examples (figure 8.11b), the model is forced to contort itself to fit the training data exactly, resulting in erratic predictions. This explains why the peak in the double descent curve is so pronounced. As we add more hidden units, the model has the ability to construct smoother functions that are likely to generalize better to new data.

这一论点是合理的。毫无疑问,随着我们向模型增加更多容量,它将具备创建更平滑函数的能力。图 8.11b–f 显示了随着隐藏单元数量增加,仍然穿过数据点的尽可能平滑的函数。当参数数量非常接近训练数据样本数量(图 8.11b)时,模型被迫扭曲自身以精确拟合训练数据,导致预测不稳定。这解释了为什么双下降曲线中的峰值如此显著。随着我们增加更多隐藏单元,模型具有构造更平滑函数的能力,这些函数可能对新数据具有更好的泛化能力。

图 8.11 增加容量(隐藏单元)使得在稀疏数据点之间可以更平滑地插值。 a) 考虑
图 8.11 增加容量(隐藏单元)使得在稀疏数据点之间可以更平滑地插值。 a) 考虑Figure 8.11 Increasing capacity (hidden units) allows smoother interpolation between sparse data points. (orange circles) are sparse; there is a large region in the center with no data examples to constrain the model to mimic the true function (black curve). b) If we fit a model with just enough capacity to fit the training data (cyan curve), then it has to contort itself to pass through the training data, and the output predictions will not be smooth. c–f) However, as we add more hidden units, the model has the ability to interpolate between the points more smoothly (smoothest possible curve plotted in each case). However, unlike in this figure, it is not obliged to.

However, this does not explain why over-parameterized models should produce smooth functions. Figure 8.12 shows three functions that can be created by the simplified model with 50 hidden units. In each case, the model fits the data exactly, so the loss is zero. If the modern regime of double descent is explained by increasing smoothness, then what exactly is encouraging this smoothness?

然而,这并不能解释为什么过参数化模型应当产生平滑函数。图 8.12 展示了由具有 50 个隐藏单元的简化模型可以创建的三个函数。在每种情况下,模型都完全拟合数据,因此损失为零。如果双下降的现代范式可以用平滑性增强来解释,那么究竟是什么在鼓励这种平滑性?

图 8.12 正则化。 a–c) 三条拟合曲线都精确经过数据点,因此各自的训练损失均为零。然而,我们可能预期面板 (a) 中的平滑曲线比面板 (b) 和 (c)
图 8.12 正则化。 a–c) 三条拟合曲线都精确经过数据点,因此各自的训练损失均为零。然而,我们可能预期面板 (a) 中的平滑曲线比面板 (b) 和 (c) 中不规则的曲线对新数据具有更好的泛化能力。任何使模型偏向具有相似训练损失的解子集的因素都称为正则化器。人们认为神经网络的初始化和 / 或拟合具有隐式正则化效应。因此,在过参数化情形中,更合理的解(如面板 (a) 中的解)会受到鼓励。Figure 8.12 Regularization. a–c) Each of the three fitted curves passes through the data points exactly, so the training loss for each is zero. However, we might expect the smooth curve in panel (a) to generalize much better to new data than the erratic curves in panels (b) and (c). Any factor that biases a model toward a subset of the solutions with a similar training loss is known as a regularizer. It is thought that the initialization and/or fitting of neural networks have an implicit regularizing effect. Consequently, in the over-parameterized regime, more reasonable solutions, such as that in panel (a), are encouraged.

The answer to this question is uncertain, but there are two likely possibilities. First, the network initialization may encourage smoothness, and the model never departs from the sub-domain of smooth function during the training process. Second, the training algorithm may somehow “prefer” to converge to smooth functions.

Any factor that biases a solution toward a subset of equivalent solutions is known as a regularizer, so one possibility is that the training algorithm acts as an implicit regularizer (see section 9.2).

这个问题的答案尚不确定,但有两种可能的解释。首先,网络初始化可能会鼓励平滑性,并且模型在训练过程中从未离开平滑函数的子域。其次,训练算法可能在某种程度上“偏好”收敛到平滑函数。任何使解产生偏差并趋向等效解中某个子集的因素都被称为正则化器,因此一种可能是训练算法充当了隐式正则化器(参见第 9.2 节)。

8.5 选择超参数
8.5 Choosing hyperparameters

In the previous section, we discussed how test performance changes with model capacity. Unfortunately, in the classical regime, we don’t have access to either the bias (which requires knowledge of the true underlying function) or the variance (which requires multiple independently sampled datasets to estimate). In the modern regime, there is no way to tell how much capacity should be added before the test error stops improving. This raises the question of exactly how we should choose model capacity in practice.

For a deep network, the model capacity depends on the numbers of hidden layers and hidden units per layer as well as other aspects of architecture that we have yet to introduce. Furthermore, the choice of learning algorithm and any associated parameters (learning rate, etc.) also affects the test performance. These elements are collectively termed hyperparameters.

The process of finding the best hyperparameters is termed hyperparameter search or (when focused on network structure) neural architecture search.

在上一节中,我们讨论了测试性能如何随模型容量变化。遗憾的是,在经典情形中,我们无法获得偏差(需要知道真实底层函数)或方差(需要多个独立采样的数据集来估计)。在现代情形中,我们无法判断在测试误差停止改善之前应增加多少容量。这就引出了一个问题:在实践中我们究竟应如何选择模型容量。

对于深度网络,模型容量取决于隐藏层的数量以及每层隐藏单元的数量,还有我们尚未介绍的其他架构方面。此外,学习算法的选择及相关参数(学习率等)也会影响测试性能。这些元素统称为超参数。寻找最佳超参数的过程称为超参数搜索或(当聚焦于网络结构时)神经架构搜索。

Hyperparameters are typically chosen empirically; we train many models with different hyperparameters on the same training set, measure their performance, and retain the best model. However, we do not measure their performance on the test set; this would admit the possibility that these hyperparameters just happen to work well for the test set but don’t generalize to further data. Instead, we introduce a third dataset known as a validation set. For every choice of hyperparameters, we train the associated model using the training set and evaluate performance on the validation set. Finally, we select the model that worked best on the validation set and measure its performance on the test set. In principle, this should give a reasonable estimate of the true performance.

The hyperparameter space is generally smaller than the parameter space but still too large to try every combination exhaustively. Unfortunately, many hyperparameters are discrete (e.g., the number of hidden layers), and others may be conditional on one another (e.g., we only need to specify the number of hidden units in the tenth hidden layer if there are ten or more layers). Hence, we cannot rely on gradient descent methods as we did for learning the model parameters. Hyperparameter optimization algorithms intelligently sample the space of hyperparameters, contingent on previous results. This procedure is computationally expensive since we must train an entire model and measure the validation performance for each combination of hyperparameters.

超参数通常通过经验进行选择;我们在同一训练集上使用不同超参数训练许多模型,测量它们的性能,并保留最佳模型。然而,我们不会在测试集上测量它们的性能;这会使一种可能性成立:这些超参数恰好对测试集表现良好,但无法泛化到更多数据。相反,我们引入第三个数据集,称为验证集。对于每一种超参数选择,我们使用训练集训练相应模型,并在验证集上评估性能。最后,我们选择在验证集上表现最佳的模型,并在测试集上测量其性能。原则上,这应能给出真实性能的合理估计。

超参数空间通常小于参数空间,但仍然大到无法穷举尝试所有组合。遗憾的是,许多超参数是离散的(例如隐藏层的数量),而其他超参数可能彼此条件相关(例如,只有当存在十层或更多层时,才需要指定第十个隐藏层中的隐藏单元数量)。因此,我们不能像学习模型参数那样依赖梯度下降方法。超参数优化算法会根据以往结果智能地对超参数空间进行采样。这一过程计算代价高昂,因为我们必须为每个超参数组合训练整个模型并衡量验证性能。

8.6 小结
8.6 Summary

To measure performance, we use a separate test set. The degree to which performance is maintained on this test set is known as generalization. Test errors can be explained by three factors: noise, bias, and variance. These combine additively in regression problems with least squares losses. Adding training data decreases the variance. When the model capacity is less than the number of training examples, increasing the capacity decreases bias but increases variance. This is known as the bias-variance trade-off, and there is a capacity where the trade-off is optimal.

However, this is balanced against a tendency for performance to improve with capacity, even when the parameters exceed the training examples. Together, these two phenomena create the double descent curve. It is thought that the model interpolates more smoothly between the training data points in the over-parameterized “modern regime,” although it is unclear what drives this. To choose the capacity and other model and training algorithm hyperparameters, we fit multiple models and evaluate their performance using a separate validation set.

为了衡量性能,我们使用单独的测试集。在该测试集上保持性能的程度称为泛化。测试误差可以由三个因素解释:噪声、偏差和方差。在采用最小二乘损失的回归问题中,这些因素以相加的方式组合。增加训练数据会降低方差。当模型容量小于训练样本数量时,增加容量会降低偏差但会增加方差。这被称为偏差 - 方差权衡,并且存在一个使权衡达到最优的容量。

然而,这与性能随容量提升而改善的倾向相平衡,即使参数数量超过训练样本数量。这两种现象共同形成了双下降曲线。人们认为,在过参数化的“现代范式”中,模型在训练数据点之间插值更为平滑,但驱动这一现象的因素尚不明确。为了选择容量以及其他模型和训练算法的超参数,我们拟合多个模型,并使用单独的验证集评估其性能。

注释
Notes

Bias-variance trade-off:

Cross-validation:

Capacity:

Double descent:

Curse of dimensionality:

Real-world performance:

Hyperparameter search:

习题
Problems
图 8.13 典型集。 a) 二维标准正态分布。圆圈表示从该分布中抽取的四个样本。随着与中心的距离增加,概率减小,但该半径处的空间体积(即相邻等间距圆之间的面积
图 8.13 典型集。 a) 二维标准正态分布。圆圈表示从该分布中抽取的四个样本。随着与中心的距离增加,概率减小,但该半径处的空间体积(即相邻等间距圆之间的面积)增加。 b) 这些因素相互抵消,使得样本与中心距离的直方图出现明显的峰值。 c) 在更高维度中,这种效应更加极端,观察到接近均值的样本的概率变得极其微小。尽管最可能的点位于分布的均值处,但典型样本出现在相对狭窄的壳层中。其中 Γ[•] 为 Gamma 函数。请利用斯特林公式证明超 - 的体积直径为一的球体(半径为 r=0.5)的体积随维度增加而变为零。问题 8。 8 ∗ 考虑一个半径为 r=1 的超球体。求总体积中位于距离中心最外侧 1% 区域(即厚度为 0.01 的最外层壳层)所占比例的表达式。证明该比例随维度增加而趋近于 1。问题 8.9 图 8.13c 展示了随着维度增加,标准正态分布样本的距离分布。请通过对 25、 100 和 500 维的标准正态分布进行采样,并绘制样本到中心距离的直方图,来实证验证这一发现。哪种闭式概率分布描述了这些距离?Figure 8.13 Typical sets. a) Standard normal distribution in two dimensions. Circles are four samples from this distribution. As the distance from the center increases, the probability decreases, but the volume of space at that radius (i.e., the area between adjacent evenly spaced circles) increases. b) These factors trade off so that the histogram of distances of samples from the center has a pronounced peak. c) In higher dimensions, this effect becomes more extreme, and the probability of observing a sample close to the mean becomes vanishingly small. Although the most likely point is at the mean of the distribution, the typical samples are found in a relatively narrow shell. where Γ[•] is the Gamma function. Show using Stirling’s formula that the volume of a hypersphere of diameter one (radius r=0.5) becomes zero as the dimension increases. Problem 8.8 ∗ Consider a hypersphere of radius r=1. Find an expression for the proportion of the total volume that lies in the outermost 1% of the distance from the center (i.e., in the outermost shell of thickness 0.01). Show that this becomes one as the dimension increases. Problem 8.9 Figure 8.13c shows the distribution of distances of samples of a standard normal distribution as the dimension increases. Empirically verify this finding by sampling from the standard normal distributions in 25, 100, and 500 dimensions and plotting a histogram of the distances from the center. What closed-form probability distribution describes these distances?