高斯混合:钟形曲线与软归属
Gaussian mixture models
推导高斯责任度与 EM 更新,检查固定方差拟合、驻点初始化和数值停止。
gaussian-mixtures允许一条观测兼容两种解释
四个虚构校准偏移为 −3、−2、2、3。只用一个以零为中心的钟形曲线,会把密度铺到中间空隙;两个钟形曲线则能在观测附近放置更多密度。零附近的读数仍可能同时兼容两种成分,强行分到一组会丢掉这份不确定性。
高斯混合模型先选择一个隐藏成分,再从该成分的高斯分布中生成观测。它是密度模型;成分归属也能用于聚类,但成分不会自动变成物理运行模式或已经核实的类别。
本章拟合两个均值及其混合权重,将共同方差固定为一。从均值 −1、1 出发,五轮 EM 后均值约为 −2.499908、2.499908;若两个均值都从零开始,它们会停留在零,训练似然低得多。同一个目标可能得到不同结果,因为初始化会产生影响。
密度的和,成分的后验
对 d 维观测和 K 个成分,令非负权重 πⱼ 之和为一。普通非奇异高斯密度要求协方差 Σⱼ 正定:
权重描述模型多频繁地选择各成分,协方差描述成分内部的散布与方向。各成分只有一个峰,混合之后却可以多峰;反过来,K 个成分也不一定形成 K 个清晰可见的峰。下面的 EM 推导假定权重为正;零权重成分可以从密度求和中省去。
对 IID 观测,最大化混合密度对数之和。这里是“和的对数”,不是“各成分对数密度的和”。数值计算时,先求成分的对数贡献 aᵢⱼ,再使用:
减去最大值,可以避免一整行微小密度在归一化之前全部下溢。但很小的后验项仍可能舍入为零。密度可以大于一;概率需要对某个区域积分。
E 步:计算责任度
责任度 rᵢⱼ 是当前模型下观测 i 来自成分 j 的后验概率:
每行责任度之和为一;Nⱼ 是有效计数,通常不是整数。这与把每个点交给最近均值不同,权重与协方差也会影响后验。
M 步:按这些分数计数拟合
保持责任度不变,最大化完整数据对数似然的期望,得到常见的无约束更新:
这些表达式要求 Nⱼ > 0。协方差使用最大似然分母 Nⱼ,而非 Nⱼ−1。如果该协方差奇异,就不能在没有额外约定或约束时,把它当成合法的非奇异高斯估计。本程序只更新权重与均值,共同正方差由用户提供,始终不估计。完整、对角、球形与共享协方差对应不同参数族。固定高斯混合指南介绍了这些选择。
责任度固定后,对均值对应的加权二次式求导,得到上面的加权均值;在权重之和为一的约束下最大化权重项,则得到 πⱼ = Nⱼ/n。在实数精确运算下,它们是本章受限模型的精确 M 步。
为什么似然应该上升,这又不证明什么
对任意每行严格为正的概率分布 r,Jensen 不等式给出下界:
取当前模型后验时,下界取等号。精确 M 步提高或保持下界,新后验又使下界贴合新似然,因此观测似然不下降。这项论证解释似然性质,不证明全局最优,也不保证参数序列普遍收敛。1977 年 EM 论文第 2—3、4.3 节发展了通用不完整数据框架及其有限混合实例。
方差固定且为正时,密度有有限上界,因此精确运算下不下降的似然值也有上界。但这仍不会选出最好的起点,也不会强迫重合的初始成分分开。浮点计算额外引入舍入,测试会在注明的数值容差内核对目标恒等式。
固定方差,记录每轮完成的拟合
下面是完整 Python 3.10+ 标准库程序。接受有限整数与浮点数,拒绝布尔值;观测数为一至 50,初始均值数为一至五,方差为正,轮数上限为零至 50 的整数。可选初始权重须为正且与均值对应,程序会归一化其相对大小。这些限制让练习保持小规模。
trace 保存初始模型及每次完成的更新。round-limit 只表示指定轮数已结束,不是收敛证书。在精确运算下,正权重与有限高斯密度给出正责任度;若有效计数为零,或将它除以样本数时下溢,导致新权重变为零,程序返回 numerical-empty-component,保留最后完成的模型,不暗中重启或删除该成分。归一化后的初始权重为零、检测到非有限结果或检查到运算溢出时,引发 ValueError。这不能检测所有下溢或精度损失。观测全部相同时,更新均值直接保留该常数,包括可表示的最小次正规数。
预测使用未经修改的拟合模型,不从查询中学习;返回成分责任度和对数密度,接受空列表,保留成分次序。由于不返回硬标签,也不需要硬标签的同分规则。
import math
def finite(value):
if type(value) not in (int, float):
raise ValueError('use finite int or float values, not booleans')
try:
value = float(value)
except OverflowError as exc:
raise ValueError('number is not representable') from exc
if not math.isfinite(value):
raise ValueError('number is not finite')
return value
def vector(values, empty=False):
if type(values) not in (list, tuple) or (not values and not empty):
raise ValueError('expected a nonempty list or tuple')
return tuple(finite(v) for v in values)
def evaluate(xs, means, weights, variance):
# Internal: positive normalized weights and fixed positive variance.
scale = math.sqrt(variance)
normalizer = (math.log(2*math.pi) + math.log(variance))/2
rows, logs = [], []
for x in xs:
terms = []
for mean, weight in zip(means, weights):
z = (x-mean)/scale
square = z*z
if not math.isfinite(square):
raise ValueError('standardized squared residual is not representable')
terms.append(math.log(weight)-normalizer-square/2)
peak = max(terms)
values = tuple(math.exp(t-peak) for t in terms)
total = math.fsum(values)
rows.append(tuple(v/total for v in values))
logs.append(peak+math.log(total))
try:
likelihood = math.fsum(logs)
except OverflowError as exc:
raise ValueError('log likelihood is not representable') from exc
if not math.isfinite(likelihood):
raise ValueError('log likelihood is not finite')
return tuple(rows), tuple(logs), likelihood
def fit(values, initial_means, variance=1, rounds=5, initial_weights=None):
xs, means = vector(values), vector(initial_means)
variance = finite(variance)
constant = all(x == xs[0] for x in xs)
if variance <= 0 or type(rounds) is not int or not 0 <= rounds <= 50:
raise ValueError('positive variance and integer rounds in 0..50 required')
if len(xs) > 50 or len(means) > 5:
raise ValueError('teaching limit: 50 observations and five components')
raw = (1.0,)*len(means) if initial_weights is None else vector(initial_weights)
if len(raw) != len(means) or any(w <= 0 for w in raw):
raise ValueError('one positive initial weight per component required')
largest = max(raw)
scaled = tuple(w/largest for w in raw)
total_weight = math.fsum(scaled)
weights = tuple(w/total_weight for w in scaled)
if any(w == 0 for w in weights):
raise ValueError('normalized initial weight underflow')
responsibilities, logs, likelihood = evaluate(xs, means, weights, variance)
trace = [(means, weights, likelihood)]
status = 'round-limit'
for _ in range(rounds):
counts = tuple(math.fsum(row[j] for row in responsibilities) for j in range(len(means)))
new_weights = tuple(count/len(xs) for count in counts)
if any(w == 0 for w in new_weights):
status = 'numerical-empty-component'
break
try:
new_means = ((xs[0],)*len(means) if constant else
tuple(math.fsum((row[j]/counts[j])*x for x, row in zip(xs, responsibilities))
for j in range(len(means))))
except OverflowError as exc:
raise ValueError('updated mean is not representable') from exc
if not all(math.isfinite(v) for v in new_means):
raise ValueError('updated mean is not representable')
responsibilities, logs, likelihood = evaluate(xs, new_means, new_weights, variance)
means, weights = new_means, new_weights
trace.append((means, weights, likelihood))
return {'means': means, 'weights': weights, 'variance': variance,
'responsibilities': responsibilities, 'log_densities': logs,
'log_likelihood': likelihood, 'trace': tuple(trace),
'rounds_completed': len(trace)-1, 'status': status}
def predict(model, values):
xs = vector(values, empty=True)
responsibilities, logs, _ = evaluate(xs, model['means'], model['weights'], model['variance'])
return {'responsibilities': responsibilities, 'log_densities': logs}
if __name__ == '__main__':
xs = [-3, -2, 2, 3]
model = fit(xs, [-1, 1], rounds=5)
print('means:', tuple(round(v, 6) for v in model['means']))
print('weights:', tuple(round(v, 6) for v in model['weights']))
print('log likelihood:', round(model['trace'][0][2], 6), '->', round(model['log_likelihood'], 6))
print('middle responsibility:', tuple(round(v, 6) for v in predict(model, [0])['responsibilities'][0]))
stuck = fit(xs, [0, 0], rounds=5)
print('identical initialization:', stuck['means'], round(stuck['log_likelihood'], 6))
print('status / completed:', model['status'], model['rounds_completed'])
empty = fit([0], [0, 1000], rounds=2)
print('numerical stop:', empty['status'], empty['rounds_completed'])
实际输出:
means: (-2.499908, 2.499908)
weights: (0.5, 0.5)
log likelihood: -11.407092 -> -6.948251
middle responsibility: (0.5, 0.5)
identical initialization: (0.0, 0.0) -16.675754
status / completed: round-limit 5
numerical stop: numerical-empty-component 0
分开的初始均值使对数似然从 −11.407092 升到 −6.948251。中点零处,两项责任度仍各为 1/2;重合初始化则一直停留在 (0,0),对数似然为 −16.675754。这是实际执行得到的较差驻点拟合,不是 EM 总能找到两组的证据。
最后一行是数值边界例。成分位于 1000,而唯一观测为零,该成分责任度极小,计算出的有效计数变为零。明确停止记录了数值分辨率的丧失;它与“高斯密度在远处恰好等于零”的断言无关。
对 n 条观测、K 个成分和 R 次完成的更新,固定方差计算需要 O((R+1)nK) 次算术或超越函数运算,保留 O(nK+(R+1)K) 个数值槽位,包含最终责任度及全部模型快照。预测 q 个点需要 O(K+qK+1) 次操作与空间,计入校验、模型归一化常数及返回行。字符串格式化和浮点可表示性另计;一般完整协方差实现还存在随维度增长的成本。
配套测试用 70 位十进制概率,对整批样本的潜成分赋值求和,将得到的后验充分统计量、均值、权重、似然与程序逐行对数计算比较;另在小数据上独立计算下界,核查 E/M 步不等式。
密度估计不只需要分数上升
若允许方差自由缩小,普通高斯混合似然可能没有有限上界。对观测 0、2 和两个成分,把一个均值放在零,并让其方差趋近零;另一个正权重成分继续为其余观测提供正密度。零处密度就会发散,这不是成功发现了一个无限精确的总体。协方差限制、正则化或先验会改变估计问题,需要明确记录。固定指南提示了协方差奇异问题;本章已知正方差排除了这种特定坍缩机制。
成分编号是任意的。同时重排权重、均值与协方差,密度不变,责任度列随之重排;相同成分还会引入额外冗余。这些现象都不允许我们无证据地给成分附加真实世界标签。识别统计成分与解释因果,是不同主张。
应在验证设计中选择成分数、协方差族与初始化策略。留出对数似然评估密度预测,与已知类别比较则评估另一任务。AIC/BIC 和留出指标各有假设,不会揭示普遍正确的组数。缩放在训练部分拟合,最终测试集与反复模型选择分开。
本模型是一维、共同固定方差,不处理缺失坐标,不拟合协方差矩阵,不做贝叶斯推断,也不保证全局解。多次重启可能改善达到的目标值;保留最好的训练拟合,本身不证明泛化能力。
读懂概率和停止原因
1. 为什么中点读数对两个拟合成分的责任度各为 1/2?
答案: 本例权重相等,均值始终关于零对称,方差相同;零处的两个加权密度相等,经贝叶斯归一化得到 (1/2,1/2)。这是模型对成分的不确定性,不是已经核实的两种物理机器模式的概率。
2. 完成五轮,是否证明收敛或最优?
答案: 不证明。round-limit 记录已完成工作。两个均值从零开始就停留在零,对数似然为 −16.675754;分开初始化达到 −6.948251。因此,固定点或小更新可以与其他位置明显更好的拟合并存。
3. 一个已知方差的成分,对观测 1、2、6 做一次 M 步会怎样?
答案: 所有责任度都是一,所以 N = 3,权重为一,新均值为 (1+2+6)/3 = 3。给定方差保持不变;估计样本方差会成为不同的参数问题。
4. 为什么数值有效计数为零,与极小正数要区别处理?
答案: 零计数会使均值更新除以零,尽管这个正权重高斯模型在实数运算下没有恰好为零的责任度。程序在更新之前停止,保留最后完成的模型。若归一化权重仍可表示,极小正计数也可更新,但拟合可能敏感;改变精度、初始化或模型约束,需要明确选择。
没有观测到的是成分归属
Dempster、Laird、Rubin 的 1977 年论文整理了通用期望/最大化框架,并讨论更早的特殊混合处理方法,并非发明了高斯混合这个分布族。在混合模型中,观测已经存在;缺失部分是每条观测由哪个成分生成,这让加权拟合的解释十分具体。
版本化混合指南将该模型与协方差限制、成分选择和变分替代方案联系起来。改变这些限制,会改变目标或参数空间;共用 EM 风格循环,不代表不同模型可以互换。
先判断,再看解释
两个初始均值相同,在指定 EM 轮数后仍相同,是否证明已得到最好的混合拟合?
学习目标
- 区分混合密度、后验责任度与真实世界类别。
- 推导分数计数 EM 更新,解释为何似然单调不代表全局最优。
- 审查固定方差浮点拟合、初始化及明确的数值停止条件。
先修与延伸
查看知识关联图 →参考文献
- Maximum Likelihood from Incomplete Data via the EM Algorithm
A. P. Dempster; N. M. Laird; D. B. Rubin · 1977 - Gaussian mixture models — scikit-learn 1.7.2
scikit-learn developers
版本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 项测试通过。4 组独立 70 位 Decimal 整批潜变量赋值计算核对 16 个模型快照、24 个最终责任度项、均值、权重与对数似然;快照间共求和 208 个完整潜赋值,区别于实现的逐行 log-sum-exp。比较使用相对/绝对容差 2e-12;另用 Jensen 下界及加权均值驻点检查一次 E/M 更新。
- 核验分开/重合初始化、中点等责任度、单成分解析均值、密度大于一、远尾有限对数分数、明确数值空成分状态、零轮、成分改名、空查询及输入/模型保全。拒绝 7 类输入/规模、9 类参数/权重组合、2 类无法表示的运算输入及非法查询。冻结前移除初始权重归一化中的重复扫描。
- 完整原创双语具有相同标准库完整 Python、7 行实际输出、5 显示公式、6 稳定锚点及 4 已答练习;严格 MDX/KaTeX 与 React 实际 HTML 通过,5 项数学注解对应。EM 推导明确使用正权重,零权重成分可省去;完成固定 Humanizer 文风复读。仅已核实发布的无监督学习使用 wiki 直链,其他相关主题使用目录链接。
- 保持 written,仅 AI 作者检查。正文说明一般协方差更新,运行模型只估计标量均值和权重,共用一个已知正方差;明确规模限制、密度非概率、标签歧义、本模型之外的协方差坍缩及浮点下溢。没有人类审校、一般协方差求解器、全局最优声称、库训练、基准、浏览器验收或全站构建。
- 独立 AI 审查发现:最小次正规常值先乘分数权重会丢失可表示的均值。现用常值观测分支直接保留;8 次单/双成分运行覆盖正负 5e-324、零及三。双语将数值报错范围收窄到实际检查,并将练习负数明确称为对数似然;停止说明还包括正计数除以 n 后下溢,已实际验证此边界;修改后重跑 8 项测试与严格实际 HTML。
- 完整正文、公式、代码和习题迁入;测试只读取正式MDX,删除临时目录回退及草稿跳过,状态断言更新为checked。没有修改算法或独立参照,最终记录绑定两语SHA。
- 出版导航将已发表主题指向完整文章并移除对应待写措辞,未发表目标保留目录入口;原理、公式、程序与习题未改,重新绑定最终正文SHA。
核对的来源位置:
- Maximum Likelihood from Incomplete Data via the EM Algorithm · Actually opened the University of Sydney 39-page scan. Cover identifies JRSS Series B 39(1), 1977, pages 1–38 including discussion; the publisher separately lists the article as pages 1–22. Read printed pages 1–3 (physical 2–4) for title/authors, 8 December 1976 presentation and general EM naming with earlier special cases; Theorem 1 and following qualifications on printed pages 7–8 (physical 8–9) for nondecreasing likelihood versus additional convergence conditions; section 4.3 on printed pages 15–16 (physical 16–17) for hidden component indicators, posterior expected sufficient statistics and earlier Gaussian-mixture work. Text extraction only; no full discussion or visual audit. Some extracted inequality signs are ambiguous, so the article independently derives the Jensen lower-bound argument and makes no universal parameter-convergence claim.
- Gaussian mixture models — scikit-learn 1.7.2 · Actually reopened fixed 1.7 guide rendered 1.7.2. Read lines 69–79 for mixture density and full/diagonal/spherical/tied covariance options, lines 99–116 for singularities and component-selection assumptions, and the variational comparison. Shared source record/URL reused exactly from the published unsupervised-learning chapter. Did not adopt the guide’s absolute fastest or guaranteed-local-optimum wording, run sklearn, or claim the scalar fixed-known-variance program implements its API.
- Maximum Likelihood from Incomplete Data via the EM Algorithm · Actually opened the University of Sydney 39-page original scan. Read the cover and printed pages 1–3: authors, 1977 journal date, separate 8 December 1976 meeting and prior special cases. Read Theorem 1 and qualifications on printed pages 7–8: nondecreasing likelihood does not by itself guarantee convergence to a maximum-likelihood estimator. Read section 4.3 printed pages 15–16 on hidden component indicators, joint complete-data likelihood and expected sufficient statistics. Text extraction has damaged inequality glyphs; monotonicity was independently checked by the valid Jensen argument, not copied from ambiguous glyphs. No full discussion or visual-page claim.
- Gaussian mixture models — scikit-learn 1.7.2 · Actually read fixed 1.7 guide rendered 1.7.2, lines 69–79 for Gaussian mixture model and covariance families, 99–116 for singular covariance and selection/EM discussion, and 140–149 for variational alternatives. Did not adopt its overbroad guaranteed-local-optimum or fastest wording. No sklearn run.
相关主题