Lecture 1 · 监督学习与线性模型家族 · Supervised Learning & the Linear Model Family

Machine Learning · Lecture 01。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

对应 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:

  1. 把任何一个监督学习方法拆成 hypothesis class + loss + optimizer 三件事,并说出本讲每个模型的三件事分别是什么。
  2. 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. 也就是说,选损失 = 选噪声假设。
  3. 说清楚 gradient descent 什么时候收敛、收敛多快(α<2/λmax⁡\alpha < 2/\lambda_{\max},步数 ∝κ\propto \kappa),以及 feature scaling、SGD 学习率衰减、Newton 法分别在解决什么问题。
  4. Explain the failure modes: singular X⊤XX^\top X, outliers under squared loss, least squares for classification, logistic regression on separable data, perceptron on non-separable data.
  5. 用指数族(exponential family)推出 GLM 的通用梯度 (hθ(x)−y) x(h_\theta(x) - y)\,x,并解释为什么神经网络的输出层要”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 讲义一致,全课统一)

符号含义
x(i)∈Rdx^{(i)} \in \mathbb{R}^d, y(i)y^{(i)}第 ii 个样本的输入(features)和输出(target / label)
nn训练样本数;{(x(i),y(i))}i=1n\{(x^{(i)}, y^{(i)})\}_{i=1}^n 是训练集
x0=1x_0 = 1截距项(intercept)。加上它之后 θ⊤x=θ0+θ1x1+…\theta^\top x = \theta_0 + \theta_1 x_1 + \dots
X∈Rn×dX \in \mathbb{R}^{n\times d}design matrix,第 ii 行是 x(i)⊤x^{(i)\top};y⃗∈Rn\vec y \in \mathbb{R}^n
hθ(x)h_\theta(x)hypothesis(模型的预测)
J(θ)J(\theta) / ℓ(θ)\ell(\theta)代价函数(要最小化)/ 对数似然(要最大化)

代码的约定:CS229 讲义写”最大化 ℓ(θ)\ell(\theta)“(gradient ascent);代码统一写成”最小化平均负对数似然 J(θ)=−ℓ(θ)/nJ(\theta) = -\ell(\theta)/n“(gradient descent),这是今天所有深度学习框架的写法。最优解相同,梯度差一个负号和 1/n1/n。

0.5 关于数字

讲义里所有实验数字都来自配套代码的实际输出(固定随机种子,同一台机器上重复运行逐字相同)。数据是合成的:我们知道”真相”,所以能检查算法有没有学对;但数字本身不代表任何真实系统。


1. The big picture · 大图景

1.1 Supervised learning in one picture

Andrew Ng 第一节课的例子:给你一堆房子的面积和价格,预测一套新房子的价格。抽象出来:

training set {(x(i),y(i))}i=1n  →learning algorithm  h:X→Y\text{training set } \{(x^{(i)}, y^{(i)})\}_{i=1}^n \;\xrightarrow{\text{learning algorithm}}\; h: \mathcal{X} \to \mathcal{Y}
  • yy 是连续值 → regression(房价);yy 是离散值 → classification(肿瘤良性 / 恶性)。
  • The hypothesis hh is picked from a hypothesis class H\mathcal{H} — for this lecture, functions of the form g(θ⊤x)g(\theta^\top x) for some fixed gg.

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 H\mathcal{H}模型能表示哪些函数?θ⊤x\theta^\top x;σ(θ⊤x)\sigma(\theta^\top x);θ⊤ϕ(x)\theta^\top \phi(x);softmax
Loss / objective J(θ)J(\theta)什么叫”拟合得好”?squared error;log loss;cross-entropy;Poisson NLL
Optimizer怎样找到最好的 θ\theta?closed form;GD;SGD;Newton

这个拆分的价值在于它们可以独立地换。线性回归可以用 normal equation 解,也可以用 SGD 解(换 optimizer,答案不变);同一个 θ⊤x\theta^\top x 可以配平方损失或 L1 损失(换 loss,答案变了);把 xx 换成 ϕ(x)\phi(x) 就换了 hypothesis class,但优化器原样可用。复习时遇到任何一个新方法,先问这三个问题。

1.3 The one thread of this lecture: loss = negative log-likelihood

本讲最重要的一句话:损失函数不是拍脑袋选的,而是”你对数据噪声的假设”的负对数似然。

p(y∣x;θ)⏟你假设的噪声模型  ⟹  θ^=arg⁡max⁡θ∑i=1nlog⁡p(y(i)∣x(i);θ)  =  arg⁡min⁡θ∑i=1n−log⁡p(y(i)∣x(i);θ)⏟loss\underbrace{p(y \mid x; \theta)}_{\text{你假设的噪声模型}} \;\Longrightarrow\; \hat\theta = \arg\max_\theta \sum_{i=1}^n \log p(y^{(i)} \mid x^{(i)}; \theta) \;=\; \arg\min_\theta \underbrace{\sum_{i=1}^n -\log p(y^{(i)} \mid x^{(i)}; \theta)}_{\text{loss}}
你假设 y∣xy \mid x 服从得到的损失得到的模型
Gaussian N(θ⊤x,σ2)\mathcal{N}(\theta^\top x, \sigma^2)squared errorlinear regression
Laplaceabsolute error(L1)least absolute deviations
Bernoulli (σ(θ⊤x))(\sigma(\theta^\top x))log loss / binary cross-entropylogistic regression
Categorical (softmax)cross-entropysoftmax regression
Poisson (eθ⊤x)(e^{\theta^\top x})Poisson NLLPoisson 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

hθ(x)=θ⊤x=∑j=0dθjxj,J(θ)=12∑i=1n(hθ(x(i))−y(i))2h_\theta(x) = \theta^\top x = \sum_{j=0}^{d} \theta_j x_j, \qquad J(\theta) = \frac{1}{2}\sum_{i=1}^{n}\big(h_\theta(x^{(i)}) - y^{(i)}\big)^2

