Lecture 2 · 生成式学习、核方法与 SVM · Generative Learning, Kernels & SVMs

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

课程源码 ZIP ↓

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

本篇目录

对应 Maps to:Stanford CS229 Autumn 2018(Andrew Ng)Lectures 5–7(GDA & Naive Bayes; Support Vector Machines; Kernels),以及 CS229 main notes(Andrew Ng & Tengyu Ma)Part I, Chapters 4–6。 CS229 当前学期(Summer 2026)的课表需要 Stanford 登录才能看,所以本讲以公开的讲义和 2018 年的录像为准;这部分内容多年来基本没变。 配套代码 Code:code/lecture02/(numpy;2 个工具模块 + 4 个脚本。04_svm_smo.py 约 10 秒,其余都在 2 秒以内;复用第 1 讲的 linear_models.py 和 datasets.py) 预计阅读时间:2.5–3 小时(含运行代码)。这是一份复习讲义:假设你见过 GDA、Naive Bayes、核函数和 SVM,重点放在”为什么”和”它们之间的联系”上。


0. 本讲导航 · How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. 说清楚 discriminative 和 generative 两条路各自对什么建模、各自付出什么代价,并用 GDA vs logistic regression 的例子解释”更省数据”和”更稳健”为什么不可兼得。
  2. Derive in one line why GDA’s posterior is exactly a logistic function — the “third origin of the sigmoid” promised in Lecture 1 §3.2 — and why the converse is false.
  3. 解释 Naive Bayes 的条件独立假设、两种 event model、Laplace smoothing;说清楚”假设错了为什么还能分类”以及”错在哪里”(过度自信的概率)。
  4. Explain the kernel trick as a consequence of two facts — the algorithm only touches inner products and the solution lies in the span of the data — and decide when a function is a valid kernel.
  5. 从”最大化几何间隔”出发得到 SVM,读懂对偶问题和 KKT 条件给出的结论(support vectors、只用内积、soft margin = hinge + L2、SMO 为什么一次改两个变量),并兑现第 1 讲 §3.5 的承诺:可分数据上 GD 的方向收敛到 max-margin 方向。

0.2 默认你已经会的 / 本讲会省略的

默认你已经会 Assumed本讲省略或只给结论 Skipped
多元高斯分布、Bayes 公式GDA 的 MLE 推导(直接给封闭解)
第 1 讲:逻辑回归、Newton 法、可分数据上 MLE 不存在Lagrange 对偶的一般理论(只给 SVM 的对偶问题和 KKT 条件的结论)
特征映射 ϕ(x)\phi(x)、ridge 的封闭解Mercer 定理的证明、RKHS 的严格定义
凸优化的基本概念(约束、可行域)SMO 的完整推导(只讲两变量子问题的思想);SVM 的泛化界的证明

0.3 本讲地图 Map

§1  Discriminative vs generative:对 p(y|x) 建模,还是对 p(x|y)p(y) 建模
§2  GDA:封闭解 / 后验恰好是逻辑回归 / 更省数据 vs 更稳健                 ← 代码 01
§3  Naive Bayes:条件独立 / 两种 event model / Laplace smoothing / 过度自信  ← 代码 02
§4  Kernel methods:θ 在数据张成的空间里 / kernel trick / 合法的核 / kernel ridge  ← 代码 03
§5  SVM:间隔 / 对偶与 KKT / support vectors / soft margin / SMO / GD 的隐式偏置  ← 代码 04
§6–10 小结、常见误区、练习、延伸阅读、下一讲预告

0.4 Notation(新增的符号)

符号含义
ϕ=p(y=1)\phi = p(y = 1);μ0,μ1\mu_0, \mu_1;Σ\SigmaGDA 的参数:先验、两类的均值、共享的协方差
Δ=(μ1−μ0)⊤Σ−1(μ1−μ0)\Delta = \sqrt{(\mu_1 - \mu_0)^\top\Sigma^{-1}(\mu_1 - \mu_0)}两类之间的马氏距离(Mahalanobis distance),决定分类难度
VV;xwx_w词表大小;词 ww 在一封邮件里出现的次数
ϕ(x)\phi(x);K(x,z)=⟨ϕ(x),ϕ(z)⟩K(x, z) = \langle\phi(x), \phi(z)\rangle特征映射;核函数。Kij=K(x(i),x(j))K_{ij} = K(x^{(i)}, x^{(j)}) 是核矩阵(Gram matrix)
y∈{−1,+1}y \in \{-1, +1\};(w,b)(w, b)SVM 的标签约定和参数(截距 bb 单独写,不并进 xx)
αi\alpha_i;CCSVM 对偶变量(每个样本一个);soft margin 的惩罚系数

第 1 讲把截距当作 xx 的一个分量(x0=1x_0 = 1);SVM 按 CS229 讲义的写法把 bb 单独拿出来。这个看似无关紧要的差别在 §5.7 会变得重要。

0.5 关于数字

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


1. Discriminative vs generative · 判别式与生成式

1.1 Two ways to build a classifier

第 1 讲的模型都直接对 p(y∣x)p(y \mid x) 建模:给定 xx,yy 是什么分布。这叫 discriminative(判别式)学习。另一条路是对数据是怎么产生的建模:先抽一个类别 y∼p(y)y \sim p(y),再从这一类的分布里抽 x∼p(x∣y)x \sim p(x \mid y)。这叫 generative(生成式)学习。预测时用 Bayes 公式反推:

p(y∣x)=p(x∣y) p(y)p(x),p(x)=∑cp(x∣y=c) p(y=c)p(y \mid x) = \frac{p(x \mid y)\,p(y)}{p(x)}, \qquad p(x) = \sum_{c} p(x \mid y = c)\,p(y = c)

分类只需要 arg⁡max⁡yp(x∣y) p(y)\arg\max_y p(x \mid y)\,p(y),分母 p(x)p(x) 对所有类别相同,可以不算。

Andrew Ng 的比喻:要区分大象和狗,判别式方法找一条把两类分开的边界;生成式方法分别画一张”大象长什么样”和一张”狗长什么样”,来了新动物就看它更像哪一张。

1.2 What each side pays for

Discriminative(logistic regression、SVM)Generative(GDA、Naive Bayes)
建模对象p(y∣x)p(y \mid x)(或者只要一个边界)p(x∣y)p(x \mid y) 和 p(y)p(y)
假设只对边界 / log-odds 的形状做假设还要对 xx 的整个分布做假设
假设对的时候估计方差较大更省数据(多用了”xx 长什么样”的信息)
假设错的时候不受影响(只要边界的形状对)有偏,数据再多也修不好
训练通常要迭代优化常常是封闭解(数一数、求平均)
附带的能力–能处理缺失特征、能采样生成新数据、能检测”不像任何一类”的输入

Vapnik’s often-quoted principle says, roughly: don’t solve a harder, more general problem as an intermediate step toward the one you care about. Estimating p(x∣y)p(x \mid y) is harder than estimating a boundary (xx is high-dimensional), which is why discriminative methods usually win when data are plentiful. 但”更难的问题”也带来了更多的结构:假设对的时候,它把这些结构变成了统计效率。§2.4 用实验把这句话变成数字。

2026 年的视角:今天的”generative model”(LLM、diffusion)建模的是 p(x)p(x) 本身,目的是生成而不是分类;但”对数据的生成过程建模”这个思想和本讲的 GDA / Naive Bayes 一脉相承。


2. Gaussian discriminant analysis · 高斯判别分析

2.1 The model

y∼Bernoulli(ϕ),x∣y=0∼N(μ0,Σ),x∣y=1∼N(μ1,Σ)y \sim \text{Bernoulli}(\phi), \qquad x \mid y = 0 \sim \mathcal{N}(\mu_0, \Sigma), \qquad x \mid y = 1 \sim \mathcal{N}(\mu_1, \Sigma)

关键的设计决定是两类共享同一个协方差 Σ\Sigma:两团形状、朝向都一样,只有中心不同。(统计学里这叫 linear discriminant analysis,LDA;两类各用自己的 Σc\Sigma_c 叫 QDA。)

2.2 MLE in closed form

最大化联合似然 ∑ilog⁡p(x(i),y(i))\sum_i \log p(x^{(i)}, y^{(i)}),各参数解耦,答案就是”数一数、求平均”:

ϕ=1n∑i1{y(i)=1},μc=∑i1{y(i)=c} x(i)∑i1{y(i)=c},Σ=1n∑i(x(i)−μy(i))(x(i)−μy(i))⊤\phi = \frac{1}{n}\sum_{i} 1\{y^{(i)} = 1\}, \quad \mu_c = \frac{\sum_i 1\{y^{(i)} = c\}\,x^{(i)}}{\sum_i 1\{y^{(i)} = c\}}, \quad \Sigma = \frac{1}{n}\sum_{i}\big(x^{(i)} - \mu_{y^{(i)}}\big)\big(x^{(i)} - \mu_{y^{(i)}}\big)^\top

