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

回归与分类Regression & Classification

监督学习只有两个基本问题:输出是一个连续的数(回归),还是若干类别之一(分类)。本节说明两者其实是同一个想法,即给数据写一个噪声模型,再做最大似然:高斯噪声给出最小二乘,伯努利与类别噪声给出交叉熵。我们在浏览器里现场训练一个预测抓取成败的逻辑回归、一个分辨地形的 softmax 分类器和一个 k 近邻分类器,最后用测试集、混淆矩阵、精确率与召回率判断它能不能上机器人。 Supervised learning comes in two basic shapes: the output is a continuous number (regression) or one of several classes (classification). This lesson shows that both are one idea: write down a noise model for the data and maximize the likelihood. Gaussian noise gives least squares; Bernoulli and categorical noise give the cross-entropy. You will train, live in the browser, a logistic regression that predicts grasp success, a softmax classifier that tells terrains apart and a k-nearest-neighbour classifier, and then judge with a test set, a confusion matrix, precision and recall whether it is fit to run on a robot.

约 45 分钟~45 min 前置:1.13 最小二乘与伪逆 · 4.6 最大似然与最大后验 · 4.11 信息论入门 · 6.3 梯度下降家族Prereqs: 1.13 Least Squares & the Pseudo-inverse · 4.6 Maximum Likelihood & MAP · 4.11 A First Look at Information Theory · 6.3 The Gradient Descent Family 6 个交互6 interactives

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

    一台机械臂准备抓一个零件。它在动手之前就想知道:这次抓取会不会成功?它能测到的只有几个数,比如夹爪最大张开量比物体宽出多少毫米,夹爪方向和物体主轴偏了多少度。成败与这些数之间的关系没有现成的公式:摩擦、表面、物体重心都会影响结果。但机器人可以把过去几百次尝试记下来,每次记一行“特征 → 成败”,然后从这些数据里学出一个规则。

    这就是监督学习:给定数据 \(\{(\mathbf x_i,y_i)\}_{i=1}^n\),其中 \(\mathbf x_i\) 是输入(特征),\(y_i\) 是我们想预测的目标,找一个函数 \(\hat y=f_{\boldsymbol\theta}(\mathbf x)\) 让它在没见过的输入上也预测得准。目标 \(y\) 是连续数值时叫回归(关节摩擦力矩、电池剩余时间、物体距离);目标是若干类别之一时叫分类(抓取成/败、地面是沥青/碎石/草地、图像里是哪个物体)。Part VI 的模仿学习本质上也是监督学习:输入是观测,目标是专家的动作(22.1 节)。

    本节不需要神经网络。我们用最简单的模型(线性模型、逻辑回归、softmax、k 近邻)把监督学习的骨架讲清楚:模型 + 噪声假设 → 似然 → 损失 → 优化 → 在测试集上评估。后面的每一节(深度网络、扩散策略、强化学习里的价值网络)都只是把这里的“模型”换得更大,骨架不变。

    A robot arm is about to pick up a part. Before it moves it would like to know: will this grasp succeed? All it can measure are a few numbers, for example how many millimetres the gripper's maximum opening exceeds the object's width, and how many degrees the gripper is misaligned with the object's main axis. No ready-made formula links these numbers to the outcome: friction, the surface and the object's centre of mass all play a part. But the robot can log its past few hundred attempts, one row "features → outcome" each, and learn a rule from that data.

    That is supervised learning: given data \(\{(\mathbf x_i,y_i)\}_{i=1}^n\), where \(\mathbf x_i\) is the input (the features) and \(y_i\) the target we want to predict, find a function \(\hat y=f_{\boldsymbol\theta}(\mathbf x)\) that also predicts well on inputs it has not seen. When the target \(y\) is a continuous number it is regression (joint friction torque, remaining battery time, distance to an object); when it is one of several classes it is classification (grasp success/failure, ground is asphalt/gravel/grass, which object is in the image). The imitation learning of Part VI is supervised learning at heart too: the input is an observation and the target is the expert's action (Lesson 22.1).

    This lesson needs no neural networks. With the simplest models (linear models, logistic regression, softmax, k nearest neighbours) we lay out the skeleton of supervised learning: model + noise assumption → likelihood → loss → optimization → evaluation on a test set. Every later lesson (deep networks, diffusion policies, value networks in reinforcement learning) only swaps in a bigger "model"; the skeleton stays the same.

    2直觉:拟合就是在问“这条线让数据有多可能”Intuition: a fit asks "how likely does this line make the data?"

    1.13 节把直线拟合当作几何问题:方程比未知数多,取让残差平方和最小的解。4.6 节从概率角度给了同一个答案的理由:如果测量 = 真值 + 高斯噪声,那么最大似然估计就是最小二乘。现在把两者放在一起,用到“拟合一个函数”上。假设数据来自下面的模型,各点的噪声 \(\varepsilon_i\) 相互独立、同分布:

    Lesson 1.13 treated line fitting as geometry: more equations than unknowns, so take the solution with the smallest sum of squared residuals. Lesson 4.6 gave the probabilistic reason for the same answer: if measurement = truth + Gaussian noise, the maximum-likelihood estimate is least squares. Now put the two together and apply them to fitting a function. Suppose the data come from the model below, with the noise \(\varepsilon_i\) of different points independent and identically distributed:

    $$ y_i = a\,x_i + b + \varepsilon_i,\qquad \varepsilon_i\sim\mathcal N(0,\hl{sig}{\sigma^2})\quad\Longrightarrow\quad p(y_i\mid x_i) = \frac{1}{\sigma\sqrt{2\pi}}\exp\!\Big(-\frac{\hl{res}{(y_i-a x_i-b)}^2}{2\sigma^2}\Big). $$

    每一条候选直线都对应一个“生成数据的故事”:在每个 \(x_i\) 处,\(y\) 应该落在以直线为中心、宽度为 \(\sigma\) 的高斯钟形里。数据的似然是所有钟形在各自数据点处的高度之积;它越大,这条直线把数据解释得越好。取负对数,乘积变成求和,就得到负对数似然(NLL):残差平方和除以 \(2\sigma^2\),再加一个只与 \(\sigma\) 有关的常数。所以无论 \(\sigma\) 取多少,让 NLL 最小的直线就是最小二乘直线。下图里你可以亲手拖直线、拖数据点,看两者怎样一起变。

    Every candidate line comes with a "story of how the data were generated": at each \(x_i\), \(y\) should fall inside a Gaussian bell centred on the line with width \(\sigma\). The likelihood of the data is the product of the heights of the bells at their data points; the larger it is, the better the line explains the data. Taking the negative log turns the product into a sum, the negative log-likelihood (NLL): the sum of squared residuals divided by \(2\sigma^2\), plus a constant that depends only on \(\sigma\). So whatever \(\sigma\) is, the line that minimizes the NLL is the least-squares line. In the figure below you can drag the line and the data points yourself and watch the two move together.

    FIG 1最小二乘 = 高斯噪声下的最大似然Least squares = maximum likelihood under Gaussian noise
    左:9 个蓝色数据点(可拖动),琥珀色直线是当前模型,红线是残差。每个数据点处画了一个青色的侧放钟形:以直线在该处的值为中心、标准差为 \(\sigma\) 的高斯密度,它在数据点高度处的“胖瘦”就是这个点的似然。“手动”模式下拖直线两端的圆圈调整直线;“最小二乘”模式下直线由正规方程直接解出。右:对当前直线,NLL 随 \(\sigma\) 变化的青色曲线,蓝点是滑块上的 \(\sigma\),琥珀色虚线标出残差的均方根(RMS)。数据由 \(y=0.5x+0.8\) 加 \(\sigma=0.7\) 的噪声生成。 Left: 9 blue data points (draggable); the amber line is the current model and the red segments are residuals. At each data point a cyan bell lies on its side: the Gaussian density centred on the line's value there with standard deviation \(\sigma\); how wide it is at the data point's height is that point's likelihood. In "by hand" mode drag the circles at the two ends of the line; in "least squares" mode the line is solved directly from the normal equations. Right: the NLL of the current line as a function of \(\sigma\) (cyan curve); the blue dot is the \(\sigma\) on the slider and the amber dashed line marks the root-mean-square (RMS) residual. The data were generated from \(y=0.5x+0.8\) plus noise with \(\sigma=0.7\).
    试一试Try this
    • 在“手动”模式下拖直线的两个端点,把残差平方和压到最小二乘最小值的 1.15 倍以内(读数会显示两者的比)。In "by hand" mode drag the two ends of the line until the sum of squared residuals is within 1.15 times the least-squares minimum (the readout shows the ratio).
    • 切到“最小二乘”,再拖 \(\sigma\) 滑块:直线纹丝不动,只有 NLL 在变。把 \(\sigma\) 调到让 NLL 最小的位置(与 RMS 残差相差 0.02 以内)。Switch to "least squares" and move the \(\sigma\) slider: the line does not move at all, only the NLL changes. Set \(\sigma\) to where the NLL is smallest (within 0.02 of the RMS residual).

    默认数据下,最小二乘直线是 \(\hat y=0.54x+0.49\),残差平方和 2.04,RMS 残差 0.48;你在初始的水平线 \(y=0\) 处看到的残差平方和是 17.97。第二个任务揭示了一件事:\(\sigma\) 的最大似然估计恰好是 RMS 残差 \(\hat\sigma=\sqrt{\tfrac1n\sum r_i^2}\)(第 5 节推导)。它比生成数据用的 0.7 小,一部分是只有 9 个点的抽样波动,另一部分是系统性的:直线本身是照着这 9 个点拟合的,残差天然偏小,这正是 4.6 节说 \(\hat\sigma^2_{\mathrm{ML}}\) 偏小、常把分母换成 \(n-2\)(这里减去两个参数)的原因。

    With the default data the least-squares line is \(\hat y=0.54x+0.49\), with a sum of squared residuals of 2.04 and an RMS residual of 0.48; the flat starting line \(y=0\) gives 17.97. The second task shows something: the maximum-likelihood estimate of \(\sigma\) is exactly the RMS residual \(\hat\sigma=\sqrt{\tfrac1n\sum r_i^2}\) (derived in Section 5). It is smaller than the 0.7 used to generate the data, partly from the sampling luck of only 9 points and partly systematically: the line was fitted to these very 9 points, so its residuals come out small. That is why Lesson 4.6 says \(\hat\sigma^2_{\mathrm{ML}}\) is biased low and the denominator is often changed, here to \(n-2\) for the two fitted parameters.

    “线性”指的是参数,不是输入"Linear" refers to the parameters, not the input

    直线太简单了。真实的关节摩擦力矩 \(\tau_f\) 和关节速度 \(v\) 的关系是弯的:静止附近有一个跳变(库仑摩擦,8.4 节),再加上随速度线性增长的粘滞摩擦。好消息是,只要把输入先变成一组特征 \(\boldsymbol\phi(v)=(\phi_1(v),\dots,\phi_d(v))\),再让模型是特征的线性组合 \(\hat y=\boldsymbol\theta^\top\hl{phi}{\boldsymbol\phi}(v)\),那么预测对 \(\boldsymbol\theta\) 仍是线性的,NLL 仍是 \(\boldsymbol\theta\) 的二次函数,解仍然是 1.13 节的正规方程,只是矩阵 \(A\) 的每一行换成了 \(\boldsymbol\phi(v_i)^\top\)。特征可以是多项式 \(1,v,v^2,\dots\),可以是一排高斯“鼓包”(径向基函数,RBF),也可以是物理给出的 \(1,\operatorname{sgn}v,v\)。

    A straight line is too simple. A real joint's friction torque \(\tau_f\) depends on the joint velocity \(v\) in a bent way: a jump near standstill (Coulomb friction, Lesson 8.4) plus viscous friction that grows linearly with speed. The good news: first turn the input into a set of features \(\boldsymbol\phi(v)=(\phi_1(v),\dots,\phi_d(v))\) and make the model a linear combination of the features, \(\hat y=\boldsymbol\theta^\top\hl{phi}{\boldsymbol\phi}(v)\). Then the prediction is still linear in \(\boldsymbol\theta\), the NLL is still quadratic in \(\boldsymbol\theta\), and the answer is still the normal equations of Lesson 1.13, with each row of the matrix \(A\) replaced by \(\boldsymbol\phi(v_i)^\top\). The features can be polynomials \(1,v,v^2,\dots\), a row of Gaussian "bumps" (radial basis functions, RBF), or the \(1,\operatorname{sgn}v,v\) that physics suggests.

    FIG 2特征回归:辨识一个关节的摩擦Feature regression: identifying a joint's friction
    左:16 个青色实心点是训练数据(用来拟合),200 个紫色空心小点是测试数据(拟合时看不见,只用来打分);绿色虚线是真实的摩擦曲线 \(\tau_f=0.05+0.35\tanh(v/0.03)+0.25v\)(N·m),测量噪声 \(\sigma=0.04\) N·m;琥珀色是拟合结果。悬停公式里的 \(\boldsymbol\phi\) 会以细虚线画出当前的每个特征函数。右:同一种特征下,训练(青)与测试(紫)RMSE 随特征个数变化(对数纵轴),竖线是当前设置,水平虚线是物理特征的两个误差,绿色点线是噪声水平。 Left: the 16 filled cyan points are the training data (used for the fit); the 200 small hollow purple points are test data (hidden from the fit, used only for scoring). The green dashed curve is the true friction \(\tau_f=0.05+0.35\tanh(v/0.03)+0.25v\) (N·m), measured with noise \(\sigma=0.04\) N·m; amber is the fit. Hovering \(\boldsymbol\phi\) in the formula draws each current feature function as a thin dashed line. Right: for the chosen feature family, the training (cyan) and test (purple) RMSE against the number of features (log vertical axis); the vertical line is the current setting, the horizontal dashed lines are the two errors of the physics features, and the green dotted line is the noise level.
    • 在“多项式”下找出测试 RMSE 最低的阶数(右图紫色曲线的最低点),再切到“物理特征”:只用 3 个数就比它更准。Under "polynomial", find the degree with the lowest test RMSE (the bottom of the purple curve on the right), then switch to "physics features": 3 numbers beat it.
    • 把多项式阶数拉到 11 或 12:训练误差降到噪声水平附近,测试误差却是训练误差的 5 倍以上,曲线在数据点之间乱甩。Push the polynomial degree to 11 or 12: the training error drops to about the noise level while the test error is more than 5 times the training error, and the curve swings wildly between the data points.

    默认数据下,多项式在 7 阶时测试 RMSE 最低(0.098 N·m);12 阶时训练 RMSE 0.040,正好是噪声水平,测试 RMSE 却到了 2.5 N·m,比摩擦本身还大。物理特征 \((1,\operatorname{sgn}v,v)\) 学到 \(\hat{\boldsymbol\theta}=(0.062,\,0.364,\,0.249)\),与真值 \((0.05,\,0.35,\,0.25)\) 很接近,测试 RMSE 0.065:剩下的误差主要来自 \(\operatorname{sgn}\) 在零速附近与真实的平滑过渡不一样(模型误差)。这里只是先碰一下“过拟合”:训练误差低不等于模型好,一定要在没参与训练的数据上打分。为什么会这样、怎样系统地选模型复杂度(验证集、交叉验证、正则化),是 16.2 节的内容。

    With the default data the polynomial's lowest test RMSE comes at degree 7 (0.098 N·m); at degree 12 the training RMSE is 0.040, exactly the noise level, while the test RMSE reaches 2.5 N·m, larger than the friction itself. The physics features \((1,\operatorname{sgn}v,v)\) learn \(\hat{\boldsymbol\theta}=(0.062,\,0.364,\,0.249)\), close to the truth \((0.05,\,0.35,\,0.25)\), with a test RMSE of 0.065; what is left comes mostly from \(\operatorname{sgn}\) differing from the true smooth transition near zero speed (model error). This is only a first touch of "overfitting": a low training error does not make a good model, and you must score on data that took no part in training. Why this happens and how to choose model complexity systematically (validation sets, cross-validation, regularization) is the subject of Lesson 16.2.

    核心洞见Key insight

    回归的损失函数不是随便挑的,它是你对噪声的假设:高斯噪声 → 平方损失(如果噪声有重尾,换成别的分布就得到别的损失,见 16.2 节)。“线性回归”可以拟合曲线,只要模型对参数是线性的;好的特征(尤其是物理给的特征)比更多的特征更值钱。8.3 节的惯性参数辨识就是这样一个线性回归:力矩对惯性参数是线性的。

    The regression loss is not an arbitrary choice; it is your assumption about the noise: Gaussian noise → squared loss (heavier-tailed noise gives other losses, see Lesson 16.2). "Linear regression" can fit curves as long as the model is linear in its parameters, and good features (especially features from physics) are worth more than many features. The inertial-parameter identification of Lesson 8.3 is exactly such a linear regression: the torque is linear in the inertial parameters.

    3动手:现场训练一个抓取成败预测器Play: train a grasp-success predictor live

    回到开头的抓取。每次尝试记两个特征:\(x_1\) = 张开余量(夹爪最大张开量减物体宽度,mm),\(x_2\) = 夹爪与物体主轴的夹角偏差(°),标签 \(y=1\) 表示成功、\(y=0\) 表示失败。能不能还用最小二乘去拟合 0 和 1?可以算,但它的输出会跑到 \([0,1]\) 之外,也不是一个概率,而且远处那些“明显成功”的点会把直线拽偏(第 7 节误区 5)。更好的做法还是先写一个噪声模型:结果是一枚有偏的硬币,成功的概率随特征平滑变化,

    Back to the grasp of the opening. Each attempt records two features: \(x_1\) = opening margin (the gripper's maximum opening minus the object's width, mm) and \(x_2\) = the misalignment between the gripper and the object's main axis (°); the label \(y=1\) means success, \(y=0\) failure. Could we still fit the 0s and 1s by least squares? It computes, but its output leaves \([0,1]\), is not a probability, and far-away "obvious success" points drag the line off (Section 7, pitfall 5). The better route is again to write a noise model first: the outcome is a biased coin whose probability of success varies smoothly with the features,

    $$ p(y=1\mid\mathbf x)=\sigma(z)=\frac{1}{1+e^{-z}},\qquad z=\mathbf w^\top\mathbf x+b, $$ $$ L(\mathbf w,b)=-\frac1n\sum_{i=1}^n\Big[y_i\log\sigma(z_i)+(1-y_i)\log\big(1-\sigma(z_i)\big)\Big]. $$

    这里 \(\sigma(\cdot)\) 是 logistic(sigmoid)函数,不是噪声的标准差。\(z\) 叫 logit,即对数几率 \(\log\frac{p}{1-p}\):4.2 节的“对数几率”专栏已经说明,两类特征是等方差高斯时后验恰好是 \(z\) 线性的 sigmoid。\(L\) 是伯努利分布的平均负对数似然,也就是标签分布与预测分布之间的交叉熵(4.11 节),机器学习库里叫二元交叉熵(BCE)。它没有闭式解,但它是凸的(第 5 节),用 6.3 节的梯度下降一定能走到全局最优,而且梯度出奇地简单:\(\nabla_{\mathbf w}L=\frac1n\sum_i(\sigma(z_i)-y_i)\,\mathbf x_i\),即“预测概率减标签”乘以输入。

    Here \(\sigma(\cdot)\) is the logistic (sigmoid) function, not the noise standard deviation. \(z\) is called the logit, the log-odds \(\log\frac{p}{1-p}\): the log-odds box of Lesson 4.2 showed that when the two classes have equal-variance Gaussian features, the posterior is exactly a sigmoid of a linear \(z\). \(L\) is the mean negative log-likelihood of a Bernoulli distribution, i.e. the cross-entropy between the label distribution and the predicted distribution (Lesson 4.11); libraries call it binary cross-entropy (BCE). It has no closed form, but it is convex (Section 5), so the gradient descent of Lesson 6.3 is sure to reach the global optimum, and the gradient is surprisingly simple: \(\nabla_{\mathbf w}L=\frac1n\sum_i(\sigma(z_i)-y_i)\,\mathbf x_i\), "predicted probability minus label" times the input.

    FIG 3逻辑回归:用梯度下降学抓取成功率Logistic regression: learning grasp success by gradient descent
    左:横轴是张开余量 \(x_1\)(mm),纵轴是角度偏差 \(x_2\)(°)。120 次训练尝试:绿色圆点是成功,红色叉是失败。底色是模型预测的成功概率:越绿越可能成功,越红越可能失败。琥珀色实线是决策边界 \(p=0.5\)(即 \(z=0\)),两条琥珀色细虚线是 \(p=0.1\) 和 \(p=0.9\);紫色虚线是生成数据用的真实边界(真实 logit \(z=0.30x_1-0.12x_2+0.6\))。“含噪”数据的标签按真实概率抛硬币得到,“可分”数据把标签取为真实边界的哪一侧并去掉了边界附近的点。选“添加”模式后点击画面可以添加你自己的数据点。右:训练集(青)与 300 个测试样本(紫)上的交叉熵随步数变化(对数纵轴),绿色虚线是真实模型在训练集上的交叉熵。训练前先用训练集的均值和标准差把两个特征标准化,读数里的 \(\mathbf w,b\) 已换回原单位。 Left: the horizontal axis is the opening margin \(x_1\) (mm), the vertical the misalignment \(x_2\) (°). 120 training attempts: green dots are successes, red crosses failures. The background is the model's predicted probability of success: the greener, the more likely success; the redder, the more likely failure. The solid amber line is the decision boundary \(p=0.5\) (that is, \(z=0\)); the two thin dashed amber lines are \(p=0.1\) and \(p=0.9\); the purple dashed line is the true boundary used to generate the data (true logit \(z=0.30x_1-0.12x_2+0.6\)). In the "noisy" data each label is a coin flip with the true probability; in the "separable" data the label is the side of the true boundary, with points near it removed. In an "add" mode, clicking the plot adds your own data points. Right: the cross-entropy on the training set (cyan) and on 300 test samples (purple) against the step count (log vertical axis); the green dashed line is the true model's cross-entropy on the training set. Both features are standardized with the training set's mean and standard deviation before training; the \(\mathbf w,b\) in the readout are converted back to the original units.
    • “含噪”数据、不添加点,按“训练”:训练交叉熵降到 0.304 以下(约 170 步,学习率 0.5)。此时它已低于真实模型在同一批数据上的 0.3041;继续训练,学到的 \(\mathbf w,b\) 收敛到 \((0.307,-0.114)\)、0.56,接近真值 \((0.30,-0.12)\)、0.6。With "noisy" data and no added points, press "Train": the training cross-entropy drops below 0.304 (about 170 steps at learning rate 0.5). It is then below the true model's 0.3041 on the same data; trained on, the learned \(\mathbf w,b\) settle at \((0.307,-0.114)\) and 0.56, close to the true \((0.30,-0.12)\) and 0.6.
    • 换成“可分”数据,训练至少 3000 步:损失降到 0.005 以下,而(标准化后的)权重长度 \(\|\mathbf w\|\) 越过 9 还在涨,边界两侧的过渡带越来越窄。Switch to "separable" data and train for at least 3000 steps: the loss falls below 0.005 while the (standardized) weight length \(\|\mathbf w\|\) passes 9 and keeps growing, and the transition band around the boundary gets ever narrower.
    有意思的细节Things worth noticing

    (1) 准确率早就不动了,损失还在降:第一步之后训练准确率就是 87.5%(测试 84.7%),再训练几百步也只到 87.5% / 86.3%。变的是概率:交叉熵从 0.69 降到 0.303,模型从处处 \(p=0.5\) 变成自信的概率(一半成功样本的预测超过 0.96)。只看准确率会以为训练早已结束。 (2) 学到的模型在训练集上的交叉熵(0.3027)低于真实模型(0.3041),这和 11.6 节 BA 收敛处代价低于真值处是同一回事:优化器多少拟合了这批数据的噪声。在测试集上两者几乎一样(0.3105 对 0.3106)。 (3) 测试准确率 86.3% 是一个上限附近的值:即使知道真实模型,按 \(p>0.5\) 去判,在这 300 个测试样本上也只有 85.3%。标签本身是抛硬币,剩下的错误是数据里固有的,不是模型的错。

    (1) Accuracy stops moving long before the loss does: after the very first step training accuracy is already 87.5% (test 84.7%), and hundreds of steps later it is only 87.5% / 86.3%. What changes is the probabilities: the cross-entropy falls from 0.69 to 0.303, and the model goes from \(p=0.5\) everywhere to confident probabilities (half of the successes get more than 0.96). Watching accuracy alone, you would think training ended long ago. (2) The learned model's training cross-entropy (0.3027) is below that of the true model (0.3041), the same thing as the BA optimum of Lesson 11.6 costing less than the ground truth: the optimizer fits some of this batch's noise. On the test set the two are nearly equal (0.3105 versus 0.3106). (3) The test accuracy of 86.3% is close to a ceiling: even the true model, deciding by \(p>0.5\), gets only 85.3% on these 300 test samples. The labels themselves are coin flips; the remaining errors are inherent in the data, not the model's fault.

    可分数据为什么停不下来?当一条直线能把两类完全分开时,把 \(\mathbf w\) 和 \(b\) 一起放大 2 倍,边界不动,但每个点的 \(|z|\) 都变大,每个点的概率都更接近它的标签,交叉熵就更小。所以损失没有最小值,只有下确界 0,最大似然解在无穷远处:梯度下降会让 \(\|\mathbf w\|\) 大致按 \(\log t\) 一直增长,模型变得无比自信(3000 步时 9.4,20000 步时 13.6)。实践中的解药是正则化(给 \(\mathbf w\) 一个先验,4.6 节的 MAP)或提前停止,见 16.2 节。

    Why does separable data never stop? When a line can split the two classes perfectly, scaling \(\mathbf w\) and \(b\) together by 2 leaves the boundary in place but makes every \(|z|\) bigger, every point's probability closer to its label, and the cross-entropy smaller. So the loss has no minimum, only an infimum of 0, and the maximum-likelihood solution sits at infinity: gradient descent makes \(\|\mathbf w\|\) grow roughly like \(\log t\) for ever and the model becomes boundlessly confident (9.4 at 3000 steps, 13.6 at 20000). The cures used in practice are regularization (a prior on \(\mathbf w\), the MAP of Lesson 4.6) or early stopping, see Lesson 16.2.

    4另外两个视角:多类别,以及“不训练”的分类器Two more views: many classes, and a classifier that does not train

    多于两类:softmax 回归More than two classes: softmax regression

    一台轮式机器人想知道自己正在什么地面上走,好调整速度和牵引控制。它有两个便宜的特征:车身竖直方向振动的 RMS(m/s²)和车轮打滑率(%)。类别有三个:沥青、碎石、草地。逻辑回归的推广是给每一类 \(k\) 一个 logit \(z_k=\mathbf w_k^\top\mathbf x+b_k\),再用 softmax 把 \(K\) 个 logit 变成 \(K\) 个加起来为 1 的概率:

    A wheeled robot wants to know what ground it is on, to adapt its speed and traction control. It has two cheap features: the RMS of the body's vertical vibration (m/s²) and the wheel slip ratio (%). There are three classes: asphalt, gravel, grass. The generalization of logistic regression gives every class \(k\) its own logit \(z_k=\mathbf w_k^\top\mathbf x+b_k\) and turns the \(K\) logits into \(K\) probabilities summing to 1 with the softmax:

    $$ \hl{pk}{p(y=k\mid\mathbf x)}=\frac{e^{z_k}}{\sum_{j=1}^K e^{z_j}},\qquad L=-\frac1n\sum_{i=1}^n\log p(y=y_i\mid\mathbf x_i). $$

    噪声模型是“掷一个 \(K\) 面的有偏骰子”(类别分布),损失仍是负对数似然 = 交叉熵。类别 \(k\) 与 \(j\) 之间的边界是 \(z_k=z_j\),即 \((\mathbf w_k-\mathbf w_j)^\top\mathbf x+(b_k-b_j)=0\):仍是直线,所以 softmax 回归把平面切成若干个凸的多边形区域。想要弯曲的边界,就像 FIG 2 一样先做特征映射:加入 \(x_1^2,x_2^2,x_1x_2\) 之后,边界在原平面里变成二次曲线(椭圆、双曲线),但模型对参数仍是线性的,损失仍是凸的。

    The noise model is "roll a biased \(K\)-sided die" (a categorical distribution), and the loss is again the negative log-likelihood = cross-entropy. The boundary between classes \(k\) and \(j\) is \(z_k=z_j\), i.e. \((\mathbf w_k-\mathbf w_j)^\top\mathbf x+(b_k-b_j)=0\): still a straight line, so softmax regression cuts the plane into convex polygonal regions. For curved boundaries, map the features first as in FIG 2: after adding \(x_1^2,x_2^2,x_1x_2\) the boundaries in the original plane become conics (ellipses, hyperbolas), yet the model is still linear in its parameters and the loss still convex.

    FIG 4softmax 回归:三类地形,线性与二次特征Softmax regression: three terrains, linear and quadratic features
    “地形”:横轴振动 RMS(m/s²),纵轴打滑率(%),每类 50 个训练点:蓝色圆点沥青、琥珀色方块碎石、绿色三角草地。“圆环”是一个玩具数据:类别只取决于到原点的距离(内圆、中环、外环,同样三种颜色)。底色是预测的类别(概率最大的那一类),底色越浓表示这个最大概率越高;悬停公式里的 \(p(y=k\mid\mathbf x)\) 会让底色更浓。在图上悬停或点按一个位置,右侧条形图显示该处三类的概率(图中用一个小圈标出该位置)。下方的小图是训练(青)与测试(紫)交叉熵(对数纵轴)。 "Terrain": horizontal axis vibration RMS (m/s²), vertical axis slip ratio (%), 50 training points per class: blue dots asphalt, amber squares gravel, green triangles grass. "Ring" is a toy data set: the class depends only on the distance from the origin (inner disc, middle ring, outer ring, same three colours). The background is the predicted class (the one with the largest probability); the stronger the tint, the higher that largest probability. Hovering \(p(y=k\mid\mathbf x)\) in the formula strengthens the tint. Hover or tap a location in the plot and the bars on the right show the three class probabilities there (a small ring marks the location). The small chart below them is the training (cyan) and test (purple) cross-entropy (log vertical axis).
    • “地形”数据训练至少 200 步,然后悬停在碎石与草地之间的交界处,找一个三类概率都低于 0.6 的位置:模型在那里知道自己没把握。Train on "terrain" for at least 200 steps, then hover the border between gravel and grass and find a spot where all three probabilities are below 0.6: the model knows it is unsure there.
    • 切到“圆环”,用线性特征训练至少 200 步:测试准确率卡在 55% 以下;再切到二次特征重新训练:测试准确率到 95% 以上。Switch to "ring" and train with linear features for at least 200 steps: test accuracy is stuck below 55%; switch to quadratic features and train again: test accuracy exceeds 95%.

    “地形”数据上线性 softmax 训练 200 步后测试准确率 94.0%。继续训练,训练准确率还会升到 98.7%,测试交叉熵却在约 200 步后从 0.194 慢慢回升(5000 步时 0.227):这又是一次过拟合的预告。“圆环”上线性模型的测试准确率只有 49%,因为没有任何一组直线能围出一个圆;二次特征 200 步就到 97.3%,1000 步到 99.3%。

    On "terrain", linear softmax reaches 94.0% test accuracy after 200 steps. Keep training and training accuracy climbs to 98.7%, yet the test cross-entropy slowly rises again after about 200 steps (from 0.194 to 0.227 at 5000 steps): another preview of overfitting. On "ring" the linear model's test accuracy is only 49%, because no set of straight lines can enclose a circle; quadratic features reach 97.3% in 200 steps and 99.3% in 1000.

    不训练的分类器:k 近邻A classifier that does not train: k nearest neighbours

    前面的模型都是参数化的:训练把数据“压缩”进 \(\mathbf w,b\),之后数据可以扔掉。k 近邻(k-NN)走另一个极端:根本不训练,把所有训练样本都存着;要分类一个新点,就找离它最近的 \(k\) 个训练样本,让它们投票。它是非参数方法:模型的复杂度随数据量增长,任何形状的边界都能表示,所以常被用作“不做任何假设时能做到多好”的基线。它的代价是:预测时要和所有样本比距离;“距离”完全取决于你怎样度量各个特征,单位不同的特征必须先标准化;维数高时“最近的邻居”也离得很远(维数灾难)。

    The models so far are parametric: training "compresses" the data into \(\mathbf w,b\) and the data can then be thrown away. k nearest neighbours (k-NN) goes to the other extreme: it does not train at all and simply stores every training sample; to classify a new point it finds the \(k\) training samples closest to it and lets them vote. It is a non-parametric method: its complexity grows with the data and it can represent boundaries of any shape, which is why it is often used as a baseline for "how well can you do with no assumptions". The price: every prediction compares distances to all samples; the "distance" depends entirely on how you measure each feature, so features with different units must be standardized first; and in high dimensions even the "nearest" neighbours are far away (the curse of dimensionality).

    FIG 5k 近邻:k 控制边界的粗细,距离的单位很重要k nearest neighbours: k sets how coarse the boundary is, and the units of distance matter
    与 FIG 4 相同的训练数据和颜色。底色是 k-NN 在每个位置的投票结果。拖动琥珀色圆圈(查询点):细线连向它的 \(k\) 个近邻,琥珀色虚线圈出包含这些近邻的邻域(标准化开启时,它在原单位下是一个椭圆)。右:训练集(青)与测试集(紫)准确率随 \(k\) 变化(\(k\) 取奇数),竖线是当前的 \(k\)。“训练准确率”是把训练点自己也当作候选邻居算的,所以 \(k=1\) 时总是 100%。 The same training data and colours as FIG 4. The background is the k-NN vote at every location. Drag the amber circle (the query point): thin lines join it to its \(k\) neighbours, and an amber dashed outline encloses the neighbourhood that contains them (with standardization on it is an ellipse in the original units). Right: training (cyan) and test (purple) accuracy against \(k\) (odd \(k\) only); the vertical line is the current \(k\). "Training accuracy" counts each training point as a candidate neighbour of itself, so it is always 100% at \(k=1\).
    • “地形”数据、标准化开启:先把 \(k\) 设为 1(训练 100%,测试只有 90%,边界支离破碎),再找一个让测试准确率达到 94% 的 \(k\)。"Terrain" data with standardization on: first set \(k\) to 1 (training 100%, test only 90%, a ragged boundary), then find a \(k\) whose test accuracy reaches 94%.
    • “地形”数据,关掉标准化并把 \(k\) 设为 25 或更大:测试准确率掉到 85% 以下。看邻域的形状:打滑率(单位 %,数值范围大十倍)几乎独占了距离。On "terrain", turn standardization off and set \(k\) to 25 or more: test accuracy drops below 85%. Look at the neighbourhood's shape: slip (in %, a ten times larger numeric range) almost monopolizes the distance.

    标准化开启时,测试准确率在 \(k=17\) 和 \(k=23\) 到 \(35\) 之间达到 94.0%,与 FIG 4 的线性 softmax 一样;关掉标准化,\(k=25\) 时只有 83.3%,\(k=41\) 时 80.0%。小 \(k\) 的边界跟着每一个噪声点走(方差大),大 \(k\) 的边界被远处的点抹平(偏差大),这又是 16.2 节偏差–方差权衡的一个例子。在“圆环”上,k-NN 不需要任何特征工程,\(k=3\) 就有 96.7%:这正是非参数方法的长处。

    With standardization on, test accuracy reaches 94.0% at \(k=17\) and for \(k=23\) to \(35\), the same as FIG 4's linear softmax; with it off, \(k=25\) gives only 83.3% and \(k=41\) gives 80.0%. A small \(k\) makes the boundary follow every noisy point (high variance); a large \(k\) smears it with far-away points (high bias), another example of the bias–variance trade-off of Lesson 16.2. On "ring", k-NN needs no feature engineering at all and gets 96.7% with \(k=3\): exactly the strength of a non-parametric method.

    5再看数学The math

    提示:把鼠标悬停在公式中带底色的符号上,图中对应的元素会被高亮(残差、钟形、特征函数、决策边界、概率等高线、softmax 底色、k-NN 邻域、混淆矩阵的行与列)。Tip: hover the highlighted symbols in the formulas and the matching elements in the figures light up (residuals, bells, feature functions, the decision boundary, probability contours, the softmax tint, the k-NN neighbourhood, a row or column of the confusion matrix).

    回归:高斯似然与正规方程Regression: the Gaussian likelihood and the normal equations

    模型 \(y_i=\boldsymbol\theta^\top\boldsymbol\phi(\mathbf x_i)+\varepsilon_i\),\(\varepsilon_i\sim\mathcal N(0,\sigma^2)\) 独立同分布。把 \(\boldsymbol\phi(\mathbf x_i)^\top\) 排成设计矩阵 \(\Phi\in\R^{n\times d}\) 的第 \(i\) 行,\(\mathbf y=(y_1,\dots,y_n)\)。负对数似然是

    The model is \(y_i=\boldsymbol\theta^\top\boldsymbol\phi(\mathbf x_i)+\varepsilon_i\) with \(\varepsilon_i\sim\mathcal N(0,\sigma^2)\) i.i.d. Stack \(\boldsymbol\phi(\mathbf x_i)^\top\) as row \(i\) of the design matrix \(\Phi\in\R^{n\times d}\), and let \(\mathbf y=(y_1,\dots,y_n)\). The negative log-likelihood is

    $$ -\log p(\mathbf y\mid\Phi,\boldsymbol\theta,\sigma)=n\log\big(\hl{sig}{\sigma}\sqrt{2\pi}\big)+\frac{1}{2\sigma^2}\sum_{i=1}^n\hl{res}{\big(y_i-\boldsymbol\theta^\top\hl{phi}{\boldsymbol\phi}(\mathbf x_i)\big)}^2 $$ $$ =n\log\big(\sigma\sqrt{2\pi}\big)+\frac{\|\mathbf y-\Phi\boldsymbol\theta\|^2}{2\sigma^2}. $$

    对 \(\boldsymbol\theta\) 求最小时第一项与 \(\boldsymbol\theta\) 无关,第二项正是 1.13 节的 \(\|A\mathbf x-\mathbf b\|^2\)(\(A=\Phi\),\(\mathbf b=\mathbf y\)),所以 \(\hat{\boldsymbol\theta}\) 满足正规方程 \(\Phi^\top\Phi\,\hat{\boldsymbol\theta}=\Phi^\top\mathbf y\),与 \(\sigma\) 无关(FIG 1 的第二个任务)。再对 \(\sigma\) 求导并令其为零:\(-n/\sigma+\|\mathbf r\|^2/\sigma^3=0\),得 \(\hat\sigma^2=\tfrac1n\|\mathbf y-\Phi\hat{\boldsymbol\theta}\|^2\),即残差的均方。数值上不要真的去求 \((\Phi^\top\Phi)^{-1}\):多项式特征的 \(\Phi\) 条件数很大,\(\Phi^\top\Phi\) 把它平方,FIG 2 用的是 QR 分解(1.13 节的伪逆也可以)。每个噪声不同的点可以给权重 \(1/\sigma_i^2\),就是 1.13 节的加权最小二乘。

    When minimizing over \(\boldsymbol\theta\) the first term does not depend on \(\boldsymbol\theta\), and the second is exactly the \(\|A\mathbf x-\mathbf b\|^2\) of Lesson 1.13 (\(A=\Phi\), \(\mathbf b=\mathbf y\)). So \(\hat{\boldsymbol\theta}\) solves the normal equations \(\Phi^\top\Phi\,\hat{\boldsymbol\theta}=\Phi^\top\mathbf y\), independently of \(\sigma\) (the second task of FIG 1). Differentiating with respect to \(\sigma\) and setting to zero, \(-n/\sigma+\|\mathbf r\|^2/\sigma^3=0\), gives \(\hat\sigma^2=\tfrac1n\|\mathbf y-\Phi\hat{\boldsymbol\theta}\|^2\), the mean squared residual. Numerically, do not actually form \((\Phi^\top\Phi)^{-1}\): with polynomial features \(\Phi\) is badly conditioned and \(\Phi^\top\Phi\) squares that; FIG 2 uses a QR factorization (the pseudo-inverse of Lesson 1.13 also works). Points with different noise levels can be weighted by \(1/\sigma_i^2\), which is the weighted least squares of Lesson 1.13.

    逻辑回归:伯努利似然、梯度与凸性Logistic regression: Bernoulli likelihood, gradient and convexity

    \(y_i\in\{0,1\}\),\(p_i=\sigma(z_i)\),\(z_i=\mathbf w^\top\mathbf x_i+b\)。伯努利分布 \(p(y\mid\mathbf x)=p^{y}(1-p)^{1-y}\) 的平均负对数似然就是二元交叉熵。用 \(\sigma'(z)=\sigma(z)(1-\sigma(z))\) 求导,几项会神奇地消掉:

    \(y_i\in\{0,1\}\), \(p_i=\sigma(z_i)\), \(z_i=\mathbf w^\top\mathbf x_i+b\). The mean negative log-likelihood of the Bernoulli distribution \(p(y\mid\mathbf x)=p^{y}(1-p)^{1-y}\) is the binary cross-entropy. Differentiating with \(\sigma'(z)=\sigma(z)(1-\sigma(z))\), terms cancel almost magically:

    $$ \frac{\partial L}{\partial z_i}=\frac1n\,(p_i-y_i),\qquad \nabla_{\mathbf w}L=\frac1n\sum_{i=1}^n(p_i-y_i)\,\mathbf x_i, $$ $$ \nabla^2_{\mathbf w}L=\frac1n\sum_{i=1}^n p_i(1-p_i)\,\mathbf x_i\mathbf x_i^\top\succeq0. $$

    三点值得记住。梯度的形状:“预测减目标”乘输入,和线性回归的 \(\nabla_{\boldsymbol\theta}=\frac1n\sum(\hat y_i-y_i)\boldsymbol\phi_i\)(差一个常数因子)一模一样;softmax 也一样,\(\partial L/\partial\mathbf z_i=\frac1n(\mathbf p_i-\mathbf e_{y_i})\),\(\mathbf e_{y_i}\) 是独热向量。这不是巧合:三者都是“指数族分布 + 典范连接函数”的广义线性模型。到了 16.3 节,这个 \(\mathbf p-\mathbf e_y\) 就是反向传播从输出层送回去的第一个信号。凸性:Hessian 是一组半正定矩阵的加权和,所以 \(L\) 是凸的,没有坏的局部极小,梯度下降、牛顿法(逻辑回归里叫 IRLS,迭代重加权最小二乘)都收敛到全局最优(数据可分时除外:最优在无穷远)。边界的几何:

    Three things are worth remembering. The shape of the gradient: "prediction minus target" times the input, the same as linear regression's \(\nabla_{\boldsymbol\theta}=\frac1n\sum(\hat y_i-y_i)\boldsymbol\phi_i\) (up to a constant factor); softmax is the same again, \(\partial L/\partial\mathbf z_i=\frac1n(\mathbf p_i-\mathbf e_{y_i})\) with \(\mathbf e_{y_i}\) the one-hot vector. This is no coincidence: all three are generalized linear models, "an exponential-family distribution + its canonical link". In Lesson 16.3 this \(\mathbf p-\mathbf e_y\) is the first signal that backpropagation sends back from the output layer. Convexity: the Hessian is a weighted sum of positive semidefinite matrices, so \(L\) is convex with no bad local minima; gradient descent and Newton's method (called IRLS, iteratively reweighted least squares, for logistic regression) both reach the global optimum (except on separable data, where the optimum is at infinity). The geometry of the boundary:

    $$ \hl{bnd}{p(y=1\mid\mathbf x)=\tfrac12\iff\mathbf w^\top\mathbf x+b=0},\qquad \hl{lvl}{p=0.9\iff z=\log 9\approx2.197}, $$ $$ d_\perp(\mathbf x)=\frac{|z|}{\|\mathbf w\|}. $$

    决策边界是一个超平面,\(\mathbf w\) 是它的法向量(1.7 节点积的几何)。\(p=0.1\) 和 \(p=0.9\) 两条等高线到边界的距离是 \(2.197/\|\mathbf w\|\):\(\|\mathbf w\|\) 越大,过渡带越窄、模型越自信,FIG 3 的可分数据里你看到的就是它。上式里的 \(d_\perp(\mathbf x)\) 是点 \(\mathbf x\) 到边界的欧氏距离(在标准化后的坐标里)。阈值不一定取 0.5:把判成功的阈值改成 \(t\),边界就平移到 \(z=\log\frac{t}{1-t}\),第 6 节会利用这一点。

    The decision boundary is a hyperplane and \(\mathbf w\) is its normal vector (the geometry of the dot product, Lesson 1.7). The \(p=0.1\) and \(p=0.9\) contours lie \(2.197/\|\mathbf w\|\) from the boundary: the larger \(\|\mathbf w\|\), the narrower the transition band and the more confident the model, which is what the separable data of FIG 3 shows. \(d_\perp(\mathbf x)\) above is the Euclidean distance from the point \(\mathbf x\) to the boundary (in standardized coordinates). The threshold need not be 0.5: deciding "success" at a threshold \(t\) shifts the boundary to \(z=\log\frac{t}{1-t}\), which Section 6 exploits.

    softmax:K 类的推广Softmax: the K-class generalization

    \(\mathbf z=W\mathbf x+\mathbf b\),\(W\in\R^{K\times d}\),\(p_k=e^{z_k}/\sum_je^{z_j}\)。给所有 logit 加同一个常数,概率不变,所以 \(K\) 组参数里只有 \(K-1\) 组是可辨识的;\(K=2\) 时 \(p_1=\sigma(z_1-z_0)\),正是逻辑回归,\(\mathbf w=\mathbf w_1-\mathbf w_0\)。数值上要先减去最大的 logit 再取指数(否则 \(e^{z}\) 会溢出),库里的交叉熵函数都直接吃 logit 而不是概率,就是为了把 log 和 softmax 合在一起稳定地算。

    \(\mathbf z=W\mathbf x+\mathbf b\) with \(W\in\R^{K\times d}\), \(p_k=e^{z_k}/\sum_je^{z_j}\). Adding the same constant to every logit leaves the probabilities unchanged, so only \(K-1\) of the \(K\) parameter sets are identifiable; with \(K=2\), \(p_1=\sigma(z_1-z_0)\), which is logistic regression with \(\mathbf w=\mathbf w_1-\mathbf w_0\). Numerically, subtract the largest logit before exponentiating (or \(e^{z}\) overflows); library cross-entropy functions take logits rather than probabilities precisely so that the log and the softmax can be combined and computed stably.

    k 近邻k nearest neighbours

    \(\hat y(\mathbf x)=\arg\max_k\big|\{i\in\hl{nbr}{\mathcal N_k(\mathbf x)}:y_i=k\}\big|\),\(\mathcal N_k(\mathbf x)\) 是离 \(\mathbf x\) 最近的 \(k\) 个训练样本(这里的距离是标准化后的欧氏距离)。平票时本页取票数并列的类里离得最近的那个样本的类别。Cover 与 Hart(1967)证明,样本数趋于无穷时,1-NN 的错误率不超过最优(贝叶斯)错误率的两倍。预测一次要 \(O(nd)\) 次运算;机器人上数据量大时用 k-d 树或近似最近邻搜索(与 12.1 节点云最近邻搜索用的 k-d 树相同)。

    \(\hat y(\mathbf x)=\arg\max_k\big|\{i\in\hl{nbr}{\mathcal N_k(\mathbf x)}:y_i=k\}\big|\), where \(\mathcal N_k(\mathbf x)\) is the set of the \(k\) training samples closest to \(\mathbf x\) (here in standardized Euclidean distance). On a tie this page takes, among the tied classes, the class of the nearest sample. Cover and Hart (1967) proved that as the number of samples goes to infinity, the error rate of 1-NN is at most twice the optimal (Bayes) error rate. One prediction costs \(O(nd)\) operations; with large data on a robot, k-d trees or approximate nearest-neighbour search are used (the same k-d trees that Lesson 12.1 uses for nearest neighbours in point clouds).

    评估:混淆矩阵与它派生的指标Evaluation: the confusion matrix and what it yields

    把“判为成功”当作正类。在测试集上数四个数:TP(判成功,真成功)、FP(判成功,实际失败)、FN(判失败,实际成功)、TN(判失败,真失败)。于是

    Take "predicted success" as the positive class. Count four numbers on the test set: TP (predicted success, was success), FP (predicted success, actually failed), FN (predicted failure, actually succeeded), TN (predicted failure, was failure). Then

    $$ \mathrm{Acc}=\frac{TP+TN}{n},\qquad \hl{prec}{\mathrm{Prec}=\frac{TP}{TP+FP}},\qquad \hl{rec}{\mathrm{Rec}=\frac{TP}{TP+FN}}, $$ $$ \mathrm{FPR}=\frac{FP}{FP+TN},\qquad F_1=\frac{2\,\mathrm{Prec}\cdot\mathrm{Rec}}{\mathrm{Prec}+\mathrm{Rec}}. $$

    这里 Acc 是准确率,Prec 是精确率(precision),Rec 是召回率(recall),FPR 是假阳性率。精确率问的是“我说会成功的里面,有多少真成功了”,召回率(recall,也叫真阳性率 TPR)问的是“真能成功的里面,我抓住了多少”。阈值 \(t\) 从 0 扫到 1,召回率单调下降,精确率大体上升,画出来就是 PR 曲线;以 FPR 为横轴、TPR 为纵轴画就是 ROC 曲线,它下方的面积 AUC 等于“随机取一个成功样本和一个失败样本,前者得分更高”的概率。ROC 不受类别比例影响,PR 曲线和精确率则直接受它影响:失败很少时,ROC 可能很好看,但精确率仍可能不够。

    Here Acc is accuracy, Prec precision, Rec recall and FPR the false-positive rate. Precision asks "of the grasps I said would succeed, how many did", recall (also the true-positive rate, TPR) asks "of the grasps that could succeed, how many did I catch". Sweeping the threshold \(t\) from 0 to 1, recall falls monotonically and precision roughly rises; plotting one against the other gives the PR curve. Plotting TPR against FPR gives the ROC curve, and the area under it, AUC, equals the probability that a randomly chosen success scores higher than a randomly chosen failure. ROC does not depend on the class ratio; the PR curve and precision depend on it directly: with few failures, the ROC curve can look excellent while precision is still not good enough.

    6机器人中的它:这个抓取预测器能上机吗?In robotics: is this grasp predictor ready for the robot?

    训练准确率说明不了什么(FIG 2 和 FIG 5 已经看到),所以要留出一份测试集:训练、调参时都不碰它,最后只用一次。可即便在测试集上,“准确率 90%”也可能毫无用处。下图是一个抓取分类器在 400 次测试抓取上给出的分数(预测的成功概率)。机器人只在分数超过阈值 \(t\) 时才执行抓取。执行了却失败(FP)的代价很高:零件掉落、产线停下;放弃了本能成功的抓取(FN)只是浪费一点时间,换一个候选抓取就行。真实的拣选场景里,候选抓取大多是能成功的,失败是少数:把“类别比例”切到“现实(90% 成功)”看看会发生什么。

    Training accuracy says little (FIG 2 and FIG 5 showed it), so hold out a test set: never touch it while training or tuning, and use it once at the end. Yet even on a test set, "90% accuracy" can be useless. The figure below shows the scores (predicted success probabilities) that a grasp classifier gives on 400 test grasps. The robot executes a grasp only when its score exceeds a threshold \(t\). Executing a grasp that then fails (FP) is expensive: a dropped part, a stopped line; skipping a grasp that would have worked (FN) only wastes a little time, since another candidate can be tried. In real picking most candidate grasps succeed and failures are the minority: set the class ratio to "realistic (90% success)" and see what happens.

    FIG 6评估:阈值、混淆矩阵、精确率与召回率Evaluation: threshold, confusion matrix, precision and recall
    左:分数直方图,横轴不变,绿色柱(横轴上方)是真实成功的抓取,红色柱(横轴下方,向下画)是真实失败的抓取;琥珀色竖线是阈值,它右边的抓取会被执行。分数由模型 \(s=\sigma(z)\) 生成:成功时 \(z\sim\mathcal N(1.6,1.2^2)\),失败时 \(z\sim\mathcal N(-1.6,1.2^2)\)。右:蓝色曲线是扫过所有阈值得到的 PR 曲线(或 ROC 曲线),琥珀色点是当前阈值;PR 图里的虚线是“全判成功”的精确率(等于成功比例),ROC 图里的虚线是随机猜测。下方是混淆矩阵:行是预测,列是真实;悬停公式里的 precision / recall 会框出用来计算它的那一行 / 那一列。 Left: score histograms on a shared horizontal axis; green bars (above the axis) are grasps that truly succeeded, red bars (below the axis, drawn downward) grasps that truly failed; the amber vertical line is the threshold, and grasps to its right are executed. The scores come from a model \(s=\sigma(z)\) with \(z\sim\mathcal N(1.6,1.2^2)\) for successes and \(z\sim\mathcal N(-1.6,1.2^2)\) for failures. Right: the blue curve is the PR curve (or ROC curve) from sweeping every threshold, and the amber dot is the current threshold; in the PR plot the dashed line is the precision of "predict success for all" (the success fraction), in the ROC plot the dashed line is random guessing. Below is the confusion matrix: rows are predictions, columns the truth; hovering precision / recall in the formula outlines the row / column used to compute it.
    • 选“现实(90% 成功)”,把阈值拉到最左(0.01 或更低):准确率是 90%,可它一次失败也没拦住(TN = 0),这个“分类器”等于什么都不做。Choose "realistic (90% success)" and drag the threshold to the far left (0.01 or lower): accuracy is 90%, yet it stops not a single failure (TN = 0); this "classifier" does nothing at all.
    • 仍在“现实”下,找一个阈值让执行的抓取里一次失败都没有(FP = 0),同时召回率不低于 0.85。Still under "realistic", find a threshold at which no executed grasp fails (FP = 0) while recall stays at 0.85 or more.

    “均衡”数据下阈值 0.5 时准确率 92.5%、精确率 0.934、召回率 0.915。“现实”数据下,让准确率最高的阈值移到了 0.22 附近(95.75%),因为失败很少,多判成功几乎不吃亏;而满足 FP = 0 且召回率 ≥ 0.85 的阈值只有 0.58 到 0.61 这一小段。别把“0 个失败”看得太绝对:测试集里一共只有 40 次失败,0/40 只能说明“失败的候选被执行”的真实比例(FPR)大概率低于 7.5% 左右(统计里的“三分之法则”:0 次发生时,95% 置信上界约为 \(3/n\))。要宣称这个比例低于 1%,需要几百次失败样本。

    On "balanced" data a threshold of 0.5 gives 92.5% accuracy, precision 0.934 and recall 0.915. On "realistic" data the threshold with the best accuracy moves to about 0.22 (95.75%), because failures are rare and predicting success costs almost nothing; while the thresholds satisfying FP = 0 with recall ≥ 0.85 form only the narrow band from 0.58 to 0.61. Do not read "0 failures" too literally: the test set holds only 40 failures in total, and 0/40 only says that the true fraction of failing candidates that get executed (the FPR) is probably below about 7.5% (the "rule of three" in statistics: with zero events in \(n\) trials, the 95% upper confidence bound is about \(3/n\)). Claiming that this fraction is below 1% needs failure samples in the hundreds.

    真实系统里In real systems

    学习抓取成功率:Pinto 与 Gupta(ICRA 2016)用机器人自己收集的 5 万次尝试(标题里的 50K tries、700 robot hours)训练 CNN,从图像块预测 18 个夹爪角度各自的成功与否;Levine 等(IJRR 2018)用多台机械臂在两个月里收集了约 80 万次抓取尝试,训练一个 CNN 预测“给定图像和一个运动指令,抓取会成功”的概率,再用它挑选指令。Dex-Net 2.0(Mahler 等,RSS 2017)的 GQ-CNN 在 670 万个合成点云样本上训练,从深度图预测平行夹爪抓取的鲁棒性。三者的输出层实质上都是本节的逻辑回归(一个 sigmoid 加交叉熵),只是特征 \(\mathbf x\) 换成了网络从图像里提出的特征(17.1 节)。 地形分类:Brooks 与 Iagnemma(IEEE T-RO 2005)用车体结构上测到的振动信号给行星车分类地形,正是 FIG 4 的问题;今天的足式和轮式机器人仍常把本体感知(IMU、电机电流、打滑)当分类特征。 动力学辨识:8.3 节提到的 Atkeson、An 与 Hollerbach(1986)把连杆和负载的惯性参数辨识写成线性最小二乘;后来的辨识工作常把摩擦项(库仑 + 粘滞)作为额外的回归列加进去,FIG 2 就是这一部分的单关节版本。 软件:scikit-learn 的 LogisticRegression 默认带 L2 正则(C=1.0),所以在可分数据上不会像 FIG 3 那样无限增长;KNeighborsClassifier 默认 \(k=5\)。PyTorch 的 nn.CrossEntropyLoss 与 nn.BCEWithLogitsLoss 都输入 logit,内部合并 log 与 softmax/sigmoid 以保证数值稳定。

    Learning grasp success: Pinto and Gupta (ICRA 2016) trained a CNN on 50 thousand attempts collected by the robot itself (the 50K tries and 700 robot hours of the title) to predict, from an image patch, success or failure for each of 18 gripper angles; Levine et al. (IJRR 2018) collected about 800,000 grasp attempts with a group of robot arms over two months and trained a CNN to predict the probability that "given the image and a motor command, the grasp succeeds", then used it to choose commands. The GQ-CNN of Dex-Net 2.0 (Mahler et al., RSS 2017) was trained on 6.7 million synthetic point-cloud samples to predict the robustness of parallel-jaw grasps from a depth image. All three end in what is in effect this lesson's logistic regression (a sigmoid plus the cross-entropy); only the features \(\mathbf x\) are replaced by features a network extracts from the image (Lesson 17.1). Terrain classification: Brooks and Iagnemma (IEEE T-RO 2005) classified terrain for planetary rovers from vibrations sensed in the rover's structure, which is FIG 4's problem; legged and wheeled robots today still often use proprioception (IMU, motor currents, slip) as classification features. Dynamics identification: Atkeson, An and Hollerbach (1986), mentioned in Lesson 8.3, wrote the identification of link and payload inertial parameters as linear least squares; later identification work commonly adds friction terms (Coulomb + viscous) as extra regressor columns, and FIG 2 is the single-joint version of that part. Software: scikit-learn's LogisticRegression is L2-regularized by default (C=1.0), so on separable data it does not grow without bound as in FIG 3; KNeighborsClassifier defaults to \(k=5\). PyTorch's nn.CrossEntropyLoss and nn.BCEWithLogitsLoss both take logits and merge the log with the softmax/sigmoid internally for numerical stability.

    7常见误区Common pitfalls

    误区 1:在训练数据上打分,或让测试集“泄漏”进训练Pitfall 1: scoring on the training data, or letting the test set leak into training

    FIG 2 的 12 阶多项式训练误差等于噪声水平,测试误差却大了 60 倍;FIG 5 的 1-NN 训练准确率永远是 100%。训练分数只说明模型能背下数据。还有更隐蔽的泄漏:用全部数据(含测试集)的均值和方差做标准化,按测试分数反复挑模型,或者把同一次抓取的相邻帧分到训练和测试两边(几乎是重复样本)。机器人数据要按场景、按物体或按时间段切分,否则测试集里全是训练集的“近亲”。

    FIG 2's degree-12 polynomial has a training error equal to the noise level and a test error 60 times larger; FIG 5's 1-NN always has 100% training accuracy. A training score only says the model can memorize the data. Subtler leaks: standardizing with the mean and variance of all the data (test set included), picking models again and again by their test score, or putting neighbouring frames of the same grasp on both sides of the split (near-duplicates). Split robot data by scene, by object or by time, or the test set is full of the training set's close relatives.

    误区 2:不做特征标准化Pitfall 2: not standardizing the features

    FIG 5 关掉标准化,打滑率(0 到 35)把振动(0 到 3.5)完全压住,k-NN 的测试准确率从 94% 掉到 83%。梯度下降也受害:特征尺度相差 10 倍,损失的等高线就被拉长,条件数变大,6.3 节的“之字形”就出现了,所以 FIG 3、FIG 4 训练前都先标准化。标准化的均值和标准差只能从训练集算,存下来,部署时对新数据用同样的数。

    With standardization off in FIG 5, slip (0 to 35) completely swamps vibration (0 to 3.5) and k-NN's test accuracy falls from 94% to 83%. Gradient descent suffers too: features whose scales differ by 10 stretch the loss contours, raise the condition number and bring back the zig-zag of Lesson 6.3, which is why FIG 3 and FIG 4 standardize before training. Compute the mean and standard deviation from the training set only, store them, and apply the same numbers to new data at deployment.

    误区 3:类别不均衡时只看准确率Pitfall 3: looking only at accuracy when classes are imbalanced

    FIG 6 里,失败占 10% 时“全判成功”就有 90% 的准确率。要看混淆矩阵,按代价选指标(误执行贵就盯精确率或 FP 数,漏检贵就盯召回率),并按代价选阈值,而不是默认 0.5。报告结果时也要报告测试集里每一类有多少个样本:少数类只有几十个时,任何百分比都带着很宽的误差棒。

    In FIG 6, with 10% failures, "predict success for everything" already scores 90% accuracy. Look at the confusion matrix, choose the metric by cost (watch precision or the FP count when executing a failure is expensive, recall when missing is expensive), and choose the threshold by cost rather than defaulting to 0.5. When reporting results, also report how many test samples each class has: with only a few dozen in the minority class, any percentage carries wide error bars.

    误区 4:把输出的“概率”当真Pitfall 4: taking the output "probability" at face value

    逻辑回归的输出只有在模型假设成立(对数几率真的对特征线性)且数据足够时才接近真实频率。FIG 3 的可分数据训练 3000 步后,模型给 62% 的训练点 0.999 以上的把握,给每个点至少 0.93,而且还在升高,可这只是 \(\|\mathbf w\|\) 无限增长的副作用。更大的模型(深度网络)往往系统性地过于自信。输出的分数可以排序,但要当概率用(例如“成功率低于 0.8 就请人帮忙”),必须先在留出数据上检验校准,见 21.3 节。而且它描述的只是训练分布里的不确定性,遇到没见过的物体,它可能非常自信地错。

    A logistic regression's output is close to the true frequency only when the model's assumption holds (the log-odds really are linear in the features) and there is enough data. After 3000 steps on FIG 3's separable data the model gives 62% of the training points more than 0.999 certainty and every point at least 0.93, still rising, a mere side effect of \(\|\mathbf w\|\) growing without bound. Larger models (deep networks) are often systematically overconfident. The scores can rank candidates, but to use them as probabilities (say, "ask a human when the success probability is below 0.8") you must first check their calibration on held-out data, see Lesson 21.3. And they describe only the uncertainty within the training distribution: on an object it has never seen, the model can be confidently wrong.

    误区 5:用回归做分类,或把类别编号当成数Pitfall 5: doing classification by regression, or treating class indices as numbers

    对 0/1 标签做最小二乘,输出会超出 \([0,1]\),而且离边界很远、本来分对了的点仍会产生很大的平方误差,把直线拽过去,边界反而变差;交叉熵对这些点的梯度 \(p-y\) 几乎为零,不受它们影响。把“沥青 = 0、碎石 = 1、草地 = 2”当作数去回归更糟:它暗含“碎石在沥青和草地中间”“草地和沥青差得最远”这种并不存在的顺序。多类别就用 softmax 和独热标签。(反过来,真正有序的目标,例如抓取力档位,有时可以当回归或有序回归处理。)

    Least squares on 0/1 labels gives outputs outside \([0,1]\), and points that are far from the boundary and already classified correctly still produce large squared errors that drag the line toward them, making the boundary worse; the cross-entropy's gradient \(p-y\) is almost zero for those points, so they do not disturb it. Regressing "asphalt = 0, gravel = 1, grass = 2" as numbers is worse: it implies an order that does not exist ("gravel lies between asphalt and grass", "grass and asphalt are the furthest apart"). For several classes use softmax with one-hot labels. (Conversely, a target that really is ordered, such as a grip-force level, can sometimes be treated by regression or ordinal regression.)

    8小练习Check yourself

    1. 模型 \(\hat y=\theta_0+\theta_1v+\theta_2v^2+\theta_3\sin v\) 为什么仍然可以用正规方程一步解出?1. Why can the model \(\hat y=\theta_0+\theta_1v+\theta_2v^2+\theta_3\sin v\) still be solved in one step by the normal equations?
    选项 C。“线性回归”的“线性”是对参数而言的。设计矩阵的第 \(i\) 行是 \((1,v_i,v_i^2,\sin v_i)\),预测 \(\Phi\boldsymbol\theta\) 对 \(\boldsymbol\theta\) 线性,平方损失是二次的,正规方程 \(\Phi^\top\Phi\hat{\boldsymbol\theta}=\Phi^\top\mathbf y\) 给出精确解。它对 \(v\) 显然不是线性的(选项 B 错),也不需要任何近似(选项 A 错)。Option C. The "linear" in "linear regression" refers to the parameters. Row \(i\) of the design matrix is \((1,v_i,v_i^2,\sin v_i)\); the prediction \(\Phi\boldsymbol\theta\) is linear in \(\boldsymbol\theta\), the squared loss is quadratic, and the normal equations \(\Phi^\top\Phi\hat{\boldsymbol\theta}=\Phi^\top\mathbf y\) give the exact solution. It is clearly not linear in \(v\) (option B is wrong), and no approximation is involved (option A is wrong).
    2. 逻辑回归的二元交叉熵对 \(\mathbf w\) 的梯度是?(\(p_i=\sigma(\mathbf w^\top\mathbf x_i+b)\))2. What is the gradient of logistic regression's binary cross-entropy with respect to \(\mathbf w\)? (\(p_i=\sigma(\mathbf w^\top\mathbf x_i+b)\))
    选项 B。\(\partial/\partial z\) 作用在 \(-[y\log\sigma(z)+(1-y)\log(1-\sigma(z))]\) 上,sigmoid 的导数 \(\sigma(1-\sigma)\) 恰好与分母约掉,得到 \(\sigma(z)-y\),再乘 \(\partial z/\partial\mathbf w=\mathbf x\)。选项 A 是对 sigmoid 输出用平方损失时的梯度(差一个因子 2):多出来的 \(p(1-p)\) 在模型很自信地错了时接近 0,梯度消失,这正是分类不用平方损失的原因之一。Option B. Applying \(\partial/\partial z\) to \(-[y\log\sigma(z)+(1-y)\log(1-\sigma(z))]\), the sigmoid's derivative \(\sigma(1-\sigma)\) cancels against the denominators, leaving \(\sigma(z)-y\), which is then multiplied by \(\partial z/\partial\mathbf w=\mathbf x\). Option A is the gradient of the squared loss on the sigmoid output (up to a factor 2): its extra \(p(1-p)\) goes to 0 when the model is confidently wrong, so the gradient vanishes, one reason why classification does not use the squared loss.
    3. 训练数据可以被一条直线完全分开。不加正则地用梯度下降训练逻辑回归,会发生什么?3. The training data can be separated perfectly by a straight line. What happens when logistic regression is trained by gradient descent without regularization?
    选项 D。把 \((\mathbf w,b)\) 放大,边界不动,每个点都离自己的标签更近,损失更小,所以最小值在无穷远处(FIG 3 的“可分”数据:3000 步时 \(\|\mathbf w\|\approx9.4\),之后仍在涨)。损失是凸的(选项 C 错),只是没有有限的极小点;\(\log 2\) 是 \(\mathbf w=0\) 处的损失,那里的梯度并不为零(选项 B 错)。L2 正则或提前停止能给出有限的解。Option D. Scaling \((\mathbf w,b)\) up leaves the boundary in place and brings every point closer to its label, lowering the loss, so the minimum is at infinity (FIG 3's "separable" data: \(\|\mathbf w\|\approx9.4\) at 3000 steps and still rising). The loss is convex (option C is wrong), it just has no finite minimizer; \(\log 2\) is the loss at \(\mathbf w=0\), where the gradient is not zero (option B is wrong). L2 regularization or early stopping gives a finite answer.
    4. 一个分拣机器人的抓取有 95% 会成功。一个分类器永远回答“会成功”。下列哪个说法正确?4. A sorting robot's grasps succeed 95% of the time. A classifier always answers "success". Which statement is correct?
    选项 A。全判成功:TP = 95%、FP = 5%、FN = TN = 0。准确率 0.95,召回率 TP/(TP+FN) = 1,精确率 TP/(TP+FP) = 0.95(选项 B 错,它把所有失败都误判成了成功),而 TN = 0,失败一个也没有拦下。所有样本得分相同,只有一个阈值点,ROC AUC 是 0.5(选项 D 错)。这就是 FIG 6 的第一个任务。Option A. Predicting success for all: TP = 95%, FP = 5%, FN = TN = 0. Accuracy is 0.95, recall TP/(TP+FN) = 1, precision TP/(TP+FP) = 0.95 (option B is wrong: every failure is predicted as a success), and TN = 0, so not one failure is stopped. All samples share one score, so there is a single operating point and the ROC AUC is 0.5 (option D is wrong). This is the first task of FIG 6.
    5. 关于 k 近邻,下列哪一项正确?5. Which statement about k nearest neighbours is correct?
    选项 C。k-NN 是非参数方法,“模型”就是训练集本身,预测时与所有样本比距离;距离由特征尺度决定(FIG 5 关掉标准化后准确率从 94% 掉到 83%)。\(k=1\) 时训练准确率就是 100%,\(k\) 增大通常让它下降(选项 A 错);它能表示任意形状的边界,FIG 5 的“圆环”就是例子(选项 D 错)。Option C. k-NN is non-parametric: the "model" is the training set itself, and prediction compares distances to every sample; the distances are set by the feature scales (in FIG 5, turning standardization off drops accuracy from 94% to 83%). At \(k=1\) training accuracy is already 100% and a larger \(k\) usually lowers it (option A is wrong); it can represent boundaries of any shape, as FIG 5's "ring" shows (option D is wrong).

    9延伸阅读Further reading

    • C. M. Bishop, Pattern Recognition and Machine Learning, Springer, 2006, Ch. 3–4 — 线性回归与线性分类的概率视角:基函数、最大似然、逻辑回归、IRLSthe probabilistic view of linear regression and classification: basis functions, maximum likelihood, logistic regression, IRLS
    • T. Hastie, R. Tibshirani & J. Friedman, The Elements of Statistical Learning, 2nd ed., Springer, 2009, Ch. 2–4 — 最小二乘与最近邻的对比、线性分类方法least squares versus nearest neighbours, linear methods for classification
    • K. P. Murphy, Probabilistic Machine Learning: An Introduction, MIT Press, 2022 — 现代、免费在线的教材,回归、逻辑回归、评估指标都有详细讨论a modern textbook, free online, with detailed chapters on regression, logistic regression and evaluation metrics
    • D. R. Cox, The Regression Analysis of Binary Sequences, Journal of the Royal Statistical Society B, 1958 — 逻辑回归的经典来源之一one of the classic origins of logistic regression
    • T. M. Cover & P. E. Hart, Nearest Neighbor Pattern Classification, IEEE Transactions on Information Theory, 1967 — 1-NN 的错误率不超过贝叶斯错误率的两倍the error of 1-NN is at most twice the Bayes error
    • J. Davis & M. Goadrich, The Relationship Between Precision-Recall and ROC Curves, ICML 2006 — 何时看 PR 曲线、何时看 ROCwhen to look at PR curves and when at ROC
    • L. Pinto & A. Gupta, Supersizing Self-supervision: Learning to Grasp from 50K Tries and 700 Robot Hours, ICRA 2016 — 机器人自己收集标签,学习抓取成败the robot collects its own labels and learns grasp success
    • S. Levine, P. Pastor, A. Krizhevsky, J. Ibarz & D. Quillen, Learning Hand-Eye Coordination for Robotic Grasping with Deep Learning and Large-Scale Data Collection, IJRR 2018 — 大规模抓取成功率预测grasp-success prediction at scale
    • J. Mahler et al., Dex-Net 2.0: Deep Learning to Plan Robust Grasps with Synthetic Point Clouds and Analytic Grasp Metrics, RSS 2017 — 用合成数据训练的抓取质量分类器a grasp-quality classifier trained on synthetic data