对应 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:
- 说清楚 discriminative 和 generative 两条路各自对什么建模、各自付出什么代价,并用 GDA vs logistic regression 的例子解释”更省数据”和”更稳健”为什么不可兼得。
- 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.
- 解释 Naive Bayes 的条件独立假设、两种 event model、Laplace smoothing;说清楚”假设错了为什么还能分类”以及”错在哪里”(过度自信的概率)。
- 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.
- 从”最大化几何间隔”出发得到 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 条件的结论) |
| 特征映射 、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(新增的符号)
| 符号 | 含义 |
|---|---|
| ;; | GDA 的参数:先验、两类的均值、共享的协方差 |
| 两类之间的马氏距离(Mahalanobis distance),决定分类难度 | |
| ; | 词表大小;词 在一封邮件里出现的次数 |
| ; | 特征映射;核函数。 是核矩阵(Gram matrix) |
| ; | SVM 的标签约定和参数(截距 单独写,不并进 ) |
| ; | SVM 对偶变量(每个样本一个);soft margin 的惩罚系数 |
第 1 讲把截距当作 的一个分量();SVM 按 CS229 讲义的写法把 单独拿出来。这个看似无关紧要的差别在 §5.7 会变得重要。
0.5 关于数字
讲义里所有实验数字都来自配套代码的实际输出(固定随机种子,同一台机器上重复运行逐字相同)。数据是合成的:我们知道”真相”,所以能检查算法有没有学对;数字本身不代表任何真实系统。和预想不一样的结果都如实写出来了,并记录在代码 README 的”关于实验结果”里。
1. Discriminative vs generative · 判别式与生成式
1.1 Two ways to build a classifier
第 1 讲的模型都直接对 建模:给定 , 是什么分布。这叫 discriminative(判别式)学习。另一条路是对数据是怎么产生的建模:先抽一个类别 ,再从这一类的分布里抽 。这叫 generative(生成式)学习。预测时用 Bayes 公式反推:
分类只需要 ,分母 对所有类别相同,可以不算。
Andrew Ng 的比喻:要区分大象和狗,判别式方法找一条把两类分开的边界;生成式方法分别画一张”大象长什么样”和一张”狗长什么样”,来了新动物就看它更像哪一张。
1.2 What each side pays for
| Discriminative(logistic regression、SVM) | Generative(GDA、Naive Bayes) | |
|---|---|---|
| 建模对象 | (或者只要一个边界) | 和 |
| 假设 | 只对边界 / log-odds 的形状做假设 | 还要对 的整个分布做假设 |
| 假设对的时候 | 估计方差较大 | 更省数据(多用了” 长什么样”的信息) |
| 假设错的时候 | 不受影响(只要边界的形状对) | 有偏,数据再多也修不好 |
| 训练 | 通常要迭代优化 | 常常是封闭解(数一数、求平均) |
| 附带的能力 | – | 能处理缺失特征、能采样生成新数据、能检测”不像任何一类”的输入 |
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 is harder than estimating a boundary ( is high-dimensional), which is why discriminative methods usually win when data are plentiful. 但”更难的问题”也带来了更多的结构:假设对的时候,它把这些结构变成了统计效率。§2.4 用实验把这句话变成数字。
2026 年的视角:今天的”generative model”(LLM、diffusion)建模的是 本身,目的是生成而不是分类;但”对数据的生成过程建模”这个思想和本讲的 GDA / Naive Bayes 一脉相承。
2. Gaussian discriminant analysis · 高斯判别分析
2.1 The model
关键的设计决定是两类共享同一个协方差 :两团形状、朝向都一样,只有中心不同。(统计学里这叫 linear discriminant analysis,LDA;两类各用自己的 叫 QDA。)
2.2 MLE in closed form
最大化联合似然 ,各参数解耦,答案就是”数一数、求平均”:
是 pooled covariance:每个点减去自己那一类的均值。不需要任何迭代 —— 对比逻辑回归要 GD 或 Newton。代码 01_gda_vs_logistic.py 演示 1(,每类 200 个点,真实 ):估计的 (真值 ),(真值对角 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 , the quadratic terms cancel, and what remains is linear in :
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 to . 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, . The posterior is again exactly logistic, with (max difference ). In general, any class-conditionals from the same exponential family that differ only in the natural parameter give a logistic posterior. So:
逻辑回归的假设严格更弱:它不在乎 长什么样,只要 log-odds 是线性的。
同一个模型族,不同的估计量。 GDA 和逻辑回归的 hypothesis class 一模一样(都是 ),但它们挑 的方式不同:GDA 最大化联合似然 ,逻辑回归最大化条件似然 。演示 1 在同一份数据上:
| 方法 | 总体错误率(精确值) | |
|---|---|---|
| GDA(封闭解,再换算) | 0.1590 | |
| logistic regression(Newton,6 步) | 0.1598 | |
| 真值(Bayes 最优) | 0.1587 |
2.4 GDA vs logistic: efficiency vs robustness
Which estimator is better? It depends on whether the Gaussian assumption is true. 演示 2、3 用学习曲线回答(,,;每个样本量重复 200 次;错误率是线性分类规则在总体上的精确错误率 —— 用 的封闭式算,不受测试集噪声影响)。
假设成立时(Bayes 最优 0.1056):
| 每类样本数 | 10 | 15 | 25 | 50 | 100 | 250 | 1000 |
|---|---|---|---|---|---|---|---|
| GDA 错误率 | 0.2287 | 0.1818 | 0.1459 | 0.1253 | 0.1148 | 0.1094 | 0.1065 |
| logistic 错误率 | 0.2022 | 0.1862 | 0.1585 | 0.1315 | 0.1174 | 0.1101 | 0.1068 |
| 多犯的错之比 LR / GDA | 0.78 | 1.06 | 1.31 | 1.32 | 1.29 | 1.21 | 1.31 |
“多犯的错”= 错误率 − Bayes 最优。从每类 15 个样本起 GDA 都更好,每类 ≥ 25 个时逻辑回归多犯的错是 GDA 的 1.2–1.3 倍,而且这个比值不随 趋于 1 —— 这就是 CS229 讲义说的”模型正确时 GDA 是 asymptotically efficient 的”:它用上了” 是高斯的”这条额外信息。(Efron 1975 专门算过逻辑回归相对于 normal discrimination 的渐近效率:两类分得越开,逻辑回归吃亏越多。)
But look at the first column: with only 10 points per class (20 points in ) GDA is worse. It has to estimate the 55 entries of ; with so few samples is poor and 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% 的正类样本被额外推远 ,落在离边界很远、毫无争议的一侧 —— 就是第 1 讲 §3.1 那些”特别大的肿瘤”的高维版本。 不再是高斯,但边界附近的后验几乎还是 sigmoid。Bayes 最优(Monte Carlo 估计)= 0.1001:
| 每类样本数 | 10 | 25 | 100 | 250 | 1000 | 100000(≈ ∞) |
|---|---|---|---|---|---|---|
| GDA 错误率 | 0.3209 | 0.2820 | 0.2019 | 0.1667 | 0.1442 | 0.1362 |
| logistic 错误率 | 0.1921 | 0.1539 | 0.1114 | 0.1048 | 0.1013 | 0.1002 |
Logistic regression wins at every sample size, and GDA’s gap does not shrink with : it stalls at 0.1362, 0.036 above Bayes, while logistic regression converges to 0.1002. Split by class (at per class), GDA errs 0.0297 on negatives but 0.2426 on positives: the tail drags away by () and stretches 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 模型的渐近错误率更低或相同。经验法则:
- 数据少、对 的形状有把握 → 生成式(GDA、Naive Bayes);
- 数据多、假设可疑 → 判别式(逻辑回归、SVM、神经网络)。
- 差别的本质是 bias–variance(第 3 讲):更强的假设 = 更小的方差 + 可能的偏差。
3. Naive Bayes · 朴素贝叶斯
3.1 Why an assumption is unavoidable
垃圾邮件分类: 表示词表里每个词出现没有。直接对 建模,一个一般的分布需要 个参数 —— 时完全不可能。必须做一个强假设。Naive Bayes 的假设是:给定类别,各个词相互独立(conditional independence):
参数从 个降到 个。注意右边:log-odds 是每个词的证据之和 —— 又是一个线性模型(在 的指示特征上),所以 Naive Bayes 也是 §2.3 那种”生成式模型的后验是逻辑函数”的例子。这个假设显然是错的(“click” 和 “here” 显然不独立),§3.4 讨论为什么它还能用。
3.2 Two event models
| Bernoulli event model | Multinomial event model | |
|---|---|---|
| 一封邮件表示成 | 维 0/1 向量:每个词出现没有 | 一串词;等价于 维计数向量 |
| 生成过程 | 每个词独立地掷一次硬币决定出现与否 | 每个位置独立地从本类的词分布 抽一个词 |
| MLE | ||
| 用上的信息 | 出现没有;没出现的词也算证据 | 出现几次;没出现的词不提供证据 |
代码 02_naive_bayes.py 构造了一个合成语料:(20 个常用词、15 个垃圾邮件词、15 个正常邮件词、250 个按 Zipf 定律递减的长尾词),每封邮件平均 20 个词,逐词独立地从本类的词分布里抽 —— multinomial NB 的假设恰好成立,用真实分布做 Bayes 最优分类的准确率是 0.9535。演示 1 的学习曲线(每个大小重复 10 次;NB 用 ,逻辑回归用词频做特征、):
| 每类邮件数 | 5 | 10 | 25 | 50 | 100 | 250 | 1000 |
|---|---|---|---|---|---|---|---|
| multinomial NB | 0.6344 | 0.7516 | 0.8673 | 0.9072 | 0.9266 | 0.9380 | 0.9475 |
| Bernoulli NB | 0.6797 | 0.7632 | 0.8704 | 0.9057 | 0.9266 | 0.9381 | 0.9471 |
| logistic regression | 0.5797 | 0.6424 | 0.7445 | 0.8451 | 0.8976 | 0.9255 | 0.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 训练集里没见过”的词, —— 无论其他词多么像垃圾邮件。
Laplace smoothing 给每个计数加 ( 就是”每个词先假装见过一次”):
| 0 | 0.001 | 0.01 | 0.1 | 0.3 | 1 | 3 | 10 | |
|---|---|---|---|---|---|---|---|---|
| multinomial 准确率 | 0.1935 | 0.8708 | 0.8708 | 0.8730 | 0.8762 | 0.8590 | 0.7993 | 0.6945 |
| Bernoulli 准确率 | 0.1925 | 0.8658 | 0.8658 | 0.8695 | 0.8732 | 0.8630 | 0.8393 | 0.7995 |
| multinomial log loss | 1.028 | 0.694 | 0.495 | 0.326 | 0.286 | 0.314 | 0.430 | 0.577 |
- : 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 , even 0.001, brings accuracy to 0.87. Accuracy is fairly insensitive to ; log loss is very sensitive — a tiny lets unseen words push probabilities to the extremes.
- 太大也不行: 时每个词”假装见过 10 次”,伪计数()远多于每类真实的约 500 个词,信号被抹平。同一个 对两种 event model 的强度不同(Bernoulli 的伪计数相对于 25 封邮件,multinomial 的相对于约 500 个词),所以大 时 Bernoulli 掉得慢。
一个构造的例子把”一票否决”看得最清楚:取 8 个真正像垃圾邮件的词(deal winner offer prize free 和 3 个长尾词),再加一个 spam 训练集里从未出现、ham 里出现过 5 次的词 “lunch”:
| P(spam | 8 个垃圾词) | P(spam | 8 个垃圾词 + lunch) | |
|---|---|---|
| 0.990 | 0.000000 | |
| 0.950 | 0.763 |
log 概率是逐词相加的,一个 压倒一切。 时 “lunch” 只是一条普通的、有限的反向证据。
Why “+α” is principled, not a hack. Laplace introduced add-one smoothing for the sunrise problem: having seen the sun rise times, the probability it rises tomorrow is , not 1. In Bayesian terms, is the posterior mean under a symmetric Dirichlet() prior on the word distribution (equivalently, the MAP estimate under Dirichlet()). So is a regularization strength expressed as pseudo-counts — the same idea as ridge = Gaussian prior in Lecture 3. 在这份数据上 log loss 最好的是 ,不是 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 假设恰好成立”的语料上训练(),再把每个词换成 个总是一起出现的不同的词(像 “click here now”),词表变成 个。NB 以为它们相互独立,于是同一份证据被数了 遍(每类 250 封训练、2000 封测试):
| NB 准确率 | NB log loss | NB ECE | “99.9% 确定”的比例 | 其中真正对的 | LR 准确率 | LR log loss | LR ECE | |
|---|---|---|---|---|---|---|---|---|
| 1 | 0.9335 | 0.155 | 0.0101 | 34.2% | 99.93% | 0.9275 | 0.193 | 0.0354 |
| 2 | 0.9335 | 0.205 | 0.0390 | 69.9% | 99.39% | 0.9235 | 0.190 | 0.0162 |
| 4 | 0.9335 | 0.363 | 0.0535 | 85.1% | 98.03% | 0.9193 | 0.198 | 0.0134 |
| 8 | 0.9335 | 0.689 | 0.0599 | 93.5% | 96.15% | 0.9135 | 0.218 | 0.0245 |
(ECE = expected calibration error:按置信度分箱,比较”说有多确定”和”实际有多准”。)
- Accuracy doesn’t move in the 4th decimal. After duplication each copy’s estimated probability is exactly of the original and every log-odds is exactly times the original (max difference , Exercise 4). Same sign, same decisions.
- Probabilities fall apart. At NB is well calibrated; at , 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 directly, so co-occurring features just share one weight instead of being counted times: its log loss only moves from 0.193 to 0.218. It isn’t untouched — the fixed L2 penalty spread over copies is effectively 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 说过:“线性模型”只要求对 线性,可以把 换成任意特征 。问题是好的特征往往非常多: 维输入的所有次数 的单项式有 个(代码 03_kernels.py 演示 1):
| 3 | 10 | 100 | 100 | 100 | 1000 | 784(MNIST) | |
|---|---|---|---|---|---|---|---|
| 次数 | 2 | 2 | 2 | 3 | 5 | 3 | 4 |
| 特征维数 | 10 | 66 | 5,151 | 176,851 |
MNIST 上的 4 次多项式特征,一个样本的特征向量就要 128 GB。在这么多特征上跑 LMS(每步 )是不可能的。
4.2 The kernel trick: θ stays in the span of the data
Run batch GD (LMS) in feature space from :
Every update adds a linear combination of the , so by induction at all times. Substitute this in and only ever appears inside inner products:
If can be computed without forming , we never pay for the dimension . For the polynomial kernel this is immediate: costs one -dimensional inner product, yet equals for a -dimensional (demo 1(a): max difference ). Demo 1(c) runs both versions of GD for 500 steps on 13-dimensional features: explicit and agree to , predictions to .
这就是 kernel trick 的全部前提,两个条件缺一不可:
- 算法只通过内积接触数据(LMS、ridge、SVM、PCA、k-means 都可以写成这样);
- 解在数据张成的空间里(representer theorem:对”损失 + 正则化”这一大类问题都成立)。
第 1 讲 §2.3 已经见过第二条的影子: 时从 0 出发的 GD 永远不会长出 列空间之外的分量,所以收敛到最小范数解。
4.3 RBF: an infinite-dimensional feature map
The Gaussian (RBF) kernel corresponds to an infinite-dimensional . In 1-D, Taylor-expand :
演示 1(b) 把这个无穷级数截断到前 维(),看近似误差:
| 输入范围 | 2 | 4 | 8 | 16 | 32 | |
|---|---|---|---|---|---|---|
| 0.63 | 0.26 | 0.019 | ||||
| 1.0 | 1.0 | 0.98 | 0.68 | 0.022 | ||
| 1.0 | 1.0 | 1.0 | 1.0 | 0.98 | 0.10 |
误差随 下降得极快,但输入范围越大需要的维数越多 —— 没有任何有限的 对所有输入都够用。核函数用 的代价”算完了”这个无穷级数。直觉上,RBF 是一个”相似度”: 时为 1,离得越远越接近 0, 决定”多远算远”。
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): is a valid kernel if and only if for every finite set of points the Gram matrix is symmetric positive semidefinite. 必要性一行就能看出来:。
演示 2 在 60 个随机二维点上算 Gram 矩阵的特征值:
| 核 | 最小特征值 | 负特征值个数 | 结论 |
|---|---|---|---|
| linear | 0 | 合法(秩 2,其余是舍入误差) | |
| poly | 0 | 合法(秩 10) | |
| RBF, | 0 | 合法 | |
| Laplace | 0.0325 | 0 | 合法 |
| RBF + poly;RBF × poly | ; | 0;0 | 合法(和与积仍是核) |
| −36.6 | 30 | 不合法 | |
| box | −4.26 | 24 | 不合法 |
| −248 | 1 | 不合法 |
- 合法的核做加法、乘法、正数缩放、 仍然合法 —— 这是构造新核的标准工具(和 = 特征拼接,积 = 特征的张量积)。
- “sigmoid 核” 在早期 SVM 文献里很流行(像一层神经网络),但这里 60 个点中有 30 个 —— 如果 ,这就是”长度的平方是负数”。
- box 核非常符合”相似度”的直觉(对称、自己和自己最像),却不合法:取最小特征值的特征向量 ,,相当于 。(Bochner 定理的直觉:平移不变的核合法 ⇔ 它的 Fourier 变换非负;盒子的 Fourier 变换是 sinc,有负的部分;高斯的还是高斯。)
- 不合法的后果:SVM 的对偶问题不再凹(没有唯一最优,SMO 的曲率可能 ≤ 0);kernel ridge 的 可能奇异。一个负特征值就足以证明不合法;一组点上没有负特征值只是”没找到反例”。
4.5 Kernel ridge regression and the O(n³) vs O(D³) trade-off
Ridge in feature space, , has two equivalent closed forms (push-through identity):
Primal solves a system, dual an one. Demo 3 checks they give the same predictions (difference with a quadratic kernel). 演示 3 的主角是第 1 讲 §2.5 的正弦数据 —— 同一份 15 个训练点(第 1 讲用多项式特征时最好的是 ,test MSE 0.159)。RBF 核、,扫带宽 :
| 0.01 | 0.03 | 0.05 | 0.1 | 0.2 | 0.3 | 0.5 | 1 | 3 | |
|---|---|---|---|---|---|---|---|---|---|
| train MSE | 0.0023 | 0.0048 | 0.0087 | 0.0238 | 0.0428 | 0.0521 | 0.1248 | 0.2196 | 0.2782 |
| test MSE | 0.4437 | 0.2869 | 0.2385 | 0.1785 | 0.1326 | 0.1330 | 0.2270 | 0.3320 | 0.4111 |
| 有效自由度 | 13.1 | 11.3 | 9.7 | 7.2 | 5.1 | 3.9 | 3.0 | 2.2 | 1.6 |
“有效自由度” ,衡量模型有多少个”有效参数”(和第 1 讲 LWR 的”有效样本数”是同一类量)。Small : 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 : all points look “equally similar” and the curve is flattened — underfitting. The best, , reaches 0.133, better than the best polynomial on the same data (0.159).
固定 扫 : 时有效自由度 10.5,曲线穿过噪声点,test MSE 3.17;、 时 0.143、0.133; 时曲线被压向 0,test MSE 0.402。RBF 核 = 无穷维特征 + ridge:表达能力无限,靠 和 两个旋钮控制复杂度(第 3 讲用交叉验证选)。
When to use the dual. small and large (ordinary linear regression) → primal. huge or infinite (high-degree polynomial, RBF) → dual. The price is the Gram matrix: memory and time. At the Gram matrix alone has 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 whose inner product approximates the kernel, then solve the primal) and Nyström (low-rank approximation of ).
4.6 Kernels in 2026
- Gaussian processes: the kernel-ridge prediction is exactly the posterior mean of a GP with covariance and noise variance ; 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): 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 . SVMs take the margin as the objective. With and :
几何间隔是点到超平面的带符号欧氏距离。functional margin 可以靠把 乘以 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 can be rescaled freely, fix the smallest functional margin to 1; maximizing is then the convex QP
为什么”最大间隔”是好的归纳偏置? 三个角度:
- Robustness. With margin , every training point can be perturbed by up to 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 , the effective capacity (VC dimension) of linear classifiers with margin is controlled roughly by rather than by the dimension (Vapnik). This is the theoretical reason an SVM can work in the infinite-dimensional RBF feature space without overfitting. Lecture 1’s Novikoff bound 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 讲感知机那份可分数据比较几个分隔面的间隔:
| 分隔面 | 空间的几何间隔 | 增广空间 的间隔 |
|---|---|---|
| perceptron(第 1 讲) | 0.4125 | 0.1759 |
| logistic,(第 1 讲) | 0.8771 | 0.3152 |
| hard-margin SVM(SMO, 不受惩罚) | 0.9396 | 0.3463 |
| 增广空间里间隔最大的方向 | 0.9396 | 0.3463 |
第 1 讲演示 4 的”间隔”(0.1759、0.3152)是在增广空间里量的(除以包括截距的 ),所以和这里的第一列不是同一个量;两种都列出来了。用增广空间里最大的间隔,Novikoff 上界从第 1 讲的 759 降到 629,仍远大于感知机实际犯错的 10 次。
5.3 Lagrange duality, KKT and support vectors (results only)
Introducing a multiplier per constraint, the dual problem is
and the KKT conditions give three facts we actually use:
- — the solution is a combination of training points (the representer theorem again).
- Complementary slackness: . Points strictly outside the margin have ; only points on the margin can have . These are the support vectors.
- Strong duality holds: the optimal primal and dual objectives are equal — a free convergence check.
The equality constraint comes from differentiating with respect to ; remember it, it explains SMO (§5.6).
演示 1 的数字:100 个点里只有 3 个 support vectors(),它们的 functional margin 恰好都是 1,其余点最小 1.041;;primal = dual = 0.566406。稀疏性的直接证明:扔掉其余 97 个点、只用 3 个 support vectors 重新训练, 的最大差是 。预测 也只需要对 support vectors 求和。
5.4 Kernel SVM
The dual and the prediction touch the data only through — condition 1 of §4.2. Replace it by and the same QP, the same solver and the same code learn a nonlinear boundary. 演示 3:同心圆(内圈负类、外圈正类,训练 200、测试 2000,):
| 核 | #SV | 训练准确率 | 测试准确率 |
|---|---|---|---|
| linear | 197 | 0.610 | 0.5705 |
| poly,degree 2 | 19 | 0.980 | 0.9780 |
| RBF, | 200 | 1.000 | 0.6710 |
| RBF, | 187 | 1.000 | 0.9180 |
| RBF, | 89 | 0.995 | 0.9735 |
| RBF, | 53 | 0.985 | 0.9770 |
| RBF, | 129 | 0.975 | 0.9730 |
| RBF, | 200 | 0.695 | 0.6710 |
- No line separates concentric circles (0.5705 ≈ guessing). The degree-2 polynomial kernel’s features include and , 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 did.
- RBF 的 又是复杂度旋钮: 时训练全对、测试 0.671,每个点都是 support vector —— 在背训练集; 时所有点之间的核值都接近 1, 下模型几乎弯不动,欠拟合(我们本以为它会”退化成线性 SVM”,实际上 0.671 比线性的 0.5705 好不少,更准确的描述是”欠拟合”)。
- The number of support vectors is a rough complexity meter: close to usually means over- or underfitting ( or badly chosen). The classical leave-one-out bound is LOO error (Exercise 6).
5.5 Soft margin, C and the hinge loss
Real data are rarely separable. Allow violations with slacks and pay per unit:
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: . KKT now sorts points into three groups: (outside the margin), (exactly on it), (inside it or misclassified).
演示 2(两团重叠的高斯,训练 200、测试 5000,特征先中心化):
| 0.001 | 0.01 | 0.1 | 1 | 10 | 100 | |
|---|---|---|---|---|---|---|
| #SV(其中 的) | 200 (200) | 134 (131) | 86 (83) | 77 (74) | 75 (72) | 75 (72) |
| 间隔宽度 | 9.75 | 2.96 | 1.87 | 1.70 | 1.70 | 1.70 |
| SVM 测试准确率 | 0.8668 | 0.8666 | 0.8602 | 0.8616 | 0.8614 | 0.8614 |
| 同 的 logistic | 0.8668 | 0.8654 | 0.8610 | 0.8594 | 0.8594 | 0.8594 |
| SMO 更新的 对数 | 100 | 88 | 79 | 1348 | 7160 | 75658 |
- Small = strong regularization: a very wide margin, with almost every point inside it and a support vector. Large : the margin narrows to 1.70 and then stops changing — the data aren’t separable, the minimum hinge loss is finite, and a larger only approaches that minimizer.
- 这份二维数据的 Bayes 边界就是一条直线,所有 的测试准确率都在 0.860–0.867,正则化的强弱影响不大。 真正重要的是高维、噪声大的数据(第 3 讲)。
- The relative duality gap (primal − dual)/primal is below for every . Larger makes SMO slower: many have to creep up to in small steps. (An earlier version also had : 780,013 pair updates, with every reported quantity (#SV, margin width, accuracy) identical to , so it was dropped to keep the runtime short.)
5.6 SMO: why two variables at a time
The dual is a QP with variables; generic QP solvers need memory and are slow. Sequential Minimal Optimization (Platt 1998) is coordinate ascent with a twist. 只改一个 不行:等式约束 会把它钉死(其他的 不动时 是确定的)。所以每次改一对 :沿着保持 不变的方向移动,目标函数是一元二次函数,最优步长有封闭解,再截断到 的盒子里。整个子问题不需要任何数值优化器。
怎样选这一对?CS229 讲义的”简化版 SMO”随机选第二个;smo_train 用 LIBSVM 的 maximal violating pair(Keerthi et al. 2001):选 KKT 条件被违反得最厉害的一对,违反程度小于容差就停止。每步更新梯度只要 。
反过来看:如果没有截距 ,对偶里就没有等式约束,可以一次只改一个 —— 这就是 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
| SVM | Logistic regression | |
|---|---|---|
| 损失 | hinge:margin ≥ 1 后恰好为 0 | logistic:永远 > 0,margin 大时趋于 0 |
| 解的结构 | 稀疏:只依赖 support vectors | 每个点都有一点贡献 |
| 输出 | 只有符号 / 到边界的距离(概率要靠 Platt scaling 另外拟合) | 校准过的概率 |
| 核化 | 自然(稀疏的对偶) | 可以(kernel logistic regression),但对偶不稀疏 |
| 多分类 | one-vs-rest / one-vs-one 拼装 | softmax 自然推广 |
| 准确率 | 通常差不多 | 通常差不多 |
演示 2 的最后一行:同样 的逻辑回归和 SVM 的测试准确率最多差 0.0022。(初版里 时逻辑回归明显更差 —— 第 1 讲的实现连截距一起惩罚,SVM 的 不受惩罚;不中心化时逻辑回归掉到 0.7612。比较两个模型时,先确认它们解的是同一个问题。)
The payoff. Lecture 1 §3.5 showed that on separable data unregularized logistic regression has no MLE: , but the direction seemed to settle, and we quoted Soudry et al. (2018): GD converges in direction to the max-margin solution. 演示 4 兑现这个承诺,用的是第 1 讲同一份可分数据、同一个 GD(步长 ,; 步时 ,和第 1 讲逐位相同):
| GD 步数 | 10 | 100 | ||||
|---|---|---|---|---|---|---|
| 0.61 | 2.05 | 4.76 | 7.95 | 11.90 | 16.73 | |
| 与 max-margin 方向的夹角 | 44.9° | 8.69° | 2.08° | 0.97° | 0.31° | 0.066° |
| L2 逻辑回归的 | 0.1 | 0.01 | ||||
|---|---|---|---|---|---|---|
| 与 max-margin 方向的夹角 | 13.8° | 4.05° | 1.72° | 0.81° | 0.26° | 0.068° |
“不加正则化跑很久的 GD”和” 的正则化路径”(Rosset, Zhu & Hastie 2003)走到同一个方向 —— 优化算法本身在做正则化,这就是第 3 讲的 implicit regularization。
一个要说清楚的细节:哪一个 SVM? 第 1 讲把截距当作 的一个分量,GD 对 一视同仁。Soudry 的定理说的是增广空间里的 max margin:
截距也被惩罚了,和 §5.2 的标准 SVM 不是同一个问题。在第 1 讲那份数据上两者恰好相同(夹角 0.0000°):3 个 support vectors 给出 3 个等式,正好钉死 3 个参数 。为了看到差别,演示 4(b) 手工构造了 6 个点 —— 负类 (1,2) (0,4) (0,0),正类 (3,2) (4,4) (4,0):
- 标准 SVM 是竖线 ,几何间隔 1,只有 2 个 support vectors,;
- 截距被惩罚的 SVM 宁可把间隔降到 0.894,换一个更小的 :,和标准 SVM 差 26.6°。
| GD 步数 | 10 | 100 | ||||
|---|---|---|---|---|---|---|
| 与”截距被惩罚的 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 明确地走向前者( 的 L2 逻辑回归也是:0.97° vs 25.7°)。所以准确的说法是:GD 最大化的是增广空间 里的间隔,它依赖于坐标原点放在哪里;只有截距不进入 (不被惩罚),才对应教科书上的 SVM。
收敛有多慢? Soudry et al. 证明方向误差一般只按 下降。(b) 里从 到 步夹角缩小 1.46 倍, 预测的是 倍 —— 吻合。(a) 在 – 步之间每 10 倍步数缩小 2–5 倍,比 快得多: 是一般情况下的速度,具体数据的几何可以更友好。两种情况都说明:别指望靠”多跑几步”得到 SVM,要 max margin 就直接解 SVM。
6. 小结 · Summary
| 方法 | 建模对象 | 关键假设 | 训练 | 预测用到 | 主要优点 | 主要风险 |
|---|---|---|---|---|---|---|
| GDA | 高斯、共享 | 封闭解 | Bayes 公式(= 逻辑函数) | 假设对时最省数据 | 假设错时有偏;小样本时 不准 | |
| Naive Bayes | 给定 各特征独立 | 数数 + 平滑 | 证据相加 | 极快、极小样本也能用 | 概率过度自信;零计数 | |
| Logistic regression | log-odds 线性 | Newton / GD | 稳健、给出校准的概率 | 小样本方差大;可分时需要正则化 | ||
| Kernel ridge | 函数在 RKHS 里”光滑” | 无穷维特征、封闭解 | 内存、 时间 | |||
| SVM | 边界 | 最大间隔 | SMO / 对偶坐标下降 | 稀疏、可核化、间隔控制复杂度 | 没有概率;、 要调 |
Five takeaways:
- 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.
- 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).
- Naive Bayes classifies well and estimates probabilities badly: double-counted evidence scales the log-odds without flipping its sign. Smoothing is a prior, and is a hyperparameter.
- 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 to .
- 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 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.” is a prior strength. Here the log loss was best at , and wiped out the signal.
- “Any similarity function is a kernel.” The box kernel and 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 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 .
- “Kernel methods scale like linear models.” The Gram matrix is ; beyond ~ points you need approximations.
8. 练习 · Exercises
练习 1(GDA 的边界与参数个数). (a) 证明两类共享 时 GDA 的决策边界是超平面;两类各有 (QDA)时是二次曲面。(b) 在 维里,GDA、QDA、逻辑回归各有多少个参数? 时分别是多少?这和 §2.4 第一列”GDA 在每类 10 个样本时更差”有什么关系?
参考答案
(a) log-odds 。高斯的对数密度里 的二次项是 ;共享 时两项相减为 0,只剩线性项,边界 是超平面。 时剩下 ,边界是二次曲面。(b) GDA:;QDA:;逻辑回归:。 时分别是 76、131、11。GDA 要估计的参数是逻辑回归的 7 倍,虽然每个参数(均值、协方差)都很容易估计,样本极少时 的误差会经过 放大到 上。QDA 更甚:每类 10 个样本时 只有 9 个自由度,在 10 维里是奇异的。
练习 2(Exponential-family class-conditionals). Suppose for , with the same and . Show that and find . Check that GDA (with known shared ) and the Poisson example of §2.3 are special cases.
参考答案
log-odds , 抵消。所以 ,。GDA:、、(共享 才能让 相同)、,和 §2.3 的公式一致。Poisson:、、,得 、,正是代码 01 演示 1(b) 用的公式。逻辑回归对这一整族生成模型都是”正确”的,这是它更稳健的根本原因。
练习 3(Smoothing as a prior). (a) Show that with a Dirichlet() prior on the word distribution , the posterior mean of is . (b) In demo 2 each class has about 500 training words and . What fraction of the “total evidence” is pseudo-counts when ? When ? Relate this to the accuracy column.
参考答案
(a) Dirichlet 是多项分布的共轭先验:后验是 Dirichlet(),Dirichlet() 第 个分量的均值是 ,代入即得。(MAP 是 ,所以”加 “也可以看成 Dirichlet() 先验下的 MAP。)(b) 伪计数 : 时 300,占 ; 时 3000,占 —— 估计出的词分布几乎就是均匀分布,信号被抹平,准确率掉到 0.6945。词表越大、训练集越小,同一个 的正则化越强,这也是 log loss 在 而不是 1 处最好的原因。
练习 4(Double-counted evidence). In demo 3 every word is replaced by always-co-occurring copies. Show that with multinomial NB and Laplace smoothing , each copy’s estimated probability is exactly (where is the estimate with the same ), and that the log-odds of every document is multiplied by exactly when the classes are balanced. Why does accuracy stay identical while log loss grows?
参考答案
复制后每个副本的计数都是 ,类的总词数变成 ,词表变成 :。一封文档里每个副本出现 次,log 似然 ; 与类别无关,在 log-odds 里抵消,剩下 (原来的 log-likelihood ratio)。先验相等时 log-odds 恰好乘以 。符号不变 → 分类不变;但 随 越来越接近 0/1,错的那些样本被”自信地”判错:一个分错的样本的损失是 ,随 大致线性增长;分对的样本损失只能降到 0,抵不过这一项。
练习 5(Valid or not?). For each, decide whether it is a valid kernel on and justify: (a) ; (b) with valid; (c) for any real function ; (d) ; (e) .
参考答案
(a) 合法:,。(b) 合法:;对应特征拼接。(c) 合法:一维特征 ,Gram 矩阵 半正定。(d) 不合法:对角线 ,所以 Gram 矩阵的迹为 0;只要两个点不同,矩阵非零,特征值之和为 0 就必有负特征值(演示 2 的 也不合法:它的迹也是 0)。(e) 一般不合法:取 , 任何非零的合法核即得反例。
练习 6(Sparsity and leave-one-out). (a) Using complementary slackness, argue that removing a training point with and retraining leaves the hard-margin SVM unchanged (demo 1 did this numerically). (b) Deduce the classical bound: leave-one-out error . (c) What does the bound say for the RBF row of §5.4, and is it useful there?
参考答案
(a) 原来的最优解 去掉第 个分量后,对新问题仍然满足 KKT 条件:原始可行(少了一个约束更容易满足)、对偶可行、(因为 )、互补松弛。凸问题里 KKT 是最优的充分条件,所以解不变。(b) 留一法里,被留出的点如果不是 support vector,解不变,而训练时它被正确分类(在间隔外),所以留一法下也分对;只有 support vector 被留出时才可能分错。所以错误数 。(soft margin 时类似的论证给出 的界。)(c) 时 200 个点全是 support vectors,上界是 1 —— 毫无用处,但它正确地报警了:support vector 太多说明模型在记忆训练集(测试准确率只有 0.671)。 时上界 ,实际测试错误率 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 的 、kernel ridge 的 和 、SVM 的 都是在”拟合训练集”和”别太复杂”之间找平衡;每类 10 个样本时 GDA 输给逻辑回归,是因为参数太多、方差太大。第 3 讲把这些统一成 bias–variance 分解,用重复采样直接”看见”偏差和方差;讲清楚 ridge = 高斯先验的 MAP(和这一讲”Laplace smoothing = Dirichlet 先验”是同一个思想)、lasso 与稀疏性、交叉验证怎样选 / / ;用最小范数插值解释 double descent;再从 Hoeffding 不等式出发讲有限假设类的样本复杂度和 VC 维 —— 本讲 §5.2 “间隔控制复杂度”的严格版本。§5.7 里”GD 自己挑出了 max-margin 解”,也会在那里作为 implicit regularization 的例子再出现。