Markov Chain Monte Carlo

You can score a posterior at any point but you cannot normalize it. A walker that only compares two heights still lands in the right places: tuned well, 1,000 steps give about 220 independent draws.

Learn how a random walk can sample any distribution you can score, why it works, and how to tell when its answer is trustworthy.

Pick a step size and press Run. Watch the teal histogram grow into the warm curve, and watch how many independent draws each step size buys. Then we build, piece by piece, the chain, the accept rule, its variants and the checks.

You need the Monte Carlo idea: an average of random samples estimates an expected value (Monte Carlo). You also need a posterior is likelihood times prior, divided by a total (Bayesian estimation). We build the rest from zero.

Part of the Monte Carlo family. The hub is Monte Carlo; the siblings are importance sampling, Hamiltonian Monte Carlo, sequential Monte Carlo, quasi-Monte Carlo and Monte Carlo tree search.

Walk the coin posterior

Target: the Beta(9,5) coin posterior from Chapter 0, scored as θ8(1 − θ)4 with no Z. The walk runs live in your browser. A seeded numpy run of 40,000 steps gives the reference. Step 0.01 accepts 98% and yields about 2 independent draws per 1,000 steps. Step 0.3 accepts 44% and yields about 220. Step 3 accepts 5% and yields about 32.

Chapter 0

A Distribution You Can Score but Cannot Sample

Score a posterior at any point, find that you cannot normalize it, and see why a ratio of two heights is enough

You flip a bent coin 10 times and see 7 heads. Before the flips you believed the coin was roughly fair. Now you want your updated belief about its chance of heads, called θ (theta). That belief is the posterior: a curve over every value of θ from 0 to 1.

Call the score of one value p̃(θ), said "p-tilde of theta": the likelihood times the prior. For this coin, with a mild Beta(2,2) prior, the score is θ8(1 − θ)4. One line of code computes it. To turn scores into probabilities, divide by their total area, the normalizing constant Z.

Say it aloud

p of theta equals p-tilde of theta, divided by Z.

p(θ)
p of theta the posterior density at one value of θ. Its total area is 1.
p̃(θ)
p-tilde of theta the score: likelihood times prior. Here θ8(1 − θ)4.
Z
Z the total area under the score curve, over every θ.
In plain words

Compute the score p̃(θ) at a point. Divide it by Z, the area of the whole score curve. The result p(θ) is a true density.

With numbers

For this coin Z = 0.000155. At θ = 0.6 the score is 0.68 × 0.44 = 0.000430, so p(0.6) = 0.000430 / 0.000155 = 2.77. A density can be above 1; only its area must be 1.

One coin has a formula for Z. Add a second parameter or a hierarchy, and Z becomes an integral over many dimensions that nobody can compute. You can feel the hill point by point, but you cannot weigh it.

Here is the escape. Compare two points by the ratio of their scores. Z sits on the top and on the bottom, so it cancels:

p(θ′) / p(θ) = p̃(θ′) / p̃(θ)

Here θ′ (theta-prime) is a second value. From θ = 0.5 to θ′ = 0.6 the ratio is 0.000430 / 0.000244 = 1.761. The value 0.6 is 1.761 times as likely as 0.5, and we never needed Z.

Guess Z and watch the ratio stay

Warm is the score divided by your guess of Z. Move the guess: the curve grows and shrinks, and its area changes. Then move the candidate θ′ and read the ratio.

0.60
1.00×

The curve and both scores are exact for the Beta(9,5) posterior. The Z slider multiplies the true Z by a factor from 0.5 to 2.

Markov chain Monte Carlo (MCMC) builds a random walk that makes every decision from such a ratio. Its visits pile up in proportion to p(θ). Average along the walk and you get the posterior mean, 9/14 = 0.643, with no Z. The hero runs that walk.

The failure: weighing the hill on a grid

Symptom: you compute Z by summing scores on a grid, and the job never ends. Measure: count the scores. A grid of 100 points for each of 10 parameters needs 10010 = 1020 scores. At a billion scores a second that takes about 3,200 years. Fix: stop gridding and sample.

