Skip to content
BIASED

Monte Carlo and Markov chains

Instead of a formula for the posterior, samples from it: the Monte Carlo estimate and its error, the inverse CDF method, rejection sampling, importance sampling, and then Markov chains: stationarity, irreducibility, aperiodicity, detailed balance, burn-in and the effective sample size.

An integral as an average over samples

The topic Variational inference replaced the posterior with the best member of a family qq. That answer is fast but biased: whatever the family cannot represent is simply missing, and nothing in the output says how much. This topic takes the other road. Instead of approximating the posterior by a formula, we draw samples from it and average.

Almost everything we want from a posterior is an expectation. The posterior mean, the probability of a set AA, the posterior predictive:

E[θ∣X],P(θ∈A∣X)=E[1{θ∈A}∣X],p(x∗∣X)=E[p(x∗∣θ)∣X].\mathbb E[\theta \mid X], \qquad P(\theta \in A \mid X) = \mathbb E\big[\mathbb 1\{\theta \in A\} \mid X\big], \qquad p(x^* \mid X) = \mathbb E\big[p(x^* \mid \theta) \mid X\big].

All three have the form I=Epf(x)=∫f(x) p(x) dxI = \mathbb E_p f(x) = \int f(x)\, p(x)\, dx. If x(1),…,x(K)x^{(1)}, \dots, x^{(K)} are independent draws from pp, the Monte Carlo estimate is the sample average:

I^K=1K∑k=1Kf(x(k)).\hat I_K = \frac{1}{K} \sum_{k=1}^{K} f\big(x^{(k)}\big).

It is unbiased, EI^K=I\mathbb E \hat I_K = I, and the law of large numbers gives I^K→I\hat I_K \to I when Ep∣f∣<∞\mathbb E_p \lvert f \rvert < \infty. If also σf2=Var⁡pf(x)<∞\sigma_f^2 = \operatorname{Var}_p f(x) < \infty, then

Var⁡I^K=σf2K,K (I^K−I)→dN(0,σf2).\operatorname{Var} \hat I_K = \frac{\sigma_f^2}{K}, \qquad \sqrt K\, (\hat I_K - I) \xrightarrow{d} \mathcal N(0, \sigma_f^2).

So the typical error is σf/K\sigma_f / \sqrt K. The normal shape is a large-KK statement, not an exact one for every KK.

The running example is the coin from the topic The Bayesian approach: a uniform prior and three heads give the posterior Beta⁡(4,1)\operatorname{Beta}(4, 1) with density p(θ∣X)=4θ3p(\theta \mid X) = 4\theta^3 on [0,1][0, 1]. Its mean is 0.80.8, the probability that the next toss is heads, and its standard deviation is σ≈0.163\sigma \approx 0.163. With K=100K = 100 posterior draws, the average of the θ(k)\theta^{(k)} lands within about 0.0160.016 of 0.80.8.

Two remarks. The rate K−1/2K^{-1/2} contains no dimension: averaging works the same way for a 1000-dimensional θ\theta. But σf\sigma_f, the cost of one draw and, later, how fast a chain mixes can all depend heavily on dimension. And the whole method rests on one assumption we have not earned yet: that we can draw from pp at all. The next three blocks do that in one dimension.

The inverse CDF method

A computer gives us uniform numbers U∼U(0,1)U \sim \mathcal U(0, 1). Simple transforms already go far: a+(b−a)Ua + (b - a)U is uniform on [a,b][a, b], and μ+σZ\mu + \sigma Z is N(μ,σ2)\mathcal N(\mu, \sigma^2) when Z∼N(0,1)Z \sim \mathcal N(0, 1) (see the topic What generative modeling is in Generative Models). An old trick, ∑i=112Ui−6\sum_{i=1}^{12} U_i - 6, has mean 00 and variance 11 but is only approximately normal: it never leaves [−6,6][-6, 6].

The general recipe is the inverse CDF method. Let F(x)=P(X≤x)F(x) = P(X \le x) be the cumulative distribution function. Then

U∼U(0,1),X=F−1(U)U \sim \mathcal U(0, 1), \qquad X = F^{-1}(U)

