MCMC: design the chain before trusting the sample
马尔可夫链蒙特卡洛
Construct exact Metropolis–Hastings flows, run dependent samples and expose the bias from a missing proposal ratio.
mcmcVisit states in the proportions you want
Suppose three states have target weights 1,2,4. We want expectations under probabilities(1,2,4)/7. Direct sampling is easy in this tiny case, which makes it a useful laboratory: we can verify every entry of a Markov chain before relying on a random run.
MCMC designs transitions whose stationary distribution is the target, then averages along the resulting dependent path. It is not an instruction to move only toward higher-probability states. Lower-weight states still need their proper share of visits. Read Markov chains and Monte Carlo integration first.
The proposal and target play different roles
Let w(x)>0 be unnormalized weights on a finite state space, and q(y|x) a proposal probability. After proposing y from the current x, Metropolis–Hastings accepts with:
If rejected, the next state is x again. Those repeated states are part of the sample. The unknown target normalizer cancels in the ratio. If the proposal is symmetric, the q terms cancel too; with an asymmetric proposal, dropping them generally changes the stationary distribution. Hastings’s 1970 paper, Section 2.2, constructs reversible transitions using a proposal and an acceptance rule.
For y≠x, P(x,y)=q(y|x)α(x,y); set the diagonal to one minus the off-diagonal row sum, including rejected proposals and proposed self-transitions. With π(x)=w(x)/Σw, the opposing flows agree:
Summing detailed balance over x proves πP=π. It does not prove that all states communicate. Aldous and Fill, Section 11.2.1, emphasizes that for general proposals the graph of bidirectionally supported moves must be connected to obtain irreducibility. A one-way proposed move with zero reverse support is rejected by this rule.
A non-symmetric proposal you can check by hand
Use the same proposal row(1/2,1/3,1/6) from every state. This is an independence proposal, but it is not symmetric as a matrix. For state 2→0, the acceptance probability is 1/12, giving transition probability 1/24. For 0→2, acceptance is 1 and the transition probability is 1/6. Their stationary flows agree: (4/7)(1/24)=(1/7)(1/6).
The resulting matrix has rows(1/2,1/3,1/6), (1/6,2/3,1/6), (1/24,1/12,7/8). All off-diagonal entries and diagonals are positive, so this finite example is irreducible and aperiodic. Those properties give convergence from any start, but do not turn consecutive retained states into independent draws.
Build the matrix and run actual proposals
This complete Python 3.12 program supports 1–8 states, positive rational weights at most one million and rational stochastic proposal rows. The sampler uses an isolated seeded generator, integer categorical draws and rational acceptance probabilities. It actually proposes and accepts or rejects; it does not simply draw independent target labels.
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)
Output:
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
Counts describe this finite seeded run after 1000 warm-up transitions and 12000 retained transitions. A count is recorded after every retained transition, including a rejection or a self-proposal. “State changes” counts changes of state, not all accepted proposals. The chosen warm-up length is a demonstration setting, not a generally sufficient burn-in rule or a proof of stationarity.
The exact matrix and balance checks provide algorithmic evidence independent of those observed frequencies. Python’s pseudorandom stream makes the example reproducible in the recorded runtime; it is not a physical source of independent randomness. This implementation expects reusable sequences for weights and proposal rows.
Building the dense matrix costs O(n²) rational operations. Sampling uses O(n) work per proposal because it scans a categorical row, plus rational bit costs; it stores counts rather than a full trajectory. A production method can sample a local proposal without constructing the entire transition matrix. We construct it here precisely because the small state space permits a complete check.
Correlation changes the uncertainty calculation
Under stationarity and a summable autocorrelation sequence for a scalar quantity f(X), a common asymptotic expression is:
The autocorrelations concern the chosen function, not just the raw state labels. The IID standard error ignores them. This program reports counts without estimating Monte Carlo standard errors or effective sample size; a trace and an error-estimation procedure would be needed for that assessment. Hastings’s Section 2.1 discusses the extra care required for dependent samples.
Burn-in, thinning or a high acceptance rate do not certify mixing. Multiple chains and diagnostics can reveal problems but are not universal proofs. A disconnected accepted-move graph cannot be repaired by running longer from one component. Target support, proposal support and transformations need attention in continuous or high-dimensional problems.
Omitting the Hastings ratio in our independence proposal yields the wrong invariant probabilities(3,4,4)/11, proportional to wᵢqᵢ. They differ from(1,2,4)/7 even after an arbitrarily long run. A longer run reduces Monte Carlo noise around the wrong target; it does not correct an algorithmic error.
Check flows before a histogram
- What is the acceptance probability of the proposed 2→0 move?
Answer 1: 1/12; multiplying by proposal probability 1/2 gives P₂₀=1/24.
- Should a rejected transition be removed from the sample path?
Answer 2: No. The repeated state is part of the chain; deleting it generally changes occupation frequencies.
- Does a symmetric proposal remove the need for the target ratio?
Answer 3: No. It cancels the proposal ratio only; the target-weight ratio remains.
- Will more samples fix an omitted proposal ratio in this example?
Answer 4: No. The faulty chain targets(3,4,4)/11 instead of(1,2,4)/7.
A correct invariant distribution is the beginning
Metropolis–Hastings is one MCMC construction. Gibbs updates, gradient-informed proposals and nonreversible methods address other sampling structures and efficiency problems. The common tasks are to justify the target invariant measure, establish exploration conditions and assess finite-run estimation error.
Project: multiply all target weights by the same positive constant and verify that the transition matrix is unchanged. Then make the proposal graph one-way and inspect which accepted transitions disappear. Finally, retain a trace and compare batch-mean uncertainty estimates across functions of the state, separating diagnostic evidence from convergence guarantees.
Make a prediction, then check
Can a longer run repair an omitted Hastings ratio for an asymmetric proposal?
Learning objectives
- Construct and verify a finite Metropolis–Hastings transition matrix.
- Distinguish dependent sample evidence, stationary validity and mixing diagnostics.
Prerequisites & connections
Explore related knowledge →References
- 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
Version1 · Editorial status: Recorded technical checks completed
View technical check record (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.
- Single-agent authored technical review: bounded primary-source locations, assumptions, original derivations, exact/literal references and matching bilingual equations/examples/exercises. Not independent human or second-agent review.
- Four focused CPython3.12.4 tests passed per chapter. Markov and MH matrices use exact fractions; EM and BP are floating-point and tested against independent analytic or enumerated references. Seeded MCMC frequencies are an observed run, not a convergence certificate.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- 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.
Related topics