The road

  1. Markov chains: a walk that forgets its start and settles into one mix.
  2. Detailed balance: the local rule that aims a chain at a target.
  3. Metropolis: propose, compare two heights, accept or stay. The hero's walker.
  4. Hastings: the correction for a lopsided proposal.
  5. Gibbs: one coordinate at a time, never rejected.
  6. Discrete spaces: spins, colourings and trees.
  7. Burn-in: drop the samples from before the chain arrived.
  8. Effective sample size: what correlated samples are worth. The hero's draw count.
  9. R-hat and step size: check that chains agree, and tune the step. The hero's three buttons.
  10. Field guide: numbers, checklist, code and where to go next.
Why can MCMC sample a posterior whose normalizing constant Z cannot be computed?

Chapter 1

Markov Chains Forget Where They Start

Step a two-state weather chain and watch every start settle into the same long-run mix

Tomorrow's weather depends only on today's. A sunny day stays sunny 70% of the time. A rainy day stays rainy 60% of the time. A process whose next state depends only on its current state is a Markov chain.

Put the moves in a table, the transition matrix P. Row Sunny is [0.7, 0.3]. Row Rainy is [0.4, 0.6]. Each row sums to 1.

Start certain it is sunny, [1, 0]. One day later the mix is [0.7, 0.3]. Two days: [0.61, 0.39]. Four days: [0.575, 0.425].

Step the weather chain

Bars show today's chance of sun (teal) and rain (pink). The line tracks the chance of sun day by day. Pick a start and press Step.

Exact arithmetic on the two-state chain; the dashed line is the stationary 4/7.

Every start lands on the same mix. That limit is the stationary distribution π (pi): the mix that one more step leaves unchanged.

Say it aloud

pi times P equals pi.

π
pi a row of probabilities, one per state, that sums to 1. Here [sun, rain].
P
P the transition matrix. Row i holds the chances of moving from state i to each state.
= π
equals pi after one step the mix is the same as before.
In plain words

Take the mix π. Send each state's share along its row of P. Add up what arrives at each state. If the result is π again, π is stationary.

With numbers

Try π = [4/7, 3/7] = [0.571, 0.429]. Sun receives 0.571 × 0.7 + 0.429 × 0.4 = 0.400 + 0.171 = 0.571. Rain keeps 0.429. The mix is unchanged, so 4/7 of days are sunny in the long run.

How fast does the start fade? The gap to π shrinks by a factor λ2 (lambda-two, the second eigenvalue of P) each step. For two states λ2 = 0.7 + 0.6 − 1 = 0.3. After 5 steps the gap is 0.35 = 0.0024 of where it began. A chain with λ2 near 1 forgets slowly, and Chapter 7 pays that bill.

Two conditions make π unique. The chain must be irreducible: it can reach every state from every state. It must be aperiodic: it does not cycle on a fixed rhythm. MCMC turns the problem around. You pick π, your posterior, and design P to reach it. Continuous-time chains are in CTMC; chains with hidden states are in HMM.

The failure: a chain that cannot cross

Symptom: the answer depends on where you start. Measure: run from two starts. With P = [[1, 0], [0, 1]] a sunny start stays [1, 0] forever and a rainy start stays [0, 1]. Fix: make every state reachable, so the chain is irreducible.

A chain has reached its stationary distribution π. What is true of one walker on it?

Chapter 2

Detailed Balance Aims the Chain

Replace a global condition with a check on each pair of states, and see that it is enough but not required

You want a chain whose π is your target. Checking πP = π ties every state to every other state. A local check is easier. Detailed balance asks, for every pair of states, that the probability flowing one way equals the probability flowing back.

Say it aloud

pi of x times P of x to x-prime equals pi of x-prime times P of x-prime to x.

π(x)
pi of x the target probability of state x.
P(x→x′)
P of x to x-prime the chance that one step moves the walker from x to x′.
π(x′)
pi of x-prime the target probability of the other state.
P(x′→x)
P of x-prime to x the chance of the move back.
In plain words

Multiply the share at x by the chance to jump to x′. That is the flow out. Do the same from x′ back to x. If the two flows match for every pair, the chain is reversible and π is stationary.

With numbers

Target π = [0.8, 0.2]. Always propose the other state and accept with min(1, π(x′)/π(x)). Then P(0→1) = 0.25 and P(1→0) = 1. The flows are 0.8 × 0.25 = 0.2 and 0.2 × 1 = 0.2. They match.

Why is this enough? Add the balance equation over every x′. The left side becomes π(x) times a full row of P, which sums to 1, so it is π(x). The right side becomes everything that flows into x, which is (πP)(x). So π = πP for every state.