has exactly the distribution FF. For a continuous, strictly increasing FF the proof is one line:

P(F−1(U)≤x)=P(U≤F(x))=F(x).P\big(F^{-1}(U) \le x\big) = P\big(U \le F(x)\big) = F(x).

Exponential. F(x)=1−e−λxF(x) = 1 - e^{-\lambda x}. Solve u=F(x)u = F(x) for xx:

X=−log⁡(1−U)λ.X = -\frac{\log(1 - U)}{\lambda}.

The coin posterior. For Beta⁡(4,1)\operatorname{Beta}(4, 1) the CDF is F(θ)=∫0θ4t3 dt=θ4F(\theta) = \int_0^\theta 4t^3\, dt = \theta^4, so θ=U1/4\theta = U^{1/4}. A draw u=0.5u = 0.5 gives θ≈0.84\theta \approx 0.84; a draw u=0.01u = 0.01 gives θ≈0.32\theta \approx 0.32. Small θ\theta are rare because θ4\theta^4 grows slowly near zero.

Discrete distributions. When FF has jumps, use the generalized inverse F−1(u)=inf⁡{x:F(x)≥u}F^{-1}(u) = \inf\{x : F(x) \ge u\}. In practice: cut [0,1][0, 1] into consecutive pieces of lengths p1,…,pmp_1, \dots, p_m and return the index of the piece that UU falls into. A Bernoulli draw is 1{U<θ}\mathbb 1\{U < \theta\}.

The limit of the method is F−1F^{-1} itself. For the normal distribution it has no elementary formula, and for a posterior known only up to a constant we cannot even write FF. The next method needs neither.

Rejection sampling

Rejection sampling draws from a density pp using a simpler proposal qq that we can sample. (Here qq is a proposal, not the variational family of the previous topic.) We need a finite constant cc with an envelope above the target:

p(x)≤c q(x)for all x.p(x) \le c\, q(x) \quad \text{for all } x.

One accepted draw is produced as follows. Draw a candidate Y∼qY \sim q and an independent U∼U(0,1)U \sim \mathcal U(0, 1). Accept YY if

U≤p(Y)c q(Y),U \le \frac{p(Y)}{c\, q(Y)},

otherwise throw YY away and draw again.

Why it works. A candidate at yy is accepted with probability p(y)/(c q(y))p(y) / (c\, q(y)), so

P(accept)=∫q(y) p(y)c q(y) dy=1c,p(y∣accept)=q(y)⋅p(y)/(c q(y))1/c=p(y).P(\text{accept}) = \int q(y)\, \frac{p(y)}{c\, q(y)}\, dy = \frac{1}{c}, \qquad p(y \mid \text{accept}) = \frac{q(y) \cdot p(y) / (c\, q(y))}{1/c} = p(y).

Accepted draws follow pp exactly. The constant cc controls speed, not accuracy: on average we spend cc candidates per accepted draw. Accepted draws from independent rounds are independent.

For the coin posterior 4θ34\theta^3 with a uniform proposal, the ratio p/q=4θ3p/q = 4\theta^3 peaks at θ=1\theta = 1, so c=4c = 4 and a quarter of candidates survive.

Unnormalized targets. A posterior is usually known only as p~(x)=Z p(x)\tilde p(x) = Z\, p(x) with unknown Z=∫p~(x) dxZ = \int \tilde p(x)\, dx, the evidence. Rejection sampling still works with an envelope p~(x)≤Mq(x)\tilde p(x) \le M q(x) and acceptance test U≤p~(Y)/(Mq(Y))U \le \tilde p(Y) / (M q(Y)). The accepted draws again follow pp, and the acceptance probability is Z/MZ / M. We never need ZZ to run the algorithm.

Two catches. The proposal must cover the support of the target, and its tails must be at least as heavy: a normal proposal cannot envelope a Cauchy target, since the ratio p/qp/q grows without bound. And in many dimensions the best cc tends to grow exponentially, so almost every candidate is rejected.

Importance sampling

