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.
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
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.
p of theta equals p-tilde of theta, divided by Z.
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.
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.
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.
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.
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.
Chapter 1
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].
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.
pi times P equals pi.
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.
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.
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.
Chapter 2
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.
pi of x times P of x to x-prime equals pi of x-prime times P of x-prime to x.
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.
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.
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.
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.
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
Chapter 3
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.
A of x to x-prime equals the minimum of 1 and p-tilde of x-prime over p-tilde of x.
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.
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.
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.
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.
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.
Chapter 4
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.
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.
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.
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.
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.
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.
Chapter 5
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.
x-one given x-two is normal, with mean rho times x-two and variance one minus rho squared.
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 ρ = 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.
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.
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.
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.
Chapter 6
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.
delta E equals two J s-i, times the sum over neighbours j of s-j.
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.
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.
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.
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 n | Unrooted binary trees, (2n − 5)!! |
|---|---|
| 5 | 5 × 3 × 1 = 15 |
| 10 | 15 × 13 × … × 1 = 2,027,025 |
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.
Chapter 7
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.
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.
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.
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.
Chapter 8
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.
N-eff equals N, divided by one plus two times the sum over k of rho-k.
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 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.
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.
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.
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.
Chapter 9
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
R-hat equals the square root of V-hat over W.
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 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.
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.
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%.
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.
Chapter 10
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.
| Term | Meaning | Number 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 unchanged | weather [0.571, 0.429] |
| Detailed balance | equal flow both ways on each pair | 0.8 × 0.25 = 0.2 × 1 |
| Metropolis A | min(1, height ratio) | 0.5 to 1.5 on the bell: 0.368 |
| Hastings A | height ratio times proposal ratio | 0.552 × 1.534 = 0.846 |
| Gibbs | exact conditional draws, never rejected | ρ = 0.8 keeps 0.64 per sweep |
| Ising Tc | where order breaks | 2.269 |
| Burn-in | steps before the chain arrives | 4 at λ2 = 0.3; 459 at 0.99 |
| Neff | N / τ | 1,000 / 19 = 53 |
| R̂ | between versus within chains | toy 1.265; flag above 1.01 |
| Acceptance target | where mixing is best | about 0.44 in 1-D, 0.234 in many |
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)
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.
| Sampler | Proposal | Steps per independent draw | Use when |
|---|---|---|---|
| Random-walk Metropolis | blind normal step | grows like d | low dimension, any score |
| Gibbs | exact conditionals | worse when correlated | conditionals have a formula |
| Langevin (MALA) | gradient plus noise | grows like d1/3 | smooth scores with gradients |
| HMC and NUTS | gradient-guided flight | grows like d1/4 | high-dimensional continuous posteriors |
Every other number on this page comes from a seeded numpy run or exact arithmetic.
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.