Σ\Sigma 是 pooled covariance:每个点减去自己那一类的均值。不需要任何迭代 —— 对比逻辑回归要 GD 或 Newton。代码 01_gda_vs_logistic.py 演示 1(d=2d = 2,每类 200 个点,真实 Δ=2\Delta = 2):估计的 μ1=[1.756,1.669]\mu_1 = [1.756, 1.669](真值 [1.732,1.732][1.732, 1.732]),Σ^=[0.9190.3980.3980.946]\hat\Sigma = \begin{bmatrix}0.919 & 0.398\\0.398 & 0.946\end{bmatrix}(真值对角 1、非对角 0.5)。

2.3 The posterior is exactly logistic — the third origin of the sigmoid

Take the log-odds and plug in the two Gaussian densities. Because both classes share Σ\Sigma, the quadratic terms −12x⊤Σ−1x-\frac12 x^\top\Sigma^{-1}x cancel, and what remains is linear in xx:

log⁡p(y=1∣x)p(y=0∣x)=(μ1−μ0)⊤Σ−1⏟θ⊤ x  −12μ1⊤Σ−1μ1+12μ0⊤Σ−1μ0+log⁡ϕ1−ϕ⏟θ0⟹p(y=1∣x)=σ(θ0+θ⊤x)\log\frac{p(y = 1 \mid x)}{p(y = 0 \mid x)} = \underbrace{(\mu_1 - \mu_0)^\top\Sigma^{-1}}_{\theta^\top}\,x \;\underbrace{-\tfrac12\mu_1^\top\Sigma^{-1}\mu_1 + \tfrac12\mu_0^\top\Sigma^{-1}\mu_0 + \log\tfrac{\phi}{1 - \phi}}_{\theta_0} \quad\Longrightarrow\quad p(y = 1 \mid x) = \sigma(\theta_0 + \theta^\top x)

The code checks this literally: gda_predict_proba computes the posterior from two Gaussian densities and Bayes’ rule — no sigmoid anywhere — and on 10,000 new points it agrees with σ(θ0+θ⊤x)\sigma(\theta_0 + \theta^\top x) to 7.8×10−167.8\times10^{-16}. This completes Lecture 1 §3.2’s list: the sigmoid is (1) a convenient squashing function, (2) the canonical response of the Bernoulli GLM, and (3) the exact posterior of Gaussian class-conditionals with shared covariance.

The converse is false. Demo 1(b) replaces the Gaussians with independent Poissons, xj∣y∼Poisson(λy,j)x_j \mid y \sim \text{Poisson}(\lambda_{y,j}). The posterior is again exactly logistic, with θj=log⁡(λ1j/λ0j)\theta_j = \log(\lambda_{1j}/\lambda_{0j}) (max difference 1.6×10−151.6\times10^{-15}). In general, any class-conditionals from the same exponential family that differ only in the natural parameter give a logistic posterior. So:

GDA  ⟹  p(y∣x) is logistic,butp(y∣x) is logistic  ⟹̸  GDA\text{GDA} \;\Longrightarrow\; p(y \mid x)\text{ is logistic}, \qquad \text{but}\qquad p(y \mid x)\text{ is logistic} \;\not\Longrightarrow\; \text{GDA}

逻辑回归的假设严格更弱:它不在乎 p(x∣y)p(x \mid y) 长什么样,只要 log-odds 是线性的。

同一个模型族,不同的估计量。 GDA 和逻辑回归的 hypothesis class 一模一样(都是 σ(θ0+θ⊤x)\sigma(\theta_0 + \theta^\top x)),但它们挑 θ\theta 的方式不同:GDA 最大化联合似然 p(x,y)p(x, y),逻辑回归最大化条件似然 p(y∣x)p(y \mid x)。演示 1 在同一份数据上:

方法θ=[θ0,θ1,θ2]\theta = [\theta_0, \theta_1, \theta_2]总体错误率(精确值)
GDA(封闭解,再换算)[−2.208,1.357,1.134][-2.208, 1.357, 1.134]0.1590
logistic regression(Newton,6 步)[−2.361,1.535,1.116][-2.361, 1.535, 1.116]0.1598
真值(Bayes 最优)[−2.000,1.155,1.155][-2.000, 1.155, 1.155]0.1587 =Φ(−Δ/2)= \Phi(-\Delta/2)

2.4 GDA vs logistic: efficiency vs robustness

Which estimator is better? It depends on whether the Gaussian assumption is true. 演示 2、3 用学习曲线回答(d=10d = 10,Σjk=0.5∣j−k∣\Sigma_{jk} = 0.5^{|j-k|},Δ=2.5\Delta = 2.5;每个样本量重复 200 次;错误率是线性分类规则在总体上的精确错误率 —— 用 Φ(⋅)\Phi(\cdot) 的封闭式算,不受测试集噪声影响)。

假设成立时(Bayes 最优 0.1056):

每类样本数101525501002501000
GDA 错误率0.22870.18180.14590.12530.11480.10940.1065
logistic 错误率0.20220.18620.15850.13150.11740.11010.1068
多犯的错之比 LR / GDA0.781.061.311.321.291.211.31

“多犯的错”= 错误率 − Bayes 最优。从每类 15 个样本起 GDA 都更好,每类 ≥ 25 个时逻辑回归多犯的错是 GDA 的 1.2–1.3 倍,而且这个比值不随 nn 趋于 1 —— 这就是 CS229 讲义说的”模型正确时 GDA 是 asymptotically efficient 的”:它用上了”xx 是高斯的”这条额外信息。(Efron 1975 专门算过逻辑回归相对于 normal discrimination 的渐近效率:两类分得越开,逻辑回归吃亏越多。)

But look at the first column: with only 10 points per class (20 points in d=10d = 10) GDA is worse. It has to estimate the 55 entries of Σ\Sigma; with so few samples Σ^\hat\Sigma is poor and Σ^−1\hat\Sigma^{-1} amplifies the error. The word asymptotically matters — at tiny sample sizes, fewer parameters (or regularization, see Exercise 2 in the code README) matter more. This contradicts the simple story “GDA is always more data-efficient”, and we report it as it came out.

假设不成立时。 演示 3 让正类有一条”单侧长尾”:10% 的正类样本被额外推远 5(μ1−μ0)5(\mu_1 - \mu_0),落在离边界很远、毫无争议的一侧 —— 就是第 1 讲 §3.1 那些”特别大的肿瘤”的高维版本。p(x∣y=1)p(x \mid y = 1) 不再是高斯,但边界附近的后验几乎还是 sigmoid。Bayes 最优(Monte Carlo 估计)= 0.1001:

每类样本数10251002501000100000(≈ ∞)
GDA 错误率0.32090.28200.20190.16670.14420.1362
logistic 错误率0.19210.15390.11140.10480.10130.1002

Logistic regression wins at every sample size, and GDA’s gap does not shrink with nn: it stalls at 0.1362, 0.036 above Bayes, while logistic regression converges to 0.1002. Split by class (at 10510^5 per class), GDA errs 0.0297 on negatives but 0.2426 on positives: the tail drags μ^1\hat\mu_1 away by 0.51∥μ1−μ0∥0.51\lVert\mu_1 - \mu_0\rVert (=10%×5= 10\% \times 5) and stretches Σ^\hat\Sigma along the separating direction, pushing the boundary into the positive class. Logistic loss goes to 0 at large margins, so those far, already-correct points contribute almost no gradient — the same mechanism as the huge tumors of Lecture 1.

两张表合起来就是 Ng & Jordan (2002) 的结论:generative 模型更快地接近它自己的渐近错误率;discriminative 模型的渐近错误率更低或相同。经验法则:

  • 数据少、对 p(x∣y)p(x \mid y) 的形状有把握 → 生成式(GDA、Naive Bayes);
  • 数据多、假设可疑 → 判别式(逻辑回归、SVM、神经网络)。
  • 差别的本质是 bias–variance(第 3 讲):更强的假设 = 更小的方差 + 可能的偏差。

3. Naive Bayes · 朴素贝叶斯

3.1 Why an assumption is unavoidable

垃圾邮件分类:x∈{0,1}Vx \in \{0, 1\}^V 表示词表里每个词出现没有。直接对 p(x∣y)p(x \mid y) 建模,一个一般的分布需要 2V−12^V - 1 个参数 —— V=50000V = 50000 时完全不可能。必须做一个强假设。Naive Bayes 的假设是:给定类别,各个词相互独立(conditional independence):

p(x1,…,xV∣y)=∏j=1Vp(xj∣y)⟹log⁡p(y=1∣x)p(y=0∣x)=log⁡p(y=1)p(y=0)+∑j=1Vlog⁡p(xj∣y=1)p(xj∣y=0)p(x_1, \dots, x_V \mid y) = \prod_{j=1}^{V} p(x_j \mid y) \qquad\Longrightarrow\qquad \log\frac{p(y = 1 \mid x)}{p(y = 0 \mid x)} = \log\frac{p(y=1)}{p(y=0)} + \sum_{j=1}^{V}\log\frac{p(x_j \mid y = 1)}{p(x_j \mid y = 0)}

参数从 2V2^V 个降到 2V+12V + 1 个。注意右边:log-odds 是每个词的证据之和 —— 又是一个线性模型(在 xx 的指示特征上),所以 Naive Bayes 也是 §2.3 那种”生成式模型的后验是逻辑函数”的例子。这个假设显然是错的(“click” 和 “here” 显然不独立),§3.4 讨论为什么它还能用。