Rejection sampling throws candidates away. Importance sampling keeps all of them and corrects each one with a weight. It does not produce draws from pp; it estimates an expectation under pp using draws from qq.

If q(x)>0q(x) > 0 wherever p(x)f(x)≠0p(x) f(x) \ne 0, multiply and divide by qq:

Epf(x)=∫f(x) p(x)q(x) q(x) dx=Eq[f(x) p(x)q(x)].\mathbb E_p f(x) = \int f(x)\, \frac{p(x)}{q(x)}\, q(x)\, dx = \mathbb E_q\Big[f(x)\, \frac{p(x)}{q(x)}\Big].

With x(k)∼qx^{(k)} \sim q and the importance weights wk=p(x(k))/q(x(k))w_k = p(x^{(k)}) / q(x^{(k)}):

I^IS=1K∑k=1Kwk f(x(k)).\hat I_{\text{IS}} = \frac{1}{K} \sum_{k=1}^{K} w_k\, f\big(x^{(k)}\big).

This estimate is unbiased. For the coin posterior with a uniform proposal, w(θ)=4θ3w(\theta) = 4\theta^3: a draw near 11 counts four times, a draw near 00 almost not at all.

Unknown normalizer. With only p~=Zp\tilde p = Z p, use vk=p~(x(k))/q(x(k))v_k = \tilde p(x^{(k)}) / q(x^{(k)}) and normalize the weights so they sum to one:

I^SNIS=∑k=1Kvk∑jvj f(x(k)).\hat I_{\text{SNIS}} = \sum_{k=1}^{K} \frac{v_k}{\sum_{j} v_j}\, f\big(x^{(k)}\big).

This self-normalized estimate is a ratio of two random averages. It is consistent, but for finite KK it is generally biased. The unbiasedness of plain importance sampling does not carry over.

Weights can hurt. Unbiased does not mean accurate. For the coin, the uniform proposal gives a per-draw standard deviation of about 1.071.07 for the estimate of E[θ∣X]\mathbb E[\theta \mid X], against 0.1630.163 for direct draws: roughly 4343 times more samples for the same error. If qq rarely visits the region that matters, one point grabs almost all the weight, and many draws carry the information of a few. A common diagnostic is the effective sample size of the weights, (∑kvk)2/∑kvk2(\sum_k v_k)^2 / \sum_k v_k^2. A good qq depends on both pp and ff; using weights does not by itself reduce variance.

Markov chains and stationarity

All three methods need a proposal that resembles the whole target. In one dimension that is easy. For a posterior over hundreds of parameters, a global proposal close enough to the posterior rarely exists: rejection stalls and importance weights degenerate.

Markov chain Monte Carlo (MCMC) changes the plan. Instead of independent draws, it builds a sequence X0,X1,X2,…X_0, X_1, X_2, \dots where each state is a small random step from the previous one, designed so that in the long run the states are distributed as the target. Then we average ff along the path.

The sequence is a Markov chain if the next state depends on the past only through the present:

P(Xt+1∈A∣X0,…,Xt)=P(Xt+1∈A∣Xt).P(X_{t+1} \in A \mid X_0, \dots, X_t) = P(X_{t+1} \in A \mid X_t).

For a homogeneous chain the rule is a fixed transition kernel T(y∣x)T(y \mid x). With finitely many states it is a transition matrix PP with rows that sum to one, Pij=P(Xt+1=j∣Xt=i)P_{ij} = P(X_{t+1} = j \mid X_t = i). Writing the distribution of XtX_t as a row vector ptp_t:

pt+1=ptP,orpt+1(y)=∫T(y∣x) pt(x) dx.p_{t+1} = p_t P, \qquad \text{or} \qquad p_{t+1}(y) = \int T(y \mid x)\, p_t(x)\, dx.

A distribution π\pi is stationary (invariant) if one step does not change it:

π=πP,orπ(y)=∫T(y∣x) π(x) dx.\pi = \pi P, \qquad \text{or} \qquad \pi(y) = \int T(y \mid x)\, \pi(x)\, dx.