Match the flows

Circle size is the target share. Arrow width is the flow. Drag the target; the chain rebuilds its moves so the two arrows stay equal. Then switch on the cycle.

0.80

Exact flows. The two-state moves use the Metropolis rule of Chapter 3; the cycle is P = [[0.5, 0.5, 0], [0, 0.5, 0.5], [0.5, 0, 0.5]].

Balance is enough, but it is not required. The three-state cycle keeps π = [1/3, 1/3, 1/3] fixed. Yet on the edge from state 0 to state 1 the flow is 1/6 one way and 0 back. Probability circulates. Some modern samplers break balance on purpose to move faster; we use it because it is easy to build.

The failure: a sampler aimed at the wrong target

Symptom: your sampler settles, but on the wrong histogram. Measure: on a small discrete target, build P and check that the flow table is symmetric. Fix: rebuild the moves until every pair balances.

pythonimport numpy as np
def balanced(pi, P):
    flow = pi[:, None] * P              # flow[i, j] = pi_i * P_ij
    return np.allclose(flow, flow.T)   # every pair matches?
balanced(np.array([0.8, 0.2]), np.array([[0.75, 0.25], [1.0, 0.0]]))   # True
Is detailed balance necessary for π to be stationary?

Chapter 3

Metropolis: Propose, Compare, Accept

Turn detailed balance into a three-line loop that always climbs and sometimes descends

Stand at a point x. Propose a candidate x′ by adding random noise. The proposal must be symmetric: moving from x to x′ is as likely as moving back. Then decide with the acceptance probability A.

Say it aloud

A of x to x-prime equals the minimum of 1 and p-tilde of x-prime over p-tilde of x.

A(x→x′)
A of x to x-prime the chance of taking the proposed move.
min(1, ·)
the minimum of 1 and caps the value at 1, because a chance cannot exceed 1.
p̃(x′)
p-tilde of x-prime the score of the candidate.
p̃(x)
p-tilde of x the score of the current point.
In plain words

Score the candidate x′ and the current point x. If x′ scores higher, move. If lower, move with a chance equal to the ratio. If you do not move, record x again.

With numbers

Target: the bell p̃(x) = e−x²/2. At x = 0.5, candidate x′ = 1.5: the ratio is e−(2.25 − 0.25)/2 = e−1 = 0.368, so A = 0.368. Candidate x′ = 0.2: the ratio is 1.111, so A = 1.

Why does this hit the target? Put P(x→x′) = q × A into detailed balance, with q the symmetric proposal chance. The left side becomes q × min(π(x), π(x′)). The right side is the same expression. Balance holds for every pair.

Make one decision at a time

The purple ghost is the candidate. The bar compares the two heights; the yellow tick is the random draw. Press Step to see one decision, or Run to fill the histogram.

1.0

Live sampler in your browser. The first Step after a reset is the worked move, 0.5 to 1.5; the rest are random.

Metropolis, the two Rosenbluths and the two Tellers published this rule in 1953. They used it on the MANIAC computer at Los Alamos to study a fluid of hard disks.

The failure: dropping the rejected steps

Symptom: the histogram is too wide. Measure: on the coin posterior with step 1.0, keep only accepted moves: the spread is 0.137 against the true 0.124, 11% too wide. Fix: append x on every step. A repeat is how the walker spends extra time where the curve is tall.

Metropolis on the bell e−x²/2: you are at x = 0.5 and propose x′ = 1.5. What happens?

Chapter 4

Hastings Corrects a Lopsided Proposal

Use a proposal that leans where you want, and pay for the lean with one extra ratio

Some quantities must stay positive: a rate, a variance. A symmetric proposal near zero keeps suggesting negative values, and each one is a wasted rejection. It is better to propose only positive values. But such a proposal is lopsided, and a lopsided proposal biases the chain.

Take the target p̃(x) = x e−x for x > 0, a Gamma(2,1) with mean 2. Propose x′ from an exponential with mean x: q(x′ | x) = (1/x) e−x′/x. From x = 2 the chance density of proposing 3 is 0.112. From x = 3 the density of proposing 2 is 0.171. Hastings (1970) restored balance with one more ratio.

Say it aloud

A equals the minimum of 1 and two ratios multiplied: p-tilde of x-prime over p-tilde of x, times q of x given x-prime over q of x-prime given x.

