泛化:先说明哪些新样本重要
Generalization
用精确有限分布计算,分清训练分数、新样本风险和组混合权重变化。
generalization高平均分可能遮住错误发生的位置
设想一个虚构字符读取器,它只有一个粗糙特征:把笔画识别为 left 或 right。固定规则是 left 预测标签 0,right 预测标签 1。字符分为两种风格。为了让每一步都能精确核对,我们手工指定概率:
| 风格组 | 在 P 中的比例 | 组内错误率 | 组内准确率 |
|---|---|---|---|
| plain:普通 | 95% | 2% | 98% |
| ornate:花体 | 5% | 40% | 60% |
总体错误率为 3.9%,即准确率 96.1%。这个平均数没有算错,只是它回答的问题不同于“读取器处理花体有多好”。如果未来两种风格各占一半,总体错误率会变成 21%,即使规则及两个组的条件错误率都没变。
本篇区分三个问题:用于拟合或选择模型的样本表现、同分布新样本上的风险,以及分布改变后的风险。一次测试分数不能同时回答三者。这张表是概率模型,不是真实字符识别系统的测量结果。
先说明风险针对哪个总体
对二元预测器 使用零一损失:标签预测错记一,正确记零。令 描述组、特征与标签的联合分布。总体风险是期望,经验风险则是某个非空样本上的平均:
学习时,拟合出的预测器 依赖训练样本。训练错误与总体风险不必相同。差值 称为泛化间隙;有些资料报告其绝对值,或对可能的训练样本再取平均,所以记号约定很重要。间隙小也不够:模型可能在训练数据和新数据上都同样差。
实际问题通常不知道完整总体分布,可用独立留出数据估计。预测器固定后,令 包含从 独立抽取的 个观察,且 与拟合的预测器独立,则:
每个错误指示量都是成功概率为该风险的伯努利变量,独立性使方差可以相加。这个结论针对反复可能抽到的测试样本,不保证某一次分数确定无误。如果用同一个测试集挑模型或调参数,就破坏了独立性前提。教材的留出集讨论明确强调了新样本的作用。Shalev-Shwartz 与 Ben-David,第 11.2.1 节。
训练、用于选择设置的验证,以及最终测试各有不同用途。把观察放在不同行,并不能建立独立性:同一原始文档的多个版本可能同时出现在划分两侧。应该按什么单位抽样,取决于部署时的“新”究竟指什么。这是评测设计的条件,不是模型能从文件名自动推断出的性质。
现在假设组构成一个划分,每个例子恰好属于一个组。对正概率组,令 为条件错误率,。由全期望公式得到:
这里的求和与最大值只遍历源分布质量为正的组;源质量为零的组需要额外信息,才能赋予目标权重。平均数按组的常见程度加权,不会给每个组相同影响力。如果审计类别相互重叠,就不能不作调整地套用这个划分公式。有限样本中没有出现的组,并没有样本错误率估计;它的错误率不是零。
在组混合权重迁移中,每个组内的特征和标签条件分布保持不变,组权重改为 。对同一个预测器:
任何加权平均都不超过最大的组错误率,把全部权重放在最大组上就能达到它。这个最坏情况结论只覆盖已指定、已知条件分布的混合,不覆盖新组或组内部行为改变。Sagawa 等人在定义 group DRO 时使用了这种组混合不确定性集合;最坏组训练损失很小,仍不必意味着最坏组总体损失很小。原论文第 2 节。
组混合变化只是分布变化的一种。预测器看不到组时,这种变化未必保持 不变。新的标签规则、测量故障或新特征值,可能需要另一个目标分布。如果条件错误率本身已不适用,仅给旧组错误率换权重无法修复这个假设。
先算总体,再审视一个样本
程序接收有限的 (group, feature, label, probability) 单元表。概率必须是精确 Fraction 或整数,非负且总和为一。重复单元的概率质量会合并。标签必须为整数 0 或 1;布尔值及浮点概率被拒绝。预测字典对每个已声明特征恰好给一个固定标签。组身份用于审计,不输入这条预测规则。
可选样本是由不带概率的观察单元组成的有序 list 或 tuple,重复观察重复计数。每个事件必须属于表中的正概率支持集。通过这项检查,并不证明抽样独立或没有人为筛选。程序不训练模型,也不提供置信区间。gap 是总体风险减去给定样本错误;若把样本解释为训练数据,还需要知道预测器如何产生。
remix 修改组权重,保留各组现有条件分布。如果原组质量为零,却要求新的正权重,它会拒绝:这些行并未确定一个可迁移的条件分布。零质量组风险和空样本错误都返回 None,不编造为零。最坏组结果只考虑条件风险有定义的正质量组。
# Python 3.10+; a known finite distribution and a fixed binary predictor.
from collections import Counter
from fractions import Fraction as F
def name(value):
if type(value) is not str or not value:
raise ValueError('group and feature names must be nonempty strings')
return value
def label(value):
if type(value) is not int or value not in (0, 1):
raise ValueError('labels must be integer 0 or 1, not booleans')
return value
def probability(value):
if type(value) not in (int, F) or value < 0:
raise ValueError('use a nonnegative exact Fraction or integer')
return F(value)
def distribution(rows):
if type(rows) not in (list, tuple):
raise ValueError('distribution must be a list or tuple')
cells = {}
for row in rows:
if type(row) is not tuple or len(row) != 4:
raise ValueError('cell: (group, feature, label, probability)')
g, x, y = name(row[0]), name(row[1]), label(row[2])
key = (g, x, y)
cells[key] = cells.get(key, F(0)) + probability(row[3])
if sum(cells.values(), F(0)) != 1:
raise ValueError('probabilities must sum exactly to one')
return tuple((*key, mass) for key, mass in sorted(cells.items()))
def assess(rows, predictions, sample=()):
table = distribution(rows)
features = {x for _, x, _, _ in table}
if type(predictions) is not dict or set(predictions) != features:
raise ValueError('supply exactly one prediction for every declared feature')
predictions = {name(x): label(y) for x, y in predictions.items()}
mass, wrong = {}, {}
support = set()
for g, x, y, weight in table:
mass[g] = mass.get(g, F(0)) + weight
wrong[g] = wrong.get(g, F(0)) + weight * (predictions[x] != y)
if weight > 0:
support.add((g, x, y))
if type(sample) not in (list, tuple):
raise ValueError('sample must be a list or tuple')
counts, errors = Counter(), Counter()
for row in sample:
if type(row) is not tuple or len(row) != 3:
raise ValueError('sample row: (group, feature, label)')
g, x, y = name(row[0]), name(row[1]), label(row[2])
if (g, x, y) not in support:
raise ValueError('sample event is outside the positive support')
counts[g] += 1
errors[g] += predictions[x] != y
risk = sum(wrong.values(), F(0))
empirical = F(sum(errors.values()), len(sample)) if sample else None
groups = {g: dict(mass=mass[g], risk=wrong[g] / mass[g] if mass[g] else None,
count=counts[g], empirical_risk=F(errors[g], counts[g])
if counts[g] else None) for g in sorted(mass)}
return dict(risk=risk, worst_group_risk=max(
v['risk'] for v in groups.values() if v['risk'] is not None),
sample_size=len(sample), empirical_risk=empirical,
gap=None if empirical is None else risk - empirical, groups=groups)
def remix(rows, weights):
table = distribution(rows)
mass = {}
for g, _, _, value in table:
mass[g] = mass.get(g, F(0)) + value
if type(weights) is not dict or set(weights) != set(mass):
raise ValueError('supply exactly the declared groups')
weights = {g: probability(value) for g, value in weights.items()}
if sum(weights.values(), F(0)) != 1:
raise ValueError('new group weights must sum to one')
if any(weights[g] > 0 and mass[g] == 0 for g in mass):
raise ValueError('cannot infer a conditional distribution from zero mass')
return tuple((g, x, y, value * weights[g] / mass[g] if mass[g] else F(0))
for g, x, y, value in table)
def font_example():
rows = []
for g, mass, error in [('plain', F(19, 20), F(1, 50)),
('ornate', F(1, 20), F(2, 5))]:
for x, predicted in [('left', 0), ('right', 1)]:
for y in (0, 1):
rows.append((g, x, y, mass * (error if predicted != y else 1-error) / 2))
return tuple(rows), {'left': 0, 'right': 1}
if __name__ == '__main__':
P, h = font_example()
# Constructed sample for inspection; not claimed to be a random draw.
sample = (('plain', 'left', 0), ('plain', 'right', 1)) * 10
report = assess(P, h, sample)
Q = remix(P, {'plain': F(1, 2), 'ornate': F(1, 2)})
print('P error:', report['risk'])
print('group errors:', tuple((g, v['risk']) for g, v in report['groups'].items()))
print('sample error:', report['empirical_risk'])
print('ornate sample count/error:', report['groups']['ornate']['count'],
report['groups']['ornate']['empirical_risk'])
print('population minus sample:', report['gap'])
print('Q error:', assess(Q, h)['risk'])
print('worst group:', report['worst_group_risk'])
print('IID chance of no ornate examples in 20:', round(float(F(19, 20)**20), 6))
完整程序输出:
P error: 39/1000
group errors: (('ornate', Fraction(2, 5)), ('plain', Fraction(1, 50)))
sample error: 0
ornate sample count/error: 0 None
population minus sample: 39/1000
Q error: 21/100
worst group: 2/5
IID chance of no ornate examples in 20: 0.358486
展示的样本是人为构造的,包含 20 个预测正确的普通字符。样本零错误不会抹去花体组 40% 的总体错误。花体观察数为零,因此样本风险是 None。若从 独立抽取 20 个观察,完全没有花体的概率为 。这是缺席概率,不是所有预测正确的概率;构造样本也没有被冒称为随机抽样结果。
这里正的样本间隙为 3.9 个百分点,却不能据此诊断过拟合:预测器事先固定,并未运行训练程序。等权目标 的风险为 ,即准确率 79%。错误率增加的 17.1 个百分点,在这个例子里完全由组权重变化造成。
给定特征在两个组里都不完美。事实上,这条规则在每个特征与组的组合中选择的都是更可能的标签。某个组错误很高,本身并不能证明另一个分类器只用这些有限信息就能消除错误。获取更好的信息、采用不同模型,与正确评测是不同的问题。
设输入分布有 行,样本有 个观察,评估需要 次字典、比较及有理数运算,辅助记录为 。计数时不保留样本历史。重加权具有相同的排序量级,但没有样本项。上界假设通常的期望散列表行为,数的是有理运算而非位运算:大分母和长名字会增加成本。示例中的小数概率仅为打印而舍入,风险运算始终精确。
独立测试把小型有理分布展开为等概率票,再数错误,不复用按概率求加权和的算法。它们核对完整报告、混合变化、缺席组及错误输入;这种穷举参照刻意只用于微型分布。
一张分组表不能代表整个部署环境
总体分数高,可以与某个组表现差同时发生。所有已选组的最坏分数也很高,仍可能遮住未定义的子组。划分和损失指标必须对应所问的问题,它们本身就是评测规格的一部分。
如果审计刻意从每个组抽相同数量的样本,未经加权的平均数估计的是这种抽样混合。要估计另一个总体的平均,需要使用目标组权重及合适的条件估计。多抽小组样本有助于了解它,但不能把额外样本数当成它在真实总体中的频率。
抽样不确定性与分布变化不同。更大的独立测试集可以改善对其抽样分布的估计,却不能证明明年的分布仍相同。反复用一个测试集作决策,也会削弱最终分数对新总体的说明力。报告分数时,应一并记录抽样单位、目标分布、组计数、预测规则及决策过程。
这个有限表把真实概率作为构造条件给出。现实中通常没有这种便利,落在已有支持集里也不证明有代表性。程序既不能发现所有迁移,也不会学习稳健预测器。训练目标见经验风险最小化,重复数据划分见交叉验证。
改数字之前,先确认问题
练习 1:计算两个总体错误率
答案:在 下为 ;两组等权时为 。准确率是一减错误率,所以分别为 96.1% 和 79%。预测器没有改变任何参数。
练习 2:没有花体样本,意味着什么?
答案:没有花体错误率的样本估计,应返回 None 并报告计数零,不能写成错误率 0% 或准确率 100%。若从 独立抽取 20 个观察,缺席概率为 ,约 35.8%。刻意只选普通字符的样本不具有这种随机抽样解释。
练习 3:重加权能预测所有未来风险吗?
答案:不能。这里有效,是因为每个组内部的条件分布没变。如果花体错误率从 40% 升至 80%,其比例仍为 5%,总体错误率会变成 。继续沿用旧条件错误率会得到 0.039,结果就错了。
练习 4:最坏组上界覆盖什么?
答案:所给两种条件分布的任何混合,错误率都不超过 40%;全部质量放在花体组上即可达到。它不约束第三种新风格或组内数据改变。把总体组错误率换成带噪声的训练估计,也不会自动保留总体保证。
总体风险是目标,数据集提供证据
Shalev-Shwartz 与 Ben-David,Understanding Machine Learning: From Theory to Algorithms(2014),作者书籍页面,第 11.2.1 节解释了用独立于训练的新样本估计风险。有限假设类的集中界证明放在独立的经验风险章节;本篇使用基本条件期望及组分解。
Sagawa、Koh、Hashimoto 与 Liang 的 Distributionally Robust Neural Networks for Group Shifts,ICLR 2020 论文、arXiv 第 2 版,区分总体组风险与对应训练目标。其经验发现依赖具体数据集、模型及正则条件。这里的字形概率、固定预测器、程序及习题均为原创,没有复现那些神经网络实验。
先判断,再看解释
普通组错误率 2%,花体组 40%。花体比例从 5% 变为 50%,组内条件分布和模型都没变,新错误率是多少?
学习目标
- 区分训练误差、同分布总体风险与一次测试估计,说明独立性和抽样单位的作用。
- 精确分解总体与组风险,解释少数组缺席为何不能记为零错误。
- 在固定组条件分布下计算重加权风险,并指出新组或组内部变化超出该保证。
先修与延伸
查看知识关联图 →参考文献
- Understanding Machine Learning: From Theory to Algorithms — author online copy
Shai Shalev-Shwartz; Shai Ben-David · 2014 - Distributionally Robust Neural Networks for Group Shifts: On the Importance of Regularization for Worst-Case Generalization
Shiori Sagawa; Pang Wei Koh; Tatsunori B. Hashimoto; Percy Liang · 2020
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.
- 8 项标准库测试通过。独立等概率票参照共核对 43 个完整报告、14,880 张票,包括四种二元预测规则与五种组混合;不复用生产加权求和。P 风险39/1000、等权Q风险21/100、最坏组2/5及组内变化反例59/1000均精确成立。
- 检查零质量组的未定义条件风险、不能从零质量组恢复条件分布、空样本与缺席组None、重复样本计数、负样本间隙、重复分布行合并、输入保全和21项非法输入。八行完整stdout实际核对;35.8%仅指IID抽样下没有花体的概率,不指零错误概率。
- 复核独立测试集均值/方差与组期望分解;混合最坏风险只涵盖已知正质量组的固定条件分布。明确构造样本并非随机抽样,程序没有训练模型;总体真概率只在这个教学表中已知,不把一次测试分数当泛化证明。
- 双语 6 锚点、4 相同显示式、相同完整程序/输出及4已答练习齐全;严格MDX/KaTeX/React实际HTML和MathML对应通过。测试统一由article_text读取正文代码及输出,出版仅需改路径。Humanizer定向扫描及逐段AI复读完成,保持written;未做全站构建、浏览器验收、人类审校或真实OCR实验。
- 完整复读双语正文、程序、8作者测试与metadata,8项均通过。固定预测器而非训练、总体减样本间隙、缺席组None、零质量条件分布、正支持集校验和限定的组混合迁移区分准确。
- 独立二元损失矩与错误次数概率生成函数未使用作者等概率票据。3目标混合与4预测器给出36总体/组风险检查及36精确IID留出均值/方差检查;12标签翻转保持完整报告,条件相同的拆组及零质量独有特征校验另有3边界,均通过。
- 核对一般期望/方差推导、组划分要求及单纯形最坏风险证明。同条件重加权不是任意分布迁移,样本属于支持集也不认证IID。没有学习过程,构造样本间隙不证明过拟合;P风险39/1000、等权风险21/100和花体缺席概率(19/20)^20的不同含义准确。
- 最终5SHA匹配。strict MDX/KaTeX及React实际HTML通过,两语各4相同显示式、6锚点4答案,完整代码输出对应。成本计入规范化排序及不保存样本历史的计数,哈希与位成本假设明确。未修改原稿或仓库,不含浏览器/全站或真实OCR核验。
- 完整正文、公式、代码和习题迁入;测试只读取正式MDX,删除临时目录回退及草稿跳过,状态断言更新为checked。没有修改算法或独立参照,最终记录绑定两语SHA。
- 出版导航把已存在正文的目录链接指向完整文章,其余目录入口保留;原理、公式、程序与习题未改,重新绑定最终正文SHA。
核对的来源位置:
- Understanding Machine Learning: From Theory to Algorithms — author online copy · Actually read the full primary-PDF text excerpt returned by targeted web search for §11.2 Validation and §11.2.1 Hold Out Set, printed p. 146: fresh examples drawn from D independently of training, and independence from the way h was generated. Also read the returned §11.3 passage, p. 151, on training, parameter selection and testing. Direct open/find attempts on the PDF failed or returned no usable text, so no full PDF or visual inspection is claimed. The article does not reproduce the excerpt’s Hoeffding theorem; its Bernoulli expectation/variance calculation is derived separately. The book card is shared with the independently sourced empirical-risk chapter.
- Distributionally Robust Neural Networks for Group Shifts: On the Importance of Regularization for Worst-Case Generalization · Actually opened and read arXiv:1911.08731v2: cover/abstract and introduction, web lines 0–110; §2, lines 111–161, defines expected population loss, empirical training loss, mixtures of fixed group distributions, maximum conditional risk, and the distinction between worst-group empirical and population risks. The header gives ICLR 2020, while line 50 records v2 on 2 April 2020. No claim to audit all 19 pages, reproduce reported percentage improvements, or execute group-DRO training.
- Understanding Machine Learning: From Theory to Algorithms — author online copy · Independently read the full targeted-search excerpt of the original author-hosted PDF, online p146, §11.2 and §11.2.1: fresh holdout observations independent of training and of how the predictor was generated. It states the bounded-loss Hoeffding result; the article’s Bernoulli mean/variance is a separate valid derivation. Direct PDF reads failed earlier in the ERM review; no full-PDF or visual inspection claimed.
- Distributionally Robust Neural Networks for Group Shifts: On the Importance of Regularization for Worst-Case Generalization · Independently opened the original 19-page arXiv PDF. Header identifies ICLR 2020 and v2 dated 2 April 2020. Read abstract/introduction for empirical-versus-population worst-group distinction and §2, lines 111–152, for mixtures of fixed conditional distributions, simplex maximization and unobserved group at prediction time. No neural-network experiments, empirical improvement figures or full optimizer audit reproduced.
相关主题