3.2 Two event models

Bernoulli event modelMultinomial event model
一封邮件表示成VV 维 0/1 向量:每个词出现没有一串词;等价于 VV 维计数向量 xwx_w
生成过程每个词独立地掷一次硬币决定出现与否每个位置独立地从本类的词分布 P(w∣y)P(w \mid y) 抽一个词
MLEpw∣c=#{含 w 的 c 类邮件}#{c 类邮件}p_{w \mid c} = \frac{\#\{\text{含 } w \text{ 的 } c \text{ 类邮件}\}}{\#\{c \text{ 类邮件}\}}P(w∣c)=c 类里 w 的总次数c 类的总词数P(w \mid c) = \frac{\text{c 类里 } w \text{ 的总次数}}{\text{c 类的总词数}}
用上的信息出现没有;没出现的词也算证据出现几次;没出现的词不提供证据

代码 02_naive_bayes.py 构造了一个合成语料:V=300V = 300(20 个常用词、15 个垃圾邮件词、15 个正常邮件词、250 个按 Zipf 定律递减的长尾词),每封邮件平均 20 个词,逐词独立地从本类的词分布里抽 —— multinomial NB 的假设恰好成立,用真实分布做 Bayes 最优分类的准确率是 0.9535。演示 1 的学习曲线(每个大小重复 10 次;NB 用 α=1\alpha = 1,逻辑回归用词频做特征、λ=10−3\lambda = 10^{-3}):

每类邮件数51025501002501000
multinomial NB0.63440.75160.86730.90720.92660.93800.9475
Bernoulli NB0.67970.76320.87040.90570.92660.93810.9471
logistic regression0.57970.64240.74450.84510.89760.92550.9413
  • NB vs logistic. With little data NB is far better (25 emails per class: 0.867 vs 0.745); the gap shrinks to 0.006 at 1000 per class. NB’s “training” is counting, with each word estimated independently; logistic regression optimizes 301 parameters jointly and has high variance when data are scarce. This is the other half of Ng & Jordan (2002). But our corpus is generated exactly by NB’s model, so logistic regression never overtakes it — the crossover Ng & Jordan saw on real datasets (the discriminative model winning once data are plentiful) cannot happen in this toy world.
  • Bernoulli vs multinomial. 本以为 multinomial 会明显更好,实际上数据多时几乎一样(0.9471 vs 0.9475),训练集极小时 Bernoulli 反而略好(我们没有深究原因)。邮件很短,关键词很少重复,“出现几次”和”出现没有”差别不大。文献里的经验(McCallum & Nigam 1998)是文档长、词表大时 multinomial 占优。

3.3 Laplace smoothing: why one zero count kills a prediction

MLE 把”训练集里没见过”估计成”概率恰好为 0”。演示 2 用每类 25 封邮件(约 1000 个词)训练:300 个词里有 218 个在 ham 训练集中从未出现、207 个在 spam 中从未出现。测试邮件里只要出现一个”spam 训练集里没见过”的词,log⁡p(x∣spam)=−∞\log p(x \mid \text{spam}) = -\infty —— 无论其他词多么像垃圾邮件。

Laplace smoothing 给每个计数加 α\alpha(α=1\alpha = 1 就是”每个词先假装见过一次”):

P(w∣c)=count(w,c)+αcount(c)+αV,pw∣c=#{含 w}+αnc+2α  (Bernoulli)P(w \mid c) = \frac{\text{count}(w, c) + \alpha}{\text{count}(c) + \alpha V}, \qquad p_{w \mid c} = \frac{\#\{\text{含 } w\} + \alpha}{n_c + 2\alpha}\ \ (\text{Bernoulli})
α\alpha00.0010.010.10.31310
multinomial 准确率0.19350.87080.87080.87300.87620.85900.79930.6945
Bernoulli 准确率0.19250.86580.86580.86950.87320.86300.83930.7995
multinomial log loss1.0280.6940.4950.3260.2860.3140.4300.577
  • α=0\alpha = 0: 3129 of 4000 test emails have probability exactly 0 under both classes (for each class they contain at least one word that class never showed in training), so the posterior is 0/0 and no decision is possible (counted as wrong). With a large vocabulary and a small training set this is almost guaranteed.
  • Any α>0\alpha > 0, even 0.001, brings accuracy to 0.87. Accuracy is fairly insensitive to α\alpha; log loss is very sensitive — a tiny α\alpha lets unseen words push probabilities to the extremes.
  • α\alpha 太大也不行:α=10\alpha = 10 时每个词”假装见过 10 次”,伪计数(10×30010 \times 300)远多于每类真实的约 500 个词,信号被抹平。同一个 α\alpha 对两种 event model 的强度不同(Bernoulli 的伪计数相对于 25 封邮件,multinomial 的相对于约 500 个词),所以大 α\alpha 时 Bernoulli 掉得慢。

一个构造的例子把”一票否决”看得最清楚:取 8 个真正像垃圾邮件的词(deal winner offer prize free 和 3 个长尾词),再加一个 spam 训练集里从未出现、ham 里出现过 5 次的词 “lunch”:

P(spam | 8 个垃圾词)P(spam | 8 个垃圾词 + lunch)
α=0\alpha = 00.9900.000000
α=1\alpha = 10.9500.763

log 概率是逐词相加的,一个 −∞-\infty 压倒一切。α>0\alpha > 0 时 “lunch” 只是一条普通的、有限的反向证据。

Why “+α” is principled, not a hack. Laplace introduced add-one smoothing for the sunrise problem: having seen the sun rise nn times, the probability it rises tomorrow is (n+1)/(n+2)(n+1)/(n+2), not 1. In Bayesian terms, count+αN+αV\frac{\text{count} + \alpha}{N + \alpha V} is the posterior mean under a symmetric Dirichlet(α\alpha) prior on the word distribution (equivalently, the MAP estimate under Dirichlet(α+1\alpha + 1)). So α\alpha is a regularization strength expressed as pseudo-counts — the same idea as ridge = Gaussian prior in Lecture 3. 在这份数据上 log loss 最好的是 α=0.3\alpha = 0.3,不是 1:它是一个要调的超参数。

3.4 Why the wrong assumption still classifies well — and what it breaks

The independence assumption is wrong for every real text corpus. Yet NB is a famously strong baseline. The reason is that classification only needs the sign of the log-odds, while probabilities need its size. Correlated words make NB count the same evidence several times, which inflates the log-odds but often doesn’t flip its sign (Domingos & Pazzani 1997 showed NB can be optimal under 0-1 loss even when independence is badly violated).

演示 3 把这件事做成一个可控的实验:先在”NB 假设恰好成立”的语料上训练(k=1k = 1),再把每个词换成 kk 个总是一起出现的不同的词(像 “click here now”),词表变成 300k300k 个。NB 以为它们相互独立,于是同一份证据被数了 kk 遍(每类 250 封训练、2000 封测试):

kkNB 准确率NB log lossNB ECE“99.9% 确定”的比例其中真正对的LR 准确率LR log lossLR ECE
10.93350.1550.010134.2%99.93%0.92750.1930.0354
20.93350.2050.039069.9%99.39%0.92350.1900.0162
40.93350.3630.053585.1%98.03%0.91930.1980.0134
80.93350.6890.059993.5%96.15%0.91350.2180.0245

(ECE = expected calibration error:按置信度分箱,比较”说有多确定”和”实际有多准”。)

  • Accuracy doesn’t move in the 4th decimal. After duplication each copy’s estimated probability is exactly 1/k1/k of the original and every log-odds is exactly kk times the original (max difference 4.5×10−134.5\times10^{-13}, Exercise 4). Same sign, same decisions.
  • Probabilities fall apart. At k=1k = 1 NB is well calibrated; at k=8k = 8, 93.5% of predictions claim to be more than 99.9% sure, yet only 96% of those are right, and the log loss is 4.4 times larger.
  • Logistic regression fits p(y∣x)p(y \mid x) directly, so kk co-occurring features just share one weight instead of being counted kk times: its log loss only moves from 0.193 to 0.218. It isn’t untouched — the fixed L2 penalty spread over kk copies is effectively kk times weaker, so variance grows and accuracy drops from 0.9275 to 0.9135 — but nothing like NB.

实践结论:NB 是很好的排序 / 分类器(垃圾邮件过滤、文本分类的强 baseline;NB 特征 + SVM 的 NBSVM 至今仍是情感分类的经典 baseline,Wang & Manning 2012),但别把它的输出直接当概率用。需要概率时做一次校准(Platt scaling、isotonic regression),或者换判别式模型。


4. Kernel methods · 核方法

4.1 From features to inner products

第 1 讲 §2.5 说过:“线性模型”只要求对 θ\theta 线性,可以把 xx 换成任意特征 ϕ(x)\phi(x)。问题是好的特征往往非常多:dd 维输入的所有次数 ≤p\le p 的单项式有 (d+pp)\binom{d+p}{p} 个(代码 03_kernels.py 演示 1):

dd3101001001001000784(MNIST)
次数 pp2223534
特征维数 DD10665,151176,8519.7×1079.7\times10^{7}1.7×1081.7\times10^{8}1.6×10101.6\times10^{10}