为什么是平方误差?有三个层次的回答:(1) 方便 —— 处处可导、有封闭解;(2) 几何 —— 最小二乘解是 y⃗\vec y 在 XX 的列空间上的正交投影;(3) 概率 —— 它是高斯噪声下的最大似然(§2.4)。第三个才是”真正的”理由,因为它告诉你什么时候不该用平方误差。

2.2 Gradient descent and the LMS rule

对单个样本求导,得到 CS229 讲义里的 LMS(least mean squares)/ Widrow–Hoff 更新:

θj:=θj+α (y(i)−hθ(x(i))) xj(i)\theta_j := \theta_j + \alpha\,\big(y^{(i)} - h_\theta(x^{(i)})\big)\,x^{(i)}_j

直觉:误差 × 输入。预测偏小(误差为正)就沿 xx 的方向把 θ\theta 往上推,误差越大推得越多;预测几乎正确时几乎不动。每个样本都这样做一次叫 stochastic GD;把所有样本的梯度加起来再走一步叫 batch GD。

When does GD converge, and how fast? Write J(θ)=12n∥Xθ−y⃗∥2J(\theta) = \frac{1}{2n}\lVert X\theta - \vec y\rVert^2. Its Hessian is the constant matrix 1nX⊤X\frac{1}{n}X^\top X with eigenvalues λmin⁡≤⋯≤λmax⁡\lambda_{\min} \le \dots \le \lambda_{\max}. Along the kk-th eigenvector, one GD step multiplies the error by (1−αλk)(1 - \alpha\lambda_k). Two consequences:

  • Stability:需要每个方向都 ∣1−αλk∣<1|1 - \alpha\lambda_k| < 1,即 α<2/λmax⁡\alpha < 2/\lambda_{\max}。上限由最陡的方向决定。
  • Speed:最慢的方向(λmin⁡\lambda_{\min})每步只缩小 (1−αλmin⁡)≈1−λmin⁡/λmax⁡(1 - \alpha\lambda_{\min}) \approx 1 - \lambda_{\min}/\lambda_{\max},所以需要的步数 ∝κ=λmax⁡/λmin⁡\propto \kappa = \lambda_{\max}/\lambda_{\min}(条件数,condition number)。

代码 01_linear_regression.py 演示 2 在标准化后的房价数据上(λ=[0.144,1,1.856]\lambda = [0.144, 1, 1.856])扫学习率:

α⋅λmax⁡\alpha \cdot \lambda_{\max}0.10.51.01.856(=2λmax⁡/(λmax⁡+λmin⁡)=2\lambda_{\max}/(\lambda_{\max}+\lambda_{\min}))1.91.992.012.2
收敛步数26165152531502212311发散发散

最快的固定步长是 2/(λmax⁡+λmin⁡)2/(\lambda_{\max} + \lambda_{\min}),它让最快和最慢的方向收缩得一样快。注意 1.99 和 2.01 两行:刚好低于上限时在陡峭方向上来回震荡、很慢;刚好高于上限时发散得也很慢(要 1040 步 JJ 才涨到初始值的 10810^8 倍)。所以训练时”loss 缓慢上升”也可能是学习率太大。

Feature scaling. 演示 3 用同一份数据、三种坐标:

特征κ\kappaGD(步长 1/λmax⁡1/\lambda_{\max})结果
原始(ft², 卧室数)6×1076\times 10^{7}20000 步后 J−J⋆J - J^\star 仍有 126
面积改用千平方英尺2233222 步收敛
标准化(均值 0、标准差 1)12181 步收敛

面积的数量级是 10310^3,截距列是 1:步长被”面积”方向限制得很小,在”截距”方向上几乎走不动。Feature scaling 不改变最优解(只是换坐标),却能让 GD 快几个数量级。这个视角也解释了很多深度学习技巧:BatchNorm / LayerNorm 和 Adam 的逐坐标步长,都可以理解为在线地改善条件数。

SGD and its noise floor. With a constant step size, SGD does not converge to θ⋆\theta^\star: even at the optimum, a single example’s gradient (θ⊤x(i)−y(i))x(i)(\theta^\top x^{(i)} - y^{(i)})x^{(i)} is nonzero, so the iterate keeps getting kicked around. 演示 4(J−J⋆J - J^\star,后 50 个 epoch 的平均):

scheduleafter epoch 1after epoch 100floor (mean of epochs 51–100)
constant α=0.05\alpha = 0.051031749
constant α=0.005\alpha = 0.00510410^40.0040.8
decaying αt=0.05/(1+t/n)\alpha_t = 0.05/(1 + t/n)600.0030.01

大步长:快速到达附近,然后停在高地板上;小步长:地板低,但起步慢;衰减的步长兼顾两者(Robbins–Monro 条件:∑tαt=∞\sum_t \alpha_t = \infty,∑tαt2<∞\sum_t \alpha_t^2 < \infty)。深度学习的 learning-rate schedule(warmup + cosine decay)是这个想法的工程版。

为什么还要 SGD?当 nn 是十亿量级时,batch GD 走一步要看完所有数据。机器学习只需要”足够接近”最优(反正还有统计误差),SGD 看一点数据就走一步,这笔账非常划算。

2.3 The normal equation

令梯度为 0:X⊤(Xθ−y⃗)=0X^\top(X\theta - \vec y) = 0,即

X⊤X θ=X⊤y⃗⟹θ=(X⊤X)−1X⊤y⃗X^\top X\,\theta = X^\top \vec y \qquad\Longrightarrow\qquad \theta = (X^\top X)^{-1}X^\top \vec y

几何意义:残差 y⃗−Xθ\vec y - X\theta 和 XX 的每一列都正交 —— XθX\theta 是 y⃗\vec y 在列空间上的投影。

