Skip to content
BIASED

Monte Carlo methods

An expectation as an average over samples, the σ/√n error bar from the CLT, Box–Muller, rejection sampling and the curse of dimensionality, importance sampling, control variates and self-normalized weights for a distribution known only up to a constant.

An integral as an average

The topic Markov chains ended with the ergodic theorem: the average of f(Xt)f(X_t) along one long run of a chain converges to Eπf\mathbb E_\pi f. Read backwards, it is a way to compute an expectation by simulation. This topic does the plain version first, with independent samples, and asks the question every simulation must answer: how wrong is the result?

Almost every number we want from a model is an expectation. A probability is the expectation of an indicator, P(A)=E[1A]P(A) = \mathbb E[\mathbb 1_A]. A model's risk is the expected loss over the data distribution. An integral over [0,1][0, 1] is an expectation too: ∫01g(x) dx=E[g(U)]\int_0^1 g(x)\, dx = \mathbb E[g(U)] for U∼U(0,1)U \sim U(0, 1). In general we want

I=E[g(X)]=∫g(x) p(x) dx.I = \mathbb E[g(X)] = \int g(x)\, p(x)\, dx .

When the integral has no closed form, draw X1,…,XnX_1, \dots, X_n i.i.d. from pp and average. This is the Monte Carlo estimate:

I^n=1n∑i=1ng(Xi).\hat I_n = \frac1n \sum_{i=1}^n g(X_i) .

By linearity, E[I^n]=I\mathbb E[\hat I_n] = I: the estimate is unbiased. By the law of large numbers, I^n→I\hat I_n \to I whenever E∣g(X)∣<∞\mathbb E\lvert g(X) \rvert < \infty. The topic The law of large numbers already used this to estimate π\pi from points in a quarter disc. The topic What probability is used it for de Méré's bet: there gg was the indicator of "at least one six in four rolls", and the share of winning games was I^n\hat I_n.

Machine learning runs on such averages. A minibatch gradient estimates the full gradient. The test error of a classifier estimates its risk. A VAE estimates its training objective from a few sampled latent codes (see Generative Models). Each of them is a Monte Carlo estimate, and each inherits its error from the next block.

The σ/√n error bar

The estimate is an average of i.i.d. terms, so the topics The law of large numbers and The central limit theorem apply directly. Write σ2=Var⁡(g(X))\sigma^2 = \operatorname{Var}(g(X)). Then

Var⁡(I^n)=σ2n,I^n≈N(I,σ2n).\operatorname{Var}(\hat I_n) = \frac{\sigma^2}{n}, \qquad \hat I_n \approx \mathcal N\Big(I, \frac{\sigma^2}{n}\Big) .

The standard error is σ/n\sigma/\sqrt n. We do not know σ\sigma, but the same samples estimate it: take the sample standard deviation σ^\hat\sigma of the values g(Xi)g(X_i). A Monte Carlo result is then reported with a 95% error bar:

I^n±1.96 σ^n.\hat I_n \pm 1.96\, \frac{\hat\sigma}{\sqrt n} .

For de Méré's bet, 100,000 games gave I^n=0.51533\hat I_n = 0.51533. The terms are 0 or 1, so σ^=I^n(1−I^n)≈0.4998\hat\sigma = \sqrt{\hat I_n (1 - \hat I_n)} \approx 0.4998. The standard error is 0.001580.00158 and the error bar is ±0.0031\pm 0.0031. The interval [0.5122,0.5184][0.5122, 0.5184] contains the exact 0.51770.5177. This is the band ±1/n\pm 1/\sqrt n from the first topic: for a probability near one half, 1.96⋅0.5/n≈1/n1.96 \cdot 0.5/\sqrt n \approx 1/\sqrt n.

Two consequences matter in practice.

  • Accuracy is expensive. One more correct decimal digit cuts the error tenfold and costs a hundred times more samples.
  • The rate does not depend on dimension. A grid with mm points per axis needs mdm^d points in dd dimensions: ten points per axis in d=20d = 20 is already 102010^{20} evaluations. The Monte Carlo error is σ/n\sigma/\sqrt n whatever the dimension of XX. That is why integrals over images, parameter vectors and latent codes are estimated by sampling.

