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 along one long run of a chain converges to . 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, . A model's risk is the expected loss over the data distribution. An integral over is an expectation too: for . In general we want
When the integral has no closed form, draw i.i.d. from and average. This is the Monte Carlo estimate:
By linearity, : the estimate is unbiased. By the law of large numbers, whenever . The topic The law of large numbers already used this to estimate from points in a quarter disc. The topic What probability is used it for de Méré's bet: there was the indicator of "at least one six in four rolls", and the share of winning games was .
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 . Then
The standard error is . We do not know , but the same samples estimate it: take the sample standard deviation of the values . A Monte Carlo result is then reported with a 95% error bar:
For de Méré's bet, 100,000 games gave . The terms are 0 or 1, so . The standard error is and the error bar is . The interval contains the exact . This is the band from the first topic: for a probability near one half, .
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 points per axis needs points in dimensions: ten points per axis in is already evaluations. The Monte Carlo error is whatever the dimension of . That is why integrals over images, parameter vectors and latent codes are estimated by sampling.
The error bar needs a finite . For a heavy-tailed the topic The central limit theorem showed what happens: the average jumps whenever a huge value arrives, and is meaningless.
Where samples come from
Everything above assumed that we can draw from . A computer gives us one thing: a stream of numbers that behave like i.i.d. . Every other distribution is built from it.
The first tool is inverse transform sampling from the topic Functions of random variables: if is a continuous, strictly increasing CDF, then has CDF . For a discrete distribution the same idea compares with the cumulative sums . 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 :
and are independent . The pair is a point in the plane written in polar form. The angle is uniform, as it must be for a rotation-invariant distribution. The squared radius is an inverse-CDF sample from ( and have the same distribution), and that is exactly the distribution of . Then gives any .
A shortcut that looks just as good is not. By the CLT, has mean and variance and looks normal. But it never leaves , and its tails are far too thin:
| , | ||
|---|---|---|
| 3 | ||
| 4 | ||
| 5 |
A sampler can match the mean and variance and still be wrong where a simulation of rare events looks.
Rejection sampling
Inversion needs , and most densities do not give one. Rejection sampling needs only the ability to evaluate . Pick a proposal density that we can sample and a constant such that
The curve is the envelope. Draw a candidate from and an independent . Keep if , otherwise throw it away and try again.
Why are the kept values distributed as ? A candidate lands near with probability and is then kept with probability . The product is , which is proportional to . Integrating over gives the acceptance probability:
The number of candidates per kept sample is from the topic Discrete distributions, with mean . A tight envelope matters.
Example: has density on . Take the uniform proposal, . The smallest valid is the maximum of , reached at the mode : . 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 .
One more property will matter later. If we know only up to a constant, , rejection still works with in place of , as long as we can bound . The unknown 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 around it. The acceptance rate is the ratio of the volumes. In the plane it is . In it is , and in it is : 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 and a slightly wider proposal . In one coordinate the ratio is at most , at . Coordinates are independent, so the ratios multiply and . That is for , about for and for . 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 promise holds only after we have independent samples from , 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 that is positive wherever ,
Draw from and average . The importance weight corrects for sampling from the wrong distribution. The estimate is unbiased for every such , but its variance depends on a great deal.
Its best use is rare events. Let for . Plain Monte Carlo with a million draws expects about 32 hits. Its relative standard error is , and in one run it saw 38 hits, an error of 20%. Now propose from , which puts half its draws beyond 4, and weight each hit by . With only 10,000 draws the relative standard error is 2%; one run gave . Plain Monte Carlo would need about 80 million draws for the same 2%.
The good proposal follows the integrand: it puts samples where is large. The danger is a proposal with lighter tails than the target. Then 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 heavier-tailed than , never lighter.
Control variates
The error is , and doubling the precision costs four times the samples. Often it is cheaper to shrink . A control variate is a quantity that moves together with and has a mean we know exactly. Average
instead of . The correction has mean zero, so the estimate stays unbiased for every constant . Its variance is , smallest at . There it equals , where is the correlation of and from the topic Joint distributions and independence. In practice is estimated from the same samples.
Example: for . Take with the known mean . The correlation is , and the variance per sample falls from to , about 60 times. One sample with the control variate is worth sixty without.
A related trick, antithetic pairs, averages and . Both have the right mean, and for a monotone they are negatively correlated, so their errors partly cancel. For 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 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: . We can evaluate , but is itself an integral we cannot compute. Importance sampling handles this by normalizing the weights. With ,
The unknown appears in every 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 . With 1000 draws, one run estimated the posterior mean as ; the exact value is .
How many draws really counted? The effective sample size of normalized weights is
Equal weights give ; one dominant weight gives . 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 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 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 in which cancels, and has 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.
Answers are saved on the server and tied to this browser until you sign in.