---
title: Sampling and Markov chain Monte Carlo
heading: Monte Carlo estimates and their 1/√N error, drawing samples by inverting the cumulative distribution, rejection and importance sampling with their efficiencies, the Metropolis algorithm, and how correlation within a chain reduces its effective sample size
eyebrow: S14 · Lesson 43 · Sampling and Markov chain Monte Carlo
xp: 50
---

::: hook
Most Bayesian posteriors aren't Gaussian or conjugate, and their averages are integrals over many dimensions that no formula or grid can handle. The way out is to draw samples and average: Monte Carlo. Its error falls as 1/√N whatever the dimension, which is why it's used for everything from yield analysis of chip designs (A11's Monte Carlo lab) to the posteriors of models with millions of unknowns. The hard part is drawing the samples, and Markov chain Monte Carlo does it for any density you can evaluate up to a constant, by running a random walk whose long-run distribution is the one you want.
:::

::: play
- Samples from an exponential distribution with rate λ, drawn by **inverting the cumulative distribution**: $x = -\ln(1 - u)/\lambda$ with u uniform on (0, 1).
- The histogram settles onto the density $\lambda e^{-\lambda x}$ as the number of samples grows, and the sample mean approaches 1/λ.
- Its error shrinks like $1/\sqrt{N}$: a hundred times more samples for one more digit.
:::

```sim plot
view: random
x: v = 0..5
slider: L = 0.5..3 step 0.1 = 1
slider: n = 10..100000 = 1000 log
sample: -ln(1 - rand(1))/L | mean: M
trials: n
bins: 40
density: L*exp(-L*v)
readout: sample mean = M | digits: 4
readout: true mean = 1/L | digits: 4
readout: standard error of the mean = 1/(L*sqrt(n)) | digits: 4
```

::: predict
## You estimate π by throwing random points into a unit square and counting the fraction inside the quarter circle, times 4. About how many points does a standard error of 0.001 take?

- [ ] About 1,000
- [ ] About 30,000
- [x] About 2.7 million
- [ ] About 10 billion

::: reveal
Each point lands inside with probability p = π/4 = 0.785, so the indicator has standard deviation $\sqrt{p(1 - p)}$ = 0.411, and 4 times its average has standard error 4 × 0.411/√N. Setting that to 0.001 gives N = (1.642/0.001)² = 2.7 million. Monte Carlo is easy and dimension-free, but slow to converge.
:::
:::

::: nameit
## Monte Carlo estimates

$E[f(x)] \approx \frac{1}{N}\sum_nf(x_n)$ with $x_n$ drawn from p. If f has standard deviation σ, the error is $\sigma/\sqrt{N}$, independent of the dimension of x. A target error ε needs $N = (\sigma/\epsilon)^2$ samples.

## Drawing samples

- **Inverse CDF:** if u is uniform, $x = F^{-1}(u)$ has CDF F. For the exponential, $x = -\ln(1 - u)/\lambda$.
- **Rejection sampling:** draw from a proposal q with $Mq(x) \ge p(x)$ everywhere and accept with probability $p(x)/Mq(x)$. For normalized p and q the acceptance rate is 1/M, which collapses in high dimensions.
- **Importance sampling:** draw from q and weight each sample by $w = p/q$. Unequal weights waste samples: the **effective sample size** is $(\sum w)^2/\sum w^2$.

## Markov chain Monte Carlo

The **Metropolis algorithm** proposes a move x → x′ from a symmetric distribution and accepts it with probability

$$\min\left(1, \frac{p(x')}{p(x)}\right)$$

otherwise staying put. Only ratios of p appear, so its normalizing constant is never needed. The rule satisfies detailed balance, so p is the chain's stationary distribution (lesson 42). Proposals that are too small creep; too large and almost all are rejected.

## Correlated samples

Successive states are correlated. If the correlation between neighbors is ρ and decays geometrically, N steps are worth about $N(1 - \rho)/(1 + \rho)$ independent samples. Early steps, before the chain reaches its typical region, are discarded as **burn-in**.
:::

::: example
## A uniform draw u = 0.7 is turned into an exponential sample with rate 2. What's the sample? And what's the effective sample size of 10,000 Metropolis steps with neighbor correlation 0.9?

::: solution
1. **Exponential sample.**
   $$\begin{aligned} x &= -\ln(0.3)/2 \\ &= 0.602 \end{aligned}$$
2. **Effective sample size.**
   $$\begin{aligned} N_\text{eff} &= 10{,}000 \times 0.1/1.9 \\ &= 526 \end{aligned}$$
   almost 19 steps per independent sample.

**Answer:** the sample is 0.602, and the chain's effective sample size is 526.
:::
:::

::: example
## A Metropolis sampler for a standard Gaussian sits at x = 1 and proposes x′ = 1.5. What's the acceptance probability? And what effective size do importance weights 1, 0.5 and 2 give?

::: solution
1. **Acceptance probability.**
   $$\begin{aligned} \frac{p(1.5)}{p(1)} &= e^{-(2.25 - 1)/2} \\ &= 0.535 \end{aligned}$$
   so it moves with probability 0.535; a proposal toward 0 would always be accepted.
2. **Importance weights.**
   $$\begin{aligned} N_\text{eff} &= \frac{(3.5)^2}{1 + 0.25 + 4} \\ &= 2.33 \end{aligned}$$
   effective samples out of 3.

**Answer:** the acceptance probability is 0.535, and the weights give 2.33 effective samples out of 3.
:::
:::

::: example
## A Gibbs sampler draws from a standard bivariate Gaussian with correlation 0.99 by alternating x | y and y | x. How fast does it move, and what effective sample size do 10,000 sweeps give?

::: solution
1. **Step size.** Each conditional is $N(\rho y, 1 - \rho^2)$: a step of standard deviation 0.14 inside a distribution 1 wide along its long axis.
2. **Chain correlation.** The x values form a chain with lag-one correlation
   $$\rho^2 = 0.980$$
3. **Effective sample size.**
   $$\begin{aligned} N_\text{eff} &= 10{,}000 \times \frac{1 - \rho^2}{1 + \rho^2} \\ &= 100 \end{aligned}$$
4. **The cure.** Strongly correlated variables crawl under Gibbs sampling; rotating to the principal axes, or updating the pair jointly, removes the problem.

**Answer:** each step moves only about 0.14, and 10,000 sweeps give an effective sample size of 100.
:::
:::

::: check
given: s = 0.5 | 2 | 10; e = 0.001 | 0.01 | 0.05
answer: (s/e)^2
tolerance: 0.5%

## A quantity with standard deviation {s} is estimated by Monte Carlo. How many samples give a standard error of {e}?

::: right
Right. $(\sigma/\epsilon)^2$ = {answer}.
:::

::: misses
- [s/e] The error falls as 1/√N, so N grows as the square.
- [any] Not yet. Solve $\sigma/\sqrt{N} = \epsilon$.
:::
:::

::: check
given: u = 0.2 | 0.6 | 0.95; L = 0.5 | 2 | 5
answer: -ln(1 - u)/L
tolerance: 0.5%

## A uniform draw u = {u} is converted to an exponential sample with rate {L} by inverting the CDF. What's the sample?

::: right
Right. $-\ln(1 - u)/\lambda$ = {answer}.
:::

::: misses
- [u/L] Invert $F(x) = 1 - e^{-\lambda x}$.
- [any] Not yet. Solve F(x) = u.
:::
:::

::: check
given: p = 1.5 | 3 | 8; L = 2 | 4
answer: 1/(p*L)
tolerance: 0.5%

## A density on an interval of length {L} has a maximum of {p}. Rejection sampling with a uniform proposal scaled to cover that maximum accepts what fraction of proposals?

::: right
Right. $1/M$ with $M = p_\max L$: {answer}.
:::

::: misses
- [1/p] The uniform proposal's density is 1/L, so M = $p_\max L$.
- [any] Not yet. The area under p over the area of the covering box.
:::
:::

::: check
given: x = 0.5 | 1 | 1.5; d = 0.5 | 1; s = 1 | 2
answer: exp(-((x + d)^2 - x^2)/(2*s^2))
tolerance: 0.5%

## A Metropolis sampler targets a zero-mean Gaussian with standard deviation {s}. It sits at x = {x} and proposes a move {d} farther out. What's the acceptance probability?

::: right
Right. $p(x')/p(x) = e^{-(x'^2 - x^2)/2\sigma^2}$ = {answer}.
:::

::: misses
- [exp(-d^2/(2*s^2))] Compare the densities at the two points, not the step itself.
- [any] Not yet. The density ratio, capped at 1.
:::
:::

::: check
given: N = 1000 | 1e4 | 1e5; r = 0.5 | 0.9 | 0.99
answer: N*(1 - r)/(1 + r)
tolerance: 0.5%

## A Markov chain's successive states have correlation {r}. About how many independent samples are {N} steps worth?

::: right
Right. $N(1 - \rho)/(1 + \rho)$ = {answer}.
:::

::: misses
- [N*(1 - r)] Use $(1 - \rho)/(1 + \rho)$.
- [any] Not yet. Effective sample size of a correlated chain.
:::
:::

::: check
given: a = 0.5 | 1; b = 0.2 | 2; c = 1 | 4
answer: (a + b + c)^2/(a^2 + b^2 + c^2)
tolerance: 0.5%

## Three importance samples have weights {a}, {b} and {c}. What's their effective sample size?

::: right
Right. $(\sum w)^2/\sum w^2$ = {answer}.
:::

::: misses
- [any] Not yet. Square of the sum over sum of squares.
:::
:::

::: check
kind: parts
given: r = 0.5 | 0.9 | 0.99; y = -1 | 2; N = 1000 | 100000

## A Gibbs sampler targets a standard bivariate Gaussian with correlation {r} and runs {N} sweeps.

::: part
answer: sqrt(1 - r^2)
tolerance: 0.5%

### What standard deviation does x | y have, the step size along x?

::: misses
- [1 - r^2] That's the variance.
- [any] $\sqrt{1 - \rho^2}$.
:::
:::

::: part
answer: N*(1 - r^2)/(1 + r^2)
unit: samples
tolerance: 0.5%

### What effective sample size do the x values give?

::: misses
- [N*(1 - r)/(1 + r)] The chain's lag-one correlation is ρ², not ρ.
- [any] $N(1 - \rho^2)/(1 + \rho^2)$.
:::
:::

::: part
answer: r*y
tolerance: 0.5%

### Where is x | y centered when y = {y}?

::: misses
- [any] $\rho y$.
:::
:::
:::

::: check
kind: derivation
vars: x = -3..3, s = 0.8..4

## Importance sampling estimates expectations under N(0, 1) from samples drawn from N(0, s²).

::: step
answer: s*exp(-x^2/2 + x^2/(2*s^2))

### What weight does a sample at x get?
:::

::: step
answer: s^2/sqrt(2*s^2 - 1)

### What is the mean squared weight?
:::

::: right
Right. The mean squared weight is infinite for $s^2 \le \frac12$: a proposal narrower than the target can make the estimate useless.
:::
:::

::: explain
## How can the Metropolis algorithm sample from a density whose normalizing constant is unknown?

::: model
The algorithm only ever compares the density at the proposed point with the density at the current point, through the ratio p(x′)/p(x), and any normalizing constant cancels in that ratio. The acceptance rule is built so that, in the long run, the probability flow from any state x to any x′ equals the flow back, which is detailed balance. A chain that satisfies detailed balance with respect to p has p as its stationary distribution, so after burn-in its states are distributed according to p, correlated with one another but correct on average. Posteriors are usually known only up to the evidence, so this property is what makes MCMC the workhorse of Bayesian computation.
:::
:::

::: practice

::: check
given: s = 0.1 | 50; e = 1e-4 | 0.5
answer: (s/e)^2
tolerance: 0.5%

## Samples for error {e}, σ = {s}?

::: misses
- [any] $(\sigma/\epsilon)^2$.
:::
:::

::: check
given: u = 0.01 | 0.99; L = 0.1 | 10
answer: -ln(1 - u)/L
tolerance: 0.5%

## Exponential sample: u = {u}, λ = {L}?

::: misses
- [any] $-\ln(1 - u)/\lambda$.
:::
:::

::: check
given: N = 100 | 1e6; r = 0.1 | 0.999
answer: N*(1 - r)/(1 + r)
tolerance: 0.5%

## Effective samples: N = {N}, ρ = {r}?

::: misses
- [any] $N(1 - \rho)/(1 + \rho)$.
:::
:::
:::