A
A the chance of taking the move from x to x′.
p̃(x′) / p̃(x)
p-tilde of x-prime over p-tilde of x the height ratio from Chapter 3.
q(x | x′) / q(x′ | x)
q of x given x-prime over q of x-prime given x how easy the reverse move is to propose, compared with the forward move.
In plain words

Compute the height ratio. Multiply it by the chance of proposing the way back, divided by the chance of proposing the way forward. Cap at 1. Moves that are easy to make but hard to undo get accepted less.

With numbers

From x = 2 to x′ = 3: the height ratio is (3e−3)/(2e−2) = 0.552. The proposal ratio is 0.171 / 0.112 = 1.534. So A = 0.552 × 1.534 = 0.846.

If the proposal is symmetric, q(x | x′) = q(x′ | x), the second ratio is 1, and the rule is Metropolis again. Metropolis is the symmetric case of Metropolis-Hastings.

Switch the correction off

Warm is the true Gamma(2,1). Teal is where the chain has been. Turn the correction off and watch the histogram slide toward zero.

Live sampler. Reference from a seeded numpy run of 200,000 steps: with the correction the mean is 1.99 (true 2); without it the mean is 0.27.

The failure: dropping the proposal ratio

Symptom: the chain settles smoothly, on the wrong distribution. Nothing looks broken. Measure: test the sampler on a target with a known mean. Here the uncorrected chain reports 0.27 for a true mean of 2. Fix: include q(x | x′) / q(x′ | x), or use a symmetric proposal.

You switch to a lopsided proposal but keep the rule min(1, p̃(x′)/p̃(x)). What happens?

Chapter 5

Gibbs Samples One Coordinate at a Time

Draw each coordinate from its exact conditional, never reject, and watch correlation slow the walk

In many dimensions one big proposal often fails: a single bad coordinate sinks the whole move. But you can often sample one coordinate when you hold the others fixed. That distribution is the coordinate's full conditional. Gibbs sampling draws each coordinate from its full conditional in turn, then repeats.

Take two coordinates x1 and x2, each a standard normal, with correlation ρ (rho) between them. Here is the conditional of x1.

Say it aloud

x-one given x-two is normal, with mean rho times x-two and variance one minus rho squared.

x1 | x2 ~
x-one given x-two is distributed as the law of x1 when you hold x2 at its current value.
ρ x2
rho times x-two the conditional mean. ρ runs from −1 to 1.
1 − ρ²
one minus rho squared the conditional variance. It shrinks as ρ grows.
In plain words

Hold x2 fixed. Draw x1 from a bell centred at ρ times x2, with variance 1 − ρ². Then hold x1 and draw x2 the same way.

With numbers

With ρ = 0.8 and x2 = 1: the mean is 0.8 × 1 = 0.8. The variance is 1 − 0.64 = 0.36, so the spread is 0.6. Knowing x2 cut the variance of x1 from 1 to 0.36.

Gibbs never rejects. It is Metropolis-Hastings whose proposal is the full conditional. Put that q into the Hastings ratio, and the conditional terms cancel the height terms. The ratio is exactly 1.

Crank the correlation

The walker moves in L-shaped steps: across for x1, then up or down for x2. Drag ρ toward 1 and watch the steps shrink inside the thin ellipse.

0.80

Live sampler. The τ figures are exact for this target. A seeded numpy run of 20,000 sweeps measured a lag-1 correlation of 0.649 at ρ = 0.8 (exact 0.64) and 0.981 at ρ = 0.99 (exact 0.980).

No rejections is not the same as fast. One sweep sets x1new = ρx2 + noise and x2 = ρx1old + noise. So each sweep keeps ρ² of the old x1. At ρ = 0.8 it keeps 0.64; at ρ = 0.99 it keeps 0.98, and the walk crawls.

The failure: a crawl with no rejections

Symptom: the acceptance rate is 100%, but the trace drifts like a slow wave. Measure: the lag-1 correlation of x1. At ρ = 0.99 it is 0.98, so 10,000 sweeps are worth about 100 independent draws. Fix: rotate the coordinates, sample both together, or use the gradient moves of Hamiltonian Monte Carlo.

Why does a Gibbs step have an acceptance probability of exactly 1?

Chapter 6

Discrete Spaces: Spins, Colourings and Trees

Run Metropolis on a lattice of magnets, see a phase transition appear, then walk spaces with no coordinates at all

