对应 Maps to:Stanford CS229 Autumn 2018(Andrew Ng)Lectures 1–4(Introduction; Linear Regression & GD; Locally Weighted & Logistic Regression; Perceptron & GLM),以及 CS229 main notes(Andrew Ng & Tengyu Ma)Part I, Chapters 1–3。 CS229 当前学期(Summer 2026)的课表需要 Stanford 登录才能看,所以本讲以公开的讲义和 2018 年的录像为准;这部分内容多年来基本没变。 配套代码 Code:
code/lecture01/(numpy;4 个脚本,每个 1 秒左右跑完) 预计阅读时间:2–3 小时(含运行代码)。这是一份复习讲义:假设你学过这些模型,重点放在”为什么”和”它们之间的联系”上。
0. 本讲导航 · How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- 把任何一个监督学习方法拆成 hypothesis class + loss + optimizer 三件事,并说出本讲每个模型的三件事分别是什么。
- Explain why squared loss, logistic loss, cross-entropy and Poisson loss are not arbitrary choices: each one is the negative log-likelihood of a noise model. 也就是说,选损失 = 选噪声假设。
- 说清楚 gradient descent 什么时候收敛、收敛多快(,步数 ),以及 feature scaling、SGD 学习率衰减、Newton 法分别在解决什么问题。
- Explain the failure modes: singular , outliers under squared loss, least squares for classification, logistic regression on separable data, perceptron on non-separable data.
- 用指数族(exponential family)推出 GLM 的通用梯度 ,并解释为什么神经网络的输出层要”sigmoid 配 BCE、softmax 配 CE”。
0.2 默认你已经会的 / 本讲会省略的
| 默认你已经会 Assumed | 本讲省略或只给结论 Skipped |
|---|---|
| 梯度下降、偏导数、矩阵乘法 | 矩阵求导的 trace 技巧(直接给结果) |
| MLE 的基本思想 | LWR 的完整推导、感知机收敛定理(Novikoff)的证明 |
| 逻辑回归的公式 | 多项分布写成指数族的完整代数(只给结论) |
| Python + numpy 基础 | CS229 讲义里的 Portland 房价真实数据(用合成数据代替) |
0.3 本讲地图 Map
§1 The big picture:三件套 + 一条主线(loss = −log-likelihood)
§2 Linear regression:GD / SGD / normal equation / 概率解释 / 特征与 LWR ← 代码 01、02
§3 Logistic regression:为什么不用最小二乘 / margin 视角 / 可分数据 / 感知机 / Newton ← 代码 03
§4 Exponential family & GLMs:a' = 均值 / 通用梯度 / Poisson / softmax / 输出层配对 ← 代码 04
§5–9 小结、常见误区、练习、延伸阅读、下一讲预告
0.4 Notation(和 CS229 讲义一致,全课统一)
| 符号 | 含义 |
|---|---|
| , | 第 个样本的输入(features)和输出(target / label) |
| 训练样本数; 是训练集 | |
| 截距项(intercept)。加上它之后 | |
| design matrix,第 行是 ; | |
| hypothesis(模型的预测) | |
| / | 代价函数(要最小化)/ 对数似然(要最大化) |
代码的约定:CS229 讲义写”最大化 “(gradient ascent);代码统一写成”最小化平均负对数似然 “(gradient descent),这是今天所有深度学习框架的写法。最优解相同,梯度差一个负号和 。
0.5 关于数字
讲义里所有实验数字都来自配套代码的实际输出(固定随机种子,同一台机器上重复运行逐字相同)。数据是合成的:我们知道”真相”,所以能检查算法有没有学对;但数字本身不代表任何真实系统。
1. The big picture · 大图景
1.1 Supervised learning in one picture
Andrew Ng 第一节课的例子:给你一堆房子的面积和价格,预测一套新房子的价格。抽象出来:
- 是连续值 → regression(房价); 是离散值 → classification(肿瘤良性 / 恶性)。
- The hypothesis is picked from a hypothesis class — for this lecture, functions of the form for some fixed .
1.2 三件套:model + loss + optimizer
Every method in this course — and almost every method in modern ML — can be decomposed into three independent choices:
| 选择 | 问的问题 | 本讲的例子 |
|---|---|---|
| Hypothesis class | 模型能表示哪些函数? | ;;;softmax |
| Loss / objective | 什么叫”拟合得好”? | squared error;log loss;cross-entropy;Poisson NLL |
| Optimizer | 怎样找到最好的 ? | closed form;GD;SGD;Newton |
这个拆分的价值在于它们可以独立地换。线性回归可以用 normal equation 解,也可以用 SGD 解(换 optimizer,答案不变);同一个 可以配平方损失或 L1 损失(换 loss,答案变了);把 换成 就换了 hypothesis class,但优化器原样可用。复习时遇到任何一个新方法,先问这三个问题。
1.3 The one thread of this lecture: loss = negative log-likelihood
本讲最重要的一句话:损失函数不是拍脑袋选的,而是”你对数据噪声的假设”的负对数似然。
| 你假设 服从 | 得到的损失 | 得到的模型 |
|---|---|---|
| Gaussian | squared error | linear regression |
| Laplace | absolute error(L1) | least absolute deviations |
| Bernoulli | log loss / binary cross-entropy | logistic regression |
| Categorical (softmax) | cross-entropy | softmax regression |
| Poisson | Poisson NLL | Poisson regression |
§2–§4 就是把这张表一行一行地展开,§4 再说明它们其实是同一个模板(GLM)。
1.4 Why review linear models in 2026?
It’s tempting to skip straight to deep learning. Some reasons not to:
- Every neural network ends in a GLM. The last layer is a linear map followed by an identity / sigmoid / softmax, trained with the matching NLL loss. Everything in §4 applies verbatim to the output head of a Transformer.
- Linear models are the best-understood baselines. Convex, closed-form or nearly so, with uncertainty estimates for free. A linear probe on frozen features is still the standard way to ask “what does this representation encode?”
- Many “nonlinear” methods are linear models in disguise: polynomial features, kernel methods (Lecture 2), random features and the neural tangent kernel are all linear in the parameters.
- The optimization lessons transfer. Conditioning, learning-rate limits, SGD noise floors, why Adam/normalization help — you can see all of them exactly in a 3-parameter least-squares problem.
2. Linear regression · 线性回归
2.1 Model and cost
为什么是平方误差?有三个层次的回答:(1) 方便 —— 处处可导、有封闭解;(2) 几何 —— 最小二乘解是 在 的列空间上的正交投影;(3) 概率 —— 它是高斯噪声下的最大似然(§2.4)。第三个才是”真正的”理由,因为它告诉你什么时候不该用平方误差。
2.2 Gradient descent and the LMS rule
对单个样本求导,得到 CS229 讲义里的 LMS(least mean squares)/ Widrow–Hoff 更新:
直觉:误差 × 输入。预测偏小(误差为正)就沿 的方向把 往上推,误差越大推得越多;预测几乎正确时几乎不动。每个样本都这样做一次叫 stochastic GD;把所有样本的梯度加起来再走一步叫 batch GD。
When does GD converge, and how fast? Write . Its Hessian is the constant matrix with eigenvalues . Along the -th eigenvector, one GD step multiplies the error by . Two consequences:
- Stability:需要每个方向都 ,即 。上限由最陡的方向决定。
- Speed:最慢的方向()每步只缩小 ,所以需要的步数 (条件数,condition number)。
代码 01_linear_regression.py 演示 2 在标准化后的房价数据上()扫学习率:
| 0.1 | 0.5 | 1.0 | 1.856() | 1.9 | 1.99 | 2.01 | 2.2 | |
|---|---|---|---|---|---|---|---|---|
| 收敛步数 | 2616 | 515 | 253 | 150 | 221 | 2311 | 发散 | 发散 |
最快的固定步长是 ,它让最快和最慢的方向收缩得一样快。注意 1.99 和 2.01 两行:刚好低于上限时在陡峭方向上来回震荡、很慢;刚好高于上限时发散得也很慢(要 1040 步 才涨到初始值的 倍)。所以训练时”loss 缓慢上升”也可能是学习率太大。
Feature scaling. 演示 3 用同一份数据、三种坐标:
| 特征 | GD(步长 )结果 | |
|---|---|---|
| 原始(ft², 卧室数) | 20000 步后 仍有 126 | |
| 面积改用千平方英尺 | 223 | 3222 步收敛 |
| 标准化(均值 0、标准差 1) | 12 | 181 步收敛 |
面积的数量级是 ,截距列是 1:步长被”面积”方向限制得很小,在”截距”方向上几乎走不动。Feature scaling 不改变最优解(只是换坐标),却能让 GD 快几个数量级。这个视角也解释了很多深度学习技巧:BatchNorm / LayerNorm 和 Adam 的逐坐标步长,都可以理解为在线地改善条件数。
SGD and its noise floor. With a constant step size, SGD does not converge to : even at the optimum, a single example’s gradient is nonzero, so the iterate keeps getting kicked around. 演示 4(,后 50 个 epoch 的平均):
| schedule | after epoch 1 | after epoch 100 | floor (mean of epochs 51–100) |
|---|---|---|---|
| constant | 103 | 17 | 49 |
| constant | 0.004 | 0.8 | |
| decaying | 60 | 0.003 | 0.01 |
大步长:快速到达附近,然后停在高地板上;小步长:地板低,但起步慢;衰减的步长兼顾两者(Robbins–Monro 条件:,)。深度学习的 learning-rate schedule(warmup + cosine decay)是这个想法的工程版。
为什么还要 SGD?当 是十亿量级时,batch GD 走一步要看完所有数据。机器学习只需要”足够接近”最优(反正还有统计误差),SGD 看一点数据就走一步,这笔账非常划算。
2.3 The normal equation
令梯度为 0:,即
几何意义:残差 和 的每一列都正交 —— 是 在列空间上的投影。
| Normal equation | Gradient descent | |
|---|---|---|
| 代价 | ,一次 | 每步 ,步数 |
| 需要调参? | 不需要 | 学习率、步数 |
| 适用 | 不超过几千 | 很大;或者没有封闭解的模型 |
When is singular. 两种常见情形(演示 6):
- 重复 / 共线特征:在房价数据上再加一列”面积(平方米)”, 的条件数变成 。normal equation 没有报错,给出 —— 两个”面积”系数之和是对的(117.31),但怎么分完全由舍入误差决定。
np.linalg.lstsq给出最小范数解,平分成 58.65 + 58.65。两者的预测完全一样,但前者的系数没法解读。 - :10 个样本、30 个特征。训练误差可以是 0,而且有无穷多个 都做到 0;它们在训练集上一模一样,在新数据上的预测却不同(演示中 −0.50 vs 5.83)。lstsq 选范数最小的那个,从 出发的 GD 也收敛到同一个(183 步,差 ):GD 的每一步都在 的列空间里,永远不会长出零空间的分量。
后一点是第 3 讲 implicit regularization 和 double descent 的核心:“优化算法本身挑选了哪个解”会影响泛化。
Practical advice: never form the inverse explicitly; use lstsq (SVD) or a QR factorization; add ridge when features are collinear (Lecture 3).
2.4 The probabilistic interpretation · 概率解释
Assume with . Then
Maximizing over is exactly minimizing . Note that drops out: it only rescales the curve, it does not move the peak. 演示 5(a) 在 附近随机扰动,三个不同的 下对数似然都下降,下降量 ; 的 MLE (真值 40)。
这个视角买到了什么?
(1) 它告诉你平方损失什么时候会出问题。 高斯分布的尾巴很薄:一个 20σ 的残差在高斯假设下”几乎不可能发生”,所以模型宁可把整条直线拉过去也要减小它。演示 5(b),,再加 5 个比正常值低 10 的离群点:
| 数据 | least squares(Gaussian) | LAD(Laplace) |
|---|---|---|
| 干净 | [1.81, 3.22] | [1.78, 3.35] |
| + 5 个离群点 | [3.37, −1.14] | [1.78, 3.25] |
([截距, 斜率],真值 [2, 3]。)5 个点就让最小二乘的斜率变号。Laplace 噪声的尾巴厚,它的负对数似然是 ,只线性增长,几个离群点拉不动。换噪声假设 = 换损失:Huber loss、Student-t 回归都是这个思路。
(2) 它给你不确定性。 高斯假设下 。演示 1 用这个公式给房价系数算 95% 置信区间,结果很有教育意义:
| 系数 | 估计 | 95% CI | 真值 |
|---|---|---|---|
| intercept | 51.1 | [35.2, 67.0] | 50 ✓ |
| area (k$/ft²) | 0.139 | [0.126, 0.152] | 0.12 ✗ |
| bedrooms (k$/间) | −3.3 | [−11.4, 4.8] | 10 ✗ |
卧室的系数估成了负数,两个区间都没盖住真值。代码错了吗?重新生成 2000 份数据重复实验:估计值的平均是 [49.75, 0.1201, 9.96](无偏),区间覆盖率是 [0.960, 0.954, 0.953](名副其实的 95%)。这份样本恰好不走运。真正的原因是共线性:卧室数和面积的相关系数 0.88,数据很难分清”贵是因为大还是因为卧室多”,一个系数高估、另一个就低估来补偿。卧室系数在重复实验中的标准差约 4,而真值才 10。
教训:预测和解读系数是两件事。三种算法给出同一个 −3.3,这不是优化的问题,是数据的信息量不够。第 3 讲的 bias–variance 会系统地讨论估计方差。
2.5 Feature maps and locally weighted regression
“Linear regression” means linear in the parameters, not in . Replace by a feature map and every tool above works unchanged. 代码 02_features_lwr.py 在 上(只有 15 个训练点)用多项式特征 :
| 次数 | 0 | 1 | 3 | 5 | 7 | 9 | 12 | 14 |
|---|---|---|---|---|---|---|---|---|
| train MSE | 0.381 | 0.261 | 0.036 | 0.035 | 0.032 | 0.009 | 0.003 | 0.000 |
| test MSE | 0.592 | 0.342 | 0.159 | 0.178 | 1.14 | 25.9 | 802 | |
| 0.05 | 0.57 | 4.3 | 3.7 | 27 | 726 |
训练误差随 单调下降(嵌套的模型族,必然如此),测试误差先降后升: underfit, overfit。过拟合时 爆炸:曲线靠巨大的、正负交替的系数在数据点之间剧烈摆动 —— 这就是”惩罚 “(ridge / weight decay)的直觉来源。噪声方差 0.09 是测试 MSE 的下限。
Locally weighted regression (LWR) takes a different route: instead of choosing features, fit a separate weighted line for every query point :
The bandwidth plays the same role as the polynomial degree (50 个训练点):
| 0.003 | 0.01 | 0.03 | 0.06 | 0.1 | 0.2 | 0.5 | 10 | |
|---|---|---|---|---|---|---|---|---|
| train MSE | 0.003 | 0.018 | 0.058 | 0.077 | 0.098 | 0.172 | 0.288 | 0.300 |
| test MSE | 9.14 | 1.36 | 0.111 | 0.099 | 0.107 | 0.170 | 0.276 | 0.287 |
| 有效样本数 | 1.3 | 2.3 | 5.5 | 10.3 | 16.3 | 28.8 | 46.3 | 50 |
Small : each prediction effectively uses one or two points (effective sample size ) — overfitting. Large : all weights are nearly equal and LWR collapses to one global line (the last column matches global least squares exactly).
几个值得记住的点:
- Parametric vs non-parametric: after fitting, a polynomial needs only numbers; LWR must keep the entire training set and solve a fresh regression for every query. Great in low dimensions with lots of data; in high dimensions there are almost no “nearby” points (curse of dimensionality) and it stops working.
- 为什么是局部”线性”而不是局部”平均”? 局部加权平均(Nadaraya–Watson)在数据的边界上会被内侧的点拉偏(boundary bias)。演示 3:端点处的平均误差 LWR 0.139 vs 局部平均 0.224,内部两者都是 0.070。代价是 太小时局部直线外推不稳定: 在 处预测出了 11.4。
- A modern echo: “weight training examples by similarity to the query, then average” is exactly the shape of attention, — attention is a learned Nadaraya–Watson smoother.
3. Classification & logistic regression · 分类与逻辑回归
3.1 Why not just use least squares?
把 当实数做线性回归、预测 判为 1,看起来也能用。Andrew Ng 的反例:往训练集里加一些特别大、标签毫无争议的恶性肿瘤。代码 03_logistic_newton.py 演示 1(准确率在 60 个原始点上算):
| 加入的大肿瘤个数 | 0 | 5 | 10 | 20 | 40 |
|---|---|---|---|---|---|
| least squares 边界(cm) | 2.89 | 3.27 | 3.40 | 3.47 | 3.49 |
| least squares 准确率 | 0.950 | 0.917 | 0.917 | 0.883 | 0.867 |
| logistic 边界(cm) | 2.89 | 2.89 | 2.89 | 2.89 | 2.89 |
Least squares wants every malignant example to have exactly 1. The huge tumors sit far above 1, and squared loss punishes them for being “too correct”, so the line flattens and the boundary drifts right. The logistic boundary doesn’t move at all (to three decimals).
3.2 The logistic model: why the sigmoid?
Three increasingly deep reasons for this particular squashing function:
- It maps to , so the output can be a probability. (Many functions do this.)
- The log-odds is linear: . Each is “how much one unit of multiplies the odds” — the standard interpretation in medicine and economics.
- It is derived, not chosen: it is the canonical response function of the Bernoulli distribution (§4), and it is also the exact posterior of a generative model with Gaussian class-conditionals (Gaussian discriminant analysis, Lecture 2).
3.3 Maximum likelihood and the familiar-looking gradient
,所以
梯度和 LMS 长得一模一样:误差 × 输入,只是 从 变成了 。CS229 讲义说”Is this coincidence, or is there a deeper reason?” —— §4 回答。另外 Hessian 是 ,半负定,所以 是凹的:没有局部最优。
3.4 The margin view of classification losses
Let and define the margin ( means correct, larger means “more confidently correct”). Every loss below is a function of alone:
| loss | ||||||
|---|---|---|---|---|---|---|
| 0-1: | 1 | 1 | 1 | 0 | 0 | 0 |
| logistic: | 2.13 | 1.31 | 0.69 | 0.31 | 0.13 | 0.02 |
| hinge(SVM): | 3 | 2 | 1 | 0 | 0 | 0 |
| squared: | 9 | 4 | 1 | 0 | 1 | 9 |
This table explains §3.1 completely: squared loss rises again for , punishing examples that are too correct, while logistic and hinge are non-increasing — once you’re right, they gradually (or entirely) stop caring. What we actually care about is the 0-1 loss, but it is discontinuous with zero gradient almost everywhere, so we optimize a convex surrogate instead: hinge, and logistic in base 2, are convex upper bounds on 0-1. The SVM of Lecture 2 is exactly “hinge loss + L2 regularization”.
3.5 Separable data: when the MLE does not exist
如果某个 把训练集完全分开,那么把它放大 倍会让每个 margin 都放大 倍,log loss 严格下降。最优点在无穷远处。演示 3(两团相距很远的点,先用感知机确认线性可分):
| GD 步数 | 10 | 100 | 1000 | ||
|---|---|---|---|---|---|
| () | 0.61 | 2.05 | 4.76 | 7.95 | 11.90 |
| 训练 loss() | 0.30 | 0.090 | 0.013 | 0.0019 | 0.00028 |
| 方向变化(度) | – | 36.2 | 7.29 | 1.34 | 0.67 |
| () | 0.60 | 1.93 | 3.06 | 3.07 | 3.07 |
Three things to notice:
- Without regularization, grows like forever and the predicted probabilities drift to 0/1 — the model becomes overconfident and its “probabilities” stop meaning anything.
- But the direction converges. Soudry et al. (2018) proved that GD on separable data converges in direction to the max-margin (hard-SVM) solution — an implicit bias of the optimizer, connecting this lecture to SVMs (Lecture 2) and implicit regularization (Lecture 3). (Lecture 2’s
04_svm_smo.pydemo 4 checks this on exactly this dataset: after GD steps the direction is from the hard-margin SVM.) - A small L2 penalty makes the problem strictly convex with a finite minimizer. This is one reason libraries regularize by default (sklearn’s
LogisticRegressionusesC=1).
3.6 The perceptron (a historical detour)
把 sigmoid 换成硬阈值 ,更新规则形式不变: —— 分对了不动,分错了推一下。演示 4:
- 可分数据:4 个 epoch 内停下,总共犯错 10 次。Novikoff 定理保证犯错次数 ( 是数据半径, 是某个分隔面的间隔);用正则化逻辑回归的方向算出的上界是 759,远大于实际的 10 —— 上界是最坏情况。这是最早的”间隔决定难度”的结果之一,和维度、样本数都无关。
- 不可分数据:每个 epoch 都在犯错、都在更新,epoch 结束时的训练准确率在 0.63–0.74 之间跳,全都明显低于逻辑回归的 0.865。
感知机的输出没有概率含义、不可分时不收敛,所以今天不直接用它。它的历史意义很大:Rosenblatt(1958)引发了第一波神经网络热潮;Minsky & Papert(1969)指出单层感知机连 XOR 都学不了,热潮随之退去。解决办法是多层网络 + 可导的激活函数 + backprop(第 4 讲)。
3.7 Newton’s method
To find a zero of , Newton’s method repeatedly jumps to the zero of the local linear approximation — equivalently, to the optimum of the local quadratic approximation of :
演示 2 在两团重叠的高斯点上比较:
| 目标精度 | |||||
|---|---|---|---|---|---|
| GD(步长 )步数 | 52 | 257 | 479 | 701 | 923 |
| Newton 步数 | 3 | 5 | 6 | 6 | 7 |
Newton 的梯度序列是 :接近最优点后每一步把误差平方(quadratic convergence),而 GD 每提高 100 倍精度要多走同样多的步数(linear convergence)。
Affine invariance. 把一个特征乘以 1000(比如单位从 km 换成 m),Newton 仍然是 7 步,系数自动变成原来的 1/1000;GD 被条件数拖垮,20 万步后训练 loss 还比最优多 0.19。Newton uses the Hessian to undo any linear change of coordinates — it is “automatic, optimal feature scaling”.
The catch:每步要构造并求解 的系统,。 在几千以内(GLM、经典统计)时 Newton 是首选 —— R 的 glm 和 statsmodels 就用它(对逻辑回归叫 IRLS,iteratively reweighted least squares,见练习 3); 的神经网络完全不可行,所以深度学习用一阶方法,再用 Adam、归一化等手段部分地弥补条件数。另外,Newton 的二次收敛只在”足够近”时成立,远处需要 line search 保护(§4.4 的 Poisson 例子)。
4. Exponential family & generalized linear models · 指数族与广义线性模型
4.1 Motivation
We now have two models with the same gradient , and the table in §1.3 suggests more. Is there one recipe that produces all of them — and tells us what to do when is a count, a category, or a positive duration? Yes: pick from the exponential family and make its natural parameter linear in .
4.2 The exponential family
是 natural parameter, 是 sufficient statistic(本讲都是 ), 是 log-partition function:它的唯一作用是让概率加起来等于 1,。三个例子(推导就是把熟悉的密度函数改写成上面的形状):
| 分布 | 改写 | = 均值 | ||
|---|---|---|---|---|
| Bernoulli | ||||
| Gaussian | ||||
| Poisson |
(多项分布 / categorical 也在指数族里, 是 one-hot 向量,结果见 §4.6。)
4.3 The key property: is the mean, is the variance
代码 04_glm_softmax.py 演示 1 用数值微分和 20 万个样本验证了三个分布、三个 值,例如 Bernoulli、: vs 样本均值 0.2694, vs 样本方差 0.1968。两个推论撑起了整个 GLM 理论:
- Convexity for free. , so is convex, so the NLL is convex in , and with it is convex in . Every canonical GLM is a convex problem: no local optima.
- The response function is . The map from natural parameter to mean is : identity for Gaussian, sigmoid for Bernoulli, exp for Poisson. The sigmoid was never a design choice — it falls out of the Bernoulli distribution.
4.4 The GLM recipe and the universal gradient
CS229 讲义的三个假设(其实是三个设计决定):
- —— 按 的类型选分布;
- 预测的目标是 ;
- —— natural parameter 是输入的线性函数(“linear” 就在这里)。
于是 , 叫 canonical response function,它的逆叫 canonical link function。对单个样本的对数似然求导只要一行:
That’s the “deeper reason” behind §3.3: every canonical GLM has gradient (target − prediction) × input, and its Hessian is . So one Newton solver fits all of them. 演示 2 用同一个函数 fit_glm_newton(X, y, family):
| family | 数据 | Newton 步数 | 对照 |
|---|---|---|---|
| gaussian | 房价 | 1 | 与 lstsq 差 (,一步就是 normal equation) |
| bernoulli | 两团点 | 6 | 与专门写的逻辑回归逐位相同 |
| poisson | 访问量 | 5 | ,真值 |
Poisson 的第一步被 backtracking line search 缩短到 1/4。不做 line search 的纯 Newton 第一步就把梯度从 9 推到 量级( 涨得太快,冲过头了),再花十来步才爬回来,总共 15 步。这就是 R 的 glm(family=...) 和 statsmodels 的工作方式:一个 IRLS 求解器 + 一个 family 参数。
4.5 Example: Poisson regression for counts
是计数(每天的访问量)时,用 Poisson + log link:。演示 3 的真实模型是 ,训练 300 天:
| 模型 | test MSE | 和真实 的 MSE | 负的预测 |
|---|---|---|---|
| linear regression | 9.92 | 3.80 | 8.2% |
| Poisson regression | 6.37 | 0.077 | 0% |
| 预算(工作日) | 0 | 0.5 | 1.0 | 1.5 | 2.0 | 2.5 |
|---|---|---|---|---|---|---|
| 真实 | 1.35 | 2.34 | 4.06 | 7.03 | 12.18 | 21.12 |
| linear | −0.20 | 2.87 | 5.93 | 9.00 | 12.06 | 15.13 |
| Poisson | 1.47 | 2.52 | 4.30 | 7.35 | 12.55 | 21.45 |
Three distinct failures of the linear model, each fixed by choosing the right distribution:
- Range:线性模型预测出负的访问量; 永远为正。
- Shape:真实关系是乘法的(预算 +1 → 访问量 ×)。直线去近似凸的指数曲线,只能两端低估、中间高估。这是 model misspecification,数据再多也消除不了(“和真实 的 MSE”一列)。
- Noise:Poisson 的方差等于均值, 大的日子噪声也大(按 分组,均值 1.45 / 3.25 / 7.26 / 14.69 对应方差 1.63 / 3.83 / 9.26 / 24.72)。最小二乘假设方差处处相同;Poisson 的 Newton 步里权重是 ,自动考虑了哪些点噪声大。(每组的方差略大于均值,是因为组内的 本身也在变。)
The practical rule: first ask what type of quantity is — real, binary, categorical, count, positive continuous — then pick the matching distribution.
4.6 Softmax regression
。把 categorical 分布写成指数族,canonical response function 就是 softmax:
又是 (target − prediction) × input。负对数似然就是 cross-entropy。演示 4 的三个要点:
- 参数冗余(over-parameterization):softmax 只依赖 logits 之间的差。给所有 加同一个向量 ,预测概率的变化是 。CS229 讲义固定 来去掉冗余;实践中保留全部 个(对称、好写),由正则化或”从 0 出发的 GD”选出一个解(GD 的梯度各列之和恒为 0,所以 一直是 0)。
- 就是逻辑回归:。演示中 softmax 的 和逻辑回归的 一致到第 4 位小数,预测概率最大差 。
- 三个高斯团上训练准确率 0.883、测试 0.870(三团有重叠,线性边界只能做到这样)。
4.7 GLMs inside every neural network · 输出层的”配对”
A deep network is a learned feature map followed by a GLM head: , then , trained with the NLL. By §4.4 the gradient at the logits is simply , which is why backprop starts from such a clean signal (Lecture 4).
如果激活和损失不配对会怎样?演示 5 比较一个 的样本在 logit 上的梯度:
| −10 | −5 | −2 | 0 | 2 | 5 | |
|---|---|---|---|---|---|---|
| sigmoid + BCE: | −1.00 | −0.99 | −0.88 | −0.50 | −0.12 | −0.007 |
| sigmoid + MSE: | −0.092 | −0.125 | −0.013 |
Canonical 配对下,错得越离谱(,模型几乎确定 ),纠错的梯度越大;sigmoid + MSE 在饱和区梯度几乎为 0,错得最离谱时反而学不动。所以标准搭配是:
| 的类型 | 输出激活 | 损失 | PyTorch |
|---|---|---|---|
| 实数 | identity | MSE | MSELoss |
| 二分类 | sigmoid | binary cross-entropy | BCEWithLogitsLoss |
| 多分类 | softmax | cross-entropy | CrossEntropyLoss |
| 计数 | exp | Poisson NLL | PoissonNLLLoss |
PyTorch 让 BCEWithLogitsLoss、CrossEntropyLoss 直接吃 logits,既是为了这个干净的梯度,也是为了数值稳定(log-sum-exp 技巧)。
5. 小结 · Summary
| 模型 | 噪声假设 | 损失 | 梯度(单样本,最小化方向) | 常用优化器 | |
|---|---|---|---|---|---|
| Linear regression | squared | normal eq. / GD / SGD | |||
| Logistic regression | Bernoulli | log loss | Newton (IRLS) / GD | ||
| Softmax regression | Categorical | cross-entropy | GD / L-BFGS | ||
| Poisson regression | Poisson | Poisson NLL | Newton + line search | ||
| Perceptron | (无概率模型) | – | (仅在分错时) | 逐样本更新 |
Five takeaways:
- Loss = negative log-likelihood. Choosing a loss is choosing a noise model; the noise model tells you when the loss will fail (outliers, heteroscedasticity, wrong range).
- GD speed is governed by conditioning: , steps . Feature scaling, normalization layers and Newton’s method all attack .
- Uniqueness is not guaranteed: singular , , separable data, softmax redundancy. When the data don’t pin down , the optimizer or the regularizer does — the theme of Lecture 3.
- Canonical GLMs share one gradient, , and one convex Newton solver. This is why sigmoid pairs with BCE and softmax with CE.
- Prediction ≠ interpretation. Collinearity can make individual coefficients wildly wrong (even the wrong sign) while predictions stay fine.
6. 常见误区 · Common pitfalls
- “Linear regression only fits straight lines.” It only has to be linear in ; can be any nonlinear map.
- “The normal equation didn’t throw, so the answer is fine.” Near-singular gives coefficients chosen by rounding error. Use
lstsqand check the condition number. - “Training loss creeping up means overfitting.” Rising training loss is more likely a learning rate just above (§2.2). Overfitting shows up in the test loss.
- “Logistic training loss reaching 0 is great.” It means the data are separable, and the probabilities are overconfident. Regularize.
- “Standardized coefficients can be read directly.” Convert back to original units — and with collinear features even those can’t be trusted.
- “All softmax weight vectors are meaningful.” Only their differences are.
7. 练习 · Exercises
练习 1(GD on a quadratic). 设 , 对称正定,特征值 。证明 GD 的误差 满足 ;求使 最小的 以及对应的收敛率。
参考答案
,所以 。在 的特征基下各分量独立地乘以 。 只由两端决定,最优时 ,得 ,收敛率 。 时约 0.85, 时约 —— 对应 §2.2 的表格。
练习 2(Choose the noise, get the loss). (a) Show that if , i.e. , the MLE of minimizes . (b) The Huber loss is quadratic for and linear beyond. What noise density does it correspond to, and why is it a reasonable compromise?
参考答案
(a) ; 不影响 的最优解。(b) 密度 :中间像高斯(对小误差高效),尾巴像 Laplace(对离群点稳健)。当你相信”大部分点是高斯噪声,少数点是坏数据”时,它恰好对应这个信念。
练习 3(Newton = IRLS). 证明逻辑回归的 Newton 步 可以写成加权最小二乘 ,其中 ,“工作响应” 。
参考答案
(用未平均的形式),。。每一步都是一个加权最小二乘,权重 是当前预测的方差 —— 拿不准的样本权重大。对任何 canonical GLM,把 换成 即可。
练习 4(Separable ⇒ no MLE). Suppose satisfies for all . Show that is strictly increasing in and is not attained. What changes with an L2 penalty?
参考答案
,每个 ,所以每一项随 严格减小并趋于 0;任何有限的 都有 ,所以下确界 0 取不到。加上 后目标函数强凸、 时趋于 ,存在唯一的有限最优解(§3.5 表格最后一行)。
练习 5(A GLM for waiting times). is a waiting time with density . Write it in exponential-family form and find , , , the canonical response function, and its domain. Why do practitioners usually use a log link instead?
参考答案
:,,,。, ✓。canonical link 要求 ,线性预测器很容易越界,优化时需要额外约束。log link 对任何 都合法,而且系数有”乘法效应”的解释。代价是不再 canonical:梯度多出一个因子,Newton 和 Fisher scoring 不再等价。canonical 是数学上最方便的选择,不一定是建模上最好的选择。
练习 6(Cross-entropy gradient). For logits and label , show . Then explain in one sentence why this means the gradient never vanishes when the model is confidently wrong.
参考答案
,对 求导得 。模型自信地错时,,梯度的第 个分量 ,大小有界且不趋于 0;而 MSE 套在 softmax 外面会多乘一个 softmax 的 Jacobian,在饱和区趋于 0(§4.7 的表格)。
代码相关的练习(“动手改一改”)见 code/lecture01/README.md。
8. 延伸阅读 · Further reading
- CS229 main notes(Ng & Ma),Part I Ch. 1–3:本讲的主要来源。Ch. 3 对 GLM 的推导比本讲更完整(包括 multinomial 的指数族形式)。
- CS229 Autumn 2018 lectures 2–4(YouTube):Andrew Ng 讲 LMS、LWR、逻辑回归、Newton 和 GLM 的原版。
- Hastie, Tibshirani & Friedman, The Elements of Statistical Learning, Ch. 3–4:线性回归的统计性质、共线性、逻辑回归与 LDA 的比较。
- Bishop, Pattern Recognition and Machine Learning, Ch. 3–4:贝叶斯视角下的线性模型、IRLS。
- McCullagh & Nelder, Generalized Linear Models(1989):GLM 的经典教材。
- Soudry, Hoffer, Nacson, Gunasekar & Srebro, “The Implicit Bias of Gradient Descent on Separable Data”, JMLR 2018:§3.5 的定理。
- Boyd & Vandenberghe, Convex Optimization, Ch. 9:GD 与 Newton 的收敛分析、条件数、backtracking line search。
9. 下一讲预告 · Next lecture
Lecture 2:生成式学习、核方法与 SVM(Generative learning, kernels & SVMs)。
本讲的模型都直接对 建模(discriminative)。另一条路是对 建模,再用 Bayes 公式反推(generative):Gaussian discriminant analysis 的后验恰好是一个逻辑回归 —— 这是 §3.2 说的”sigmoid 的第三个来源”;Naive Bayes 在文本分类上用极少的数据就能工作。之后回到 §3.4–3.5 留下的线索:hinge loss + 最大间隔 = SVM;把 换成只通过内积 使用的特征,就得到 kernel trick —— 能在无穷维特征空间里做线性模型。