MCMC:先核对链,再相信样本
Markov chain Monte Carlo
构造精确 Metropolis–Hastings 流量,运行相关采样,展示漏掉提议比的偏差。
mcmc按目标比例访问状态
三个状态的目标权重为1、2、4,希望在概率(1,2,4)/7下计算期望。小例子直接抽样很容易,正适合作实验台:依赖随机运行前,可以先核对马尔可夫链每个表项。
MCMC 设计以目标为平稳分布的转移,再沿相关路径取平均。它不是“只往高概率状态走”的指令,低权重状态也需要正确访问份额。先读马尔可夫链与Monte Carlo 积分。
提议与目标承担不同角色
有限状态空间上,w(x)>0是未归一化权重,q(y|x)是提议概率。从当前 x 提议 y 后,Metropolis–Hastings 接受概率为:
拒绝时下一状态仍为 x,重复状态也是样本。未知目标归一化量在比值中抵消;提议对称时 q 项也抵消。非对称时丢掉 q 项,通常改变平稳分布。Hastings1970年论文第2.2节用提议和接受规则构造可逆转移。
y≠x时,P(x,y)=q(y|x)α(x,y);对角设为1减非对角行和,纳入拒绝与自提议。令 π(x)=w(x)/Σw,相反方向流量相等:
对 x 求和,详细平衡证明 πP=π,但不证明所有状态互通。Aldous 与 Fill 第11.2.1节强调,一般提议需要双向支持移动构成的图连通,才能获得不可约性。反向支持为零的单向提议,会被此规则拒绝。
可以手算的非对称提议
每个状态都用同一提议行(1/2,1/3,1/6)。这是独立提议,但矩阵并不对称。2→0接受概率为1/12,转移概率1/24;0→2接受概率1,转移概率1/6。平稳流量相等:(4/7)(1/24)=(1/7)(1/6)。
所得矩阵三行为(1/2,1/3,1/6)、(1/6,2/3,1/6)、(1/24,1/12,7/8)。所有非对角和对角都为正,所以这个有限例子不可约且非周期,能从任意初态收敛。但连续保留状态仍不是独立抽取。
构造矩阵,真实提议与接受
完整 Python3.12 程序支持1–8个状态、至多一百万的正有理权重和有理随机提议行。采样器使用独立种子生成器、整数类别抽样与有理接受概率,实际执行提议和接受或拒绝,没有直接独立抽取目标标签。
from fractions import Fraction as F
from math import lcm
from random import Random
def metropolis_matrix(weights, proposal):
w=list(weights);q=[list(row) for row in proposal];n=len(w)
if not 1<=n<=8 or len(q)!=n or any(len(row)!=n for row in q):
raise ValueError('one to eight states and a square proposal required')
if any(type(x) not in (int,F) or not 0<x<=1000000 for x in w):
raise ValueError('positive rational target weights at most1000000 required')
for row in q:
if any(type(x) not in (int,F) or not 0<=x<=1 for x in row) or sum(row,F(0))!=1:
raise ValueError('rational proposal rows summing to one required')
w=list(map(F,w));q=[list(map(F,row)) for row in q]
p=[[F(0) for _ in w] for _ in w]
for i in range(n):
for j in range(n):
if i!=j and q[i][j]:p[i][j]=q[i][j]*min(F(1),w[j]*q[j][i]/(w[i]*q[i][j]))
p[i][i]=1-sum(p[i],F(0))
return p
def sample_mh(weights, proposal, steps=12000, burn=1000, seed=2026, start=0):
metropolis_matrix(weights,proposal)
w=list(map(F,weights));q=[list(map(F,row)) for row in proposal];n=len(w)
if type(steps) is not int or not 1<=steps<=100000 or type(burn) is not int or not 0<=burn<=100000:
raise ValueError('bounded integer sample count and burn-in required')
if type(seed) is not int or not 0<=seed<2**32 or type(start) is not int or not 0<=start<n:
raise ValueError('32-bit integer seed and valid starting state required')
rng=Random(seed);tables=[]
for row in q:
denominator=lcm(*(x.denominator for x in row))
tables.append((denominator,[int(x*denominator) for x in row]))
counts=[0]*n;state=start;changes=0
for t in range(burn+steps):
denominator,masses=tables[state];draw=rng.randrange(denominator);candidate=0
for j,mass in enumerate(masses):
if draw<mass:candidate=j;break
draw-=mass
alpha=min(F(1),w[candidate]*q[candidate][state]/(w[state]*q[state][candidate]))
old=state
if rng.randrange(alpha.denominator)<alpha.numerator:state=candidate
if t>=burn:
counts[state]+=1;changes+=state!=old
return counts,changes
if __name__ == '__main__':
w=[1,2,4];q=[[F(1,2),F(1,3),F(1,6)] for _ in w]
p=metropolis_matrix(w,q);pi=[F(x,sum(w)) for x in w]
print('transition matrix:')
for row in p:print(*[str(x) for x in row])
print('target:',*[str(x) for x in pi])
print('target times transition:',*[str(sum(pi[i]*p[i][j] for i in range(3))) for j in range(3)])
counts,changes=sample_mh(w,q)
print('retained counts:',counts)
print('observed frequencies:',*[f'{x/sum(counts):.6f}' for x in counts])
print('state changes among retained transitions:',changes)
输出:
transition matrix:
1/2 1/3 1/6
1/6 2/3 1/6
1/24 1/12 7/8
target: 1/7 2/7 4/7
target times transition: 1/7 2/7 4/7
retained counts: [1862, 3443, 6695]
observed frequencies: 0.155167 0.286917 0.557917
state changes among retained transitions: 2941
计数来自本次固定种子运行:先1000次预热转移,再保留12000次。每次保留转移后都记录状态,包括拒绝或自提议。“状态变化”只数实际换状态,不是全部接受提议。预热长度是演示设置,不是普遍足够的烧入规则,也不证明已经平稳。
精确矩阵与平衡检查为算法提供独立于观察频数的证据。Python 伪随机流让记录环境中的例子可复现,不是物理独立随机源。此实现要求权重与提议行使用可重复读取的序列。
稠密矩阵构造需 O(n²) 次有理运算。采样每次扫描类别行,需 O(n) 工作,另计有理数位成本;只存计数,不存完整轨迹。生产方法可以不构造完整转移矩阵、直接抽局部提议;这里恰因状态空间小,才构造它来全面核对。
相关性改变不确定性计算
平稳且标量 f(X)的自相关序列可求和时,常见渐近表达为:
自相关针对所选函数,不只是原始状态标签;IID 标准误差忽略它。本程序报告计数,没有估计 Monte Carlo 标准误差或有效样本量,需要轨迹与误差估计程序才能评估。Hastings 第2.1节讨论相关样本所需的额外谨慎。
烧入、稀疏保留或高接受率都不认证混合充分。多链和诊断能揭示问题,却不是普遍证明。接受移动图不连通时,从一个分量跑更久无法修复。连续或高维问题还需关注目标支持、提议支持与变量变换。
本独立提议若漏掉 Hastings 比,错误不变概率为(3,4,4)/11,与 wᵢqᵢ成比例。它与(1,2,4)/7不同,跑再久也一样。长运行减少围绕错误目标的 Monte Carlo 噪声,不能纠正算法错误。
先查流量,再看直方图
- 提议2→0的接受概率是多少?
答案1: 1/12,再乘提议概率1/2,得到 P₂₀=1/24。
- 应从路径删除拒绝转移吗?
答案2: 不应。重复状态是链的一部分,删除通常改变占用频数。
- 对称提议是否可以省略目标比?
答案3: 不可以,只抵消提议比,目标权重比仍保留。
- 本例漏掉提议比,增加样本能修复吗?
答案4: 不能。错误链目标是(3,4,4)/11,而非(1,2,4)/7。
正确不变分布只是起点
Metropolis–Hastings 是一种 MCMC 构造。Gibbs 更新、使用梯度的提议与非可逆方法处理其他结构和效率问题。共同任务是说明目标不变测度、建立探索条件,并评估有限运行的估计误差。
项目练习:全部目标权重乘同一正常数,验证转移矩阵不变;再把提议图改成单向,检查哪些接受转移消失。最后保留轨迹,对不同状态函数比较批均值不确定性估计,区分诊断证据与收敛保证。
先判断,再看解释
非对称提议漏掉 Hastings 比,跑更久能修复吗?
学习目标
- 构造并验证有限 Metropolis–Hastings 转移矩阵。
- 区分相关采样证据、平稳有效性与混合诊断。
先修与延伸
查看知识关联图 →参考文献
- Monte Carlo sampling methods using Markov chains and their applications
W. K. Hastings · 1970 - Reversible Markov Chains and Random Walks on Graphs — Section11.2
David Aldous; James Allen Fill · 2001
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-06 · Codex single-agent authored technical review: cited primary-source scope, explicit assumptions, original calculations and counterexamples, runnable tests and bilingual review; not independent human or second-agent review.
- 单AI作者技术检查:限定的一手来源位置、假设、原创推导、精确/字面参照及对应双语公式、例子、习题。不冒充人工或第二代理独立审校。
- 每篇四项CPython3.12.4针对性测试通过。马尔可夫及MH矩阵用精确分数;EM、BP浮点运算与独立解析或穷举参照比较。固定种子MCMC频数是观察运行,不是收敛认证。
- 完整正文、公式、代码和习题迁入;测试只读取正式MDX,删除临时目录回退及草稿跳过,状态断言更新为checked。没有修改算法或独立参照,最终记录绑定两语SHA。
- 出版导航将已发表主题指向完整文章并移除对应待写措辞,未发表目标保留目录入口;原理、公式、程序与习题未改,重新绑定最终正文SHA。
核对的来源位置:
- Monte Carlo sampling methods using Markov chains and their applications · 1970 Biometrika57(1),97–109; Sections2.1–2.2 discuss dependent sample variance, proposal/acceptance construction, reversibility and the need to check irreducibility.
- Reversible Markov Chains and Random Walks on Graphs — Section11.2 · Section11.2.1 equations11.5 and following: asymmetric Hastings correction, minimum opposing flows, bidirectional-support connectivity. Chapter header2001; HTML generation2014 is distinct.
相关主题