Part V · 第 16 章 从数据中学习 · 16.2Part V · Ch. 16 Learning from Data · 16.2

损失、泛化与正则化Losses, Generalization & Regularization

训练只能在手头的数据上把损失压低,机器人要的却是在没见过的情况里也做对。损失函数决定你惩罚什么(它其实是对噪声的一个假设),泛化问的是训练集上的好成绩能不能带到新数据上,正则化则是防止灵活的模型把训练数据连同噪声一起背下来的各种办法。本节在浏览器里现场训练小网络:看它过拟合、早停、被 L2、dropout 和数据增广拉回来,再看偏差与方差、L1 与 L2、双下降,以及机器人最大的泛化难题:部署时的数据分布与训练时不同。 Training can only push the loss down on the data at hand; a robot needs to be right in situations it has never seen. The loss decides what you penalize (it is really an assumption about the noise), generalization asks whether a good score on the training set carries over to new data, and regularization is the family of tricks that stop a flexible model from memorizing the training data, noise and all. This lesson trains small networks live in your browser: watch one overfit, stop early, and get pulled back by L2, dropout and data augmentation; then see bias and variance, L1 versus L2, double descent, and the robot's biggest generalization problem: at deployment the data come from a different distribution than in training.

约 45 分钟~45 min 前置:16.1 回归与分类 · 6.4 随机梯度下降 · 4.6 最大似然与最大后验Prereqs: 16.1 Regression & Classification · 6.4 Stochastic Gradient Descent · 4.6 Maximum Likelihood & MAP 7 个交互7 interactives

    1为什么机器人需要它Why robots need this

    机器人越来越多的部件是从数据里学出来的:关节摩擦的补偿模型、“这次抓取会不会成功”的预测器、从人类示教学来的整套策略。16.1 节用最大似然拟合了回归和分类模型,并在留出的测试集上打分。训练时我们最小化的是训练集上的平均损失,可我们真正在乎的是机器人明天遇到的情况:新的物体、新的光照、新的速度。两者之差就是泛化问题。

    有三件事决定泛化好不好。第一,损失函数:平方误差、L1、Huber 和交叉熵各自隐含着对噪声的不同假设,遇到传感器野值或类别标签时表现完全不同。第二,容量与正则化:一个参数比数据点多得多的网络能把训练误差压到几乎为零,包括把噪声也背下来;验证集、早停、L2、dropout、数据增广是防止这件事的工具。第三,对机器人最要命的是分布偏移:机器人自己的动作会改变它接下来看到的东西,部署时的输入分布和训练时不同,而模型在训练分布之外几乎没有任何保证(22.1 节的模仿学习会把这个问题放大成误差累积)。

    More and more of a robot is learned from data: a compensation model for joint friction, a predictor of "will this grasp succeed", a whole policy learned from human demonstrations. Lesson 16.1 fitted regression and classification models by maximum likelihood and scored them on a held-out test set. During training we minimize the average loss on the training set, but what we really care about is what the robot meets tomorrow: new objects, new lighting, new speeds. The difference between the two is the generalization problem.

    Three things decide how well a model generalizes. First, the loss: squared error, L1, Huber and cross-entropy each carry a different assumption about the noise, and they behave completely differently on sensor outliers or class labels. Second, capacity and regularization: a network with far more parameters than data points can drive its training error to almost zero, memorizing the noise along the way; validation sets, early stopping, L2, dropout and data augmentation are the tools against that. Third, and worst for robots, distribution shift: a robot's own actions change what it sees next, so the inputs at deployment are distributed differently from those in training, and a model has almost no guarantee outside its training distribution (imitation learning in Lesson 22.1 turns this into compounding errors).

    2直觉:损失函数是对噪声的一个假设Intuition: a loss is an assumption about the noise

    4.6 节已经推出:如果测量噪声是高斯的,最大似然就是最小化平方误差;如果是拉普拉斯的(尾巴更厚),就是最小化绝对误差,估计值从均值变成中位数。换句话说,选损失就是选噪声模型。对拟合过程更直观的看法是每个数据点对拟合施加的“拉力”:损失 \(\hl{rho}{\rho(r)}\) 对残差 \(r\) 的导数 \(\hl{psi}{\psi(r)=\rho'(r)}\) 叫影响函数。平方损失的拉力与残差成正比,一个离谱的点拉力最大;L1 的拉力恒为 ±1,与残差大小无关;Huber 损失在 \(|r|\le\delta\) 时是平方、之外是线性,拉力被截在 ±δ。

    下图是一个力传感器的标定:横轴是加的载荷,纵轴是读数,10 个点基本在一条直线上,外加一个可以拖动的点。把它拖成一个“野值”(比如接触瞬间的冲击读数),看三条拟合直线各被拉走多少。

    Lesson 4.6 derived that if the measurement noise is Gaussian, maximum likelihood means minimizing the squared error; if it is Laplace (heavier tails), it means minimizing the absolute error, and the estimate moves from the mean to the median. In other words, choosing a loss is choosing a noise model. A more tangible view of what happens during fitting is the "pull" each data point exerts on the fit: the derivative \(\hl{psi}{\psi(r)=\rho'(r)}\) of the loss \(\hl{rho}{\rho(r)}\) with respect to the residual \(r\), called the influence function. Under the squared loss the pull grows with the residual, so the most absurd point pulls hardest; under L1 the pull is always ±1, whatever the residual; the Huber loss is quadratic for \(|r|\le\delta\) and linear beyond, so its pull is capped at ±δ.

    The figure below is the calibration of a force sensor: load applied on the horizontal axis, reading on the vertical axis; 10 points lie roughly on a line, plus one point you can drag. Turn it into an "outlier" (say an impact spike at the moment of contact) and watch how far each of the three fitted lines gets pulled.

    FIG 1回归损失:一个野值能把拟合拉走多远Regression losses: how far one outlier can drag the fit
    左:10 个普通数据点(灰色实心点)和一个可拖动的点(琥珀色空心圈)。三条直线是对全部 11 个点的拟合:红 = 平方损失,绿 = Huber,紫 = L1;青色虚线是只用那 10 个普通点的平方损失拟合,作为“干净”的参照。被突出显示的损失画得更粗,并画出每个点到它的残差线段。右上:三种损失 \(\rho(r)\);右下:它们的影响函数 \(\psi(r)\),点是当前各个数据点的残差(琥珀色圈是可拖动的那个点)。三条线都用 IRLS(迭代重加权最小二乘,6.9 节)求到收敛;读数里的“偏离”是该直线与干净拟合在 \(x\in[-1,1]\) 上的均方根距离。 Left: 10 ordinary data points (filled grey dots) and one draggable point (the hollow amber ring). The three lines are fits to all 11 points: red = squared loss, green = Huber, purple = L1; the dashed cyan line is the squared-loss fit to the 10 ordinary points only, the "clean" reference. The highlighted loss is drawn thicker, with each point's residual segment to it. Top right: the three losses \(\rho(r)\); bottom right: their influence functions \(\psi(r)\), with dots at the current residual of every point (the amber ring is the draggable one). All three lines are solved to convergence by IRLS (iteratively reweighted least squares, Lesson 6.9); "off by" in the readout is the RMS distance between that line and the clean fit over \(x\in[-1,1]\).
    试一试Try this
    • 把琥珀色圈往下拖,直到它离青色干净直线至少 1 V(读数第一行),Huber 阈值保持 δ ≤ 0.25:红色平方损失直线被拉走的距离是绿色 Huber 和紫色 L1 的 2.5 倍以上。Drag the amber ring down until it is at least 1 V from the cyan clean line (first line of the readout), keeping the Huber threshold δ ≤ 0.25: the red squared-loss line is dragged more than 2.5 times as far as the green Huber and purple L1 lines.

    在默认位置 \(x=0.7\),把这个点拖到离干净直线 1.5 V 时,平方拟合偏离 0.18 V,Huber(δ = 0.2)只偏离 0.03 V,L1 偏离 0.04 V;再往下拖,平方拟合继续跟着走(2.0 V 时 0.24 V),而 Huber 和 L1 几乎不再动:它们对这个点的拉力已经封顶了。代价是什么?把 δ 拉到 2,Huber 在这个范围内就退化成平方损失;而即使琥珀色圈就在直线上,L1 也和干净拟合差 0.02 V,因为它估计的是条件中位数而不是均值,在噪声真是高斯时浪费了一些数据。Huber 的阈值通常取噪声标准差的 1 到 2 倍左右(经典取法是 1.345σ,在高斯噪声下保留 95% 的效率),这里噪声 σ = 0.07 V,默认 δ = 0.2 V 约为 3σ。

    At the default position \(x=0.7\), with the point dragged 1.5 V away from the clean line, the squared fit is off by 0.18 V while Huber (δ = 0.2) is off by only 0.03 V and L1 by 0.04 V; drag further and the squared fit keeps following (0.24 V at 2.0 V) while Huber and L1 hardly move: their pull from this point is already capped. What is the price? Raise δ to 2 and Huber turns back into the squared loss over this range; and L1 is 0.02 V off the clean fit even when the ring sits on the line, because it estimates the conditional median rather than the mean and wastes some data when the noise really is Gaussian. The Huber threshold is usually set at about 1 to 2 noise standard deviations (the classic choice 1.345σ keeps 95% efficiency under Gaussian noise); here the noise is σ = 0.07 V and the default δ = 0.2 V is about 3σ.

    分类:为什么用交叉熵而不是平方误差Classification: why cross-entropy and not squared error

    分类器输出一个 logit \(z\),经过 sigmoid 得到概率 \(\sigma(z)\)(多类时是 softmax,16.1 节)。最大似然给出交叉熵 \(\hl{ce}{-\log\sigma(z)}\)(真实标签 \(y=1\) 时)。你也可以图省事,对概率用平方误差 \(\hl{sqp}{(\sigma(z)-y)^2}\),两者的最小值都在 \(\sigma(z)=1\)。区别在于模型错得很自信时:比如 \(z=-6\),模型以 99.75% 的把握说“不会成功”而实际成功了。交叉熵对 \(z\) 的梯度是 \(\sigma(z)-y\approx-1\),推力最大;平方误差的梯度多了一个因子 \(\sigma(z)(1-\sigma(z))\approx0.0025\),几乎推不动:sigmoid 在饱和区是平的,平方误差把这种平坦原样传给了梯度,交叉熵的对数恰好把它抵消掉。

    A classifier outputs a logit \(z\) and turns it into a probability \(\sigma(z)\) with the sigmoid (softmax for several classes, Lesson 16.1). Maximum likelihood gives the cross-entropy \(\hl{ce}{-\log\sigma(z)}\) (for the true label \(y=1\)). You could also take a shortcut and use the squared error on the probability, \(\hl{sqp}{(\sigma(z)-y)^2}\); both are minimized at \(\sigma(z)=1\). The difference shows when the model is confidently wrong: say \(z=-6\), so the model says "will fail" with 99.75% confidence and the grasp actually succeeded. The gradient of cross-entropy with respect to \(z\) is \(\sigma(z)-y\approx-1\), the strongest push there is; the gradient of the squared error carries an extra factor \(\sigma(z)(1-\sigma(z))\approx0.0025\) and barely pushes at all: the sigmoid is flat when saturated, the squared error passes that flatness on to the gradient, and the logarithm in the cross-entropy cancels it exactly.

    FIG 2自信地错了:交叉熵用力推,平方误差推不动;标签平滑让最优 logit 变成有限值Confidently wrong: cross-entropy pushes hard, squared error barely moves; label smoothing makes the best logit finite
    一个样本,真实标签 \(y=1\),我们直接对 logit \(z\) 做梯度下降(学习率 η = 1),两种损失从同一个初值 \(z_0\) 出发。左上:蓝 = 交叉熵,红 = 概率上的平方误差,点是当前位置;左下:两者对 \(z\) 的梯度。右:预测概率随步数的变化,灰色虚线是 0.5,绿色虚线是标签平滑后的目标 \(1-\varepsilon/2\);左图的绿色竖虚线是平滑后交叉熵的最优 logit \(z^\ast\)(ε = 0 时它在无穷远,不画)。 One example with true label \(y=1\); we run gradient descent directly on its logit \(z\) (learning rate η = 1), both losses starting from the same \(z_0\). Top left: blue = cross-entropy, red = squared error on the probability, dots mark the current positions; bottom left: their gradients with respect to \(z\). Right: the predicted probability against the step count; the grey dashed line is 0.5, the green dashed line is the smoothed target \(1-\varepsilon/2\); the green vertical dashed line on the left is the best logit \(z^\ast\) of the smoothed cross-entropy (at infinity for ε = 0, so not drawn).
    • 把初始 logit 设到 −5 或更低(模型自信地错了),ε = 0,按“训练”:交叉熵不到 10 步就越过 0.5,平方误差至少要多 10 倍的步数(−5 时 85 步,−6 时 214 步)。Set the initial logit to −5 or lower (confidently wrong), ε = 0, and press "Train": cross-entropy crosses 0.5 within 10 steps, squared error needs at least 10 times as many (85 steps from −5, 214 from −6).
    • 选标签平滑 ε = 0.1 或 0.2 并训练至少 150 步:交叉熵的 logit 停在有限的 \(z^\ast\)(ε = 0.1 时为 2.944),不再无限增大;对比 ε = 0 时 400 步后 \(z\) 仍在缓慢上涨。Choose label smoothing ε = 0.1 or 0.2 and train for at least 150 steps: the cross-entropy logit settles at a finite \(z^\ast\) (2.944 for ε = 0.1) instead of growing forever; compare ε = 0, where \(z\) is still creeping up after 400 steps.

    第二个任务揭示了交叉熵的另一面:对于可分的数据,它的最小值在 \(z\to\infty\),模型会被一直推向“100% 确定”,权重越来越大。标签平滑(label smoothing)把目标从 1 改成 \(1-\varepsilon+\varepsilon/K\)(\(K\) 类,图里 \(K=2\),即 \(1-\varepsilon/2\)),最优 logit 就成了有限值 \(z^\ast=\log\frac{1-\varepsilon/2}{\varepsilon/2}\)。这是一种正则化:它阻止模型过度自信,对标注噪声也更宽容;代价是预测概率被系统性地压低,需要校准好的概率时要小心。

    The second task reveals the other side of cross-entropy: on separable data its minimum is at \(z\to\infty\), so the model keeps being pushed towards "100% sure" and its weights keep growing. Label smoothing changes the target from 1 to \(1-\varepsilon+\varepsilon/K\) (\(K\) classes; \(K=2\) in the figure, i.e. \(1-\varepsilon/2\)), and the best logit becomes the finite \(z^\ast=\log\frac{1-\varepsilon/2}{\varepsilon/2}\). This is a regularizer: it stops the model from becoming overconfident and is more forgiving of label noise; the price is that predicted probabilities are pulled down systematically, so be careful where calibrated probabilities matter.

    核心洞见Key insight

    选损失要回答两个问题:噪声长什么样(高斯 → 平方,有野值 → Huber 或 L1,类别 → 交叉熵),以及梯度在哪里还有力气(平方误差加 sigmoid 在饱和区没有梯度,交叉熵有)。下面三节转向第二件事:损失再合适,模型也可能把训练数据背下来。

    Choosing a loss answers two questions: what does the noise look like (Gaussian → squared, outliers → Huber or L1, classes → cross-entropy), and where does the gradient still have strength (squared error behind a sigmoid has none in the saturated region, cross-entropy does). The next three sections turn to the second issue: even with the right loss, a model can memorize its training data.

    3动手:看一个网络过拟合,再把它拉回来Play: watch a network overfit, then pull it back

    一个直观的比喻:学生拿到去年的考卷和答案。背答案,去年的卷子能考满分,换一套题就不行;理解了方法,两套卷子都考得好。训练集就是去年的卷子,验证集是你自己留出来、训练时从不用于更新参数的另一套题,测试集是最后才打开一次的真正考试。16.1 节已经引入了训练/测试的划分;这里多出的验证集用来做所有“选择”:训练多久、正则化多强、用哪个模型。测试集只能用来报告最终结果,一旦你根据它做了选择,它就不再是公正的估计。

    下图在你的浏览器里现场训练一个两层隐藏层、每层 32 个 tanh 单元的网络(1153 个参数),去拟合一个关节的摩擦力矩随速度变化的曲线(库仑摩擦 + 低速的 Stribeck 峰 + 粘性摩擦),只有 12 个带噪声(σ = 0.15 N·m)的测量点。用 Adam(学习率 0.01),每一步用全部训练点(多于 16 个时随机取 16 个)。

    A familiar analogy: a student gets last year's exam with the answers. Memorize the answers and last year's paper scores 100%, but a new paper does not; understand the method and both papers go well. The training set is last year's paper; the validation set is another paper you set aside yourself and never use to update parameters; the test set is the real exam, opened once at the very end. Lesson 16.1 introduced the train/test split; the extra validation set is where every "choice" is made: how long to train, how strong the regularization, which model. The test set is only for reporting the final result: once you have made a choice based on it, it is no longer an unbiased estimate.

    The figure below trains, live in your browser, a network with two hidden layers of 32 tanh units (1153 parameters) to fit the friction torque of a joint as a function of its velocity (Coulomb friction + a Stribeck peak at low speed + viscous friction), from only 12 noisy (σ = 0.15 N·m) measurements. It uses Adam (learning rate 0.01), each step on all training points (16 random ones when there are more than 16).

    FIG 3过拟合现场:训练损失一路下降,验证损失先降后升Overfitting live: the training loss keeps falling, the validation loss falls and then rises
    左:青色虚线是真实的摩擦曲线,蓝点是训练点,紫色空心圈是 40 个验证点(同一分布、同样的噪声,从不参与训练),琥珀色是网络当前的预测,绿色虚线是验证损失最低时(早停点)的网络。右:训练和验证均方误差(对数坐标),青色虚线是噪声水平 σ² = 0.0225:验证损失平均不可能低于它,训练损失却可以一路降到零;绿色竖虚线标出早停点。“与真实函数的误差”是预测与青色曲线之间的均方误差,只有在模拟里才算得出来。改动任何设置都会重新开始训练;网络初始化和数据都有固定的随机种子。 Left: the dashed cyan curve is the true friction curve, blue dots are training points, hollow purple rings are the 40 validation points (same distribution, same noise, never used for training), amber is the network's current prediction, and the dashed green curve is the network at its lowest validation loss (the early-stopping point). Right: the training and validation mean squared errors (log scale); the dashed cyan line is the noise floor σ² = 0.0225: on average the validation loss cannot go below it, while the training loss can go all the way to zero; the green vertical dashed line marks the early-stopping point. "Error vs the true function" is the mean squared error between the prediction and the cyan curve, something only a simulation can compute. Changing any setting restarts training; the network initialization and the data have fixed random seeds.
    • 默认设置(12 个点、不加任何正则化)下按“训练”:验证损失在第 285 步左右最低(约 0.025,接近噪声水平),之后回升,到第 1200 步左右超过最低值的 1.5 倍;训练损失则一路降到 \(10^{-5}\) 以下。With the defaults (12 points, no regularization) press "Train": the validation loss bottoms out near step 285 (about 0.025, close to the noise floor), then climbs back and passes 1.5 times its minimum near step 1200, while the training loss falls below \(10^{-5}\).
    • 仍用 12 个点,只把 L2 系数设为 \(\lambda\ge 3\times10^{-4}\),训练到第 3000 步以后:读数里“最近 1000 步平均 / 最低”低于 1.4(λ = 3×10⁻⁴ 时约 1.16,λ = 10⁻³ 时约 1.08),不加正则化时这个数约是 2.5。Still with 12 points, set only the L2 weight to \(\lambda\ge 3\times10^{-4}\) and train past step 3000: "last-1000-step mean / best" in the readout stays below 1.4 (about 1.16 for λ = 3×10⁻⁴, 1.08 for λ = 10⁻³), against about 2.5 without regularization.
    • 去掉所有正则化,把训练点数加到 48 个以上,训练到第 3000 步以后:同一个 1153 参数的网络不再明显过拟合,“最近 1000 步平均 / 最低”低于 1.4。Remove all regularization, raise the training points to 48 or more and train past step 3000: the same 1153-parameter network no longer overfits noticeably; "last-1000-step mean / best" stays below 1.4.

    注意默认运行里发生的事:到第 2000 步,训练损失只有约 \(2\times10^{-5}\),网络几乎精确地穿过了每一个训练点,包括它们的噪声;琥珀色曲线在点与点之间剧烈弯曲。验证损失约 0.066,是最低时的 2.6 倍;用真实函数衡量,当前网络的误差(约 0.03)是早停点(约 0.004)的 7 倍左右。这就是过拟合:训练误差和真实误差之间的差距(泛化差距)在扩大。

    几种补救方法的效果(同样 12 个点,训练 5000 步,看第 4000 到 5000 步验证损失的平均值除以其最低值):不加正则化 2.4;L2 系数 \(10^{-4}\) 只是推迟了过拟合(第 3000 步时 1.3,第 5000 步时 2.4),\(3\times10^{-4}\)、\(10^{-3}\) 分别为 1.17、1.08;dropout p = 0.1 或 0.2 约 1.3;输入抖动 0.05 或 0.1(每一步给训练输入加一点高斯噪声,这是 1 维输入上最简单的数据增广)约 1.3;训练点加到 48 个约 1.3,96 个约 1.16。带随机性的方法(dropout、抖动、多于 16 个点时的小批量)会让验证损失一直小幅抖动,所以读数里同时给出“现在”和“最近 1000 步平均”。早停是最便宜的一种:按“早停:恢复最佳权重”,就得到绿色虚线那个网络。

    Notice what happens in the default run: by step 2000 the training loss is only about \(2\times10^{-5}\); the network passes almost exactly through every training point, noise included, and the amber curve bends wildly between them. The validation loss is about 0.066, 2.6 times its minimum; measured against the true function, the current network's error (about 0.03) is about 7 times that at the early-stopping point (about 0.004). This is overfitting: the gap between the training error and the true error (the generalization gap) is widening.

    How the remedies fare (same 12 points, 5000 steps, mean validation loss over steps 4000 to 5000 divided by its minimum): no regularization 2.4; an L2 weight of \(10^{-4}\) only delays overfitting (1.3 at step 3000, 2.4 at step 5000), \(3\times10^{-4}\) and \(10^{-3}\) give 1.17 and 1.08; dropout p = 0.1 or 0.2: about 1.3; input jitter 0.05 or 0.1 (a little Gaussian noise added to the training inputs at every step, the simplest data augmentation for a 1D input): about 1.3; 48 training points: about 1.3, 96: about 1.16. Methods with randomness (dropout, jitter, minibatches once there are more than 16 points) keep the validation loss jittering a little, which is why the readout shows both "now" and "last-1000-step mean". Early stopping is the cheapest of all: press "Early stop: restore best" and you get the network of the dashed green curve.

    有意思的细节Things worth noticing

    (1) 验证损失的最低值(约 0.025)贴近噪声水平 0.0225:这个模型能做到的最好,就是只剩下不可约的测量噪声。(2) 过拟合不是因为“训练太久”本身,而是参数太多、数据太少、又没有约束;同样训练 5000 步,96 个点就几乎不过拟合。(3) 一个运行的数字依赖于随机种子:按“换一组数据”试几次,最低点可能在 100 到 450 步之间,但“训练一路降、验证先降后升”的形状每次都在。

    (1) The lowest validation loss (about 0.025) sits close to the noise floor 0.0225: the best this model can do is leave only the irreducible measurement noise. (2) Overfitting is not caused by "training too long" as such, but by too many parameters, too little data and no constraint; trained for the same 5000 steps, 96 points hardly overfit. (3) The numbers of one run depend on the random seed: press "New data" a few times and the minimum may land anywhere between about 100 and 450 steps, but the shape, training loss falling and validation loss falling then rising, is there every time.

    4另一个视角:偏差、方差与交叉验证Another view: bias, variance and cross-validation

    为什么模型越灵活越容易过拟合?设想你可以从同一个分布里抽出很多个不同的训练集,每个都拟合一次。偏差是这些拟合的平均离真实函数有多远:模型太僵硬(比如用直线拟合 S 形曲线),平均下来也是错的。方差是这些拟合彼此差多少:模型太灵活,就会跟着每个训练集特有的噪声走,换一组数据就换一个样子。平方误差恰好能分解成三部分:

    Why does a more flexible model overfit more easily? Imagine you could draw many different training sets from the same distribution and fit each once. The bias is how far the average of these fits is from the true function: a model that is too rigid (a straight line through an S-shaped curve) is wrong even on average. The variance is how much the fits differ from each other: a model that is too flexible follows the noise peculiar to each training set and changes shape with every new set. The squared error splits exactly into three parts:

    $$ \mathbb E\big[(y-\hat f(x))^2\big] = \hl{noise}{\sigma^2} + \hl{bias}{\big(\mathbb E[\hat f(x)]-f(x)\big)^2} + \hl{var}{\mathbb E\Big[\big(\hat f(x)-\mathbb E[\hat f(x)]\big)^2\Big]} $$

    左边是期望测试误差,期望是对“抽一个训练集”(以及新样本的噪声)取的;右边第一项是测量噪声(不可约),第二项是偏差的平方,第三项是方差(推导见第 7 节)。下图用多项式回归把它们算出来:多项式的次数就是“容量”旋钮。它是线性最小二乘,有闭式解,所以可以一次对 40 个训练集各拟合一遍。

    The left side is the expected test error, the expectation being over "draw a training set" (and the noise of the new example); on the right, the first term is the measurement noise (irreducible), the second the squared bias, the third the variance (derivation in Section 7). The figure below computes them for polynomial regression, with the polynomial degree as the "capacity" knob. It is linear least squares with a closed-form solution, so we can fit each of 40 training sets at once.

    FIG 4偏差–方差:容量太小是偏差,容量太大是方差Bias–variance: too little capacity is bias, too much is variance
    同一条摩擦曲线,每个训练集 15 个点(每个 \(1/15\) 区间里随机取一个速度),噪声 σ = 0.15,共 40 个训练集。左:紫色细线是其中 25 个训练集各自的拟合,琥珀色是全部 40 个拟合的平均,青色虚线是真实曲线,蓝点是用于交叉验证的那一个训练集。琥珀色离青色的距离就是偏差,紫线散开的程度就是方差。右:随次数变化的 偏差²、方差、期望测试误差(三者之和,含青色虚线的噪声 σ²)、训练误差,以及用那一个训练集算出的 5 折交叉验证误差(虚线)。特征用勒让德多项式(数值稳定);岭系数 λ 惩罚除常数项外所有系数的平方和。 The same friction curve; each training set has 15 points (one random velocity in each \(1/15\) slot), noise σ = 0.15, 40 training sets in all. Left: thin purple lines are the fits of 25 of these training sets, amber is the average of all 40 fits, the dashed cyan curve is the truth, and the blue dots are the one training set used for cross-validation. The distance from amber to cyan is the bias; how widely the purple lines spread is the variance. Right: against the degree, the bias², the variance, the expected test error (their sum, including the noise σ² of the dashed cyan line), the training error, and the 5-fold cross-validation error (dashed) computed from that one training set. The features are Legendre polynomials (numerically stable); the ridge weight λ penalizes the sum of squares of all coefficients except the constant.
    • λ = 0 时把次数拉到 9 或更高:方差超过偏差²的 5 倍,紫线在两端乱甩,而训练误差还在继续下降。With λ = 0 push the degree to 9 or higher: the variance exceeds 5 times the bias², the purple lines flail at both ends, and the training error keeps falling.
    • 保持次数 ≥ 9,把岭系数 λ 往右拉:找到一个 λ,让期望测试误差低于“不加正则化时所有次数里最好的那个”(λ = 0 时次数 5,0.053)。Keep the degree ≥ 9 and move the ridge weight λ to the right: find a λ for which the expected test error is below "the best of all degrees without regularization" (degree 5 at λ = 0, 0.053).

    λ = 0 时曲线是教科书式的 U 形:次数 0 和 1 偏差很大(直线拟合不了摩擦在零速附近的跳变),次数 5 的期望测试误差最低(0.053),次数 9 时方差已有 0.40,是偏差²(0.025)的十几倍,次数 12 时测试误差超过 20。第二个任务的结论更重要:一个灵活的模型加上合适的正则化,胜过最好的小模型;次数 9 到 12 加上 λ = 0.01,测试误差约 0.042 到 0.045。这正是深度学习的常态:用比需要更大的网络,再用正则化和足够的数据把方差压下去。

    交叉验证是现实里估计测试误差的办法,因为你只有一个数据集,不能抽 40 个。\(k\) 折交叉验证把数据分成 \(k\) 份,轮流用 \(k-1\) 份训练、剩下 1 份评估,再取平均(第 7 节)。紫色虚线就是它:它比真正的测试误差噪声大得多,但大致跟着 U 形走;在数据集 #1 上它选了次数 3,测试误差 0.058,离最好的 0.053 不远。按“换一个数据集做 CV”看它怎样随数据抖动。

    At λ = 0 the curve is the textbook U: degrees 0 and 1 have a large bias (a line cannot follow the jump of friction near zero speed), degree 5 has the lowest expected test error (0.053), at degree 9 the variance is already 0.40, more than ten times the bias² (0.025), and at degree 12 the test error exceeds 20. The conclusion of the second task matters more: a flexible model with the right regularization beats the best small model; degrees 9 to 12 with λ = 0.01 reach a test error of about 0.042 to 0.045. This is the normal situation in deep learning: use a bigger network than needed, then keep the variance down with regularization and enough data.

    Cross-validation is how you estimate the test error in reality, where you have one dataset, not 40. \(k\)-fold cross-validation splits the data into \(k\) parts, trains on \(k-1\) of them and evaluates on the remaining one, in turn, and averages (Section 7). The dashed purple curve is that: much noisier than the true test error, but roughly following the U; on dataset #1 it picks degree 3, with test error 0.058, not far from the best 0.053. Press "Another dataset for CV" to see how it jitters with the data.

    5正则化:L2 让参数变小,L1 让参数变成零Regularization: L2 makes parameters small, L1 makes them zero

    正则化就是在训练损失后面加一项惩罚 \(\lambda\,\Omega(\boldsymbol\theta)\)。4.6 节说过它就是一个先验:\(\hl{pen}{\Omega=\|\boldsymbol\theta\|_2^2}\)(L2,岭回归,权重衰减)对应高斯先验,\(\Omega=\|\boldsymbol\theta\|_1\)(L1,lasso)对应拉普拉斯先验。两者都让参数变小,但方式完全不同。几何上看,带惩罚的最小化等价于“在一个范数球里找损失最低的点”(λ 越大,球越小):L2 的球是圆的,损失的等高椭圆一般在某个没有坐标为零的地方碰到它;L1 的球是一个菱形,有尖角在坐标轴上,椭圆往往先碰到尖角,于是某些坐标恰好等于零。

    Regularization adds a penalty \(\lambda\,\Omega(\boldsymbol\theta)\) to the training loss. Lesson 4.6 showed that this is a prior: \(\hl{pen}{\Omega=\|\boldsymbol\theta\|_2^2}\) (L2, ridge, weight decay) corresponds to a Gaussian prior and \(\Omega=\|\boldsymbol\theta\|_1\) (L1, lasso) to a Laplace prior. Both make parameters smaller, but in completely different ways. Geometrically, penalized minimization is equivalent to "find the lowest-loss point inside a norm ball" (larger λ, smaller ball): the L2 ball is round, and the elliptical loss contours usually touch it where no coordinate is zero; the L1 ball is a diamond with corners on the axes, the ellipse tends to hit a corner first, and some coordinates come out exactly zero.

    FIG 5L1 与 L2:菱形的尖角带来稀疏L1 versus L2: the corners of the diamond bring sparsity
    左:两个参数 \((w_1,w_2)\) 的二次损失 \(\tfrac12(\mathbf w-\hat{\mathbf w})^\top A(\mathbf w-\hat{\mathbf w})\),青色椭圆是等高线,中心 \(\hat{\mathbf w}\)(琥珀色,可拖动)是不加正则化的解。紫色菱形与紫点是 L1 惩罚下的解及经过它的 L1 球,蓝色圆与蓝点是 L2 下的解及经过它的 L2 球;虚线椭圆是经过所突出那个解的等高线,它与球相切。点线是 λ 从 0 增大到很大时解走过的路径:L2 的路径平滑地缩向原点,L1 的路径会先撞到一条坐标轴再沿着它走。右:一个 8 个候选特征的回归(比如用 8 个传感器信号预测电机电流,40 个样本,特征彼此相关),真正有用的只有第 1、3、6 个(琥珀色曲线),其余 5 个(灰线)真实系数为 0;横轴是 λ,红色竖虚线是当前 λ。 Left: a quadratic loss \(\tfrac12(\mathbf w-\hat{\mathbf w})^\top A(\mathbf w-\hat{\mathbf w})\) in two parameters \((w_1,w_2)\); the cyan ellipses are its contours and their centre \(\hat{\mathbf w}\) (amber, draggable) is the unregularized solution. The purple diamond and dot are the L1 solution and the L1 ball through it; the blue circle and dot are the L2 solution and the L2 ball through it; the dashed ellipse is the contour through the emphasized solution, tangent to its ball. The dotted lines are the paths the solutions follow as λ grows from 0 to very large: the L2 path shrinks smoothly towards the origin, the L1 path hits an axis and then runs along it. Right: a regression with 8 candidate features (say, predicting a motor current from 8 sensor signals; 40 samples, correlated features), of which only features 1, 3 and 6 matter (amber curves); the other 5 (grey lines) have true coefficient 0. The horizontal axis is λ, the red vertical dashed line is the current λ.
    • 选“L1”,调 λ 让右图里非零的系数恰好是第 1、3、6 个:lasso 自己挑出了真正有用的特征(λ 在 0.14 到 0.40 之间都可以)。再切到“L2”看:没有一个系数会变成零。Choose "L1" and tune λ so that exactly coefficients 1, 3 and 6 are nonzero on the right: the lasso has picked out the useful features by itself (any λ between 0.14 and 0.40 works). Then switch to "L2": no coefficient ever becomes zero.

    其他正则化手段Other regularizers

    深度学习里显式的 L1/L2 只是一部分,更常见的是下面这些,FIG 3 里试过其中三种:

    • 权重衰减:每步把权重乘以略小于 1 的数。对普通 SGD 这与 L2 惩罚等价,对 Adam 不等价(第 7 节),所以现在通常用 AdamW 的“解耦”权重衰减。
    • 早停:用验证集挑训练得最好的那一刻。对二次损失上的梯度下降,训练 \(t\) 步大致等价于 \(\lambda\approx1/(\eta t)\) 的 L2(第 7 节):训练时间本身就是一个正则化旋钮。
    • Dropout:训练时每个隐藏单元以概率 \(p\) 被随机置零,留下的乘以 \(1/(1-p)\);测试时全部保留。网络不能依赖任何单个单元,相当于训练了大量共享权重的子网络的集成。
    • 数据增广:对输入做不改变标签的变换,制造“免费”的新样本。对机器人图像是随机裁剪、平移、颜色抖动;对 1 维输入就是 FIG 3 的输入抖动,训练时加小噪声在一定条件下等价于一种平滑正则(Tikhonov 正则化,Bishop 1995)。增广编码了你对不变性的先验知识,常常是最有效的一种。
    • 标签平滑:FIG 2,限制分类器的自信程度。
    • SGD 的噪声:6.4 节的小批量噪声本身也有正则化作用,这也是极大批量训练常常泛化更差、需要重新调学习率的原因之一。

    In deep learning explicit L1/L2 are only part of the story; more common are the following, three of which you tried in FIG 3:

    • Weight decay: multiply the weights by a number slightly below 1 at every step. For plain SGD this is equivalent to an L2 penalty, for Adam it is not (Section 7), which is why AdamW's "decoupled" weight decay is the usual choice today.
    • Early stopping: use the validation set to pick the best moment of training. For gradient descent on a quadratic loss, training for \(t\) steps is roughly equivalent to L2 with \(\lambda\approx1/(\eta t)\) (Section 7): training time itself is a regularization knob.
    • Dropout: during training each hidden unit is zeroed at random with probability \(p\) and the survivors are multiplied by \(1/(1-p)\); at test time all units are kept. The network cannot rely on any single unit, which amounts to training a huge ensemble of weight-sharing subnetworks.
    • Data augmentation: apply label-preserving transformations to the inputs to make "free" new examples. For robot images: random crops, shifts, colour jitter; for a 1D input: the input jitter of FIG 3, and training with small input noise is, under some conditions, equivalent to a smoothness regularizer (Tikhonov regularization, Bishop 1995). Augmentation encodes your prior knowledge of invariances and is often the most effective of all.
    • Label smoothing: FIG 2; limits how confident a classifier can get.
    • SGD noise: the minibatch noise of Lesson 6.4 regularizes too, one reason why very large batches often generalize worse and need the learning rate retuned.

    6再多一点参数:双下降Even more parameters: double descent

    按照 U 形曲线,参数远多于数据的现代网络应该过拟合得一塌糊涂,可它们常常泛化得很好。一个可以完全看清楚的例子:用 \(p\) 个随机 ReLU 特征 \(\phi_j(x)=\max(0,s_j(x-t_j))\)(随机的拐点 \(t_j\) 和方向 \(s_j\))做线性回归,只学最后一层权重。\(p<n\) 时用最小二乘;\(p>n\) 时有无穷多组权重能精确穿过所有训练点,我们取其中范数最小的那一组 \(\hl{minnorm}{\mathbf w=\Phi^{+}\mathbf y}\)(1.13 节的伪逆)。测试误差随 \(p\) 先降、在 \(\hl{thresh}{p\approx n}\) 处冲上一个尖峰、然后再次下降,这叫双下降。

    By the U-shaped curve, modern networks with far more parameters than data should overfit terribly, yet they often generalize well. An example you can see completely: linear regression on \(p\) random ReLU features \(\phi_j(x)=\max(0,s_j(x-t_j))\) (random kinks \(t_j\) and directions \(s_j\)), learning only the last-layer weights. For \(p<n\) use least squares; for \(p>n\) infinitely many weight vectors pass exactly through all training points, and we take the one with the smallest norm, \(\hl{minnorm}{\mathbf w=\Phi^{+}\mathbf y}\) (the pseudo-inverse of Lesson 1.13). The test error first falls as \(p\) grows, shoots up to a spike at \(\hl{thresh}{p\approx n}\), and then falls again: double descent.

    FIG 6双下降:插值阈值处的尖峰,以及过参数化之后的第二次下降Double descent: a spike at the interpolation threshold, then a second descent when over-parametrized
    n = 16 个训练点(同一条摩擦曲线,噪声 σ = 0.1)。左:一次抽样(数据和特征一起抽)的拟合,琥珀色是预测,青色虚线是真实曲线,蓝点是训练点。右:测试误差(与真实曲线的均方误差)随特征数 \(p\) 的变化,两轴都是对数:紫色小点是 20 次抽样各自的误差(蓝点是左图那一次),琥珀色是 20 次的平均,青色虚线是 20 次的中位数,红色竖虚线是 \(p=n\),绿色水平虚线是经典区(\(p<n\))里平均误差的最低值。超出画面的点画在上边缘。 n = 16 training points (the same friction curve, noise σ = 0.1). Left: the fit for one draw (data and features drawn together); amber is the prediction, the dashed cyan curve the truth, blue dots the training points. Right: the test error (mean squared error against the true curve) against the number of features \(p\), both axes logarithmic: small purple dots are the errors of the 20 individual draws (the blue dot is the draw on the left), amber is their mean, the dashed cyan line their median, the red vertical dashed line is \(p=n\), and the green horizontal dashed line is the lowest mean error in the classical regime (\(p<n\)). Points beyond the plot are drawn at its top edge.
    • λ = 0:先把 \(p\) 拉到 15 到 17 之间,看平均误差冲到上千(左图的拟合在点之间剧烈震荡);再拉到 \(p\ge100\):平均误差回落到绿色虚线以下,比经典区里最好的还低。最后试试 λ = 10⁻⁵:尖峰消失。λ = 0: first move \(p\) to between 15 and 17 and see the mean error shoot into the thousands (the fit on the left oscillates wildly between the points); then move to \(p\ge100\): the mean error falls back below the green dashed line, lower than the best of the classical regime. Finally try λ = 10⁻⁵: the spike is gone.

    数字:经典区(\(p<n\))里平均误差最低约 0.054(\(p=6\));\(p=15\) 时平均误差约 8600,\(p\ge100\) 时回落到 0.017 到 0.019。看紫色小点就会发现,平均值的巨大尖峰几乎全来自 20 次抽样中的一次(它在 \(p=15\) 时误差约 \(10^5\));中位数(典型的一次抽样)也有一个温和得多的鼓包:从 \(p=8\) 时的 0.027 升到 \(p=12\) 到 13 时的 0.08,再降到 \(p\ge100\) 时的 0.013,不到它在经典区最好值的一半。为什么会有尖峰?\(p\approx n\) 时特征矩阵 \(\Phi\) 接近方阵,它的最小奇异值可能很小,为了精确穿过每一个带噪声的点,权重必须非常大(方差随 \(\sum 1/s_i^2\) 增长,第 7 节);\(p\) 再大,能穿过所有点的解有很多,最小范数的那个最“平缓”,方差反而下降。一点点岭正则化(λ = 10⁻⁵)就把尖峰抹平,这是实践中很少看到尖峰的一个原因:几乎总有某种显式或隐式的正则化。深度网络里也观察到了随模型大小、甚至随训练轮数出现的双下降(Nakkiran 等,2020)。本节只点到为止;它说明“参数个数”并不是衡量容量的好指标,有效容量还取决于优化器隐式偏好的那类解。

    The numbers: the lowest mean error in the classical regime (\(p<n\)) is about 0.054 (\(p=6\)); at \(p=15\) the mean error is about 8600, and for \(p\ge100\) it falls back to 0.017 to 0.019. The purple dots show that the huge spike of the mean comes almost entirely from one of the 20 draws (whose error at \(p=15\) is about \(10^5\)); the median (a typical draw) has a much gentler bump: from 0.027 at \(p=8\) up to 0.08 at \(p=12\) to 13, and down to 0.013 for \(p\ge100\), less than half its best in the classical regime. Why the spike? At \(p\approx n\) the feature matrix \(\Phi\) is nearly square and its smallest singular value can be tiny, so passing exactly through every noisy point needs very large weights (the variance grows like \(\sum 1/s_i^2\), Section 7); with larger \(p\) many solutions pass through all points, the minimum-norm one is the "gentlest", and its variance goes down. A tiny ridge (λ = 10⁻⁵) flattens the spike, which is one reason it is rarely seen in practice: there is almost always some explicit or implicit regularization. Double descent has also been observed in deep networks, as a function of model size and even of training epochs (Nakkiran et al., 2020). This section only touches on it; its lesson is that "number of parameters" is a poor measure of capacity, because the effective capacity also depends on which solutions the optimizer implicitly prefers.

    7再看数学The math

    提示:把鼠标悬停在公式中带底色的符号上,图中对应的元素会被高亮(损失与影响函数曲线、交叉熵与平方误差曲线、最优 logit、训练与验证曲线、偏差/方差/噪声曲线、范数球、最小范数曲线与插值阈值、测试分布)。Tip: hover the highlighted symbols in the formulas; matching elements in the figures light up (loss and influence curves, cross-entropy and squared-error curves, the best logit, training and validation curves, bias/variance/noise curves, the norm balls, the minimum-norm curve and the interpolation threshold, the test distribution).

    风险、经验风险与泛化差距Risk, empirical risk and the generalization gap

    模型 \(f_{\boldsymbol\theta}\),逐样本损失 \(\ell(\hat y,y)\),数据来自分布 \(p(x,y)\)。我们想要小的风险(期望损失),手里却只有 \(n\) 个样本上的经验风险:

    A model \(f_{\boldsymbol\theta}\), a per-example loss \(\ell(\hat y,y)\), data from a distribution \(p(x,y)\). We want a small risk (expected loss), but all we have is the empirical risk over \(n\) examples:

    $$ R(\boldsymbol\theta)=\mathbb E_{(x,y)\sim p}\big[\ell(f_{\boldsymbol\theta}(x),y)\big],\qquad \hl{train}{\hat R(\boldsymbol\theta)}=\frac1n\sum_{i=1}^n \ell(f_{\boldsymbol\theta}(x_i),y_i),\qquad \Delta=R(\hat{\boldsymbol\theta})-\hat R(\hat{\boldsymbol\theta}) $$

    对固定的 \(\boldsymbol\theta\),\(\hat R\) 是 \(R\) 的无偏估计;但 \(\hat{\boldsymbol\theta}\) 是用同一批数据挑出来的,挑选过程偏向那些恰好在这批数据上表现好的参数,所以 \(\hat R(\hat{\boldsymbol\theta})\) 系统性地偏低,泛化差距 \(\Delta\) 为正。验证集上的损失 \(\hl{val}{\hat R_{\mathrm{val}}}\) 用的是没参与挑选的数据,因此是 \(R\) 的公正估计;可一旦你用它来挑选(早停、调 λ),它也会开始偏低,只是偏得少得多,这就是还要留一个测试集的原因。

    For a fixed \(\boldsymbol\theta\), \(\hat R\) is an unbiased estimate of \(R\); but \(\hat{\boldsymbol\theta}\) was chosen using the same data, and the choice favours parameters that happen to do well on this particular sample, so \(\hat R(\hat{\boldsymbol\theta})\) is biased low and the generalization gap \(\Delta\) is positive. The validation loss \(\hl{val}{\hat R_{\mathrm{val}}}\) uses data that took no part in the choice, so it is an unbiased estimate of \(R\); once you use it to choose (early stopping, tuning λ) it starts to be biased low too, only much less, which is why a test set is kept as well.

    损失 = 负对数似然Losses as negative log-likelihoods

    损失 \(\rho(r)\),\(r=\hat y-y\)Loss \(\rho(r)\), \(r=\hat y-y\)影响 \(\psi=\rho'\)Influence \(\psi=\rho'\)噪声模型 \(p(r)\propto e^{-\rho(r)}\)Noise model \(p(r)\propto e^{-\rho(r)}\)估计的是Estimates
    平方 \(\tfrac12 r^2\)(MSE)squared \(\tfrac12 r^2\) (MSE)\(r\)高斯Gaussian条件均值conditional mean
    L1 \(|r|\)\(\operatorname{sign} r\)拉普拉斯Laplace条件中位数conditional median
    Huber \(\rho_\delta\)\(\operatorname{clip}(r,-\delta,\delta)\)中间高斯、尾部拉普拉斯Gaussian centre, Laplace tails介于两者之间in between
    $$ \rho_\delta(r)=\begin{cases}\tfrac12 r^2, & |r|\le\delta\\ \delta\big(|r|-\tfrac12\delta\big), & |r|>\delta\end{cases}\qquad\quad \min_{\boldsymbol\theta}\sum_i\hl{rho}{\rho}(r_i)\ \Rightarrow\ \sum_i \hl{psi}{\psi}(r_i)\,\frac{\partial r_i}{\partial\boldsymbol\theta}=0 $$

    右边的最优条件说明了“拉力”的含义:每个点按 \(\psi(r_i)\) 对参数施力,所有力平衡时就是解。写成 \(\psi(r_i)=w_i r_i\),\(w_i=\psi(r_i)/r_i\),就是带权最小二乘的条件,交替更新权重和解就是 FIG 1 用的 IRLS(6.9 节)。平方损失前面的 \(\tfrac12\) 和 MSE 的 \(\tfrac1n\) 只改变尺度,不改变最小值点。

    The optimality condition on the right is what "pull" means: each point acts on the parameters with force \(\psi(r_i)\), and the solution is where all forces balance. Writing \(\psi(r_i)=w_i r_i\) with \(w_i=\psi(r_i)/r_i\) turns it into the condition of weighted least squares, and alternating between the weights and the solution is the IRLS used in FIG 1 (Lesson 6.9). The \(\tfrac12\) in front of the squared loss and the \(\tfrac1n\) of the MSE change the scale only, not the minimizer.

    分类。\(K\) 类,logit \(\mathbf z\),概率 \(\mathbf p=\operatorname{softmax}(\mathbf z)\),目标分布 \(\mathbf y\)(one-hot 或平滑后的)。交叉熵与它的梯度(4.11 节的交叉熵,16.1 节的 softmax):

    Classification. \(K\) classes, logits \(\mathbf z\), probabilities \(\mathbf p=\operatorname{softmax}(\mathbf z)\), a target distribution \(\mathbf y\) (one-hot or smoothed). The cross-entropy and its gradient (cross-entropy from Lesson 4.11, softmax from Lesson 16.1):

    $$ \hl{ce}{L_{\mathrm{CE}}}=-\sum_k y_k\log p_k,\qquad \frac{\partial L_{\mathrm{CE}}}{\partial\mathbf z}=\mathbf p-\mathbf y $$ $$ \hl{sqp}{L_{\mathrm{sq}}}=(\sigma(z)-y)^2,\qquad \frac{\partial L_{\mathrm{sq}}}{\partial z}=2(\sigma(z)-y)\,\sigma(z)\big(1-\sigma(z)\big) $$

    交叉熵的梯度就是“预测减目标”,在完全错误时大小接近 1;平方误差多出的 \(\sigma(1-\sigma)\) 在饱和区趋于 0,这就是 FIG 2 里 85 步对 6 步的来源。标签平滑:\(\mathbf y_\varepsilon=(1-\varepsilon)\mathbf e_c+\varepsilon\mathbf 1/K\)。梯度 \(\mathbf p-\mathbf y_\varepsilon=0\) 在 \(\mathbf p=\mathbf y_\varepsilon\) 处成立,即正确类与其他类的 logit 之差为

    The cross-entropy gradient is just "prediction minus target", with magnitude close to 1 when the prediction is completely wrong; the extra \(\sigma(1-\sigma)\) of the squared error goes to 0 when saturated, which is where FIG 2's 85 steps versus 6 come from. Label smoothing: \(\mathbf y_\varepsilon=(1-\varepsilon)\mathbf e_c+\varepsilon\mathbf 1/K\). The gradient \(\mathbf p-\mathbf y_\varepsilon\) vanishes at \(\mathbf p=\mathbf y_\varepsilon\), i.e. when the logit of the correct class exceeds the others by

    $$ \hl{zstar}{z_c-z_{k\ne c}}=\log\frac{1-\varepsilon+\varepsilon/K}{\varepsilon/K} $$ $$ K=2:\quad z^\ast=\log\tfrac{1-\varepsilon/2}{\varepsilon/2},\qquad \varepsilon=0.1\ \Rightarrow\ z^\ast=\log 19\approx2.944 $$

    偏差–方差分解的推导Deriving the bias–variance decomposition

    固定一个输入 \(x\)。\(y=f(x)+\epsilon\),噪声 \(\mathbb E\epsilon=0\)、\(\operatorname{Var}\epsilon=\sigma^2\),且与训练集无关;\(\hat f\) 依赖于随机的训练集,记 \(\bar f=\mathbb E[\hat f(x)]\)。把 \(y-\hat f\) 拆成三段 \(\epsilon+(f-\bar f)+(\bar f-\hat f)\) 再平方取期望,三个交叉项都为零(\(\epsilon\) 均值为零且与 \(\hat f\) 独立;\(f-\bar f\) 是常数而 \(\mathbb E[\bar f-\hat f]=0\)),于是剩下

    Fix an input \(x\). \(y=f(x)+\epsilon\) with noise \(\mathbb E\epsilon=0\), \(\operatorname{Var}\epsilon=\sigma^2\), independent of the training set; \(\hat f\) depends on the random training set; write \(\bar f=\mathbb E[\hat f(x)]\). Split \(y-\hat f\) into the three pieces \(\epsilon+(f-\bar f)+(\bar f-\hat f)\), square and take expectations; all three cross terms vanish (\(\epsilon\) has mean zero and is independent of \(\hat f\); \(f-\bar f\) is a constant and \(\mathbb E[\bar f-\hat f]=0\)), leaving

    $$ \mathbb E\big[(y-\hat f)^2\big]=\hl{noise}{\sigma^2}+\hl{bias}{(f-\bar f)^2}+\hl{var}{\mathbb E\big[(\hat f-\bar f)^2\big]} $$

    FIG 4 把它在 81 个均匀分布的 \(x\) 上平均,期望用 40 个训练集的平均近似。分解只对平方损失这么干净;对 0-1 损失或交叉熵有类似但不可加的版本。\(k\) 折交叉验证把索引分成 \(k\) 组 \(I_1,\dots,I_k\),\(\hat f^{(-j)}\) 是不用第 \(j\) 组训练出的模型:

    FIG 4 averages this over 81 evenly spaced \(x\), approximating the expectation by the average over 40 training sets. The decomposition is this clean only for the squared loss; for the 0-1 loss or cross-entropy there are similar but non-additive versions. \(k\)-fold cross-validation splits the indices into \(k\) groups \(I_1,\dots,I_k\); \(\hat f^{(-j)}\) is the model trained without group \(j\):

    $$ \mathrm{CV}_k=\frac1n\sum_{j=1}^k\sum_{i\in I_j}\ell\big(\hat f^{(-j)}(x_i),\,y_i\big) $$

    L2 与 L1 的解The L2 and L1 solutions

    对线性最小二乘 \(\frac1{2n}\|X\mathbf w-\mathbf y\|^2\),记 \(A=X^\top X/n\)、\(\hat{\mathbf w}\) 为无正则化的解,则损失等于 \(\tfrac12(\mathbf w-\hat{\mathbf w})^\top A(\mathbf w-\hat{\mathbf w})\) 加常数(FIG 5 用的就是这个形式)。加上 \(\tfrac\lambda2\|\mathbf w\|_2^2\),令梯度为零:

    For linear least squares \(\frac1{2n}\|X\mathbf w-\mathbf y\|^2\), with \(A=X^\top X/n\) and \(\hat{\mathbf w}\) the unregularized solution, the loss equals \(\tfrac12(\mathbf w-\hat{\mathbf w})^\top A(\mathbf w-\hat{\mathbf w})\) plus a constant (the form FIG 5 uses). Add \(\tfrac\lambda2\|\mathbf w\|_2^2\) and set the gradient to zero:

    $$ \mathbf w_{\mathrm{L2}}=(A+\lambda I)^{-1}A\,\hat{\mathbf w}=\sum_i \frac{d_i}{d_i+\lambda}\,(\mathbf u_i^\top\hat{\mathbf w})\,\mathbf u_i\qquad(A=\textstyle\sum_i d_i\mathbf u_i\mathbf u_i^\top) $$

    L2 把每个特征方向按 \(d_i/(d_i+\lambda)\) 收缩:数据约束强的方向(大 \(d_i\))几乎不动,数据几乎不约束的方向(小 \(d_i\),方差的主要来源)被压向零,但永远不会恰好为零。L1 不可导,用次梯度:在 \(A\) 为对角阵(特征正交)时问题按坐标分开,每个坐标的最优条件 \(d_i(w_i-\hat w_i)+\lambda\,\partial|w_i|\ni0\) 给出软阈值

    L2 shrinks each feature direction by \(d_i/(d_i+\lambda)\): directions the data constrain strongly (large \(d_i\)) barely move, directions the data hardly constrain (small \(d_i\), the main source of variance) are pushed towards zero, but never exactly to zero. L1 is not differentiable, so use subgradients: when \(A\) is diagonal (orthogonal features) the problem separates by coordinate, and the optimality condition \(d_i(w_i-\hat w_i)+\lambda\,\partial|w_i|\ni0\) of each coordinate gives the soft threshold

    $$ w_i=\operatorname{sign}(\hat w_i)\,\max\!\Big(0,\ |\hat w_i|-\frac{\lambda}{d_i}\Big) $$

    只要 \(|\hat w_i|\le\lambda/d_i\),解就精确为零:这就是稀疏性的代数来源,对应几何上的菱形尖角。特征相关时没有闭式解,FIG 5 用坐标下降:反复对每个坐标做上面这个软阈值,其他坐标暂时固定。lasso 的已知弱点也在这里:一组高度相关的有用特征,它往往只留一个、随意丢掉其余的。

    Whenever \(|\hat w_i|\le\lambda/d_i\), the solution is exactly zero: this is the algebraic source of sparsity, matching the corners of the diamond. With correlated features there is no closed form, and FIG 5 uses coordinate descent: apply this soft threshold to each coordinate in turn with the others held fixed, and repeat. The lasso's known weakness shows here too: from a group of highly correlated useful features it tends to keep one and drop the rest more or less arbitrarily.

    早停、权重衰减与优化器Early stopping, weight decay and the optimizer

    对上面的二次损失从 \(\mathbf w=0\) 出发做梯度下降(学习率 \(\eta\)),沿第 \(i\) 个特征方向第 \(t\) 步的分量是 \(\big(1-(1-\eta d_i)^t\big)\,\hat w_i\)。与 L2 的 \(d_i/(d_i+\lambda)\) 比较:两者都让大 \(d_i\) 方向先学到、小 \(d_i\) 方向被抑制;当 \(\eta d_i\ll1\) 时,\(t\) 步的早停大致相当于 \(\lambda\approx1/(\eta t)\)(Goodfellow 等《深度学习》7.8 节)。所以 FIG 3 里验证损失先降后升,是因为网络先学到了数据支持强的平滑部分,后学到的是被噪声主导的方向。

    权重衰减 ≠ L2(对 Adam)。L2 惩罚把 \(2\lambda\boldsymbol\theta\) 加进梯度;SGD 的一步 \(\boldsymbol\theta\leftarrow\boldsymbol\theta-\eta(\mathbf g+2\lambda\boldsymbol\theta)=(1-2\eta\lambda)\boldsymbol\theta-\eta\mathbf g\) 正好就是“先衰减再走一步”。Adam 却会把整个梯度除以它的二阶矩估计(6.3、6.4 节),于是 \(2\lambda\boldsymbol\theta\) 这一项也被逐坐标缩放,梯度大的参数几乎不被衰减。AdamW(Loshchilov & Hutter, 2019)把衰减从梯度里拿出来单独做:\(\boldsymbol\theta\leftarrow\boldsymbol\theta-\eta\,(\mathbf u_t+\lambda\boldsymbol\theta)\),其中 \(\mathbf u_t\) 是 Adam 本来要走的那一步(只由数据损失的梯度算出)。FIG 3 用的是写进损失的 L2 惩罚(加在梯度里,再交给 Adam),这在我们这里也足够有效。

    Dropout:训练时隐藏单元输出 \(h_j\) 换成 \(m_j h_j/(1-p)\),\(m_j\sim\mathrm{Bernoulli}(1-p)\),于是 \(\mathbb E[m_jh_j/(1-p)]=h_j\),测试时直接用 \(h_j\),期望不变(“inverted dropout”)。

    Run gradient descent with learning rate \(\eta\) on the quadratic above, starting from \(\mathbf w=0\); after \(t\) steps the component along feature direction \(i\) is \(\big(1-(1-\eta d_i)^t\big)\,\hat w_i\). Compare with L2's \(d_i/(d_i+\lambda)\): both let large-\(d_i\) directions be learned first and hold back small-\(d_i\) ones; for \(\eta d_i\ll1\), stopping after \(t\) steps is roughly \(\lambda\approx1/(\eta t)\) (Goodfellow et al., Deep Learning, Section 7.8). That is why FIG 3's validation loss falls and then rises: the network learns the smooth part strongly supported by the data first and the noise-dominated directions later.

    Weight decay ≠ L2 (for Adam). An L2 penalty adds \(2\lambda\boldsymbol\theta\) to the gradient; an SGD step \(\boldsymbol\theta\leftarrow\boldsymbol\theta-\eta(\mathbf g+2\lambda\boldsymbol\theta)=(1-2\eta\lambda)\boldsymbol\theta-\eta\mathbf g\) is exactly "decay, then step". Adam, however, divides the whole gradient by its second-moment estimate (Lessons 6.3 and 6.4), so the \(2\lambda\boldsymbol\theta\) term is rescaled per coordinate as well, and parameters with large gradients are barely decayed. AdamW (Loshchilov & Hutter, 2019) takes the decay out of the gradient and applies it separately: \(\boldsymbol\theta\leftarrow\boldsymbol\theta-\eta\,(\mathbf u_t+\lambda\boldsymbol\theta)\), where \(\mathbf u_t\) is the step Adam would take (computed from the gradient of the data loss only). FIG 3 uses an L2 penalty written into the loss (added to the gradient, then handed to Adam), which is effective enough here.

    Dropout: during training a hidden output \(h_j\) is replaced by \(m_j h_j/(1-p)\) with \(m_j\sim\mathrm{Bernoulli}(1-p)\), so \(\mathbb E[m_jh_j/(1-p)]=h_j\) and at test time \(h_j\) is used as is, with the same expectation ("inverted dropout").

    最小范数解与双下降The minimum-norm solution and double descent

    \(\Phi\in\R^{n\times p}\) 的奇异值分解 \(\Phi=\sum_i s_i\mathbf u_i\mathbf v_i^\top\)。\(p\ge n\) 且满秩时,所有插值解中范数最小的是 \(\mathbf w=\Phi^+\mathbf y=\sum_i \frac{\mathbf u_i^\top\mathbf y}{s_i}\mathbf v_i\)(1.13 节)。观测噪声 \(\boldsymbol\epsilon\) 通过 \(1/s_i\) 被放大,噪声在权重上造成的方差是 \(\sigma^2\sum_i 1/s_i^2\);\(p\) 刚好等于 \(n\) 附近时最小的 \(s_i\) 最接近零,所以出现尖峰。加岭正则把 \(1/s_i\) 换成 \(s_i/(s_i^2+n\lambda)\),上限是 \(1/(2\sqrt{n\lambda})\),尖峰随之消失。

    Take the SVD \(\Phi=\sum_i s_i\mathbf u_i\mathbf v_i^\top\) of \(\Phi\in\R^{n\times p}\). For \(p\ge n\) and full rank, the minimum-norm interpolating solution is \(\mathbf w=\Phi^+\mathbf y=\sum_i \frac{\mathbf u_i^\top\mathbf y}{s_i}\mathbf v_i\) (Lesson 1.13). Observation noise \(\boldsymbol\epsilon\) is amplified by \(1/s_i\), and the variance it causes in the weights is \(\sigma^2\sum_i 1/s_i^2\); near \(p=n\) the smallest \(s_i\) is closest to zero, hence the spike. A ridge replaces \(1/s_i\) by \(s_i/(s_i^2+n\lambda)\), which is at most \(1/(2\sqrt{n\lambda})\), and the spike disappears.

    分布偏移Distribution shift

    上面所有的保证都假设训练数据和测试数据来自同一个分布。协变量偏移是最常见的破坏方式(下标 tr 表示训练,te 表示测试):\(p(y\mid x)\) 不变(物理规律没变),但输入的分布从 \(p_{\mathrm{tr}}(x)\) 变成了 \(\hl{shift}{p_{\mathrm{te}}(x)}\)(机器人去了没去过的状态)。测试风险可以改写成训练分布上的加权期望:

    Every guarantee above assumes that training and test data come from the same distribution. Covariate shift is the most common way this breaks (subscripts tr for training, te for test): \(p(y\mid x)\) stays the same (the physics has not changed), but the input distribution moves from \(p_{\mathrm{tr}}(x)\) to \(\hl{shift}{p_{\mathrm{te}}(x)}\) (the robot goes to states it has not visited). The test risk can be rewritten as a weighted expectation over the training distribution:

    $$ R_{\mathrm{te}}=\mathbb E_{x\sim p_{\mathrm{te}}}\big[\ell\big]=\mathbb E_{x\sim p_{\mathrm{tr}}}\Big[\frac{\hl{shift}{p_{\mathrm{te}}(x)}}{p_{\mathrm{tr}}(x)}\,\ell\Big] $$

    这就是重要性加权(Shimodaira, 2000),前提是 \(p_{\mathrm{tr}}(x)>0\) 处处覆盖 \(p_{\mathrm{te}}\)。如果测试分布落在训练分布完全没有覆盖的地方,权重是无穷大,任何重新加权都救不了:模型在那里的预测只取决于它的结构偏好(外推),数据不提供任何约束。下一节就是这种情形。

    This is importance weighting (Shimodaira, 2000), and it requires \(p_{\mathrm{tr}}(x)>0\) wherever \(p_{\mathrm{te}}\) has mass. If the test distribution lands where the training distribution has no coverage at all, the weight is infinite and no reweighting can help: the model's predictions there depend only on its structural preferences (extrapolation), with no constraint from data. The next section is exactly that case.

    8机器人中的它:分布偏移是头号泛化问题In robotics: distribution shift is the number-one generalization problem

    一台机械臂要学一个关节的重力补偿力矩 \(\tau_g(q)=2\sin q\)(N·m)。采数据时为了安全,只在 \(|q|\le0.8\) rad 的小范围里动,得到 40 个带噪声(0.05 N·m)的点;在这个范围里 \(\sin q\) 几乎是一条直线。训练 5 个初值不同的网络(深度集成,各训练 800 步),然后让机器人去 \(q\approx2\) rad 的位置工作。拖动下方红色的测试分布,看误差和集成的分歧怎样变化。

    A robot arm is to learn the gravity-compensation torque of one joint, \(\tau_g(q)=2\sin q\) (N·m). For safety, data were collected only in the small range \(|q|\le0.8\) rad, giving 40 noisy (0.05 N·m) points; over this range \(\sin q\) is almost a straight line. Train 5 networks from different initializations (a deep ensemble, 800 steps each), then send the robot to work near \(q\approx2\) rad. Drag the red test distribution below and watch how the error and the disagreement of the ensemble change.

    FIG 7分布偏移:训练范围之外,误差暴涨,集成的分歧只涨了一点Distribution shift: outside the training range the error explodes, and the ensemble's disagreement grows only a little
    左:蓝色竖带是训练数据的范围,蓝点是训练数据,绿点是之后新采的数据;青色虚线是真实的 \(2\sin q\),紫色细线是 5 个网络各自的预测,琥珀色是它们的平均;红色竖带是测试分布 \(\mathcal N(\mu,0.2^2)\) 的 ±2σ 范围,拖底部的红圈或用滑块移动 μ。右(训练完成后):测试分布中心 μ 处的 均方误差和集成方差(5 个预测的方差,与均方误差同单位),两者都对数显示;红色竖虚线是当前 μ。网络为 [1, 32, 32, 1] tanh,Adam,学习率 0.01,全批量;只有画面在屏幕上时才训练。 Left: the blue band is the range of the training data, blue dots the training data, green dots data collected later; the dashed cyan curve is the true \(2\sin q\), the thin purple lines the predictions of the 5 networks, amber their mean; the red band is the ±2σ range of the test distribution \(\mathcal N(\mu,0.2^2)\); drag the red ring at the bottom or use the slider to move μ. Right (once training finishes): the mean squared error and the ensemble variance (the variance of the 5 predictions, in the same units as the squared error) as functions of the test centre μ, both on a log scale; the red vertical dashed line is the current μ. Networks are [1, 32, 32, 1] tanh, Adam, learning rate 0.01, full batch; training runs only while the figure is on screen.
    • 训练完成后,把测试分布移到 \(|\mu|\ge1.5\) rad:均方误差变成训练分布内(μ = 0)的 100 倍以上(μ = 2 时约 4000 倍)。看一眼读数:集成标准差只涨到约 0.05 N·m,而实际误差的均方根约 0.7 N·m。Once training is done, move the test distribution to \(|\mu|\ge1.5\) rad: the mean squared error becomes more than 100 times the in-distribution value at μ = 0 (about 4000 times at μ = 2). Check the readout: the ensemble std has only risen to about 0.05 N·m while the actual RMS error is about 0.7 N·m.
    • 在 \(|\mu|\ge2\) 处按“在测试分布处采 10 个新点并继续训练”,等训练结束(μ 不要移动超过 0.3):那里的均方误差降到采集前的 1/20 以下。At \(|\mu|\ge2\) press "Collect 10 points at the test distribution and retrain" and wait for training to finish (do not move μ by more than 0.3): the mean squared error there drops below 1/20 of its value before collecting.

    三点观察。(1) 在训练范围里,5 个网络的误差都很小(μ = 0 时均方误差约 \(10^{-4}\)),在范围之外它们各自“合理地”外推,可数据完全不约束这种外推,μ = 2 时均方误差约 0.5,μ = 3 时约 6。(2) 集成的分歧确实随偏移增大(标准差从不到 0.001 增到 μ = 2 时约 0.05),可以当作“我到了没见过的地方”的报警信号(21.3 节),但它严重低估了真实误差:5 个网络犯了相似的错误。(3) 唯一真正有效的办法是到那里去采数据。机器人领域有一整套方法都是这个思路:DAgger 让策略自己跑、在它到达的状态上请专家标注(22.1 节);域随机化在仿真里把训练分布撑得足够宽,让真实世界落在里面(23.2 节)。

    Three observations. (1) Inside the training range all 5 networks are accurate (mean squared error about \(10^{-4}\) at μ = 0); outside it each extrapolates "plausibly", but nothing in the data constrains that extrapolation: the mean squared error is about 0.5 at μ = 2 and about 6 at μ = 3. (2) The ensemble's disagreement does grow with the shift (its std goes from under 0.001 to about 0.05 at μ = 2) and can serve as an "I am somewhere new" alarm (Lesson 21.3), but it badly underestimates the actual error: the 5 networks make similar mistakes. (3) The only remedy that really works is to go there and collect data. A whole family of robotics methods follows that idea: DAgger runs the policy and asks an expert to label the states it reaches (Lesson 22.1); domain randomization widens the training distribution in simulation until the real world falls inside it (Lesson 23.2).

    真实系统里In real systems

    鲁棒损失:DQN(Mnih 等,Nature 2015)把 TD 误差截断在 [−1, 1],等价于 Huber 损失;Fast R-CNN(Girshick, 2015)用 smooth L1 回归检测框;ACT(Zhao 等,RSS 2023,22.2 节)用 L1 而不是 L2 作为动作的重建损失。 模仿学习里的 MSE:示教在同一个状态下可能有两种做法(从左绕或从右绕),MSE 学到的是它们的平均,可能直接撞上障碍;这就是 ACT、Diffusion Policy 等生成式策略存在的原因(22.1、22.2 节)。 数据增广:从像素学习的强化学习中,随机平移/裁剪一类的增广带来了很大提升(RAD:Laskin 等,2020;DrQ:Kostrikov 等,2020),视觉运动策略普遍使用随机裁剪和颜色抖动。 验证损失与真实成功率:robomimic(Mandlekar 等,CoRL 2021)的研究发现,按最低验证损失挑选的策略检查点并不可靠,需要在环境里实际评估;原因之一正是闭环执行时的分布偏移。 集成与不确定性:PETS(Chua 等,2018)用概率网络的集成学习动力学模型(24.2 节);深度集成(Lakshminarayanan 等,2017)是估计不确定性的常用基线(21.3 节)。 按轨迹划分数据:同一条示教轨迹里相邻的帧几乎一样,随机按帧划分训练/验证会让验证集“偷看”到训练数据,应按轨迹、场景或物体划分。

    Robust losses: DQN (Mnih et al., Nature 2015) clips the TD error to [−1, 1], which is equivalent to a Huber loss; Fast R-CNN (Girshick, 2015) regresses boxes with a smooth L1 loss; ACT (Zhao et al., RSS 2023, Lesson 22.2) uses L1 rather than L2 as its action reconstruction loss. MSE in imitation learning: demonstrations may contain two ways to act in the same state (pass left or pass right); MSE learns their average, which may drive straight into the obstacle; this is why generative policies such as ACT and Diffusion Policy exist (Lessons 22.1 and 22.2). Data augmentation: in reinforcement learning from pixels, random shift/crop augmentations brought large gains (RAD: Laskin et al., 2020; DrQ: Kostrikov et al., 2020), and visuomotor policies commonly use random crops and colour jitter. Validation loss versus real success: the robomimic study (Mandlekar et al., CoRL 2021) found that picking policy checkpoints by lowest validation loss is unreliable and that policies must be evaluated in the environment; closed-loop distribution shift is one reason. Ensembles and uncertainty: PETS (Chua et al., 2018) learns dynamics models with an ensemble of probabilistic networks (Lesson 24.2); deep ensembles (Lakshminarayanan et al., 2017) are a standard baseline for uncertainty (Lesson 21.3). Split by trajectory: neighbouring frames of one demonstration are nearly identical, so splitting train/validation randomly by frame lets the validation set "peek" at the training data; split by trajectory, scene or object instead.

    9常见误区Common pitfalls

    误区 1:在测试集上调参,或数据泄漏Pitfall 1: tuning on the test set, or leaking data

    每用测试集做一次选择(挑模型、挑 λ、挑训练轮数),它就多一分乐观。调参只用验证集或交叉验证,测试集最后只看一次。机器人数据里泄漏更隐蔽:同一条轨迹的相邻帧、同一个物体的不同角度、同一个场景的不同时刻高度相关,随机按样本划分会让验证误差和训练误差一样漂亮,部署时却完全不是那么回事。按轨迹、物体或场景划分。

    Every choice made on the test set (which model, which λ, how many epochs) makes it a little more optimistic. Tune on the validation set or by cross-validation, and look at the test set once, at the end. In robot data leakage is subtler: neighbouring frames of one trajectory, different views of one object and different moments in one scene are highly correlated, so a random per-sample split gives a validation error as pretty as the training error, and deployment looks nothing like it. Split by trajectory, object or scene.

    误区 2:把低验证损失当成好机器人Pitfall 2: taking a low validation loss for a good robot

    验证集仍然来自训练时的分布(比如人类示教的状态)。机器人闭环执行时,自己的小错误会把它带到示教里没有的状态(FIG 7、22.1 节),开环的逐样本损失看不到这一点。验证损失是必要的诊断,但策略要在真实或仿真环境里评估成功率,最好多次、多个随机种子。

    The validation set still comes from the training distribution (for instance the states visited by human demonstrations). Running closed loop, a robot's own small errors take it to states the demonstrations never visited (FIG 7, Lesson 22.1), and an open-loop per-sample loss cannot see that. The validation loss is a necessary diagnostic, but policies must be evaluated by their success rate in a real or simulated environment, ideally many times and over several random seeds.

    误区 3:不想就用 MSEPitfall 3: reaching for MSE without thinking

    MSE 假设高斯噪声、单峰的目标。传感器有野值时一个坏点就能拉偏整个模型(FIG 1);分类时它在饱和区没有梯度(FIG 2);目标有多个合理答案时它给出平均值,可能哪个都不是(避障时从左绕和从右绕的平均就是撞上去)。L1 给出中位数,同样只有一个答案;多峰的目标需要能表示分布的模型(第 19 章的生成模型、22.2 节)。

    MSE assumes Gaussian noise and a unimodal target. With sensor outliers one bad point can drag the whole model (FIG 1); for classification it has no gradient when saturated (FIG 2); when the target has several valid answers it returns their average, which may be none of them (the average of passing left and passing right is a collision). L1 returns the median, again a single answer; multimodal targets need models that represent a distribution (the generative models of Chapter 19, Lesson 22.2).

    误区 4:特征没标准化就加 L1/L2Pitfall 4: adding L1/L2 to unstandardized features

    惩罚 \(\lambda\|\mathbf w\|^2\) 对所有系数一视同仁,但系数的大小取决于特征的单位:同一个关节速度用 rad/s 还是 deg/s 表示,系数相差 57 倍,被惩罚的程度也天差地别。加正则前先把每个特征减均值、除标准差;偏置(截距)一般不惩罚(FIG 4 也是这样做的)。在网络里,偏置和归一化层的参数通常也不做权重衰减。

    The penalty \(\lambda\|\mathbf w\|^2\) treats all coefficients alike, but a coefficient's size depends on its feature's units: the same joint velocity in rad/s or in deg/s gives coefficients 57 times apart, penalized completely differently. Standardize every feature (subtract the mean, divide by the standard deviation) before regularizing, and usually leave the bias (intercept) unpenalized (as FIG 4 does). In networks, biases and normalization-layer parameters are usually exempt from weight decay as well.

    误区 5:在 Adam 里当 L2 用权重衰减,或测试时忘了关 dropoutPitfall 5: treating weight decay in Adam as L2, or leaving dropout on at test time

    两个实现层面的坑。(a) 在 Adam 里把 L2 惩罚加进梯度,效果和 SGD 里不同(第 7 节),想要权重衰减就用 AdamW,而且换优化器时 λ 要重新调。(b) dropout、数据增广和 BatchNorm 训练时与测试时行为不同;部署前忘了切到评估模式(PyTorch 的 model.eval()),预测会带随机噪声,机器人动作会抖。

    Two implementation traps. (a) Adding an L2 penalty to the gradient in Adam does not behave as it does in SGD (Section 7); if you want weight decay use AdamW, and retune λ whenever you change optimizer. (b) Dropout, data augmentation and BatchNorm behave differently in training and at test time; forget to switch to evaluation mode before deployment (PyTorch's model.eval()) and predictions carry random noise and the robot's actions jitter.

    10小练习Check yourself

    1. 你在拟合力传感器的标定曲线,大部分读数噪声很小,但偶尔有接触冲击造成的巨大尖峰。哪个损失最合适?1. You are fitting a force sensor's calibration curve; most readings have small noise, but now and then a contact impact causes a huge spike. Which loss fits best?
    噪声是“大部分高斯 + 少数野值”。Huber 在 \(|r|\le\delta\) 时就是平方损失(对正常数据保持高效),之外线性增长,野值的拉力被截在 δ(FIG 1)。选项 A 的平方损失让野值的拉力与残差成正比;选项 D 更糟,拉力随 \(r^3\) 增长;选项 B 的交叉熵用于类别标签,不适用于连续读数。The noise is "mostly Gaussian plus a few outliers". Huber is the squared loss for \(|r|\le\delta\) (staying efficient on normal data) and linear beyond, so an outlier's pull is capped at δ (FIG 1). The squared loss of option A lets an outlier pull in proportion to its residual; option D is worse, with a pull growing like \(r^3\); the cross-entropy of option B is for class labels, not continuous readings.
    2. 一个抓取成功预测器:训练准确率 99.8%,验证准确率 71%。最可能的诊断和最合理的第一步是?2. A grasp-success predictor: 99.8% training accuracy, 71% validation accuracy. What is the most likely diagnosis and the most sensible first step?
    训练集上几乎完美、验证集上差得多,是典型的高方差:模型记住了训练集(FIG 3)。选项 A 和 C 都会让它记得更牢。选项 D 不能排除,但 29 个百分点的差距一般不是验证集的随机波动能解释的,而且若怀疑,应先检查验证集是否和训练集按轨迹、物体分开了,而不是忽略。Nearly perfect on training and much worse on validation is classic high variance: the model has memorized its training set (FIG 3). Options A and C would make it memorize harder. Option D cannot be ruled out, but a 29-point gap is rarely explained by validation-set noise, and if in doubt the first check is whether validation is split from training by trajectory or object, not to ignore it.
    3. 二分类,真实标签 1,模型的 logit 是 −8。用“sigmoid + 平方误差”训练时梯度几乎为零,用交叉熵时不会。原因是?3. Binary classification, true label 1, the model's logit is −8. Trained with "sigmoid + squared error" the gradient is almost zero; with cross-entropy it is not. Why?
    \(\sigma(-8)\approx3.4\times10^{-4}\),所以 \(\sigma(1-\sigma)\approx3.4\times10^{-4}\),平方误差的梯度 \(2(\sigma-1)\sigma(1-\sigma)\approx-6.7\times10^{-4}\)。交叉熵 \(-\log\sigma(z)\) 的对数恰好消掉了 sigmoid 的饱和,梯度接近 −1(用 FIG 2 的同一更新计算:从 −8 出发,交叉熵 9 步越过 0.5,平方误差要约 1500 步,远超图中显示的 400 步)。选项 C 反了:交叉熵在 \(z\to+\infty\) 才最小。\(\sigma(-8)\approx3.4\times10^{-4}\), so \(\sigma(1-\sigma)\approx3.4\times10^{-4}\) and the squared-error gradient \(2(\sigma-1)\sigma(1-\sigma)\approx-6.7\times10^{-4}\). The logarithm in the cross-entropy \(-\log\sigma(z)\) cancels the sigmoid's saturation exactly, so its gradient is close to −1 (with FIG 2's update: from −8 cross-entropy crosses 0.5 in 9 steps, squared error needs about 1500, far beyond the 400 steps the figure shows). Option C is backwards: cross-entropy is minimized only as \(z\to+\infty\).
    4. 你想从 50 个候选的传感器特征里自动挑出少数几个真正有用的。应该用哪种正则化,为什么?4. You want to pick, automatically, the few really useful features among 50 candidate sensor features. Which regularizer, and why?
    L1 的解是 \(\operatorname{sign}(\hat w_i)\max(0,|\hat w_i|-\lambda/d_i)\),有一段 \(\hat w_i\) 被精确映射到 0;几何上是菱形的尖角(FIG 5,λ 在 0.14 到 0.40 之间时 8 个特征里恰好留下真正的 3 个)。L2 按 \(d_i/(d_i+\lambda)\) 收缩,永远不会恰好为零(选项 B 错)。dropout 和早停都不产生精确的零。The L1 solution is \(\operatorname{sign}(\hat w_i)\max(0,|\hat w_i|-\lambda/d_i)\), which maps a whole interval of \(\hat w_i\) exactly to 0; geometrically, the corners of the diamond (FIG 5: for λ between 0.14 and 0.40 exactly the 3 true features of 8 survive). L2 shrinks by \(d_i/(d_i+\lambda)\) and never reaches exactly zero (option B is wrong). Neither dropout nor early stopping produces exact zeros.
    5. 你用 50 条示教轨迹训练行为克隆策略,把所有帧打乱后随机分出 10% 做验证集。验证损失几乎和训练损失一样低,可真机上成功率只有 30%。最主要的两个原因是?5. You train a behaviour-cloning policy on 50 demonstration trajectories, shuffling all frames and holding out a random 10% for validation. The validation loss is nearly as low as the training loss, yet on the real robot the success rate is only 30%. What are the two main reasons?
    同一条轨迹里相邻帧几乎一样,验证帧的“邻居”就在训练集里,所以验证损失说明不了对新轨迹的泛化(误区 1,应按轨迹划分)。即使划分正确,逐帧损失也是开环的:机器人自己的小误差会把它带离示教分布,在那里策略没有数据约束(FIG 7、误区 2),22.1 节会讲这如何累积。Neighbouring frames of a trajectory are nearly identical, so each validation frame's "neighbours" sit in the training set and the validation loss says little about generalizing to new trajectories (Pitfall 1: split by trajectory). Even with a correct split the per-frame loss is open loop: the robot's own small errors carry it off the demonstration distribution, where nothing constrains the policy (FIG 7, Pitfall 2); Lesson 22.1 shows how this compounds.

    11延伸阅读Further reading

    • T. Hastie, R. Tibshirani & J. Friedman, The Elements of Statistical Learning, 2nd ed., Springer, 2009, Ch. 3 and 7 — 岭回归与 lasso、偏差–方差、交叉验证的标准参考the standard reference for ridge and lasso, bias–variance and cross-validation
    • I. Goodfellow, Y. Bengio & A. Courville, Deep Learning, MIT Press, 2016, Ch. 5 and 7 — 深度学习里的正则化:权重衰减、早停与 L2 的关系、dropout、数据增广regularization in deep learning: weight decay, early stopping and its link to L2, dropout, augmentation
    • C. M. Bishop, Pattern Recognition and Machine Learning, Springer, 2006, Ch. 1 and 3 — 损失与概率模型、偏差–方差分解losses as probabilistic models, the bias–variance decomposition
    • P. J. Huber, Robust Estimation of a Location Parameter, Annals of Mathematical Statistics, 1964 — Huber 损失的原始论文the original Huber loss
    • S. Geman, E. Bienenstock & R. Doursat, Neural Networks and the Bias/Variance Dilemma, Neural Computation, 1992 — 把偏差–方差带进神经网络的经典the classic that brought bias–variance to neural networks
    • R. Tibshirani, Regression Shrinkage and Selection via the Lasso, Journal of the Royal Statistical Society B, 1996 — lassothe lasso
    • N. Srivastava, G. Hinton, A. Krizhevsky, I. Sutskever & R. Salakhutdinov, Dropout: A Simple Way to Prevent Neural Networks from Overfitting, JMLR, 2014
    • C. M. Bishop, Training with Noise is Equivalent to Tikhonov Regularization, Neural Computation, 1995 — 输入噪声与平滑正则的联系input noise and smoothness regularization
    • C. Szegedy, V. Vanhoucke, S. Ioffe, J. Shlens & Z. Wojna, Rethinking the Inception Architecture for Computer Vision, CVPR 2016 — 提出标签平滑introduces label smoothing
    • I. Loshchilov & F. Hutter, Decoupled Weight Decay Regularization, ICLR 2019 — AdamW:为什么 Adam 里权重衰减不等于 L2AdamW: why weight decay is not L2 in Adam
    • C. Zhang, S. Bengio, M. Hardt, B. Recht & O. Vinyals, Understanding Deep Learning Requires Rethinking Generalization, ICLR 2017 — 网络能完美拟合随机标签networks can fit random labels perfectly
    • M. Belkin, D. Hsu, S. Ma & S. Mandal, Reconciling Modern Machine-Learning Practice and the Classical Bias–Variance Trade-off, PNAS, 2019; P. Nakkiran et al., Deep Double Descent: Where Bigger Models and More Data Hurt, ICLR 2020 — 双下降double descent
    • H. Shimodaira, Improving Predictive Inference under Covariate Shift by Weighting the Log-Likelihood Function, Journal of Statistical Planning and Inference, 2000 — 协变量偏移与重要性加权covariate shift and importance weighting
    • B. Lakshminarayanan, A. Pritzel & C. Blundell, Simple and Scalable Predictive Uncertainty Estimation using Deep Ensembles, NeurIPS 2017 — FIG 7 用的深度集成the deep ensembles of FIG 7
    • A. Mandlekar et al., What Matters in Learning from Offline Human Demonstrations for Robot Manipulation, CoRL 2021 — robomimic:模仿学习的实际经验,包括检查点选择robomimic: practical lessons for imitation learning, including checkpoint selection