The error bar needs a finite σ\sigma. For a heavy-tailed g(X)g(X) the topic The central limit theorem showed what happens: the average jumps whenever a huge value arrives, and σ^\hat\sigma is meaningless.

Where samples come from

Everything above assumed that we can draw from pp. A computer gives us one thing: a stream of numbers that behave like i.i.d. U(0,1)U(0, 1). Every other distribution is built from it.

The first tool is inverse transform sampling from the topic Functions of random variables: if FF is a continuous, strictly increasing CDF, then F−1(U)F^{-1}(U) has CDF FF. For a discrete distribution the same idea compares UU with the cumulative sums p1,p1+p2,…p_1, p_1 + p_2, \dots. A language model picks its next token exactly this way.

The normal CDF has no elementary inverse. The Box–Muller transform gets around it with two uniforms U1,U2U_1, U_2:

Z1=−2ln⁡U1 cos⁡(2πU2),Z2=−2ln⁡U1 sin⁡(2πU2).Z_1 = \sqrt{-2 \ln U_1}\, \cos(2\pi U_2), \qquad Z_2 = \sqrt{-2 \ln U_1}\, \sin(2\pi U_2) .

Z1Z_1 and Z2Z_2 are independent N(0,1)\mathcal N(0, 1). The pair is a point in the plane written in polar form. The angle 2πU22\pi U_2 is uniform, as it must be for a rotation-invariant distribution. The squared radius −2ln⁡U1-2 \ln U_1 is an inverse-CDF sample from Exp⁡(1/2)\operatorname{Exp}(1/2) (U1U_1 and 1−U11 - U_1 have the same distribution), and that is exactly the distribution of Z12+Z22Z_1^2 + Z_2^2. Then μ+σZ\mu + \sigma Z gives any N(μ,σ2)\mathcal N(\mu, \sigma^2).

A shortcut that looks just as good is not. By the CLT, X=U1+⋯+U12−6X = U_1 + \dots + U_{12} - 6 has mean 00 and variance 11 and looks normal. But it never leaves [−6,6][-6, 6], and its tails are far too thin:

tt P(X>t)P(X > t) P(Z>t)P(Z > t), Z∼N(0,1)Z \sim \mathcal N(0, 1)
3 1.0⋅10−31.0 \cdot 10^{-3} 1.3⋅10−31.3 \cdot 10^{-3}
4 8.5⋅10−68.5 \cdot 10^{-6} 3.2⋅10−53.2 \cdot 10^{-5}
5 2.1⋅10−92.1 \cdot 10^{-9} 2.9⋅10−72.9 \cdot 10^{-7}

A sampler can match the mean and variance and still be wrong where a simulation of rare events looks.

Rejection sampling

Inversion needs F−1F^{-1}, and most densities do not give one. Rejection sampling needs only the ability to evaluate p(x)p(x). Pick a proposal density qq that we can sample and a constant MM such that

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

The curve MqM q is the envelope. Draw a candidate YY from qq and an independent U∼U(0,1)U \sim U(0, 1). Keep YY if U≤p(Y)/(Mq(Y))U \le p(Y) / (M q(Y)), otherwise throw it away and try again.

Why are the kept values distributed as pp? A candidate lands near xx with probability q(x) dxq(x)\, dx and is then kept with probability p(x)/(Mq(x))p(x)/(M q(x)). The product is p(x) dx/Mp(x)\, dx / M, which is proportional to p(x)p(x). Integrating over xx gives the acceptance probability:

P(accept)=1M.P(\text{accept}) = \frac1M .

The number of candidates per kept sample is Geom⁡(1/M)\operatorname{Geom}(1/M) from the topic Discrete distributions, with mean MM. A tight envelope matters.

Example: Beta⁡(2,5)\operatorname{Beta}(2, 5) has density p(x)=30 x(1−x)4p(x) = 30\, x (1 - x)^4 on [0,1][0, 1]. Take the uniform proposal, q(x)=1q(x) = 1. The smallest valid MM is the maximum of pp, reached at the mode x=0.2x = 0.2: M=30⋅0.2⋅0.84=2.4576M = 30 \cdot 0.2 \cdot 0.8^4 = 2.4576. About 41% of candidates survive. In one run of 100,000 candidates, 40.8% did, and the kept values passed a goodness-of-fit test against Beta⁡(2,5)\operatorname{Beta}(2, 5).