Example: three states in a row. From an end state, stay or move to the middle with probability 1/21/2 each; from the middle, stay with 1/21/2 and move to each end with 1/41/4:

P=(1/21/201/41/21/401/21/2),π=(14, 12, 14).P = \begin{pmatrix} 1/2 & 1/2 & 0 \\ 1/4 & 1/2 & 1/4 \\ 0 & 1/2 & 1/2 \end{pmatrix}, \qquad \pi = \big(\tfrac14,\ \tfrac12,\ \tfrac14\big).

Check the first entry: 14⋅12+12⋅14=14\tfrac14 \cdot \tfrac12 + \tfrac12 \cdot \tfrac14 = \tfrac14. Starting from p0=(1,0,0)p_0 = (1, 0, 0) the chain gives p1=(0.5,0.5,0)p_1 = (0.5, 0.5, 0), p2=(0.375,0.5,0.125)p_2 = (0.375, 0.5, 0.125), and by t=10t = 10 it is within 0.0010.001 of π\pi.

Stationarity is a statement about marginals: if Xt∼πX_t \sim \pi then Xt+1∼πX_{t+1} \sim \pi. It does not make neighbouring states independent. In this chain, Xt+1X_{t+1} equals XtX_t half the time.

Irreducibility, aperiodicity and burn-in

A stationary distribution alone does not make a chain useful. The chain Xt+1=XtX_{t+1} = X_t (transition matrix II) keeps every distribution, so it never forgets where it started. We want more: whatever X0X_0 is, the distribution of XtX_t should approach π\pi.

For a chain with finitely many states two conditions are enough.

  1. Irreducibility. From every state one can reach every other state in some finite number of steps with positive probability. The identity chain fails: it never leaves its state.
  2. Aperiodicity. The period of state ii is gcd⁡{n≥1:(Pn)ii>0}\gcd\{n \ge 1 : (P^n)_{ii} > 0\}; we need period 11. Remove the "stay" moves from the three-state example, and the chain jumps between the middle and the ends: from the left end it returns only in an even number of steps. Its distribution oscillates, p1=(0,1,0)p_1 = (0, 1, 0), p2=(0.5,0,0.5)p_2 = (0.5, 0, 0.5), p3=(0,1,0)p_3 = (0, 1, 0), …, though π=(14,12,14)\pi = (\tfrac14, \tfrac12, \tfrac14) is still stationary.

If a finite chain is irreducible and aperiodic, its stationary distribution is unique and pt→πp_t \to \pi from any start. For an irreducible chain, one state with a positive probability of staying put already makes it aperiodic. Positive transitions between all pairs in one step are more than needed. For infinite and continuous state spaces the conditions are stated with sets of positive probability (Harris recurrence); the idea is the same.

What we actually use is the ergodic theorem, a law of large numbers along the path:

1K∑k=1Kf(Xk)→a.s.Eπf(x).\frac{1}{K} \sum_{k=1}^{K} f(X_k) \xrightarrow{\text{a.s.}} \mathbb E_\pi f(x).

It does not need independent states. Note the difference between two statements. For a finite chain, irreducibility alone is enough for the time average to converge; aperiodicity is needed for the distribution of a single XtX_t to converge.

In practice the first part of the path is discarded as burn-in, so the arbitrary start weighs less. There is no universal step after which the states are exactly π\pi-distributed. Started from an arbitrary point, an MCMC average is usually biased for finite KK; started from π\pi itself it is unbiased, dependence notwithstanding.

Detailed balance

Checking π=πP\pi = \pi P means summing over all states. A simpler condition is local. A chain satisfies detailed balance with respect to π\pi if for every pair of states

π(x) T(y∣x)=π(y) T(x∣y).\pi(x)\, T(y \mid x) = \pi(y)\, T(x \mid y).

In the stationary regime, the probability flow from xx to yy equals the flow back. Integrating over xx shows that detailed balance implies stationarity:

∫π(x) T(y∣x) dx=π(y)∫T(x∣y) dx=π(y).\int \pi(x)\, T(y \mid x)\, dx = \pi(y) \int T(x \mid y)\, dx = \pi(y).

