MCMC I: Metropolis-Hastings and how to know it works
MCMC constructs a Markov chain whose stationary distribution is the posterior. We prove detailed balance suffices, construct Metropolis-Hastings, study optimal random-walk scaling and implement modern diagnostics: autocorrelation, effective sample size, Monte Carlo standard error and rank-normalized R-hat.
After this lesson you can
- Prove detailed balance implies stationarity and that the Metropolis-Hastings kernel satisfies it.
- Implement random-walk and independent Metropolis-Hastings with warmup adaptation.
- Explain the 0.234 acceptance rate and proposal scaling with dimension.
- Calculate ESS using Geyer's initial monotone sequence and rank-normalized R-hat.
- Detect mixing problems with multiple chains that a single trace does not reveal.
Before you start
- 14Bayesian logistic regressionLaplace approximationSelf-normalized importance samplingImportance-sampling effective sample size
- 26Stationary distributionCommunicating classes and irreducibilityMarkov chain convergence theorem
- 09Monte Carlo estimatorMonte Carlo error and confidence intervals
- 04Central limit theorem
Sampling without knowing the constant
Suppose you know but not the posterior’s normalizing constant. Markov chain Monte Carlo constructs a process whose stationary distribution is and approximates expectations using its states. Successive samples are dependent: their count is not automatically the number of independent samples.
A chain is stationary with respect to if . Stationarity alone does not imply convergence from an arbitrary start: appropriate conditions such as irreducibility and aperiodicity are also needed. Detailed balance, , suffices for stationarity by summing over , but is not necessary. In continuous spaces it is interpreted as equality of flow measures.
Metropolis-Hastings
From , propose and accept with probability
If rejected, the chain repeats ; that repetition is part of the sample. For , both accepted flows equal . Thus the Metropolis-Hastings kernel satisfies detailed balance. The normalizing constant of cancels. A symmetric random-walk proposal also cancels the proposal ratio; for independent proposal it remains and must not be omitted.
Work in log space: compare with . In zero-support regions valid transitions must be carefully defined. The figure starts from one point and shows the whole trajectory; acceptance frequency is descriptive, not a convergence proof.
Scale, warmup and cost
Optimal scaling has a specific result: for a family of product targets under particular regularity assumptions and increasing dimension, Roberts, Gelman and Gilks obtain scaling for an isotropic Gaussian random walk and limiting acceptance near 0.234. This is asymptotic, not a universal rate: small dimension, correlation, irregular geometry and other kernels change the optimum. The figure estimates acceptance when the initial state already follows a standard normal; it does not measure time to reach it.
Adaptation can tune scale or covariance during warmup. Then freeze the kernel and discard warmup states. Adapting throughout the chain without additional conditions invalidates the fixed-kernel justification; adaptive methods with their own conditions exist, but do not follow from detailed balance of each isolated kernel. Thinning by retaining every -th state can save storage or analysis cost, but normally discards information and does not improve total ESS of what was already simulated without considering that cost.
Autocorrelation and diagnostics
For a scalar function , if the Markov-chain central limit theorem assumptions hold, variance of its mean is approximately , where . MCMC effective sample size is and estimated Monte Carlo standard error for the mean is approximately . It can exceed with negative correlations; it depends on . It is not importance-weight ESS, which measures weight concentration in another problem.
Estimating the infinite sum from noisy lags is unstable. Geyer’s initial positive and monotone sequence groups consecutive autocorrelations, stops at the first negative pair and forces retained pairs not to increase. The multichain version combines within- and between-chain variation; it does not replace mode inspection or diagnose every function.
Split rank-normalized R-hat splits each chain, transforms pooled ranks to normal quantiles and compares variation between and within halves. It is also calculated on absolute distances from the median and the maximum taken, to detect scale differences. Vehtari and colleagues explain these improvements and localized ESS. Four chains that never cross between modes can appear individually stable; disagreement between them reveals the problem.
R-hat near 1 and large ESS are useful signals, not demonstrations that no mode is missing. Besides ranks and traces, inspect tail ESS and Monte Carlo error for quantities you will use; compare initializations and check predictions.
Lab: logistic regression and diagnostics
Use the same data and prior as m14-l07: 40 observations, seed 2026 and precision 1.5. The generator and Laplace fit are in logreg.py; the first cell reproduces the module so this lab is self-contained.
"""MAP logístico con prior gaussiano y aproximación de Laplace."""
import numpy as np
from scipy.special import expit
def negative_log_posterior(w, X, y, alpha):
z = X @ w
p = expit(z)
value = np.logaddexp(0., z).sum() - y @ z + .5 * alpha * (w @ w)
gradient = X.T @ (p-y) + alpha*w
H = X.T @ ((p*(1-p))[:,None]*X) + alpha*np.eye(X.shape[1])
return value, gradient, H
def fit_laplace(X, y, alpha=1., tol=1e-9, max_iter=100):
X=np.asarray(X,dtype=float);y=np.asarray(y,dtype=float)
if X.ndim!=2 or y.shape!=(X.shape[0],) or X.shape[1]==0:
raise ValueError('dimensiones incompatibles')
if not np.all(np.isfinite(X)) or not np.all(np.isfinite(y)) or np.any((y!=0)&(y!=1)) or not np.isfinite(alpha) or alpha<=0 or tol<=0 or max_iter<1:
raise ValueError('datos finitos, etiquetas binarias, alpha y tolerancia positivos y al menos una iteración')
w=np.zeros(X.shape[1]); converged=False
for iteration in range(max_iter):
value,gradient,H=negative_log_posterior(w,X,y,alpha)
if np.linalg.norm(gradient,np.inf)<tol:
converged=True;break
direction=np.linalg.solve(H,gradient)
rate=1.
while rate>1e-12:
candidate=w-rate*direction
if negative_log_posterior(candidate,X,y,alpha)[0]<=value-1e-4*rate*(gradient@direction):
break
rate*=.5
if rate<=1e-12:break
w=candidate
value,gradient,H=negative_log_posterior(w,X,y,alpha)
if np.linalg.norm(gradient,np.inf)<tol:converged=True
cov=np.linalg.solve(H,np.eye(X.shape[1]))
return w,cov,{'converged':converged,'iterations':iteration+1,
'gradient_inf':np.linalg.norm(gradient,np.inf),'objective':value}
def predict_probit(X, mean, covariance):
X=np.asarray(X,dtype=float)
variance=np.einsum('ij,jk,ik->i',X,covariance,X)
return expit((X@mean)/np.sqrt(1+np.pi*np.maximum(variance,0)/8))
def synthetic_data(seed=2026,n_train=40,n_test=2000):
"""Datos sintéticos Bernoulli, partición de test independiente en el mismo generador."""
rng=np.random.default_rng(seed)
true_w=np.array([-.4,1.4,-1.])
def generate(n):
X=np.column_stack((np.ones(n),rng.normal(size=(n,2))))
y=rng.binomial(1,expit(X@true_w))
return X,y
X,y=generate(n_train);X_test,y_test=generate(n_test)
return X,y,X_test,y_test,true_wThe walk updates scale only during the first 1000 steps and then freezes it for 4000 samples. The independent proposal uses the Laplace Gaussian and includes the density ratio. For ESS use FFT autocovariances and the initial positive and monotone sequence. Rank R-hat takes the maximum of ordinary and folded ranks. Results depend on seed, model and length; they do not establish convergence.
import numpy as np
from scipy.special import ndtri
from scipy.stats import rankdata
def metropolis(logp,start,seed,warmup=1000,draws=4000,scale=.5):
rg=np.random.default_rng(seed);x=np.array(start,dtype=float);lp=logp(x);logs=np.log(scale);samples=[];accepted=0
for t in range(warmup+draws):
candidate=x+np.exp(logs)*rg.normal(size=x.size);new=logp(candidate)
take=np.log(rg.random())<min(0.,new-lp)
if take:x=candidate;lp=new
if t<warmup:logs+=.8*(t+20)**(-.6)*(take-.234)
else:samples.append(x.copy());accepted+=take
return np.array(samples),accepted/draws,np.exp(logs)
def independent_mh(logp,start,proposal_mean,proposal_cov,seed,draws=4000):
rg=np.random.default_rng(seed);L=np.linalg.cholesky(proposal_cov);x=np.array(start,dtype=float);lp=logp(x);out=[];accepted=0
def logq(w):
z=np.linalg.solve(L,w-proposal_mean)
return -.5*(z@z) # Las constantes comunes de la normal se cancelan.
lq=logq(x)
for _ in range(draws):
y=proposal_mean+L@rg.normal(size=x.size);new=logp(y);newq=logq(y)
if np.log(rg.random())<min(0.,new-lp+lq-newq):x=y;lp=new;lq=newq;accepted+=1
out.append(x.copy())
return np.array(out),accepted/draws
def autocov(x):
x=np.asarray(x);n=len(x);x=x-x.mean();size=1<<(2*n-1).bit_length()
f=np.fft.rfft(x,n=size)
return np.fft.irfft(f*np.conjugate(f),n=size)[:n]/n
def split(chains):
n=chains.shape[1]//2
if n<2:raise ValueError('se requieren al menos cuatro muestras por cadena')
return np.concatenate((chains[:,:n],chains[:,-n:]),axis=0)
def basic_rhat(chains):
m,n=chains.shape;W=chains.var(axis=1,ddof=1).mean();B=n*chains.mean(axis=1).var(ddof=1)
if W==0:return np.inf if B>0 else np.nan
return np.sqrt(((n-1)*W/n+B/n)/W)
def rank_normalize(x):
ranks=rankdata(x.reshape(-1),method='average').reshape(x.shape)
return ndtri((ranks-3/8)/(x.size+1/4))
def rhat_rank(chains):
s=split(np.asarray(chains));z=rank_normalize(s)
folded=rank_normalize(np.abs(s-np.median(s)))
return max(basic_rhat(z),basic_rhat(folded))
def ess_geyer(chains):
x=np.asarray(chains);m,n=x.shape
acov=np.array([autocov(row) for row in x]);W=acov[:,0].mean()*n/(n-1)
varplus=(n-1)*W/n+x.mean(axis=1).var(ddof=1) if m>1 else (n-1)*W/n
if varplus<=0:return np.nan
rho=np.ones(n);rho[1:]=1-(W-acov[:,1:].mean(axis=0))/varplus
pairs=[]
for i in range(0,n-1,2):
pair=rho[i]+rho[i+1]
if pair<0:break
pairs.append(min(pair,pairs[-1]) if pairs else pair)
tau=max(1/np.log10(m*n),-1+2*sum(pairs))
return m*n/tau
def bulk_ess(chains):return ess_geyer(rank_normalize(split(np.asarray(chains))))X,y,Xtest,ytest,_=synthetic_data();alpha=1.5
def logposterior(w):
z=X@w
return float(y@z-np.logaddexp(0,z).sum()-.5*alpha*(w@w))
mode,cov,info=fit_laplace(X,y,alpha=alpha)
chains=[]
starts=[[-1,0,0],[1,0,0],[0,-1,0],[0,1,0]]
def run_chain(i):
draws,rate,scale=metropolis(logposterior,mode+starts[i],101+i)
chains.append(draws)
print('cadena',i,'aceptación',round(rate,4),'escala final',round(scale,4))run_chain(0)run_chain(1)run_chain(2)run_chain(3)chains=np.array(chains)
for j in range(3):
c=chains[:,:,j]
print('coef',j,'media',c.mean(),'ESS bulk',bulk_ess(c),'R-hat',rhat_rank(c),
'MCSE media',c.std(ddof=1)/np.sqrt(ess_geyer(c)))
print('media Laplace',mode,'desviaciones',np.sqrt(np.diag(cov)))
print('media MCMC',chains.mean(axis=(0,1)))independent,rate=independent_mh(logposterior,mode,mode,cov,2121)
print('aceptación',rate,'media',independent.mean(axis=0))In the reproducible run, MCMC means were approximately and Laplace mean . Differences reflect approximations and Monte Carlo noise, not a general quality ranking. Four acceptance rates lay between 0.191 and 0.261; they are measured after warmup.
Comparison with ArviZ
The local cell regenerates the same chains before comparing and plotting traces and ranks. In ArviZ 1.3, from_dict returns an xarray DataTree, replacing the old InferenceData structure; code uses that version’s interface. Manual rank R-hat and bulk ESS match ArviZ in this run. The final line compares ESS for the mean: our estimate uses unsplit chains whereas ArviZ uses its own convention, so exact equality is not expected. Rank plots help find differences between chains; their bands and tests also require interpretation of temporal dependence.
"""MAP logístico con prior gaussiano y aproximación de Laplace."""
import numpy as np
from scipy.special import expit
def negative_log_posterior(w, X, y, alpha):
z = X @ w
p = expit(z)
value = np.logaddexp(0., z).sum() - y @ z + .5 * alpha * (w @ w)
gradient = X.T @ (p-y) + alpha*w
H = X.T @ ((p*(1-p))[:,None]*X) + alpha*np.eye(X.shape[1])
return value, gradient, H
def fit_laplace(X, y, alpha=1., tol=1e-9, max_iter=100):
X=np.asarray(X,dtype=float);y=np.asarray(y,dtype=float)
if X.ndim!=2 or y.shape!=(X.shape[0],) or X.shape[1]==0:
raise ValueError('dimensiones incompatibles')
if not np.all(np.isfinite(X)) or not np.all(np.isfinite(y)) or np.any((y!=0)&(y!=1)) or not np.isfinite(alpha) or alpha<=0 or tol<=0 or max_iter<1:
raise ValueError('datos finitos, etiquetas binarias, alpha y tolerancia positivos y al menos una iteración')
w=np.zeros(X.shape[1]); converged=False
for iteration in range(max_iter):
value,gradient,H=negative_log_posterior(w,X,y,alpha)
if np.linalg.norm(gradient,np.inf)<tol:
converged=True;break
direction=np.linalg.solve(H,gradient)
rate=1.
while rate>1e-12:
candidate=w-rate*direction
if negative_log_posterior(candidate,X,y,alpha)[0]<=value-1e-4*rate*(gradient@direction):
break
rate*=.5
if rate<=1e-12:break
w=candidate
value,gradient,H=negative_log_posterior(w,X,y,alpha)
if np.linalg.norm(gradient,np.inf)<tol:converged=True
cov=np.linalg.solve(H,np.eye(X.shape[1]))
return w,cov,{'converged':converged,'iterations':iteration+1,
'gradient_inf':np.linalg.norm(gradient,np.inf),'objective':value}
def predict_probit(X, mean, covariance):
X=np.asarray(X,dtype=float)
variance=np.einsum('ij,jk,ik->i',X,covariance,X)
return expit((X@mean)/np.sqrt(1+np.pi*np.maximum(variance,0)/8))
def synthetic_data(seed=2026,n_train=40,n_test=2000):
"""Datos sintéticos Bernoulli, partición de test independiente en el mismo generador."""
rng=np.random.default_rng(seed)
true_w=np.array([-.4,1.4,-1.])
def generate(n):
X=np.column_stack((np.ones(n),rng.normal(size=(n,2))))
y=rng.binomial(1,expit(X@true_w))
return X,y
X,y=generate(n_train);X_test,y_test=generate(n_test)
return X,y,X_test,y_test,true_w
import numpy as np
from scipy.special import ndtri
from scipy.stats import rankdata
def metropolis(logp,start,seed,warmup=1000,draws=4000,scale=.5):
rg=np.random.default_rng(seed);x=np.array(start,dtype=float);lp=logp(x);logs=np.log(scale);samples=[];accepted=0
for t in range(warmup+draws):
candidate=x+np.exp(logs)*rg.normal(size=x.size);new=logp(candidate)
take=np.log(rg.random())<min(0.,new-lp)
if take:x=candidate;lp=new
if t<warmup:logs+=.8*(t+20)**(-.6)*(take-.234)
else:samples.append(x.copy());accepted+=take
return np.array(samples),accepted/draws,np.exp(logs)
def independent_mh(logp,start,proposal_mean,proposal_cov,seed,draws=4000):
rg=np.random.default_rng(seed);L=np.linalg.cholesky(proposal_cov);x=np.array(start,dtype=float);lp=logp(x);out=[];accepted=0
def logq(w):
z=np.linalg.solve(L,w-proposal_mean)
return -.5*(z@z) # Las constantes comunes de la normal se cancelan.
lq=logq(x)
for _ in range(draws):
y=proposal_mean+L@rg.normal(size=x.size);new=logp(y);newq=logq(y)
if np.log(rg.random())<min(0.,new-lp+lq-newq):x=y;lp=new;lq=newq;accepted+=1
out.append(x.copy())
return np.array(out),accepted/draws
def autocov(x):
x=np.asarray(x);n=len(x);x=x-x.mean();size=1<<(2*n-1).bit_length()
f=np.fft.rfft(x,n=size)
return np.fft.irfft(f*np.conjugate(f),n=size)[:n]/n
def split(chains):
n=chains.shape[1]//2
if n<2:raise ValueError('se requieren al menos cuatro muestras por cadena')
return np.concatenate((chains[:,:n],chains[:,-n:]),axis=0)
def basic_rhat(chains):
m,n=chains.shape;W=chains.var(axis=1,ddof=1).mean();B=n*chains.mean(axis=1).var(ddof=1)
if W==0:return np.inf if B>0 else np.nan
return np.sqrt(((n-1)*W/n+B/n)/W)
def rank_normalize(x):
ranks=rankdata(x.reshape(-1),method='average').reshape(x.shape)
return ndtri((ranks-3/8)/(x.size+1/4))
def rhat_rank(chains):
s=split(np.asarray(chains));z=rank_normalize(s)
folded=rank_normalize(np.abs(s-np.median(s)))
return max(basic_rhat(z),basic_rhat(folded))
def ess_geyer(chains):
x=np.asarray(chains);m,n=x.shape
acov=np.array([autocov(row) for row in x]);W=acov[:,0].mean()*n/(n-1)
varplus=(n-1)*W/n+x.mean(axis=1).var(ddof=1) if m>1 else (n-1)*W/n
if varplus<=0:return np.nan
rho=np.ones(n);rho[1:]=1-(W-acov[:,1:].mean(axis=0))/varplus
pairs=[]
for i in range(0,n-1,2):
pair=rho[i]+rho[i+1]
if pair<0:break
pairs.append(min(pair,pairs[-1]) if pairs else pair)
tau=max(1/np.log10(m*n),-1+2*sum(pairs))
return m*n/tau
def bulk_ess(chains):return ess_geyer(rank_normalize(split(np.asarray(chains))))
X,y,Xtest,ytest,_=synthetic_data();alpha=1.5
def logposterior(w):
z=X@w
return float(y@z-np.logaddexp(0,z).sum()-.5*alpha*(w@w))
mode,cov,info=fit_laplace(X,y,alpha=alpha)
chains=[]
for i,delta in enumerate(([-1,0,0],[1,0,0],[0,-1,0],[0,1,0])):
samples,rate,scale=metropolis(logposterior,mode+delta,101+i)
chains.append(samples);print('chain',i,'accept',round(rate,4),'scale',round(scale,4))
chains=np.array(chains)
for j in range(3):
c=chains[:,:,j]
print('coef',j,'mean',c.mean(),'std',c.std(),'ESS bulk',bulk_ess(c),'Rhat rank folded',rhat_rank(c),'MCSE mean',c.std(ddof=1)/np.sqrt(ess_geyer(c)))
print('Laplace mean',mode,'std',np.sqrt(np.diag(cov)),'MCMC mean',chains.mean(axis=(0,1)))
independent,rate=independent_mh(logposterior,mode,mode,cov,2121)
print('independent acceptance',rate,'mean',independent.mean(axis=0))
import arviz as az
import matplotlib.pyplot as plt
idata=az.from_dict({'posterior':{'w':chains}})
print('ArviZ',az.__version__)
print('R-hat ArviZ',az.rhat(idata,method='rank')['w'].values)
print('R-hat manual',[rhat_rank(chains[:,:,j]) for j in range(3)])
print('ESS bulk ArviZ',az.ess(idata,method='bulk')['w'].values)
print('ESS bulk manual',[bulk_ess(chains[:,:,j]) for j in range(3)])
print('ESS media ArviZ',az.ess(idata,method='mean')['w'].values)
print('ESS media sin dividir',[ess_geyer(chains[:,:,j]) for j in range(3)])
az.plot_trace(idata,var_names=['w']);plt.show()
az.plot_rank(idata,var_names=['w']);plt.show()npm run lab and open the connection link.Exercises
Step 1 of 2. What is ?
Step 1 of 2. How is accepted flow expressed?
ess_geyer(x) with FFT autocovariance, consecutive autocorrelation pairs, initial positive sequence and monotone adjustment. Return NaN for a constant chain. Use denominator N in autocovariance; allow ESS greater than N for anticorrelation.def ess_geyer(x):
passrhat_rank(chains) for an array of shape (cadenas, iteraciones). Split each chain into two equal halves, discard the middle if length is odd, transform average ranks with Blom's formula, and return the maximum of ordinary rank R-hat and that calculated on distances from the median. Assume positive within-half variation.def rhat_rank(chains):
passSummary
- The proposal ratio is essential without symmetry, and rejections are repeated states.
- The 0.234 scaling arises under specific high-dimensional assumptions; it is not a universal rule.
- ESS, MCSE, rank R-hat and traces provide complementary evidence without guaranteeing all modes were explored.