MNIST 上的 4 次多项式特征,一个样本的特征向量就要 128 GB。在这么多特征上跑 LMS(每步 O(nD)O(nD))是不可能的。

4.2 The kernel trick: θ stays in the span of the data

Run batch GD (LMS) in feature space from θ=0\theta = 0:

θ:=θ+α∑i=1n(y(i)−θ⊤ϕ(x(i))) ϕ(x(i))\theta := \theta + \alpha\sum_{i=1}^{n}\big(y^{(i)} - \theta^\top\phi(x^{(i)})\big)\,\phi(x^{(i)})

Every update adds a linear combination of the ϕ(x(i))\phi(x^{(i)}), so by induction θ=∑iβi ϕ(x(i))\theta = \sum_i \beta_i\,\phi(x^{(i)}) at all times. Substitute this in and ϕ\phi only ever appears inside inner products:

β:=β+α (y⃗−Kβ),Kij=⟨ϕ(x(i)),ϕ(x(j))⟩,h(x)=∑iβi K(x(i),x)\beta := \beta + \alpha\,(\vec y - K\beta), \qquad K_{ij} = \langle\phi(x^{(i)}), \phi(x^{(j)})\rangle, \qquad h(x) = \sum_{i}\beta_i\,K(x^{(i)}, x)

If K(x,z)K(x, z) can be computed without forming ϕ\phi, we never pay for the dimension DD. For the polynomial kernel this is immediate: (x⊤z+c)2(x^\top z + c)^2 costs one dd-dimensional inner product, yet equals ϕ(x)⊤ϕ(z)\phi(x)^\top\phi(z) for a (d2+d+1)(d^2 + d + 1)-dimensional ϕ\phi (demo 1(a): max difference 7.1×10−157.1\times10^{-15}). Demo 1(c) runs both versions of GD for 500 steps on 13-dimensional features: explicit θ\theta and ∑iβiϕ(x(i))\sum_i\beta_i\phi(x^{(i)}) agree to 1.0×10−151.0\times10^{-15}, predictions to 4.0×10−154.0\times10^{-15}.

这就是 kernel trick 的全部前提,两个条件缺一不可:

  1. 算法只通过内积接触数据(LMS、ridge、SVM、PCA、k-means 都可以写成这样);
  2. 解在数据张成的空间里(representer theorem:对”损失 + ∥θ∥2\lVert\theta\rVert^2 正则化”这一大类问题都成立)。

第 1 讲 §2.3 已经见过第二条的影子:d>nd > n 时从 0 出发的 GD 永远不会长出 X⊤X^\top 列空间之外的分量,所以收敛到最小范数解。

4.3 RBF: an infinite-dimensional feature map

The Gaussian (RBF) kernel K(x,z)=exp⁡(−∥x−z∥2/(2σ2))K(x, z) = \exp\big(-\lVert x - z\rVert^2/(2\sigma^2)\big) corresponds to an infinite-dimensional ϕ\phi. In 1-D, Taylor-expand exz/σ2e^{xz/\sigma^2}:

K(x,z)=∑k=0∞ϕk(x) ϕk(z),ϕk(x)=e−x2/(2σ2) xkσkk!K(x, z) = \sum_{k=0}^{\infty}\phi_k(x)\,\phi_k(z), \qquad \phi_k(x) = e^{-x^2/(2\sigma^2)}\,\frac{x^k}{\sigma^k\sqrt{k!}}

演示 1(b) 把这个无穷级数截断到前 KK 维(σ=1\sigma = 1),看近似误差:

输入范围K=1K = 12481632
∣x∣≤1\lvert x\rvert \le 10.630.260.0191.0×10−51.0\times10^{-5}1.9×10−141.9\times10^{-14}3.3×10−163.3\times10^{-16}
∣x∣≤3\lvert x\rvert \le 31.01.00.980.680.0222.2×10−92.2\times10^{-9}
∣x∣≤5\lvert x\rvert \le 51.01.01.01.00.980.10

误差随 KK 下降得极快,但输入范围越大需要的维数越多 —— 没有任何有限的 KK 对所有输入都够用。核函数用 O(d)O(d) 的代价”算完了”这个无穷级数。直觉上,RBF 是一个”相似度”:x=zx = z 时为 1,离得越远越接近 0,σ\sigma 决定”多远算远”。

4.4 Which functions are valid kernels?

Not every similarity function is an inner product in some feature space. Mercer’s theorem (finite-sample form, as in the CS229 notes): KK is a valid kernel if and only if for every finite set of points the Gram matrix Kij=K(x(i),x(j))K_{ij} = K(x^{(i)}, x^{(j)}) is symmetric positive semidefinite. 必要性一行就能看出来:v⊤Kv=∥∑iviϕ(x(i))∥2≥0v^\top K v = \lVert\sum_i v_i\phi(x^{(i)})\rVert^2 \ge 0。

演示 2 在 60 个随机二维点上算 Gram 矩阵的特征值:

核最小特征值负特征值个数结论
linear x⊤zx^\top z−1.2×10−14-1.2\times10^{-14}0合法(秩 2,其余是舍入误差)
poly (x⊤z+1)3(x^\top z + 1)^3−4.45×10−13-4.45\times10^{-13}0合法(秩 10)
RBF,σ=1\sigma = 15.5×10−145.5\times10^{-14}0合法
Laplace e−∥x−z∥e^{-\lVert x - z\rVert}0.03250合法
RBF + poly;RBF × poly5.9×10−145.9\times10^{-14};6.1×10−126.1\times10^{-12}0;0合法(和与积仍是核)
tanh⁡(x⊤z−1)\tanh(x^\top z - 1)−36.630不合法
box 1{∥x−z∥<1}1\{\lVert x - z\rVert < 1\}−4.2624不合法
−∥x−z∥2-\lVert x - z\rVert^2−2481不合法
  • 合法的核做加法、乘法、正数缩放、f(x)f(z)K(x,z)f(x)f(z)K(x,z) 仍然合法 —— 这是构造新核的标准工具(和 = 特征拼接,积 = 特征的张量积)。
  • “sigmoid 核” tanh⁡(a x⊤z+b)\tanh(a\,x^\top z + b) 在早期 SVM 文献里很流行(像一层神经网络),但这里 60 个点中有 30 个 K(x,x)<0K(x, x) < 0 —— 如果 K(x,x)=∥ϕ(x)∥2K(x, x) = \lVert\phi(x)\rVert^2,这就是”长度的平方是负数”。
  • box 核非常符合”相似度”的直觉(对称、自己和自己最像),却不合法:取最小特征值的特征向量 vv,v⊤Kv=−4.26v^\top K v = -4.26,相当于 ∥∑iviϕ(x(i))∥2<0\lVert\sum_i v_i\phi(x^{(i)})\rVert^2 < 0。(Bochner 定理的直觉:平移不变的核合法 ⇔ 它的 Fourier 变换非负;盒子的 Fourier 变换是 sinc,有负的部分;高斯的还是高斯。)
  • 不合法的后果:SVM 的对偶问题不再凹(没有唯一最优,SMO 的曲率可能 ≤ 0);kernel ridge 的 K+λIK + \lambda I 可能奇异。一个负特征值就足以证明不合法;一组点上没有负特征值只是”没找到反例”。

4.5 Kernel ridge regression and the O(n³) vs O(D³) trade-off

Ridge in feature space, min⁡θ∑i(y(i)−θ⊤ϕ(x(i)))2+λ∥θ∥2\min_\theta \sum_i (y^{(i)} - \theta^\top\phi(x^{(i)}))^2 + \lambda\lVert\theta\rVert^2, has two equivalent closed forms (push-through identity):

θ=(Φ⊤Φ+λID)−1Φ⊤y⃗=Φ⊤(K+λIn)−1y⃗⏟α,f(x)=∑iαi K(x(i),x)\theta = (\Phi^\top\Phi + \lambda I_D)^{-1}\Phi^\top\vec y = \Phi^\top\underbrace{(K + \lambda I_n)^{-1}\vec y}_{\alpha}, \qquad f(x) = \sum_{i}\alpha_i\,K(x^{(i)}, x)

Primal solves a D×DD \times D system, dual an n×nn \times n one. Demo 3 checks they give the same predictions (difference 2.4×10−142.4\times10^{-14} with a quadratic kernel). 演示 3 的主角是第 1 讲 §2.5 的正弦数据 —— 同一份 15 个训练点(第 1 讲用多项式特征时最好的是 k=3k = 3,test MSE 0.159)。RBF 核、λ=0.1\lambda = 0.1,扫带宽 σ\sigma:

σ\sigma0.010.030.050.10.20.30.513
train MSE0.00230.00480.00870.02380.04280.05210.12480.21960.2782
test MSE0.44370.28690.23850.17850.13260.13300.22700.33200.4111
有效自由度13.111.39.77.25.13.93.02.21.6

“有效自由度” =tr(K(K+λI)−1)= \text{tr}\big(K(K + \lambda I)^{-1}\big),衡量模型有多少个”有效参数”(和第 1 讲 LWR 的”有效样本数”是同一类量)。Small σ\sigma: each training point lights up only a tiny neighborhood, so the fit is exact at the training points and close to 0 elsewhere — overfitting. Large σ\sigma: all points look “equally similar” and the curve is flattened — underfitting. The best, σ=0.2\sigma = 0.2, reaches 0.133, better than the best polynomial on the same data (0.159).