Normal equationGradient descent
代价O(nd2+d3)O(nd^2 + d^3),一次每步 O(nd)O(nd),步数 ∝κ\propto\kappa
需要调参?不需要学习率、步数
适用dd 不超过几千dd 很大;或者没有封闭解的模型

When X⊤XX^\top X is singular. 两种常见情形(演示 6):

  • 重复 / 共线特征:在房价数据上再加一列”面积(平方米)”,X⊤XX^\top X 的条件数变成 3×10163\times10^{16}。normal equation 没有报错,给出 θ=[379.5,31.24,17.55,86.07]\theta = [379.5, 31.24, 17.55, 86.07] —— 两个”面积”系数之和是对的(117.31),但怎么分完全由舍入误差决定。np.linalg.lstsq 给出最小范数解,平分成 58.65 + 58.65。两者的预测完全一样,但前者的系数没法解读。
  • d>nd > n:10 个样本、30 个特征。训练误差可以是 0,而且有无穷多个 θ\theta 都做到 0;它们在训练集上一模一样,在新数据上的预测却不同(演示中 −0.50 vs 5.83)。lstsq 选范数最小的那个,从 θ=0\theta = 0 出发的 GD 也收敛到同一个(183 步,差 10−1210^{-12}):GD 的每一步都在 X⊤X^\top 的列空间里,永远不会长出零空间的分量。

后一点是第 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 y(i)=θ⊤x(i)+ϵ(i)y^{(i)} = \theta^\top x^{(i)} + \epsilon^{(i)} with ϵ(i)∼iidN(0,σ2)\epsilon^{(i)} \overset{\text{iid}}{\sim} \mathcal{N}(0, \sigma^2). Then

ℓ(θ)=∑i=1nlog⁡12πσexp⁡(−(y(i)−θ⊤x(i))22σ2)=nlog⁡12πσ−12σ2∑i=1n(y(i)−θ⊤x(i))2\ell(\theta) = \sum_{i=1}^n \log \frac{1}{\sqrt{2\pi}\sigma}\exp\Big(-\frac{(y^{(i)} - \theta^\top x^{(i)})^2}{2\sigma^2}\Big) = n\log\frac{1}{\sqrt{2\pi}\sigma} - \frac{1}{2\sigma^2}\sum_{i=1}^n \big(y^{(i)} - \theta^\top x^{(i)}\big)^2

Maximizing ℓ\ell over θ\theta is exactly minimizing J(θ)J(\theta). Note that σ\sigma drops out: it only rescales the curve, it does not move the peak. 演示 5(a) 在 θLS\theta_{LS} 附近随机扰动,三个不同的 σ\sigma 下对数似然都下降,下降量 ∝1/σ2\propto 1/\sigma^2;σ\sigma 的 MLE RSS/n=40.12\sqrt{\text{RSS}/n} = 40.12(真值 40)。

这个视角买到了什么?

(1) 它告诉你平方损失什么时候会出问题。 高斯分布的尾巴很薄:一个 20σ 的残差在高斯假设下”几乎不可能发生”,所以模型宁可把整条直线拉过去也要减小它。演示 5(b),y=2+3x+N(0,0.52)y = 2 + 3x + \mathcal{N}(0, 0.5^2),再加 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 噪声的尾巴厚,它的负对数似然是 ∣r∣|r|,只线性增长,几个离群点拉不动。换噪声假设 = 换损失:Huber loss、Student-t 回归都是这个思路。

(2) 它给你不确定性。 高斯假设下 Cov(θ^)=σ2(X⊤X)−1\text{Cov}(\hat\theta) = \sigma^2(X^\top X)^{-1}。演示 1 用这个公式给房价系数算 95% 置信区间,结果很有教育意义:

系数估计95% CI真值
intercept51.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 xx. Replace xx by a feature map ϕ(x)\phi(x) and every tool above works unchanged. 代码 02_features_lwr.py 在 y=sin⁡(2πx)+N(0,0.32)y = \sin(2\pi x) + \mathcal{N}(0, 0.3^2) 上(只有 15 个训练点)用多项式特征 ϕ(x)=[1,x,…,xk]\phi(x) = [1, x, \dots, x^k]:

次数 kk0135791214
train MSE0.3810.2610.0360.0350.0320.0090.0030.000
test MSE0.5920.3420.1590.1781.1425.98022×1092\times10^{9}
∥θ∥\lVert\theta\rVert0.050.574.33.72772610410^49×1069\times10^{6}