Picture a grid of tiny magnets. Each spin si is +1 or −1, and each one prefers to agree with its four neighbours. This is the Ising model. A grid state s has an energy E(s). Each agreeing pair of neighbours lowers it by J, the coupling. Each disagreeing pair raises it by J. At temperature T, a state's probability is proportional to e−E(s)/T.

Here Z sums over every grid state, and a 40 by 40 grid has 21600, about 10482, of them. Metropolis does not care. Flip one spin, and only its four neighbour pairs change.

Say it aloud

delta E equals two J s-i, times the sum over neighbours j of s-j.

ΔE
delta E the change in energy if spin i flips.
J
J the coupling: how much one agreeing pair lowers the energy. Here J = 1.
si
s-i the spin before the flip, +1 or −1.
Σj sj
the sum over neighbours j of s-j add the four neighbour spins: a whole number from −4 to 4.
In plain words

Add the four neighbour spins. Multiply by the spin and by 2J. That is ΔE. Accept the flip with min(1, e−ΔE/T), the Metropolis rule with the score e−E/T.

With numbers

A spin of +1 with four +1 neighbours: ΔE = 2 × 1 × 1 × 4 = 8. At T = 2 Metropolis accepts the flip with chance e−4 = 0.018. With three up and one down, ΔE = 4; at T = 2.5 the chance is e−1.6 = 0.202.

Cool the magnet

Warm cells are +1, teal cells are −1. Press Run, then slide T below 2.27 and watch one colour take over. Slide it above and watch the order dissolve.

2.00

Live sampler, one sweep per frame. A seeded numpy run on a 32 by 32 grid, started all +1, gives the reference over sweeps 200 to 400. It found |m| = 0.99 at T = 1.5, 0.92 at 2.0, 0.75 at 2.27, 0.14 at 2.6 and 0.07 at 3.5.

The magnetization m is the average spin. Below the critical temperature Tc = 2 / ln(1 + √2) = 2.269, found exactly by Onsager in 1944, costly flips are rare and one colour wins. Above it, noise wins and m falls to near 0. A small grid blurs the edge.

MCMC needs only a neighbour move and a ratio, so it works where there are no coordinates. In a 3-colouring of a graph, Gibbs recolours one node from the colours its neighbours leave free; neighbours Red and Green force Blue. Bayesian phylogenetics walks over trees: tools such as MrBayes and BEAST propose a local rearrangement and accept it by the Metropolis-Hastings ratio.

Species nUnrooted binary trees, (2n − 5)!!
55 × 3 × 1 = 15
1015 × 13 × … × 1 = 2,027,025

The failure: a cold start that never orders

Symptom: at T = 1.5 from a random start, stripes of both colours survive for thousands of sweeps. Measure: run again from all +1 and compare |m|. Fix: run much longer, cool slowly from a high T, or use moves that flip whole clusters.

A +1 spin has four +1 neighbours, with J = 1 and T = 2. What is the chance that Metropolis flips it?

Chapter 7

Burn-in: Drop the Walk to the Hill

See how a far start biases the average, and cut the samples from before the chain arrived

You must start the walker somewhere, and a guess may sit far out in a tail. The first steps are then not draws from the target. They are the walk to the hill. Average them in, and the estimate leans toward the start.

Burn-in is the first stretch of the chain, which you discard. The tool for seeing it is the trace plot: the sampled value against the step number. Start two chains far apart. While they disagree, they are still arriving. Once they share one noisy band, they have arrived.

Cut the burn-in

Teal starts at 8 and pink at 5; the warm band is the target's middle, from −1 to 1. Drag the cutoff and watch the kept mean move toward 0. Shrink the step and the walk to the hill gets longer.

0
0.40

Live Metropolis on a standard normal (true mean 0), 600 steps per chain. Toy starts, chosen to make the bias easy to see.

How long is enough? Chapter 1 showed that the gap to π shrinks by λ2 each step. Call the gap you accept ε (epsilon). You need k steps with λ2 to the k at most ε. Take logarithms:

k ≥ ln(ε) / ln(λ2)

For the weather chain, λ2 = 0.3 and ε = 0.01: k ≥ (−4.61) / (−1.20) = 3.82, so 4 steps. A slow chain with λ2 = 0.99 needs 459 steps for the same 1%. Real posteriors have no λ2 you can read off, so you watch the traces.

