Module contents
Lesson 21 of 27Core 120 min

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

Sampling without knowing the constant

Suppose you know π~(x)∝π(x)\tilde\pi(x)\propto\pi(x) but not the posterior’s normalizing constant. Markov chain Monte Carlo constructs a process whose stationary distribution is π\pi 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 π\pi if πP=π\pi P=\pi. Stationarity alone does not imply convergence from an arbitrary start: appropriate conditions such as irreducibility and aperiodicity are also needed. Detailed balance, πiPij=πjPji\pi_iP_{ij}=\pi_jP_{ji}, suffices for stationarity by summing over ii, but is not necessary. In continuous spaces it is interpreted as equality of flow measures.

InteractiveProbability flows
0.1670.1670.1670.1670.1670.167123
π = (1/3, 1/3, 1/3); each arrow shows flow πᵢPᵢⱼ. Global error measures πP − π.
0.50
0.50
0.50
Maximum global balance error0.0000
Maximum detailed balance error0.0000
Each row distributes its probability among the other two states; arrows show flows for uniform π. The cycle with all three controls at 1 preserves π but breaks detailed balance.

Metropolis-Hastings

From xx, propose y∼q(y∣x)y\sim q(y\mid x) and accept with probability

α(x,y)=min⁡{1,π~(y)q(x∣y)π~(x)q(y∣x)}.\alpha(x,y)=\min\left\{1,\frac{\tilde\pi(y)q(x\mid y)}{\tilde\pi(x)q(y\mid x)}\right\}.

If rejected, the chain repeats xx; that repetition is part of the sample. For x≠yx\ne y, both accepted flows equal min⁡{π(x)q(y∣x),π(y)q(x∣y)}\min\{\pi(x)q(y\mid x),\pi(y)q(x\mid y)\}. Thus the Metropolis-Hastings kernel satisfies detailed balance. The normalizing constant of π\pi cancels. A symmetric random-walk proposal also cancels the proposal ratio; for independent proposal q(y∣x)=g(y)q(y\mid x)=g(y) it remains g(x)/g(y)g(x)/g(y) and must not be omitted.

Work in log space: compare log⁡U\log U with min⁡(0,log⁡π~(y)−log⁡π~(x)+log⁡q(x∣y)−log⁡q(y∣x))\min(0,\log\tilde\pi(y)-\log\tilde\pi(x)+\log q(x\mid y)-\log q(y\mid x)). 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.

InteractiveRandom walk and its scale
Trace of the first coordinate
Empirical autocorrelation of x
0.8
Acceptance0.664
Steps1800
Change target and scale: a very small step moves slowly and a large one is often rejected. The plane shows the last 250 steps; trace and autocorrelation use the entire reproducible chain.

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 2.38/d2.38/\sqrt d 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.

InteractiveAcceptance and dimension
  • Fixed scale 1
  • 2.38 / √d
4
Dimension20
Fixed-scale acceptance0.0359
Acceptance at 2.38/√d scale0.2412
10,000 proposals from a standard normal are averaged per dimension. Fixed scale is 1; decreasing scale is 2.38/√d. Very small rates have greater Monte Carlo uncertainty.

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 kk-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 hh, if the Markov-chain central limit theorem assumptions hold, variance of its mean is approximately σh2τ/N\sigma_h^2\tau/N, where τ=1+2∑t≥1ρt\tau=1+2\sum_{t\ge1}\rho_t. MCMC effective sample size is Neff=N/τN_{\rm eff}=N/\tau and estimated Monte Carlo standard error for the mean is approximately sh/Neffs_h/\sqrt{N_{\rm eff}}. It can exceed NN with negative correlations; it depends on hh. 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.

InteractiveFour chains do not lie
  • Chain 1
  • Chain 2
  • Chain 3
  • Chain 4
4.0
1.0
Rank and folded R-hat1.741
Approximate bulk ESS15
Chains × steps4 × 1000
Four chains start near both modes and rank R-hat and bulk ESS are calculated. In the figure autocorrelations are truncated at 200 lags per half.

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.

[ ]Generator and Laplace from m14-l07Browser
"""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

The 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.

[ ]Metropolis and diagnosticsBrowser
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):
        [email protected](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))))
[ ]Prepare logistic regressionBrowser
X,y,Xtest,ytest,_=synthetic_data();alpha=1.5
def logposterior(w):
    z=X@w
    return float([email protected](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))
[ ]Chain 1Browser
run_chain(0)
[ ]Chain 2Browser
run_chain(1)
[ ]Chain 3Browser
run_chain(2)
[ ]Chain 4Browser
run_chain(3)
[ ]Diagnostics and comparison with LaplaceBrowser
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 proposalBrowser
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 (−0.418,1.884,−0.460)(-0.418,1.884,-0.460) and Laplace mean (−0.406,1.737,−0.463)(-0.406,1.737,-0.463). 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.

[ ]ArviZ: comparison and plotsLocal GPU
"""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):
        [email protected](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([email protected](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()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

NumericESS of an AR(1)
A long chain has N=10 000N=10\,000 states and theoretical autocorrelation ρt=0.9t\rho_t=0.9^t. Approximate its ESS for the mean using the infinite autocorrelation sum.
QuizThin?
What is the effect of saving only every kth already-simulated iteration?
ProofDetailed balance implies stationarity
Prove: If πiPij=πjPji\pi_iP_{ij}=\pi_jP_{ji} for all states, then πP=π\pi P=\pi.
0
Assume PP is row stochastic and π\pi a distribution.

Step 1 of 2. What is (πP)j(\pi P)_j?

ProofMH detailed balance
Prove: The Metropolis-Hastings kernel satisfies detailed balance.
0
For x≠yx\ne y, define P(x,y)=q(y∣x)α(x,y)P(x,y)=q(y\mid x)\alpha(x,y) and assume ratios are defined on the support considered.

Step 1 of 2. How is accepted flow expressed?

CodeESS of a chain
Implement 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):
  pass
Shift+Enter to run
CodeSplit rank R-hat
Implement rhat_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):
  pass
Shift+Enter to run

Summary

Key idea
MH constructs transitions with the desired posterior as stationary; mixing and Monte Carlo error must be checked with multiple chains and diagnostics appropriate to the quantity of interest.
  • 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.