Chains with this property are called reversible. Two cautions. Detailed balance is sufficient but not necessary: there are correct non-reversible chains. And it gives invariance only; convergence from an arbitrary start still needs irreducibility and aperiodicity.

Back to the coin, now with θ\theta restricted to a grid {0.25,0.5,0.75}\{0.25, 0.5, 0.75\} and a uniform prior on it. After three heads the posterior is proportional to θ3\theta^3, that is to 1:8:271 : 8 : 27, so π=(1,8,27)/36\pi = (1, 8, 27) / 36. Here is a chain on the grid:

P=(1/21/201/167/161/204/2723/27).P = \begin{pmatrix} 1/2 & 1/2 & 0 \\ 1/16 & 7/16 & 1/2 \\ 0 & 4/27 & 23/27 \end{pmatrix}.

Check the flows. Between the first two states: 136⋅12=172\frac{1}{36} \cdot \frac12 = \frac{1}{72} and 836⋅116=172\frac{8}{36} \cdot \frac{1}{16} = \frac{1}{72}. Between the last two: 836⋅12=19\frac{8}{36} \cdot \frac12 = \frac19 and 2736⋅427=19\frac{27}{36} \cdot \frac{4}{27} = \frac19. Detailed balance holds, so π\pi is stationary. Every state can reach every other and the diagonal is positive, so the chain converges to the posterior from any start. Notice how the matrix was built: moves towards higher posterior are always taken, moves away from it are often refused. Where these numbers come from is the subject of the next topic.

Autocorrelation and effective sample size

MCMC states are dependent, and that changes the error. For a stationary chain, let σf2=Var⁡πf(x)\sigma_f^2 = \operatorname{Var}_\pi f(x) and ρh=Corr⁡(f(Xt),f(Xt+h))\rho_h = \operatorname{Corr}\big(f(X_t), f(X_{t+h})\big) the autocorrelation at lag hh. Then

Var⁡I^K=σf2K[1+2∑h=1K−1(1−hK)ρh].\operatorname{Var} \hat I_K = \frac{\sigma_f^2}{K} \Big[ 1 + 2 \sum_{h=1}^{K-1} \Big(1 - \frac{h}{K}\Big) \rho_h \Big].

When correlations die out fast enough, the bracket tends to the integrated autocorrelation time, and the chain behaves like a smaller independent sample:

τint=1+2∑h=1∞ρh,Keff≈Kτint,MCSE≈σfKeff.\tau_{\text{int}} = 1 + 2 \sum_{h=1}^{\infty} \rho_h, \qquad K_{\text{eff}} \approx \frac{K}{\tau_{\text{int}}}, \qquad \text{MCSE} \approx \frac{\sigma_f}{\sqrt{K_{\text{eff}}}}.

KeffK_{\text{eff}} is the effective sample size (ESS) and MCSE is the Monte Carlo standard error. Example: a chain for the coin parameter runs K=10 000K = 10\,000 steps, and its autocorrelations add up to τint=20\tau_{\text{int}} = 20. Then Keff=500K_{\text{eff}} = 500, and the posterior mean is known to about 0.163/500≈0.0070.163 / \sqrt{500} \approx 0.007, not to the 0.00160.0016 that 10 00010\,000 independent draws would give.

Three points that are easy to get wrong:

  • ESS belongs to a function ff, not to the chain: θ\theta and θ2\theta^2 have different autocorrelations.
  • With negative correlations, τint<1\tau_{\text{int}} < 1 and the ESS can exceed KK.
  • Thinning, keeping every mm-th state, does not make states independent and, for the same number of steps, usually loses information. It saves memory.

Mixing is the informal name for how fast the chain forgets its past; slow mixing means large τint\tau_{\text{int}}. Everything now hinges on one design problem. Monte Carlo needs draws from the posterior; one-dimensional samplers do not scale; a Markov chain can wander through a complex space with local steps if its stationary distribution is the posterior. The grid chain above shows it is possible. How do we build such a chain for an arbitrary posterior known only up to the evidence p(X)p(X)? That is the topic Gibbs sampling and Metropolis–Hastings.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.