Burn-in ends one job and starts another. Mixing is how fast the chain moves around the target once it is there. A chain can arrive and still crawl. Chapter 8 measures that.

The failure: a flat trace that is stuck

Symptom: one chain's trace looks calm, so you call it done. Measure: start a second chain far away. If it settles at a different level, the first was stuck, not converged. Fix: always run several chains from spread-out starts; Chapter 9 turns this into a number.

Why discard the burn-in part of a chain?

Chapter 8

Effective Sample Size: What Your Samples Are Worth

Measure how much each sample repeats the last one, and turn a raw count into an honest one

You have 1,000 MCMC samples. They are not 1,000 independent draws: each one is a small step from the last. Plain Monte Carlo gives an error of σ/√N, where σ (sigma) is the spread of the target and N the sample count. Use that N here and you overstate your precision.

The autocorrelation at lag k, written ρk (rho-k), is the correlation between samples k steps apart. Add them up and you get the effective sample size.

Say it aloud

N-eff equals N, divided by one plus two times the sum over k of rho-k.

Neff
N-eff the number of independent draws the chain is worth.
N
N the raw number of samples kept.
Σk≥1
the sum over k from 1 add one term per lag, until the terms fall to about 0.
ρk
rho-k the correlation between samples k steps apart, from −1 to 1.
In plain words

Measure ρk at lag 1, 2, 3 and on. Double their sum and add 1. That is the integrated autocorrelation time τ (tau): raw steps per fresh draw. Divide N by τ to get Neff.

With numbers

With made-up numbers: a chain where ρk = 0.9k and N = 1,000. The sum is 0.9 + 0.81 + … = 9, so τ = 1 + 18 = 19 and Neff = 1,000 / 19 = 53. The honest error bar is √19 = 4.4 times wider than the naive one.

Make the chain sticky

Top: the trace. Middle: the measured autocorrelation by lag, with the exact curve in warm. Bottom: the naive error bar and the honest one. Drag the stickiness.

0.90

A toy chain, xt = ρxt−1 + noise (an AR(1) process), 1,000 steps, with fixed noise so the slider morphs one chain. Its exact τ is (1 + ρ)/(1 − ρ).

The hero's draw counts are Neff. A tiny step accepts almost everything, so each sample nearly repeats the last, and τ is huge. The importance sampling lesson has a different effective sample size, built from the spread of weights. Same name, different formula.

The failure: the raw count in the error bar

Symptom: a confident interval that later runs disagree with. Measure: compute Neff; at ρ = 0.9 it is 53, not 1,000. Fix: report σ/√Neff, and run longer until Neff is large enough.

A chain of N = 1,000 has τ = 19. What is Neff, and what does it do to the error bar?

Chapter 9

R-hat and the Step Size

Compare several chains to decide if they agree, and tune the one knob that sets how fast they get there

Run m chains from spread-out starts, each with n samples. If they have all reached the target, the spread between their means should be small next to the spread inside each chain. Two numbers capture this. The within-chain variance W is the average of each chain's own variance. The between-chain variance B is n/(m − 1) times the sum of squared gaps between each chain mean and the grand mean. Blend them into V̂ (V-hat):

V̂ = ((n − 1)/n) W + B/n

Say it aloud

R-hat equals the square root of V-hat over W.

R̂
R-hat the Gelman-Rubin statistic. It is near 1 when chains agree.
V̂
V-hat the pooled variance: mostly W, plus B/n for the gaps between chain means.
W
W the average variance inside each chain.
√( )
the square root of turns a ratio of variances into a ratio of spreads.
In plain words

Compute W from inside the chains and V̂ from inside and between. Divide V̂ by W and take the square root. If the chain means disagree, B is large, and R̂ climbs above 1.

With numbers

With made-up numbers: chains [1, 2, 3, 4, 5] and [3, 4, 5, 6, 7], so m = 2 and n = 5. W = 2.5. The means are 3 and 5, so B = 5 × (1 + 1) = 10. V̂ = 0.8 × 2.5 + 10/5 = 4. R̂ = √(4/2.5) = 1.265: not converged.

Stan and ArviZ compute a split, rank-normalized version of R̂ and flag any value above 1.01. The knob that decides how fast R̂ falls is the step size.

Tune the step

Four chains start at −6, −2, 2 and 6 on a standard normal. Drag the step and press Run. Read the acceptance and R̂ after 500 steps.

2.4

