Skip to content

Probabilistic inference, Monte Carlo, and posterior computation · Probabilistic computation and inference foundations · INF009 · Algorithm

Metropolis–Hastings (MH)

Constructs a Markov chain with a chosen target stationary distribution by correcting proposal moves with an acceptance ratio.

Runs as a notebook Complete calculation CodeSplash's run and the reference's record

In CodeSplash

No method yet, but the reference's example runs here as a notebook.

Do it in CodeSplash Open the reference's example as a Python or R notebook.

Availability
Runs as a notebook
Code example
Complete calculation
Who ran it
CodeSplash's run and the reference's record
CodeSplash's run
The reference's example ran here in one language.
The reference's record
Python: Ran in the reference's review. The report doesn't record which version of the code ran. R: Reviewed but not run: R wasn't available to the reference's authors.

Purpose

Constructs a Markov chain with a chosen target stationary distribution by correcting proposal moves with an acceptance ratio. It needs the target only up to a normalizing constant and supports both discrete and continuous states when suitable proposals exist.

Question / hypotheses

How can a convenient proposal transition be corrected so that its long-run state distribution is the intended posterior?

Architecture / computational structure

Propose a state, compare log target and proposal ratios, accept or retain the current state, and repeat. Rejections must appear as repeated states in the chain. The displayed random-walk proposal is symmetric, so its proposal-density terms cancel; this simplification is not universal.

Assumptions

The chain must have appropriate support, irreducibility, and recurrence properties; stationarity alone does not ensure useful finite-run exploration. Forward and reverse proposal densities must be correctly included. Chains must be run long enough for the inferential quantities of interest.

Formula / computational definition

α(x,y)=min⁡(1,p~(y)q(x∣y)p~(x)q(y∣x)),xt+1={yu<αxtotherwise.\alpha(x,y)=\min\left(1,\frac{\tilde p(y)q(x\mid y)}{\tilde p(x)q(y\mid x)}\right),\qquad x_{t+1}=\begin{cases}y&u<\alpha\\x_t&otherwise.\end{cases}

Parameters and notation

The evolving state is a posterior draw candidate, not an optimized parameter estimate. Proposal covariance, scale, blocking, warmup length, and retained draws are algorithmic choices. Adapt proposal settings during a justified warmup, then freeze them unless using an adaptive-MCMC scheme with demonstrated validity.

Fitting, fine-tuning, and adaptation

Initialize several dispersed chains, tune proposal geometry on warmup, and retain post-warmup draws under the intended kernel. After a model or dataset change, the previous chain no longer targets the new posterior; it can supply starts but cannot simply be pooled with new draws.

How to use and calibrate

Inspect trace plots, multiple-chain convergence diagnostics, autocorrelation, effective sample size, and Monte Carlo standard errors. Compare numerical moments against a known target before extending the model. An acceptance rate is a tuning diagnostic, not a convergence certificate or universal target.

Example application

Sample a nonconjugate latent-model parameter whose unnormalized posterior is evaluable but whose conditional distribution cannot be drawn directly.

Interpretation / pitfalls

Watch out

A chain can have excellent acceptance while barely moving or remain trapped in one mode. Retaining only accepted proposals biases averages toward the jump chain. Treating correlated draws as independent understates Monte Carlo error; thinning usually does not solve poor mixing.

Python and R code examples

Scope: Complete short random-walk MH chain for a standard normal target; no claim of general convergence or production posterior validation.

Implementation route: Python NumPy and base R implement the transition directly. More complex models require correct proposal ratios and model log densities; a short hand-coded example should be checked before replacing an established sampler.

Dependencies and validation: Python — executed successfully on the supplied synthetic inputs; imports identify NumPy/SciPy dependencies. R — base R, reviewed but not executed because Rscript is unavailable. Random-number streams differ between languages; matching seed integers do not imply matching draws.

Python and R

The reference's own programs, shown as written. A component demo shows one central piece of the method; it doesn't train a full model.

Python

Complete calculation — Complete short random-walk MH chain for a standard normal target; no claim of general convergence or production posterior validation. · needs numpy

import numpy as np
rng=np.random.default_rng(7); x=3.; draws=[]; accepted=0
for _ in range(6000):
    y=x+rng.normal(0,.8); loga=min(0.,-.5*y*y+.5*x*x)
    if np.log(rng.uniform())<loga: x=y; accepted+=1
    draws.append(x)
d=np.array(draws[1000:])
print('mean',d.mean(),'variance',d.var(),'acceptance',accepted/6000)
R

Complete calculation — Complete short random-walk MH chain for a standard normal target; no claim of general convergence or production posterior validation.

set.seed(7); x <- 3; draws <- numeric(6000); accepted <- 0
for(i in seq_along(draws)) {
  y <- x+rnorm(1,0,.8); loga <- min(0,-.5*y*y+.5*x*x)
  if(log(runif(1))<loga) {x <- y; accepted <- accepted+1}
  draws[i] <- x
}
d <- draws[1001:6000]; print(c(mean=mean(d),variance=mean((d-mean(d))^2),acceptance=accepted/6000))

Sources

From the CodeSplash reference, entry INF009.