One more property will matter later. If we know pp only up to a constant, p(x)=p~(x)/Zp(x) = \tilde p(x)/Z, rejection still works with p~\tilde p in place of pp, as long as we can bound p~≤Mq\tilde p \le M q. The unknown ZZ only changes the acceptance rate.

Rejection in high dimensions

The Monte Carlo error did not depend on dimension. Rejection sampling does, and badly.

Sample a uniform point in the unit ball by proposing uniform points in the cube [−1,1]d[-1, 1]^d around it. The acceptance rate is the ratio of the volumes. In the plane it is π/4≈0.785\pi/4 \approx 0.785. In d=10d = 10 it is 0.00250.0025, and in d=20d = 20 it is 2.5⋅10−82.5 \cdot 10^{-8}: forty million candidates per kept point. Almost all the volume of a high-dimensional cube sits in its corners, where the ball is not.

Smooth densities fare no better. Take the target N(0,Id)\mathcal N(0, I_d) and a slightly wider proposal N(0,1.12Id)\mathcal N(0, 1.1^2 I_d). In one coordinate the ratio p/qp/q is at most 1.11.1, at x=0x = 0. Coordinates are independent, so the ratios multiply and M=1.1dM = 1.1^d. That is 2.62.6 for d=10d = 10, about 13,80013{,}800 for d=100d = 100 and 2.5⋅10412.5 \cdot 10^{41} for d=1000d = 1000. A proposal that is wrong by 10% in each direction is hopeless in a thousand directions.

So the curse of dimensionality did not disappear. It moved from the error formula into the sampler. The σ/n\sigma/\sqrt n promise holds only after we have independent samples from pp, and in high dimension getting them is the hard part.

Importance sampling

Rejection throws candidates away. Importance sampling keeps all of them and reweights. For any density qq that is positive wherever g(x)p(x)≠0g(x) p(x) \ne 0,

I=∫g(x) p(x) dx=∫g(x) p(x)q(x) q(x) dx=Eq[g(Y) w(Y)],w(x)=p(x)q(x).I = \int g(x)\, p(x)\, dx = \int g(x)\, \frac{p(x)}{q(x)}\, q(x)\, dx = \mathbb E_q\big[g(Y)\, w(Y)\big], \qquad w(x) = \frac{p(x)}{q(x)} .

Draw Y1,…,YnY_1, \dots, Y_n from qq and average g(Yi) w(Yi)g(Y_i)\, w(Y_i). The importance weight ww corrects for sampling from the wrong distribution. The estimate is unbiased for every such qq, but its variance depends on qq a great deal.

Its best use is rare events. Let I=P(Z>4)=3.17⋅10−5I = P(Z > 4) = 3.17 \cdot 10^{-5} for Z∼N(0,1)Z \sim \mathcal N(0, 1). Plain Monte Carlo with a million draws expects about 32 hits. Its relative standard error is (1−I)/(nI)≈18%\sqrt{(1 - I)/(nI)} \approx 18\%, and in one run it saw 38 hits, an error of 20%. Now propose from q=N(4,1)q = \mathcal N(4, 1), which puts half its draws beyond 4, and weight each hit by p/qp/q. With only 10,000 draws the relative standard error is 2%; one run gave 3.16⋅10−53.16 \cdot 10^{-5}. Plain Monte Carlo would need about 80 million draws for the same 2%.

The good proposal follows the integrand: it puts samples where g(x)p(x)g(x) p(x) is large. The danger is a proposal with lighter tails than the target. Then w=p/qw = p/q grows without bound in the tails, the variance of the estimate can be infinite, and the running average looks stable for a long time and then jumps when a rare huge weight arrives. Nothing in a short run warns you. The safe rule: make qq heavier-tailed than pp, never lighter.

Control variates

The error is σ/n\sigma/\sqrt n, and doubling the precision costs four times the samples. Often it is cheaper to shrink σ\sigma. A control variate is a quantity h(X)h(X) that moves together with g(X)g(X) and has a mean μh\mu_h we know exactly. Average