固定 σ=0.2\sigma = 0.2 扫 λ\lambda:λ=10−6\lambda = 10^{-6} 时有效自由度 10.5,曲线穿过噪声点,test MSE 3.17;λ=0.01\lambda = 0.01、0.10.1 时 0.143、0.133;λ=10\lambda = 10 时曲线被压向 0,test MSE 0.402。RBF 核 = 无穷维特征 + ridge:表达能力无限,靠 σ\sigma 和 λ\lambda 两个旋钮控制复杂度(第 3 讲用交叉验证选)。

When to use the dual. DD small and nn large (ordinary linear regression) → primal. DD huge or infinite (high-degree polynomial, RBF) → dual. The price is the n×nn \times n Gram matrix: O(n2)O(n^2) memory and O(n3)O(n^3) time. At n=106n = 10^6 the Gram matrix alone has 101210^{12} entries (8 TB). This is the main reason kernel methods lost ground to neural networks on large datasets; the standard escapes are random Fourier features (Rahimi & Recht 2007: sample a finite ϕ\phi whose inner product approximates the kernel, then solve the primal) and Nyström (low-rank approximation of KK).

4.6 Kernels in 2026

  • Gaussian processes: the kernel-ridge prediction is exactly the posterior mean of a GP with covariance KK and noise variance λ\lambda; the GP adds error bars. Bayesian optimization of hyperparameters is built on this.
  • Neural tangent kernel (Jacot et al. 2018): an infinitely wide network trained by GD with a small learning rate behaves like kernel regression with a specific kernel. Much of deep-learning theory is phrased in kernel language.
  • Attention (Lecture 1 §2.5): ∑isoftmax(q⊤ki) vi\sum_i\text{softmax}(q^\top k_i)\,v_i is a kernel smoother with a learned, asymmetric similarity — not a Mercer kernel, which is fine because it is never used as an inner product in a feature space.

5. Support vector machines · 支持向量机

5.1 Margins: functional vs geometric

Lecture 1 §3.4 put every classification loss on the axis of the margin t=y θ⊤xt = y\,\theta^\top x. SVMs take the margin as the objective. With y∈{−1,+1}y \in \{-1, +1\} and f(x)=w⊤x+bf(x) = w^\top x + b:

γ^(i)=y(i)(w⊤x(i)+b)  (functional margin),γ(i)=γ^(i)∥w∥  (geometric margin)\hat\gamma^{(i)} = y^{(i)}\big(w^\top x^{(i)} + b\big)\ \ (\text{functional margin}), \qquad \gamma^{(i)} = \frac{\hat\gamma^{(i)}}{\lVert w\rVert}\ \ (\text{geometric margin})

几何间隔是点到超平面的带符号欧氏距离。functional margin 可以靠把 (w,b)(w, b) 乘以 10 任意放大,超平面却没变(代码 04_svm_smo.py 演示 1:最小 functional margin 1.000 → 10.000,几何间隔 0.9396 → 0.9396)。所以只有几何间隔是有意义的”置信度”。

5.2 The optimal margin classifier

Maximize the smallest geometric margin. Since (w,b)(w, b) can be rescaled freely, fix the smallest functional margin to 1; maximizing 1/∥w∥1/\lVert w\rVert is then the convex QP

min⁡w,b 12∥w∥2s.t.y(i)(w⊤x(i)+b)≥1,i=1,…,n\min_{w, b}\ \frac12\lVert w\rVert^2 \qquad \text{s.t.}\quad y^{(i)}\big(w^\top x^{(i)} + b\big) \ge 1,\quad i = 1, \dots, n

为什么”最大间隔”是好的归纳偏置? 三个角度:

  • Robustness. With margin γ\gamma, every training point can be perturbed by up to γ\gamma without changing its label. If test points look like noisy versions of training points, a wider margin is safer.
  • Dimension-free generalization. For data in a ball of radius RR, the effective capacity (VC dimension) of linear classifiers with margin γ\gamma is controlled roughly by R2/γ2R^2/\gamma^2 rather than by the dimension dd (Vapnik). This is the theoretical reason an SVM can work in the infinite-dimensional RBF feature space without overfitting. Lecture 1’s Novikoff bound (R/γ)2(R/\gamma)^2 is the same quantity — the margin sets the difficulty.
  • Uniqueness. Separable data admit infinitely many separators (where the perceptron stops depends on the example order); the maximum-margin one is unique.

演示 1 用第 1 讲感知机那份可分数据比较几个分隔面的间隔:

分隔面xx 空间的几何间隔增广空间 [1,x][1, x] 的间隔
perceptron(第 1 讲)0.41250.1759
logistic,λ=10−3\lambda = 10^{-3}(第 1 讲)0.87710.3152
hard-margin SVM(SMO,bb 不受惩罚)0.93960.3463
增广空间里间隔最大的方向0.93960.3463

第 1 讲演示 4 的”间隔”(0.1759、0.3152)是在增广空间里量的(除以包括截距的 ∥θ∥\lVert\theta\rVert),所以和这里的第一列不是同一个量;两种都列出来了。用增广空间里最大的间隔,Novikoff 上界从第 1 讲的 759 降到 629,仍远大于感知机实际犯错的 10 次。

5.3 Lagrange duality, KKT and support vectors (results only)

Introducing a multiplier αi≥0\alpha_i \ge 0 per constraint, the dual problem is

max⁡α W(α)=∑iαi−12∑i,jy(i)y(j)αiαj ⟨x(i),x(j)⟩s.t.αi≥0,∑iαiy(i)=0\max_{\alpha}\ W(\alpha) = \sum_{i}\alpha_i - \frac12\sum_{i,j}y^{(i)}y^{(j)}\alpha_i\alpha_j\,\langle x^{(i)}, x^{(j)}\rangle \qquad \text{s.t.}\quad \alpha_i \ge 0,\quad \sum_i\alpha_i y^{(i)} = 0

and the KKT conditions give three facts we actually use:

  1. w=∑iαiy(i)x(i)w = \sum_i\alpha_i y^{(i)}x^{(i)} — the solution is a combination of training points (the representer theorem again).
  2. Complementary slackness: αi(y(i)(w⊤x(i)+b)−1)=0\alpha_i\big(y^{(i)}(w^\top x^{(i)} + b) - 1\big) = 0. Points strictly outside the margin have αi=0\alpha_i = 0; only points on the margin can have αi>0\alpha_i > 0. These are the support vectors.
  3. Strong duality holds: the optimal primal and dual objectives are equal — a free convergence check.

The equality constraint ∑iαiy(i)=0\sum_i\alpha_i y^{(i)} = 0 comes from differentiating with respect to bb; remember it, it explains SMO (§5.6).

演示 1 的数字:100 个点里只有 3 个 support vectors(α=0.137,0.429,0.566\alpha = 0.137, 0.429, 0.566),它们的 functional margin 恰好都是 1,其余点最小 1.041;∑αiyi=2×10−16\sum\alpha_i y_i = 2\times10^{-16};primal 12∥w∥2\frac12\lVert w\rVert^2 = dual W(α)W(\alpha) = 0.566406。稀疏性的直接证明:扔掉其余 97 个点、只用 3 个 support vectors 重新训练,(w,b)(w, b) 的最大差是 3.6×10−113.6\times10^{-11}。预测 f(x)=∑iαiy(i)⟨x(i),x⟩+bf(x) = \sum_i\alpha_i y^{(i)}\langle x^{(i)}, x\rangle + b 也只需要对 support vectors 求和。

5.4 Kernel SVM

The dual and the prediction touch the data only through ⟨x(i),x(j)⟩\langle x^{(i)}, x^{(j)}\rangle — condition 1 of §4.2. Replace it by K(x(i),x(j))K(x^{(i)}, x^{(j)}) and the same QP, the same solver and the same code learn a nonlinear boundary. 演示 3:同心圆(内圈负类、外圈正类,训练 200、测试 2000,C=1C = 1):

核#SV训练准确率测试准确率
linear1970.6100.5705
poly,degree 2190.9800.9780
RBF,σ=0.03\sigma = 0.032001.0000.6710
RBF,σ=0.1\sigma = 0.11871.0000.9180
RBF,σ=0.3\sigma = 0.3890.9950.9735
RBF,σ=1\sigma = 1530.9850.9770
RBF,σ=3\sigma = 31290.9750.9730
RBF,σ=10\sigma = 102000.6950.6710
  • No line separates concentric circles (0.5705 ≈ guessing). The degree-2 polynomial kernel’s features include x12x_1^2 and x22x_2^2, in which “radius squared = constant” is a hyperplane: 0.978 with only 19 support vectors. The model and the optimizer did not change by a single character; only KK did.
  • RBF 的 σ\sigma 又是复杂度旋钮:σ=0.03\sigma = 0.03 时训练全对、测试 0.671,每个点都是 support vector —— 在背训练集;σ=10\sigma = 10 时所有点之间的核值都接近 1,C=1C = 1 下模型几乎弯不动,欠拟合(我们本以为它会”退化成线性 SVM”,实际上 0.671 比线性的 0.5705 好不少,更准确的描述是”欠拟合”)。
  • The number of support vectors is a rough complexity meter: close to nn usually means over- or underfitting (CC or σ\sigma badly chosen). The classical leave-one-out bound is LOO error ≤#SV/n\le \#\text{SV}/n (Exercise 6).