Live seeded sampler; R̂ here is the classic formula above. A seeded numpy run gave R̂ after 500 steps of 1.99 at step 0.1, 1.006 at step 2.4 and 1.008 at step 15.

A tiny step accepts almost every move but barely moves. A huge step overshoots into the tails and is almost always rejected. In between sits the best mixing. Take a one-dimensional standard normal. A seeded numpy run found the most independent draws at step 2.4, with 44% accepted. That step gave 9,000 per 40,000 steps, against 1,530 at step 0.5. In many dimensions the best acceptance falls to about 0.234 (Roberts, Gelman and Gilks, 1997). In 50 dimensions, a step of 2.38/√50 accepted 24%.

The failure: chains that agree on the wrong answer

Symptom: R̂ is 1.00, but the posterior has two peaks and every chain sits on one. Measure: start chains in every region you suspect, and compare their histograms. Fix: spread the starts wider, and pair R̂ with Neff.

Your sampler reports 98% acceptance. Why is that often a bad sign?

Chapter 10

Field Guide

Keep the numbers, the checklist and the code, and pick the next sampler for your problem

Build a chain whose stationary distribution is your target. Decide every move from a ratio of scores, so Z cancels. Drop the burn-in, measure Neff, and check R̂ across several chains before you trust the average.

Terms and numbers

TermMeaningNumber from this page
Score p̃likelihood times prior, no Zθ8(1 − θ)4; posterior mean 9/14 = 0.643
Stationary πthe mix one step leaves unchangedweather [0.571, 0.429]
Detailed balanceequal flow both ways on each pair0.8 × 0.25 = 0.2 × 1
Metropolis Amin(1, height ratio)0.5 to 1.5 on the bell: 0.368
Hastings Aheight ratio times proposal ratio0.552 × 1.534 = 0.846
Gibbsexact conditional draws, never rejectedρ = 0.8 keeps 0.64 per sweep
Ising Tcwhere order breaks2.269
Burn-insteps before the chain arrives4 at λ2 = 0.3; 459 at 0.99
NeffN / τ1,000 / 19 = 53
R̂between versus within chainstoy 1.265; flag above 1.01
Acceptance targetwhere mixing is bestabout 0.44 in 1-D, 0.234 in many

Checklist before you trust a chain

The core in code

pythonimport numpy as np
def metropolis(log_score, x0, step, n, seed=0):
    rng = np.random.default_rng(seed)
    x, lp, chain, acc = x0, log_score(x0), [], 0
    for _ in range(n):
        xp = x + step * rng.normal()          # symmetric proposal
        lpp = log_score(xp)
        if np.log(rng.random()) < lpp - lp:     # accept with min(1, ratio); Z cancels
            x, lp, acc = xp, lpp, acc + 1
        chain.append(x)                          # a rejection records x again
    return np.array(chain), acc / n

def log_score(t):                                # Beta(9,5) coin, no Z
    return 8*np.log(t) + 4*np.log(1-t) if 0 < t < 1 else -np.inf
chain, rate = metropolis(log_score, 0.5, 0.3, 40000)
print(chain[1000:].mean(), rate)                # about 0.643 and 0.44

import arviz as az                                 # the library checks
az.ess(chain), az.rhat(chains_array)           # chains_array: shape (chains, draws)

Which sampler next

A blind random step gets worse as the dimension d grows. Gradient samplers use the slope of the log score to propose better moves. The scalings below are the published optimal-scaling results for simple product targets.

SamplerProposalSteps per independent drawUse when
Random-walk Metropolisblind normal stepgrows like dlow dimension, any score
Gibbsexact conditionalsworse when correlatedconditionals have a formula
Langevin (MALA)gradient plus noisegrows like d1/3smooth scores with gradients
HMC and NUTSgradient-guided flightgrows like d1/4high-dimensional continuous posteriors

Keep going

Sources

Every other number on this page comes from a seeded numpy run or exact arithmetic.

The takeaway. You never need the normalizing constant. You need a chain whose stationary distribution is your target, and the honesty to check that it got there.

Now press Present or Teach and explain from memory why Z cancels, why Metropolis satisfies detailed balance, and what Neff and R̂ tell you. Then go back to the hero and say why the tuned step beats both the tiny and the huge one.

Markov Chain Monte Carlo
The Monte Carlo family · Next: Hamiltonian Monte Carlo · Back to Gleams