g(Xi)−c (h(Xi)−μh)g(X_i) - c\, \big(h(X_i) - \mu_h\big)

instead of g(Xi)g(X_i). The correction has mean zero, so the estimate stays unbiased for every constant cc. Its variance is Var⁡(g)−2c Cov⁡(g,h)+c2Var⁡(h)\operatorname{Var}(g) - 2c\, \operatorname{Cov}(g, h) + c^2 \operatorname{Var}(h), smallest at c∗=Cov⁡(g,h)/Var⁡(h)c^* = \operatorname{Cov}(g, h)/\operatorname{Var}(h). There it equals Var⁡(g)(1−ρ2)\operatorname{Var}(g)(1 - \rho^2), where ρ\rho is the correlation of gg and hh from the topic Joint distributions and independence. In practice c∗c^* is estimated from the same samples.

Example: I=E[eU]=e−1I = \mathbb E[e^U] = e - 1 for U∼U(0,1)U \sim U(0, 1). Take h(U)=Uh(U) = U with the known mean 1/21/2. The correlation is 0.9920.992, and the variance per sample falls from 0.2420.242 to 0.00390.0039, about 60 times. One sample with the control variate is worth sixty without.

A related trick, antithetic pairs, averages g(U)g(U) and g(1−U)g(1 - U). Both have the right mean, and for a monotone gg they are negatively correlated, so their errors partly cancel. For eUe^U a pair beats two independent draws about 30 times.

You have met control variates before without the name. The baseline in policy-gradient reinforcement learning is a control variate: the score ∇log⁡p\nabla \log p has mean zero, so subtracting a baseline times it changes nothing on average and removes much of the noise.

Up to a constant

One case is left, and it is the one that matters most in Bayesian statistics. In the topic Bayesian inference the posterior is prior times likelihood divided by the evidence: p(θ∣x)=p~(θ)/Zp(\theta \mid x) = \tilde p(\theta)/Z. We can evaluate p~\tilde p, but ZZ is itself an integral we cannot compute. Importance sampling handles this by normalizing the weights. With w~i=p~(Yi)/q(Yi)\tilde w_i = \tilde p(Y_i)/q(Y_i),

I^n=∑iw~i g(Yi)∑iw~i.\hat I_n = \frac{\sum_i \tilde w_i\, g(Y_i)}{\sum_i \tilde w_i} .

The unknown ZZ appears in every w~i\tilde w_i and cancels in the ratio. This self-normalized estimate is slightly biased, being a ratio of two averages, but consistent.

Take the coin with unknown bias, a uniform prior and 7 heads in 10 tosses. Propose from the prior, so the weights are the likelihoods θ7(1−θ)3\theta^7 (1 - \theta)^3. With 1000 draws, one run estimated the posterior mean as 0.6620.662; the exact value is 8/12≈0.6678/12 \approx 0.667.

How many draws really counted? The effective sample size of normalized weights wˉi=w~i/∑jw~j\bar w_i = \tilde w_i / \sum_j \tilde w_j is

neff=1∑iwˉi2.n_{\text{eff}} = \frac{1}{\sum_i \bar w_i^2} .

Equal weights give neff=nn_{\text{eff}} = n; one dominant weight gives neff≈1n_{\text{eff}} \approx 1. In the coin run it was 460 of 1000. After 700 heads in 1000 tosses the posterior is narrow, and the prior proposal keeps only about 5%. A model with ten such parameters keeps about 0.0510≈10−130.05^{10} \approx 10^{-13} of its draws.

This is the wall. Rejection and importance sampling both cope with an unknown constant, but both propose blindly over the whole space and wait to land where pp lives. In high dimension they almost never do. The next topic, Markov chain Monte Carlo, proposes locally instead: a Markov chain that moves step by step, uses only ratios p~(x′)/p~(x)\tilde p(x')/\tilde p(x) in which ZZ cancels, and has pp as its stationary distribution. The ergodic theorem from the topic Markov chains then turns its run into a Monte Carlo estimate. How these samplers serve Bayesian models in practice is the subject of Bayesian Methods in Machine Learning.

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.