5.5 Soft margin, C and the hinge loss

Real data are rarely separable. Allow violations with slacks ξi≥0\xi_i \ge 0 and pay CC per unit:

min⁡w,b,ξ 12∥w∥2+C∑iξis.t.y(i)(w⊤x(i)+b)≥1−ξi,  ξi≥0⟺min⁡w,b 1n∑imax⁡(0,1−y(i)f(x(i)))⏟hinge loss+λ2∥w∥2,  λ=1nC\min_{w, b, \xi}\ \frac12\lVert w\rVert^2 + C\sum_i\xi_i \quad\text{s.t.}\quad y^{(i)}(w^\top x^{(i)} + b) \ge 1 - \xi_i,\ \ \xi_i \ge 0 \quad\Longleftrightarrow\quad \min_{w, b}\ \frac1n\sum_i\underbrace{\max\big(0, 1 - y^{(i)}f(x^{(i)})\big)}_{\text{hinge loss}} + \frac{\lambda}{2}\lVert w\rVert^2,\ \ \lambda = \frac{1}{nC}

The right-hand form is Lecture 1 §3.4’s promise: the SVM is hinge loss + L2 regularization — the same “loss + regularizer” template as ridge or regularized logistic regression, with a different loss. In the dual the only change is a box: 0≤αi≤C0 \le \alpha_i \le C. KKT now sorts points into three groups: αi=0\alpha_i = 0 (outside the margin), 0<αi<C0 < \alpha_i < C (exactly on it), αi=C\alpha_i = C (inside it or misclassified).

演示 2(两团重叠的高斯,训练 200、测试 5000,特征先中心化):