训练误差随 kk 单调下降(嵌套的模型族,必然如此),测试误差先降后升:k≤1k \le 1 underfit,k≥7k \ge 7 overfit。过拟合时 ∥θ∥\lVert\theta\rVert 爆炸:曲线靠巨大的、正负交替的系数在数据点之间剧烈摆动 —— 这就是”惩罚 ∥θ∥\lVert\theta\rVert“(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 xx:

min⁡θ∑iw(i)(y(i)−θ⊤x(i))2,w(i)=exp⁡(−(x(i)−x)22τ2)\min_\theta \sum_i w^{(i)}\big(y^{(i)} - \theta^\top x^{(i)}\big)^2, \qquad w^{(i)} = \exp\Big(-\frac{(x^{(i)} - x)^2}{2\tau^2}\Big)

The bandwidth τ\tau plays the same role as the polynomial degree (50 个训练点):

τ\tau0.0030.010.030.060.10.20.510
train MSE0.0030.0180.0580.0770.0980.1720.2880.300
test MSE9.141.360.1110.0990.1070.1700.2760.287
有效样本数1.32.35.510.316.328.846.350

Small τ\tau: each prediction effectively uses one or two points (effective sample size (∑w)2/∑w2≈1(\sum w)^2/\sum w^2 \approx 1) — overfitting. Large τ\tau: 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 k+1k+1 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。代价是 τ\tau 太小时局部直线外推不稳定:τ=0.01\tau = 0.01 在 x=1x = 1 处预测出了 11.4。
  • A modern echo: “weight training examples by similarity to the query, then average” is exactly the shape of attention, y^=∑isoftmax(q⊤ki) vi\hat y = \sum_i \text{softmax}(q^\top k_i)\,v_i — attention is a learned Nadaraya–Watson smoother.

3. Classification & logistic regression · 分类与逻辑回归

3.1 Why not just use least squares?

把 y∈{0,1}y \in \{0, 1\} 当实数做线性回归、预测 ≥0.5\ge 0.5 判为 1,看起来也能用。Andrew Ng 的反例:往训练集里加一些特别大、标签毫无争议的恶性肿瘤。代码 03_logistic_newton.py 演示 1(准确率在 60 个原始点上算):

加入的大肿瘤个数05102040
least squares 边界(cm)2.893.273.403.473.49
least squares 准确率0.9500.9170.9170.8830.867
logistic 边界(cm)2.892.892.892.892.89

Least squares wants every malignant example to have θ⊤x\theta^\top x 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?

hθ(x)=g(θ⊤x)=11+e−θ⊤x,g′(z)=g(z) (1−g(z))h_\theta(x) = g(\theta^\top x) = \frac{1}{1 + e^{-\theta^\top x}}, \qquad g'(z) = g(z)\,(1 - g(z))

Three increasingly deep reasons for this particular squashing function:

  1. It maps R\mathbb{R} to (0,1)(0, 1), so the output can be a probability. (Many functions do this.)
  2. The log-odds is linear: log⁡P(y=1∣x)P(y=0∣x)=θ⊤x\log\frac{P(y=1\mid x)}{P(y=0\mid x)} = \theta^\top x. Each θj\theta_j is “how much one unit of xjx_j multiplies the odds” — the standard interpretation in medicine and economics.
  3. 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

P(y∣x;θ)=hθ(x)y (1−hθ(x))1−yP(y \mid x; \theta) = h_\theta(x)^y\,(1 - h_\theta(x))^{1-y},所以

ℓ(θ)=∑i=1ny(i)log⁡hθ(x(i))+(1−y(i))log⁡(1−hθ(x(i))),∇θ ℓ=∑i=1n(y(i)−hθ(x(i))) x(i)\ell(\theta) = \sum_{i=1}^n y^{(i)}\log h_\theta(x^{(i)}) + (1 - y^{(i)})\log\big(1 - h_\theta(x^{(i)})\big), \qquad \nabla_\theta\,\ell = \sum_{i=1}^n \big(y^{(i)} - h_\theta(x^{(i)})\big)\,x^{(i)}

梯度和 LMS 长得一模一样:误差 × 输入,只是 hθh_\theta 从 θ⊤x\theta^\top x 变成了 g(θ⊤x)g(\theta^\top x)。CS229 讲义说”Is this coincidence, or is there a deeper reason?” —— §4 回答。另外 Hessian 是 −∑ih(1−h) x(i)x(i)⊤-\sum_i h(1-h)\,x^{(i)}x^{(i)\top},半负定,所以 ℓ\ell 是凹的:没有局部最优。

3.4 The margin view of classification losses

Let y′=2y−1∈{−1,+1}y' = 2y - 1 \in \{-1, +1\} and define the margin t=y′ θ⊤xt = y'\,\theta^\top x (t>0t > 0 means correct, larger means “more confidently correct”). Every loss below is a function of tt alone:

losst=−2t=-2t=−1t=-1t=0t=0t=1t=1t=2t=2t=4t=4
0-1:1{t≤0}1\{t \le 0\}111000
logistic:log⁡(1+e−t)\log(1 + e^{-t})2.131.310.690.310.130.02
hinge(SVM):max⁡(0,1−t)\max(0, 1 - t)321000
squared:(1−t)2(1 - t)^2941019

This table explains §3.1 completely: squared loss rises again for t>1t > 1, 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

如果某个 θ\theta 把训练集完全分开,那么把它放大 cc 倍会让每个 margin 都放大 cc 倍,log loss 严格下降。最优点在无穷远处。演示 3(两团相距很远的点,先用感知机确认线性可分):

GD 步数10100100010410^410510^5
∥θ∥\lVert\theta\rVert(λ=0\lambda = 0)0.612.054.767.9511.90
训练 loss(λ=0\lambda = 0)0.300.0900.0130.00190.00028
方向变化(度)–36.27.291.340.67
∥θ∥\lVert\theta\rVert(λ=0.01\lambda = 0.01)0.601.933.063.073.07

Three things to notice:

  • Without regularization, ∥θ∥\lVert\theta\rVert grows like log⁡t\log t forever and the predicted probabilities drift to 0/1 — the model becomes overconfident and its “probabilities” stop meaning anything.
  • But the direction θ/∥θ∥\theta/\lVert\theta\rVert 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.py demo 4 checks this on exactly this dataset: after 10610^6 GD steps the direction is 0.066°0.066° 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 LogisticRegression uses C=1).

3.6 The perceptron (a historical detour)

把 sigmoid 换成硬阈值 g(z)=1{z≥0}g(z) = 1\{z \ge 0\},更新规则形式不变:θ:=θ+α (y(i)−hθ(x(i))) x(i)\theta := \theta + \alpha\,(y^{(i)} - h_\theta(x^{(i)}))\,x^{(i)} —— 分对了不动,分错了推一下。演示 4:

  • 可分数据:4 个 epoch 内停下,总共犯错 10 次。Novikoff 定理保证犯错次数 ≤(R/γ)2\le (R/\gamma)^2(RR 是数据半径,γ\gamma 是某个分隔面的间隔);用正则化逻辑回归的方向算出的上界是 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 f(θ)=∇ℓ(θ)f(\theta) = \nabla\ell(\theta), Newton’s method repeatedly jumps to the zero of the local linear approximation — equivalently, to the optimum of the local quadratic approximation of ℓ\ell:

θ:=θ−H−1∇θ ℓ(θ),Hjk=∂2ℓ∂θj ∂θk\theta := \theta - H^{-1}\nabla_\theta\,\ell(\theta), \qquad H_{jk} = \frac{\partial^2 \ell}{\partial\theta_j\,\partial\theta_k}

演示 2 在两团重叠的高斯点上比较:

目标精度 ∥∇J∥∞<\lVert\nabla J\rVert_\infty <10−210^{-2}10−410^{-4}10−610^{-6}10−810^{-8}10−1010^{-10}
GD(步长 1/L1/L)步数52257479701923
Newton 步数35667

Newton 的梯度序列是 0.44→0.12→0.038→0.008→6×10−4→4×10−6→2×10−10→10−160.44 \to 0.12 \to 0.038 \to 0.008 \to 6\times10^{-4} \to 4\times10^{-6} \to 2\times10^{-10} \to 10^{-16}:接近最优点后每一步把误差平方(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:每步要构造并求解 d×dd\times d 的系统,O(nd2+d3)O(nd^2 + d^3)。dd 在几千以内(GLM、经典统计)时 Newton 是首选 —— R 的 glm 和 statsmodels 就用它(对逻辑回归叫 IRLS,iteratively reweighted least squares,见练习 3);d=109d = 10^9 的神经网络完全不可行,所以深度学习用一阶方法,再用 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 (y−hθ(x)) x(y - h_\theta(x))\,x, and the table in §1.3 suggests more. Is there one recipe that produces all of them — and tells us what to do when yy is a count, a category, or a positive duration? Yes: pick p(y∣x)p(y \mid x) from the exponential family and make its natural parameter linear in xx.

4.2 The exponential family

p(y;η)=b(y) exp⁡(η⊤T(y)−a(η))p(y; \eta) = b(y)\,\exp\big(\eta^\top T(y) - a(\eta)\big)

η\eta 是 natural parameter,T(y)T(y) 是 sufficient statistic(本讲都是 T(y)=yT(y) = y),a(η)a(\eta) 是 log-partition function:它的唯一作用是让概率加起来等于 1,a(η)=log⁡∫b(y) eη⊤T(y) dya(\eta) = \log\int b(y)\,e^{\eta^\top T(y)}\,dy。三个例子(推导就是把熟悉的密度函数改写成上面的形状):

分布改写η\etaa(η)a(\eta)a′(η)a'(\eta) = 均值
Bernoulli(ϕ)(\phi)exp⁡(ylog⁡ϕ1−ϕ+log⁡(1−ϕ))\exp\big(y\log\frac{\phi}{1-\phi} + \log(1-\phi)\big)log⁡ϕ1−ϕ\log\frac{\phi}{1-\phi}log⁡(1+eη)\log(1 + e^\eta)σ(η)\sigma(\eta)
Gaussian(μ,1)(\mu, 1)12πe−y2/2exp⁡(μy−μ22)\frac{1}{\sqrt{2\pi}}e^{-y^2/2}\exp\big(\mu y - \frac{\mu^2}{2}\big)μ\muη2/2\eta^2/2η\eta
Poisson(λ)(\lambda)1y!exp⁡(ylog⁡λ−λ)\frac{1}{y!}\exp\big(y\log\lambda - \lambda\big)log⁡λ\log\lambdaeηe^\etaeηe^\eta

(多项分布 / categorical 也在指数族里,T(y)T(y) 是 one-hot 向量,结果见 §4.6。)

4.3 The key property: a′a' is the mean, a′′a'' is the variance

ddηa(η)=E[T(y)],d2dη2a(η)=Var[T(y)]\frac{d}{d\eta}a(\eta) = \mathbb{E}[T(y)], \qquad \frac{d^2}{d\eta^2}a(\eta) = \text{Var}[T(y)]

代码 04_glm_softmax.py 演示 1 用数值微分和 20 万个样本验证了三个分布、三个 η\eta 值,例如 Bernoulli、η=−1\eta = -1:a′=0.2689a' = 0.2689 vs 样本均值 0.2694,a′′=0.1966a'' = 0.1966 vs 样本方差 0.1968。两个推论撑起了整个 GLM 理论:

  1. Convexity for free. a′′=Var≥0a'' = \text{Var} \ge 0, so aa is convex, so the NLL a(η)−yηa(\eta) - y\eta is convex in η\eta, and with η=θ⊤x\eta = \theta^\top x it is convex in θ\theta. Every canonical GLM is a convex problem: no local optima.
  2. The response function is a′a'. The map from natural parameter to mean is a′a': 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 讲义的三个假设(其实是三个设计决定):

  1. y∣x;θ∼ExponentialFamily(η)y \mid x; \theta \sim \text{ExponentialFamily}(\eta) —— 按 yy 的类型选分布;
  2. 预测的目标是 hθ(x)=E[T(y)∣x]h_\theta(x) = \mathbb{E}[T(y) \mid x];
  3. η=θ⊤x\eta = \theta^\top x —— natural parameter 是输入的线性函数(“linear” 就在这里)。

于是 hθ(x)=a′(θ⊤x)h_\theta(x) = a'(\theta^\top x),a′a' 叫 canonical response function,它的逆叫 canonical link function。对单个样本的对数似然求导只要一行:

∇θ[η y−a(η)]η=θ⊤x=(y−a′(θ⊤x)) x=(y−hθ(x)) x,∇θ2=−a′′(θ⊤x) x x⊤\nabla_\theta \big[\eta\,y - a(\eta)\big]_{\eta = \theta^\top x} = \big(y - a'(\theta^\top x)\big)\,x = \big(y - h_\theta(x)\big)\,x, \qquad \nabla^2_\theta = -a''(\theta^\top x)\,x\,x^\top

That’s the “deeper reason” behind §3.3: every canonical GLM has gradient (target − prediction) × input, and its Hessian is −X⊤diag(Var[y∣x]) X-X^\top \text{diag}(\text{Var}[y\mid x])\,X. So one Newton solver fits all of them. 演示 2 用同一个函数 fit_glm_newton(X, y, family):

family数据Newton 步数对照
gaussian房价1与 lstsq 差 5×10−135\times10^{-13}(a′′≡1a'' \equiv 1,一步就是 normal equation)
bernoulli两团点6与专门写的逻辑回归逐位相同
poisson访问量5θ^=[0.320,1.090,−0.727]\hat\theta = [0.320, 1.090, -0.727],真值 [0.3,1.1,−0.7][0.3, 1.1, -0.7]

Poisson 的第一步被 backtracking line search 缩短到 1/4。不做 line search 的纯 Newton 第一步就把梯度从 9 推到 10510^5 量级(eηe^\eta 涨得太快,冲过头了),再花十来步才爬回来,总共 15 步。这就是 R 的 glm(family=...) 和 statsmodels 的工作方式:一个 IRLS 求解器 + 一个 family 参数。

4.5 Example: Poisson regression for counts

yy 是计数(每天的访问量)时,用 Poisson + log link:log⁡E[y∣x]=θ⊤x\log\mathbb{E}[y \mid x] = \theta^\top x。演示 3 的真实模型是 λ=exp⁡(0.3+1.1⋅budget−0.7⋅weekend)\lambda = \exp(0.3 + 1.1\cdot\text{budget} - 0.7\cdot\text{weekend}),训练 300 天:

模型test MSE和真实 λ\lambda 的 MSE负的预测
linear regression9.923.808.2%
Poisson regression6.370.0770%
预算(工作日)00.51.01.52.02.5
真实 λ\lambda1.352.344.067.0312.1821.12
linear−0.202.875.939.0012.0615.13
Poisson1.472.524.307.3512.5521.45

Three distinct failures of the linear model, each fixed by choosing the right distribution:

  • Range:线性模型预测出负的访问量;eθ⊤xe^{\theta^\top x} 永远为正。
  • Shape:真实关系是乘法的(预算 +1 → 访问量 ×e1.07≈2.9e^{1.07} \approx 2.9)。直线去近似凸的指数曲线,只能两端低估、中间高估。这是 model misspecification,数据再多也消除不了(“和真实 λ\lambda 的 MSE”一列)。
  • Noise:Poisson 的方差等于均值,λ\lambda 大的日子噪声也大(按 λ\lambda 分组,均值 1.45 / 3.25 / 7.26 / 14.69 对应方差 1.63 / 3.83 / 9.26 / 24.72)。最小二乘假设方差处处相同;Poisson 的 Newton 步里权重是 a′′(η)=λa''(\eta) = \lambda,自动考虑了哪些点噪声大。(每组的方差略大于均值,是因为组内的 λ\lambda 本身也在变。)

The practical rule: first ask what type of quantity yy is — real, binary, categorical, count, positive continuous — then pick the matching distribution.

4.6 Softmax regression

y∈{1,…,K}y \in \{1, \dots, K\}。把 categorical 分布写成指数族,canonical response function 就是 softmax:

p(y=k∣x;θ)=exp⁡(θk⊤x)∑j=1Kexp⁡(θj⊤x),∇θkℓ=∑i=1n(1{y(i)=k}−p(y=k∣x(i))) x(i)p(y = k \mid x; \theta) = \frac{\exp(\theta_k^\top x)}{\sum_{j=1}^K \exp(\theta_j^\top x)}, \qquad \nabla_{\theta_k}\ell = \sum_{i=1}^n \big(1\{y^{(i)} = k\} - p(y = k \mid x^{(i)})\big)\,x^{(i)}

又是 (target − prediction) × input。负对数似然就是 cross-entropy。演示 4 的三个要点:

  • 参数冗余(over-parameterization):softmax 只依赖 logits 之间的差。给所有 θk\theta_k 加同一个向量 cc,预测概率的变化是 7×10−167\times10^{-16}。CS229 讲义固定 θK=0\theta_K = 0 来去掉冗余;实践中保留全部 KK 个(对称、好写),由正则化或”从 0 出发的 GD”选出一个解(GD 的梯度各列之和恒为 0,所以 ∑kθk\sum_k\theta_k 一直是 0)。
  • K=2K = 2 就是逻辑回归:ez1ez0+ez1=σ(z1−z0)\frac{e^{z_1}}{e^{z_0} + e^{z_1}} = \sigma(z_1 - z_0)。演示中 softmax 的 θ1−θ0\theta_1 - \theta_0 和逻辑回归的 θ\theta 一致到第 4 位小数,预测概率最大差 5×10−105\times10^{-10}。
  • 三个高斯团上训练准确率 0.883、测试 0.870(三团有重叠,线性边界只能做到这样)。

4.7 GLMs inside every neural network · 输出层的”配对”

A deep network is a learned feature map ϕW(x)\phi_W(x) followed by a GLM head: η=θ⊤ϕW(x)\eta = \theta^\top\phi_W(x), then a′(η)a'(\eta), trained with the NLL. By §4.4 the gradient at the logits is simply a′(η)−y=y^−ya'(\eta) - y = \hat y - y, which is why backprop starts from such a clean signal (Lecture 4).

如果激活和损失不配对会怎样?演示 5 比较一个 y=1y = 1 的样本在 logit zz 上的梯度:

zz−10−5−2025
sigmoid + BCE:σ(z)−y\sigma(z) - y−1.00−0.99−0.88−0.50−0.12−0.007
sigmoid + MSE:(σ−y) σ(1−σ)(\sigma - y)\,\sigma(1-\sigma)−4.5×10−5-4.5\times10^{-5}−6.6×10−3-6.6\times10^{-3}−0.092−0.125−0.013−4.5×10−5-4.5\times10^{-5}

Canonical 配对下,错得越离谱(z=−10z = -10,模型几乎确定 y=0y = 0),纠错的梯度越大;sigmoid + MSE 在饱和区梯度几乎为 0,错得最离谱时反而学不动。所以标准搭配是:

yy 的类型输出激活损失PyTorch
实数identityMSEMSELoss
二分类sigmoidbinary cross-entropyBCEWithLogitsLoss
多分类softmaxcross-entropyCrossEntropyLoss
计数expPoisson NLLPoissonNLLLoss

PyTorch 让 BCEWithLogitsLoss、CrossEntropyLoss 直接吃 logits,既是为了这个干净的梯度,也是为了数值稳定(log-sum-exp 技巧)。


5. 小结 · Summary

模型噪声假设 p(y∣x)p(y\mid x)hθ(x)h_\theta(x)损失梯度(单样本,最小化方向)常用优化器
Linear regressionN(θ⊤x,σ2)\mathcal{N}(\theta^\top x, \sigma^2)θ⊤x\theta^\top xsquared(h−y) x(h - y)\,xnormal eq. / GD / SGD
Logistic regressionBernoulliσ(θ⊤x)\sigma(\theta^\top x)log loss(h−y) x(h - y)\,xNewton (IRLS) / GD
Softmax regressionCategoricalsoftmax(Θ⊤x)\text{softmax}(\Theta^\top x)cross-entropyx (h−ey)⊤x\,(h - e_y)^\topGD / L-BFGS
Poisson regressionPoissoneθ⊤xe^{\theta^\top x}Poisson NLL(h−y) x(h - y)\,xNewton + line search
Perceptron(无概率模型)1{θ⊤x≥0}1\{\theta^\top x \ge 0\}–(h−y) x(h - y)\,x(仅在分错时)逐样本更新

Five takeaways:

  1. 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).
  2. GD speed is governed by conditioning: α<2/λmax⁡\alpha < 2/\lambda_{\max}, steps ∝κ\propto\kappa. Feature scaling, normalization layers and Newton’s method all attack κ\kappa.
  3. Uniqueness is not guaranteed: singular X⊤XX^\top X, d>nd > n, separable data, softmax redundancy. When the data don’t pin down θ\theta, the optimizer or the regularizer does — the theme of Lecture 3.
  4. Canonical GLMs share one gradient, (hθ(x)−y) x(h_\theta(x) - y)\,x, and one convex Newton solver. This is why sigmoid pairs with BCE and softmax with CE.
  5. 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 θ\theta; ϕ(x)\phi(x) can be any nonlinear map.
  • “The normal equation didn’t throw, so the answer is fine.” Near-singular X⊤XX^\top X gives coefficients chosen by rounding error. Use lstsq and check the condition number.
  • “Training loss creeping up means overfitting.” Rising training loss is more likely a learning rate just above 2/λmax⁡2/\lambda_{\max} (§2.2). Overfitting shows up in the test loss.
  • “Logistic training loss reaching 0 is great.” It means the data are separable, ∥θ∥→∞\lVert\theta\rVert\to\infty 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 KK softmax weight vectors are meaningful.” Only their differences are.

7. 练习 · Exercises

练习 1(GD on a quadratic). 设 J(θ)=12(θ−θ⋆)⊤A(θ−θ⋆)J(\theta) = \frac{1}{2}(\theta - \theta^\star)^\top A(\theta - \theta^\star),AA 对称正定,特征值 λmin⁡,…,λmax⁡\lambda_{\min}, \dots, \lambda_{\max}。证明 GD 的误差 et=θt−θ⋆e_t = \theta_t - \theta^\star 满足 et+1=(I−αA)ete_{t+1} = (I - \alpha A)e_t;求使 max⁡k∣1−αλk∣\max_k |1 - \alpha\lambda_k| 最小的 α\alpha 以及对应的收敛率。

参考答案

∇J=A(θ−θ⋆)\nabla J = A(\theta - \theta^\star),所以 et+1=et−αAete_{t+1} = e_t - \alpha A e_t。在 AA 的特征基下各分量独立地乘以 1−αλk1 - \alpha\lambda_k。max⁡k∣1−αλk∣\max_k|1 - \alpha\lambda_k| 只由两端决定,最优时 1−αλmin⁡=−(1−αλmax⁡)1 - \alpha\lambda_{\min} = -(1 - \alpha\lambda_{\max}),得 α⋆=2/(λmax⁡+λmin⁡)\alpha^\star = 2/(\lambda_{\max} + \lambda_{\min}),收敛率 κ−1κ+1\frac{\kappa - 1}{\kappa + 1}。κ=12\kappa = 12 时约 0.85,κ=6×107\kappa = 6\times10^7 时约 1−3×10−81 - 3\times10^{-8} —— 对应 §2.2 的表格。

练习 2(Choose the noise, get the loss). (a) Show that if ϵ∼Laplace(0,b)\epsilon \sim \text{Laplace}(0, b), i.e. p(ϵ)=12be−∣ϵ∣/bp(\epsilon) = \frac{1}{2b}e^{-|\epsilon|/b}, the MLE of θ\theta minimizes ∑i∣y(i)−θ⊤x(i)∣\sum_i |y^{(i)} - \theta^\top x^{(i)}|. (b) The Huber loss is quadratic for ∣r∣≤δ|r| \le \delta and linear beyond. What noise density does it correspond to, and why is it a reasonable compromise?

参考答案

(a) ℓ(θ)=−nlog⁡(2b)−1b∑i∣y(i)−θ⊤x(i)∣\ell(\theta) = -n\log(2b) - \frac{1}{b}\sum_i|y^{(i)} - \theta^\top x^{(i)}|;bb 不影响 θ\theta 的最优解。(b) 密度 ∝exp⁡(−Huberδ(r))\propto \exp(-\text{Huber}_\delta(r)):中间像高斯(对小误差高效),尾巴像 Laplace(对离群点稳健)。当你相信”大部分点是高斯噪声,少数点是坏数据”时,它恰好对应这个信念。

练习 3(Newton = IRLS). 证明逻辑回归的 Newton 步 θnew=θ−H−1∇J\theta_{\text{new}} = \theta - H^{-1}\nabla J 可以写成加权最小二乘 θnew=(X⊤WX)−1X⊤Wz\theta_{\text{new}} = (X^\top WX)^{-1}X^\top W z,其中 W=diag(hi(1−hi))W = \text{diag}(h_i(1 - h_i)),“工作响应” z=Xθ+W−1(y−h)z = X\theta + W^{-1}(y - h)。

参考答案

(用未平均的形式)∇J=X⊤(h−y)\nabla J = X^\top(h - y),H=X⊤WXH = X^\top WX。θ−(X⊤WX)−1X⊤(h−y)=(X⊤WX)−1[X⊤WXθ+X⊤(y−h)]=(X⊤WX)−1X⊤W[Xθ+W−1(y−h)]\theta - (X^\top WX)^{-1}X^\top(h - y) = (X^\top WX)^{-1}\big[X^\top WX\theta + X^\top(y - h)\big] = (X^\top WX)^{-1}X^\top W\big[X\theta + W^{-1}(y - h)\big]。每一步都是一个加权最小二乘,权重 h(1−h)h(1-h) 是当前预测的方差 —— 拿不准的样本权重大。对任何 canonical GLM,把 WW 换成 a′′(η)a''(\eta) 即可。

练习 4(Separable ⇒ no MLE). Suppose θ0\theta_0 satisfies y′(i)θ0⊤x(i)>0y'^{(i)}\theta_0^\top x^{(i)} > 0 for all ii. Show that ℓ(c θ0)\ell(c\,\theta_0) is strictly increasing in c>0c > 0 and sup⁡θℓ(θ)=0\sup_\theta\ell(\theta) = 0 is not attained. What changes with an L2 penalty?

参考答案

−ℓ(cθ0)=∑ilog⁡(1+e−c ti)-\ell(c\theta_0) = \sum_i\log(1 + e^{-c\,t_i}),每个 ti>0t_i > 0,所以每一项随 cc 严格减小并趋于 0;任何有限的 θ\theta 都有 −ℓ>0-\ell > 0,所以下确界 0 取不到。加上 λ2∥θ∥2\frac{\lambda}{2}\lVert\theta\rVert^2 后目标函数强凸、∥θ∥→∞\lVert\theta\rVert\to\infty 时趋于 ∞\infty,存在唯一的有限最优解(§3.5 表格最后一行)。

练习 5(A GLM for waiting times). y>0y > 0 is a waiting time with density p(y;λ)=λe−λyp(y;\lambda) = \lambda e^{-\lambda y}. Write it in exponential-family form and find η\eta, T(y)T(y), a(η)a(\eta), the canonical response function, and its domain. Why do practitioners usually use a log link instead?

参考答案

p=exp⁡(−λy+log⁡λ)p = \exp(-\lambda y + \log\lambda):η=−λ\eta = -\lambda,T(y)=yT(y) = y,a(η)=−log⁡(−η)a(\eta) = -\log(-\eta),b(y)=1b(y) = 1。a′(η)=−1/η=1/λ=E[y]a'(\eta) = -1/\eta = 1/\lambda = \mathbb{E}[y],a′′(η)=1/η2=Var[y]a''(\eta) = 1/\eta^2 = \text{Var}[y] ✓。canonical link 要求 η=θ⊤x<0\eta = \theta^\top x < 0,线性预测器很容易越界,优化时需要额外约束。log link log⁡E[y]=θ⊤x\log\mathbb{E}[y] = \theta^\top x 对任何 θ\theta 都合法,而且系数有”乘法效应”的解释。代价是不再 canonical:梯度多出一个因子,Newton 和 Fisher scoring 不再等价。canonical 是数学上最方便的选择,不一定是建模上最好的选择。

练习 6(Cross-entropy gradient). For logits z∈RKz \in \mathbb{R}^K and label yy, show ∂∂z[−log⁡softmax(z)y]=softmax(z)−ey\frac{\partial}{\partial z}\big[-\log\text{softmax}(z)_y\big] = \text{softmax}(z) - e_y. Then explain in one sentence why this means the gradient never vanishes when the model is confidently wrong.

参考答案

−log⁡softmax(z)y=−zy+log⁡∑jezj-\log\text{softmax}(z)_y = -z_y + \log\sum_j e^{z_j},对 zkz_k 求导得 −1{k=y}+softmax(z)k-1\{k = y\} + \text{softmax}(z)_k。模型自信地错时,softmax(z)y≈0\text{softmax}(z)_y \approx 0,梯度的第 yy 个分量 ≈−1\approx -1,大小有界且不趋于 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)。

本讲的模型都直接对 p(y∣x)p(y \mid x) 建模(discriminative)。另一条路是对 p(x∣y)p(x \mid y) 建模,再用 Bayes 公式反推(generative):Gaussian discriminant analysis 的后验恰好是一个逻辑回归 —— 这是 §3.2 说的”sigmoid 的第三个来源”;Naive Bayes 在文本分类上用极少的数据就能工作。之后回到 §3.4–3.5 留下的线索:hinge loss + 最大间隔 = SVM;把 ϕ(x)\phi(x) 换成只通过内积 ⟨ϕ(x),ϕ(z)⟩=K(x,z)\langle\phi(x), \phi(z)\rangle = K(x, z) 使用的特征,就得到 kernel trick —— 能在无穷维特征空间里做线性模型。

← 返回课程目录