CC0.0010.010.1110100
#SV(其中 α=C\alpha = C 的)200 (200)134 (131)86 (83)77 (74)75 (72)75 (72)
间隔宽度 2/∥w∥2/\lVert w\rVert9.752.961.871.701.701.70
SVM 测试准确率0.86680.86660.86020.86160.86140.8614
同 λ\lambda 的 logistic0.86680.86540.86100.85940.85940.8594
SMO 更新的 α\alpha 对数10088791348716075658
  • Small CC = strong regularization: a very wide margin, with almost every point inside it and a support vector. Large CC: the margin narrows to 1.70 and then stops changing — the data aren’t separable, the minimum hinge loss is finite, and a larger CC only approaches that minimizer.
  • 这份二维数据的 Bayes 边界就是一条直线,所有 CC 的测试准确率都在 0.860–0.867,正则化的强弱影响不大。CC 真正重要的是高维、噪声大的数据(第 3 讲)。
  • The relative duality gap (primal − dual)/primal is below 10−810^{-8} for every CC. Larger CC makes SMO slower: many αi\alpha_i have to creep up to CC in small steps. (An earlier version also had C=1000C = 1000: 780,013 pair updates, with every reported quantity (#SV, margin width, accuracy) identical to C=100C = 100, so it was dropped to keep the runtime short.)

5.6 SMO: why two variables at a time

The dual is a QP with nn variables; generic QP solvers need O(n2)O(n^2) memory and are slow. Sequential Minimal Optimization (Platt 1998) is coordinate ascent with a twist. 只改一个 αi\alpha_i 不行:等式约束 ∑iαiy(i)=0\sum_i\alpha_i y^{(i)} = 0 会把它钉死(其他的 α\alpha 不动时 αi\alpha_i 是确定的)。所以每次改一对 (αi,αj)(\alpha_i, \alpha_j):沿着保持 αiy(i)+αjy(j)\alpha_i y^{(i)} + \alpha_j y^{(j)} 不变的方向移动,目标函数是一元二次函数,最优步长有封闭解,再截断到 [0,C][0, C] 的盒子里。整个子问题不需要任何数值优化器。

怎样选这一对?CS229 讲义的”简化版 SMO”随机选第二个;smo_train 用 LIBSVM 的 maximal violating pair(Keerthi et al. 2001):选 KKT 条件被违反得最厉害的一对,违反程度小于容差就停止。每步更新梯度只要 O(n)O(n)。

反过来看:如果没有截距 bb,对偶里就没有等式约束,可以一次只改一个 αi\alpha_i —— 这就是 LIBLINEAR 的 dual coordinate descent(Hsieh et al. 2008),代码里的 dcd_svm_nobias。§5.7 会用到它。

5.7 SVM vs logistic regression, and the payoff of Lecture 1 §3.5

SVMLogistic regression
损失hinge:margin ≥ 1 后恰好为 0logistic:永远 > 0,margin 大时趋于 0
解的结构稀疏:只依赖 support vectors每个点都有一点贡献
输出只有符号 / 到边界的距离(概率要靠 Platt scaling 另外拟合)校准过的概率
核化自然(稀疏的对偶)可以(kernel logistic regression),但对偶不稀疏
多分类one-vs-rest / one-vs-one 拼装softmax 自然推广
准确率通常差不多通常差不多

演示 2 的最后一行:同样 λ\lambda 的逻辑回归和 SVM 的测试准确率最多差 0.0022。(初版里 C=0.001C = 0.001 时逻辑回归明显更差 —— 第 1 讲的实现连截距一起惩罚,SVM 的 bb 不受惩罚;不中心化时逻辑回归掉到 0.7612。比较两个模型时,先确认它们解的是同一个问题。)

The payoff. Lecture 1 §3.5 showed that on separable data unregularized logistic regression has no MLE: ∥θ∥→∞\lVert\theta\rVert\to\infty, but the direction θ/∥θ∥\theta/\lVert\theta\rVert seemed to settle, and we quoted Soudry et al. (2018): GD converges in direction to the max-margin solution. 演示 4 兑现这个承诺,用的是第 1 讲同一份可分数据、同一个 GD(步长 1/L1/L,λ=0\lambda = 0;10510^5 步时 ∥θ∥=11.897\lVert\theta\rVert = 11.897,和第 1 讲逐位相同):

GD 步数1010010310^310410^410510^510610^6
∥θ∥\lVert\theta\rVert0.612.054.767.9511.9016.73
与 max-margin 方向的夹角44.9°8.69°2.08°0.97°0.31°0.066°
L2 逻辑回归的 λ\lambda0.10.0110−310^{-3}10−410^{-4}10−510^{-5}10−610^{-6}
与 max-margin 方向的夹角13.8°4.05°1.72°0.81°0.26°0.068°

“不加正则化跑很久的 GD”和”λ→0\lambda \to 0 的正则化路径”(Rosset, Zhu & Hastie 2003)走到同一个方向 —— 优化算法本身在做正则化,这就是第 3 讲的 implicit regularization。

一个要说清楚的细节:哪一个 SVM? 第 1 讲把截距当作 xx 的一个分量,GD 对 [θ0,θ1,θ2][\theta_0, \theta_1, \theta_2] 一视同仁。Soudry 的定理说的是增广空间里的 max margin:

min⁡b,w 12(b2+∥w∥2)s.t.y(i)(w⊤x(i)+b)≥1\min_{b, w}\ \tfrac12\big(b^2 + \lVert w\rVert^2\big)\quad\text{s.t.}\quad y^{(i)}(w^\top x^{(i)} + b) \ge 1

截距也被惩罚了,和 §5.2 的标准 SVM 不是同一个问题。在第 1 讲那份数据上两者恰好相同(夹角 0.0000°):3 个 support vectors 给出 3 个等式,正好钉死 3 个参数 [b,w1,w2][b, w_1, w_2]。为了看到差别,演示 4(b) 手工构造了 6 个点 —— 负类 (1,2) (0,4) (0,0),正类 (3,2) (4,4) (4,0):

  • 标准 SVM 是竖线 x1=2x_1 = 2,几何间隔 1,只有 2 个 support vectors,b=−2b = -2;
  • 截距被惩罚的 SVM 宁可把间隔降到 0.894,换一个更小的 ∣b∣\lvert b\rvert:[b,w]=[−1,1,−0.5][b, w] = [-1, 1, -0.5],和标准 SVM 差 26.6°。
GD 步数1010010310^310410^410510^510610^6
与”截距被惩罚的 SVM”的夹角22.7°4.53°2.12°1.95°1.62°1.34°
与标准 SVM 的夹角47.2°29.5°25.1°24.9°25.1°25.3°

GD 明确地走向前者(λ=10−8\lambda = 10^{-8} 的 L2 逻辑回归也是:0.97° vs 25.7°)。所以准确的说法是:GD 最大化的是增广空间 [1,x][1, x] 里的间隔,它依赖于坐标原点放在哪里;只有截距不进入 ∥⋅∥2\lVert\cdot\rVert^2(不被惩罚),才对应教科书上的 SVM。

收敛有多慢? Soudry et al. 证明方向误差一般只按 O(1/log⁡t)O(1/\log t) 下降。(b) 里从 10410^4 到 10610^6 步夹角缩小 1.46 倍,1/log⁡t1/\log t 预测的是 log⁡106/log⁡104=1.5\log 10^6/\log 10^4 = 1.5 倍 —— 吻合。(a) 在 10310^3–10610^6 步之间每 10 倍步数缩小 2–5 倍,比 1/log⁡t1/\log t 快得多:O(1/log⁡t)O(1/\log t) 是一般情况下的速度,具体数据的几何可以更友好。两种情况都说明:别指望靠”多跑几步”得到 SVM,要 max margin 就直接解 SVM。


6. 小结 · Summary

方法建模对象关键假设训练预测用到主要优点主要风险
GDAp(x∣y)p(y)p(x \mid y)p(y)高斯、共享 Σ\Sigma封闭解Bayes 公式(= 逻辑函数)假设对时最省数据假设错时有偏;小样本时 Σ^\hat\Sigma 不准
Naive Bayesp(x∣y)p(y)p(x \mid y)p(y)给定 yy 各特征独立数数 + 平滑证据相加极快、极小样本也能用概率过度自信;零计数
Logistic regressionp(y∣x)p(y \mid x)log-odds 线性Newton / GDσ(θ⊤x)\sigma(\theta^\top x)稳健、给出校准的概率小样本方差大;可分时需要正则化
Kernel ridgef(x)f(x)函数在 RKHS 里”光滑”(K+λI)−1y(K + \lambda I)^{-1}y∑iαiK(xi,x)\sum_i\alpha_i K(x_i, x)无穷维特征、封闭解O(n2)O(n^2) 内存、O(n3)O(n^3) 时间
SVM边界最大间隔SMO / 对偶坐标下降∑i∈SVαiyiK(xi,x)+b\sum_{i \in SV}\alpha_i y_i K(x_i, x) + b稀疏、可核化、间隔控制复杂度没有概率;CC、σ\sigma 要调

Five takeaways:

  1. Generative vs discriminative is a bias–variance trade. A correct generative model is more data-efficient (logistic regression made 1.2–1.3× as many excess errors as GDA); a wrong one is biased forever (GDA stuck at 0.136 vs 0.100). Logistic regression assumes strictly less.
  2. The sigmoid has three origins: a squashing function, the canonical Bernoulli GLM response, and the exact posterior of shared-covariance Gaussians (or any exponential-family class-conditionals).
  3. Naive Bayes classifies well and estimates probabilities badly: double-counted evidence scales the log-odds without flipping its sign. Smoothing is a prior, and α\alpha is a hyperparameter.
  4. The kernel trick needs two things: an algorithm that only uses inner products, and a solution in the span of the data. Valid kernels are exactly those with PSD Gram matrices; the cost moves from DD to nn.
  5. SVM = hinge loss + L2 = maximum margin. KKT gives sparsity (support vectors) and kernelization for free; and GD on logistic regression secretly heads toward a max-margin solution — in the coordinates you gave it, and slowly.

7. 常见误区 · Common pitfalls

  • “GDA and logistic regression are the same model.” Same hypothesis class, different estimators (joint vs conditional likelihood): different θ\theta on the same data, different data efficiency, different robustness.
  • “Generative models are always more data-efficient.” Only asymptotically and only when the assumptions hold. With 10 points per class in 10 dimensions, GDA lost to logistic regression (0.229 vs 0.202).
  • “Naive Bayes outputs probabilities.” It outputs very confident numbers. With correlated features they are badly overconfident (93.5% of predictions “over 99.9% sure”, only 96% of them right).
  • “Laplace smoothing means add one.” α\alpha is a prior strength. Here the log loss was best at α=0.3\alpha = 0.3, and α=10\alpha = 10 wiped out the signal.
  • “Any similarity function is a kernel.” The box kernel and tanh⁡\tanh are intuitive similarities with negative eigenvalues. Check, or build kernels from sums and products of known ones.
  • “RBF kernels are smooth, so they can’t overfit.” Small σ\sigma memorizes the training set (train 1.000, test 0.671 on the circles).
  • “The SVM decision value is a probability.” It’s a scaled distance to the boundary; calibrate with Platt scaling if you need probabilities.
  • “Run GD long enough and you get the SVM.” You get the max-margin solution in the augmented space (intercept penalized), at a rate that can be O(1/log⁡t)O(1/\log t).
  • “Kernel methods scale like linear models.” The Gram matrix is n×nn \times n; beyond ~10510^5 points you need approximations.

8. 练习 · Exercises

练习 1(GDA 的边界与参数个数). (a) 证明两类共享 Σ\Sigma 时 GDA 的决策边界是超平面;两类各有 Σ0≠Σ1\Sigma_0 \ne \Sigma_1(QDA)时是二次曲面。(b) 在 dd 维里,GDA、QDA、逻辑回归各有多少个参数?d=10d = 10 时分别是多少?这和 §2.4 第一列”GDA 在每类 10 个样本时更差”有什么关系?

参考答案

(a) log-odds =log⁡p(x∣1)−log⁡p(x∣0)+const= \log p(x \mid 1) - \log p(x \mid 0) + \text{const}。高斯的对数密度里 xx 的二次项是 −12x⊤Σc−1x-\frac12 x^\top\Sigma_c^{-1}x;共享 Σ\Sigma 时两项相减为 0,只剩线性项,边界 {log-odds=0}\{\text{log-odds} = 0\} 是超平面。Σ0≠Σ1\Sigma_0 \ne \Sigma_1 时剩下 −12x⊤(Σ1−1−Σ0−1)x-\frac12 x^\top(\Sigma_1^{-1} - \Sigma_0^{-1})x,边界是二次曲面。(b) GDA:1+2d+d(d+1)/21 + 2d + d(d+1)/2;QDA:1+2d+d(d+1)1 + 2d + d(d+1);逻辑回归:d+1d + 1。d=10d = 10 时分别是 76、131、11。GDA 要估计的参数是逻辑回归的 7 倍,虽然每个参数(均值、协方差)都很容易估计,样本极少时 Σ^\hat\Sigma 的误差会经过 Σ^−1\hat\Sigma^{-1} 放大到 θ\theta 上。QDA 更甚:每类 10 个样本时 Σ^c\hat\Sigma_c 只有 9 个自由度,在 10 维里是奇异的。

练习 2(Exponential-family class-conditionals). Suppose p(x∣y=c)=h(x)exp⁡(ηc⊤T(x)−a(ηc))p(x \mid y = c) = h(x)\exp\big(\eta_c^\top T(x) - a(\eta_c)\big) for c=0,1c = 0, 1, with the same hh and TT. Show that p(y=1∣x)=σ(θ⊤T(x)+θ0)p(y = 1 \mid x) = \sigma(\theta^\top T(x) + \theta_0) and find θ,θ0\theta, \theta_0. Check that GDA (with known shared Σ\Sigma) and the Poisson example of §2.3 are special cases.

参考答案

log-odds =(η1−η0)⊤T(x)−a(η1)+a(η0)+log⁡ϕ1−ϕ= (\eta_1 - \eta_0)^\top T(x) - a(\eta_1) + a(\eta_0) + \log\frac{\phi}{1-\phi},h(x)h(x) 抵消。所以 θ=η1−η0\theta = \eta_1 - \eta_0,θ0=a(η0)−a(η1)+log⁡ϕ1−ϕ\theta_0 = a(\eta_0) - a(\eta_1) + \log\frac{\phi}{1-\phi}。GDA:T(x)=xT(x) = x、ηc=Σ−1μc\eta_c = \Sigma^{-1}\mu_c、h(x)∝e−x⊤Σ−1x/2h(x) \propto e^{-x^\top\Sigma^{-1}x/2}(共享 Σ\Sigma 才能让 hh 相同)、a(ηc)=12μc⊤Σ−1μca(\eta_c) = \frac12\mu_c^\top\Sigma^{-1}\mu_c,和 §2.3 的公式一致。Poisson:T(x)=xT(x) = x、ηc,j=log⁡λc,j\eta_{c,j} = \log\lambda_{c,j}、a=∑jλc,ja = \sum_j\lambda_{c,j},得 θj=log⁡(λ1j/λ0j)\theta_j = \log(\lambda_{1j}/\lambda_{0j})、θ0=log⁡ϕ1−ϕ−∑j(λ1j−λ0j)\theta_0 = \log\frac{\phi}{1-\phi} - \sum_j(\lambda_{1j} - \lambda_{0j}),正是代码 01 演示 1(b) 用的公式。逻辑回归对这一整族生成模型都是”正确”的,这是它更稳健的根本原因。

练习 3(Smoothing as a prior). (a) Show that with a Dirichlet(α,…,α\alpha, \dots, \alpha) prior on the word distribution P(⋅∣c)P(\cdot \mid c), the posterior mean of P(w∣c)P(w \mid c) is count(w,c)+αNc+αV\frac{\text{count}(w, c) + \alpha}{N_c + \alpha V}. (b) In demo 2 each class has about 500 training words and V=300V = 300. What fraction of the “total evidence” is pseudo-counts when α=1\alpha = 1? When α=10\alpha = 10? Relate this to the accuracy column.

参考答案

(a) Dirichlet 是多项分布的共轭先验:后验是 Dirichlet(α+count(w1,c),…\alpha + \text{count}(w_1, c), \dots),Dirichlet(β\beta) 第 ww 个分量的均值是 βw/∑vβv\beta_w/\sum_v\beta_v,代入即得。(MAP 是 count+α−1Nc+(α−1)V\frac{\text{count} + \alpha - 1}{N_c + (\alpha - 1)V},所以”加 α\alpha“也可以看成 Dirichlet(α+1\alpha + 1) 先验下的 MAP。)(b) 伪计数 αV\alpha V:α=1\alpha = 1 时 300,占 300/800≈38%300/800 \approx 38\%;α=10\alpha = 10 时 3000,占 3000/3500≈86%3000/3500 \approx 86\% —— 估计出的词分布几乎就是均匀分布,信号被抹平,准确率掉到 0.6945。词表越大、训练集越小,同一个 α\alpha 的正则化越强,这也是 log loss 在 α=0.3\alpha = 0.3 而不是 1 处最好的原因。

练习 4(Double-counted evidence). In demo 3 every word is replaced by kk always-co-occurring copies. Show that with multinomial NB and Laplace smoothing α\alpha, each copy’s estimated probability is exactly P(w∣c)/kP(w \mid c)/k (where P(w∣c)P(w \mid c) is the k=1k = 1 estimate with the same α\alpha), and that the log-odds of every document is multiplied by exactly kk when the classes are balanced. Why does accuracy stay identical while log loss grows?

参考答案

复制后每个副本的计数都是 count(w,c)\text{count}(w, c),类的总词数变成 kNckN_c,词表变成 kVkV:count(w,c)+αkNc+αkV=1kP(w∣c)\frac{\text{count}(w,c) + \alpha}{kN_c + \alpha kV} = \frac1k P(w \mid c)。一封文档里每个副本出现 xwx_w 次,log 似然 =∑wk xw(log⁡P(w∣c)−log⁡k)= \sum_w k\,x_w\big(\log P(w \mid c) - \log k\big);−klog⁡k∑wxw-k\log k\sum_w x_w 与类别无关,在 log-odds 里抵消,剩下 k×k \times(原来的 log-likelihood ratio)。先验相等时 log-odds 恰好乘以 kk。符号不变 → 分类不变;但 σ(k z)\sigma(k\,z) 随 kk 越来越接近 0/1,错的那些样本被”自信地”判错:一个分错的样本的损失是 log⁡(1+ek∣z∣)≈k∣z∣\log(1 + e^{k|z|}) \approx k|z|,随 kk 大致线性增长;分对的样本损失只能降到 0,抵不过这一项。

练习 5(Valid or not?). For each, decide whether it is a valid kernel on Rd\mathbb{R}^d and justify: (a) K(x,z)=(x⊤z)2K(x, z) = (x^\top z)^2; (b) K(x,z)=K1(x,z)+K2(x,z)K(x, z) = K_1(x, z) + K_2(x, z) with K1,K2K_1, K_2 valid; (c) K(x,z)=f(x)f(z)K(x, z) = f(x)f(z) for any real function ff; (d) K(x,z)=∥x−z∥2K(x, z) = \lVert x - z\rVert^2; (e) K(x,z)=K1(x,z)−K2(x,z)K(x, z) = K_1(x, z) - K_2(x, z).

参考答案

(a) 合法:ϕ(x)=(xixj)i,j\phi(x) = (x_ix_j)_{i,j},ϕ(x)⊤ϕ(z)=∑i,jxixjzizj=(x⊤z)2\phi(x)^\top\phi(z) = \sum_{i,j}x_ix_jz_iz_j = (x^\top z)^2。(b) 合法:v⊤(K1+K2)v=v⊤K1v+v⊤K2v≥0v^\top(K_1 + K_2)v = v^\top K_1v + v^\top K_2v \ge 0;对应特征拼接。(c) 合法:一维特征 ϕ(x)=f(x)\phi(x) = f(x),Gram 矩阵 ff⊤ff^\top 半正定。(d) 不合法:对角线 K(x,x)=0K(x, x) = 0,所以 Gram 矩阵的迹为 0;只要两个点不同,矩阵非零,特征值之和为 0 就必有负特征值(演示 2 的 −∥x−z∥2-\lVert x-z\rVert^2 也不合法:它的迹也是 0)。(e) 一般不合法:取 K1=0K_1 = 0,K2K_2 任何非零的合法核即得反例。

练习 6(Sparsity and leave-one-out). (a) Using complementary slackness, argue that removing a training point with αi=0\alpha_i = 0 and retraining leaves the hard-margin SVM unchanged (demo 1 did this numerically). (b) Deduce the classical bound: leave-one-out error ≤#SV/n\le \#\text{SV}/n. (c) What does the bound say for the RBF σ=0.03\sigma = 0.03 row of §5.4, and is it useful there?

参考答案

(a) 原来的最优解 (w,b,α)(w, b, \alpha) 去掉第 ii 个分量后,对新问题仍然满足 KKT 条件:原始可行(少了一个约束更容易满足)、对偶可行、w=∑j≠iαjyjxjw = \sum_{j \ne i}\alpha_j y_j x_j(因为 αi=0\alpha_i = 0)、互补松弛。凸问题里 KKT 是最优的充分条件,所以解不变。(b) 留一法里,被留出的点如果不是 support vector,解不变,而训练时它被正确分类(在间隔外),所以留一法下也分对;只有 support vector 被留出时才可能分错。所以错误数 ≤#SV\le \#\text{SV}。(soft margin 时类似的论证给出 #{αi>0}/n\#\{\alpha_i > 0\}/n 的界。)(c) σ=0.03\sigma = 0.03 时 200 个点全是 support vectors,上界是 1 —— 毫无用处,但它正确地报警了:support vector 太多说明模型在记忆训练集(测试准确率只有 0.671)。σ=1\sigma = 1 时上界 53/200=0.26553/200 = 0.265,实际测试错误率 0.023,上界很松,但方向是对的。

代码相关的练习(“动手改一改”)见 code/lecture02/README.md。


9. 延伸阅读 · Further reading

  • CS229 main notes(Ng & Ma),Part I Ch. 4–6:本讲的主要来源(GDA、Naive Bayes 与 Laplace smoothing、kernel methods、SVM 与 SMO)。CS229 还有一份单独的 The Simplified SMO Algorithm 讲义。
  • CS229 Autumn 2018 lectures 5–7(YouTube):Andrew Ng 讲生成式学习、SVM 和核方法的原版。
  • Ng & Jordan, “On Discriminative vs. Generative Classifiers: A comparison of logistic regression and naive Bayes”, NIPS 14(2002):§2.4、§3.2 的学习曲线对比。
  • Efron, “The Efficiency of Logistic Regression Compared to Normal Discriminant Analysis”, JASA 1975:GDA vs logistic 的渐近效率。
  • McCallum & Nigam, “A Comparison of Event Models for Naive Bayes Text Classification”, AAAI Workshop 1998;Domingos & Pazzani, “On the Optimality of the Simple Bayesian Classifier under Zero-One Loss”, Machine Learning 1997;Wang & Manning, “Baselines and Bigrams”, ACL 2012。
  • Schölkopf & Smola, Learning with Kernels(2002);Rasmussen & Williams, Gaussian Processes for Machine Learning(2006):核方法与 GP 的标准教材。
  • Cortes & Vapnik, “Support-Vector Networks”, Machine Learning 1995;Platt, “Sequential Minimal Optimization”, 1998;Keerthi et al., “Improvements to Platt’s SMO Algorithm”, Neural Computation 2001;Hsieh et al., “A Dual Coordinate Descent Method for Large-scale Linear SVM”, ICML 2008。
  • Rahimi & Recht, “Random Features for Large-Scale Kernel Machines”, NIPS 2007;Jacot, Gabriel & Hongler, “Neural Tangent Kernel”, NeurIPS 2018。
  • Soudry et al., “The Implicit Bias of Gradient Descent on Separable Data”, JMLR 2018;Rosset, Zhu & Hastie, “Margin Maximizing Loss Functions”, NIPS 2003:§5.7 的两个结果。

10. 下一讲预告 · Next lecture

Lecture 3:泛化、正则化与模型选择(Generalization, regularization & model selection)。

这一讲反复出现了同一个问题,只是换了名字:GDA 的强假设换来低方差、付出偏差;Laplace 的 α\alpha、kernel ridge 的 λ\lambda 和 σ\sigma、SVM 的 CC 都是在”拟合训练集”和”别太复杂”之间找平衡;每类 10 个样本时 GDA 输给逻辑回归,是因为参数太多、方差太大。第 3 讲把这些统一成 bias–variance 分解,用重复采样直接”看见”偏差和方差;讲清楚 ridge = 高斯先验的 MAP(和这一讲”Laplace smoothing = Dirichlet 先验”是同一个思想)、lasso 与稀疏性、交叉验证怎样选 λ\lambda / CC / σ\sigma;用最小范数插值解释 double descent;再从 Hoeffding 不等式出发讲有限假设类的样本复杂度和 VC 维 —— 本讲 §5.2 “间隔控制复杂度”的严格版本。§5.7 里”GD 自己挑出了 max-margin 解”,也会在那里作为 implicit regularization 的例子再出现。

← 返回课程目录