Throw darts at random onto a square board that has a quarter circle drawn in it. Count the darts that land inside the quarter circle. The share of darts inside is close to , so four times that share is close to : a number from geometry, found by throwing random darts. How good is the answer after darts, and after a million? And what does that have to do with training a neural network, or with a language model choosing its next word?
This is Monte Carlo: estimating a quantity by averaging random samples. Earlier lessons promised it. P1.D1 said that repeating a random experiment and counting is a way to estimate a probability. P1.D2 and P1.D3 said that other random draws are built from uniform ones. P1.C9 said that random points are how high-dimensional integrals are estimated. P1.D8 proved that averages settle and gave the error . Here we use all of it.
Why sample at all?
Three kinds of quantity come up again and again:
- a probability of a complicated event, such as “a model answers wrongly on a random input”;
- an expectation , such as the expected loss of a model over the whole distribution of inputs;
- an integral or a volume, such as the area of a strange shape.
For most real problems none of these can be computed exactly. The sum has too many terms, the integral has no antiderivative (P1.C9), or the distribution of is only known as “a program that produces one draw”. But one draw is often cheap. Sampling means producing such draws, and Monte Carlo means averaging them. Every quantity above turns out to be an average in disguise.
Estimating a probability: darts and π
Throw a dart so that its position has both coordinates uniform on (P1.D3), independent of each other (P1.D5). The darts then land evenly over the unit square, which has area . The quarter circle has area . For a uniform dart the probability of a region is its area, so
We do not know , but we can estimate it by throwing darts and counting the hits (darts inside the quarter circle). The estimate is , and the estimate of is . With darts and hits, the estimate is . Try it:
Things to try. Throw darts one at a time and note that the estimate can only be or after the first dart. Throw , then , then , and watch the line leave the wide early swings and creep toward . Press New seed and run again: the path is different, but it ends in the same place. Press Restart with the same seed and the same darts come back, so the same path.
How big is the error?
Each dart is a hit with probability and a miss otherwise, so the number of hits is binomial (P1.D3) and is an average of zeros and ones. P1.D8 gave its spread: the standard deviation of is . The estimate of is , so its standard deviation is four times that:
The last step puts in .
| darts | sd of the estimate of | band | |
|---|---|---|---|
By the central limit theorem (P1.D8) the estimate is roughly Gaussian for large , so for large it lands inside the band in about of runs. That is the shaded band in the widget. Two lessons sit in the table. First, ten times more precision costs a hundred times more darts: from to , a hundred times the darts, the standard deviation falls from to , only ten times. Second, throwing darts is a poor way to compute . To be within with confidence you need darts.
One honest detail. The band above uses the true , which a real experiment does not know. In practice you plug in the data: gives the standard error from the data, , shown in the last readout of the widget. It is close to the formula for any that is not tiny.
Estimating an expectation
Now the general rule. Let be a random variable with density (or PMF) , and any function. To estimate , draw independently from and average:
A probability is the special case an indicator: , and the average of the indicator is the fraction of hits. That is the darts. The estimate has three properties, all from P1.D4 and P1.D8:
- It is unbiased: , so its average over many repeats is the true value.
- It is consistent: by the law of large numbers it settles on as grows.
- Its standard error is , where is the standard deviation of (finite, and the draws independent). The CLT says is roughly Gaussian, so is a rough interval.
We do not know either, but the samples give it: compute , the sample standard deviation of the numbers (with in the denominator), and report . An estimate without its standard error is half an answer.
Small example with a known answer. Let be uniform on and . Then , and . With samples the standard error is , so the estimate is typically within a few hundredths of . With it is .
Monte Carlo integration
An integral is an expectation. If is uniform on , its density is , so
so that
and replacing the expectation by an average over uniform points gives
In words: the integral is the length of the interval times the average height of the function, and we measure the average height at random points. P1.C9 added up thin strips at evenly spaced points (a Riemann sum). Monte Carlo evaluates the function at random points instead. A region of area inside a box of area works the same way, with the indicator of the region: . That is the darts again, with .
Example with an exact answer: (P1.C9). Here has and mean , so , and the estimate has standard error . At that is . The code cell below does it: one seeded run gives . The error was , about a third of the standard error, which is ordinary.
Notice what the cell also shows. In one dimension the midpoint rule with the same function values gives , which is off by less than . For a smooth function of one variable, evenly spaced points are far better than random ones. Monte Carlo earns its place only when there are many variables.
The error rate does not depend on the dimension
A grid with points per axis has points in dimensions. With that is evaluations for , for , and for , which is out of reach. Monte Carlo spends exactly evaluations, whatever is, and its standard error is still . The dimension enters only through .
Take for uniform in the cube . Its mean is and (the terms are independent, each with variance ). With samples:
| dimension | exact mean | standard error (relative) | |
|---|---|---|---|
| () | |||
| () | |||
| () |
A grid with points per axis would need , and evaluations for these three rows. Ten thousand random points give a good estimate in a hundred dimensions, where the grid is hopeless. The relative error shrinks down the table only because the mean of this grows like while grows like ; other functions behave differently.
Be honest about three limits. (1) can itself grow with the dimension for a badly behaved , and then Monte Carlo is no cure. (2) In one to three dimensions a grid beats random points for smooth functions: the midpoint rule’s error with points shrinks like , which is faster than when and slower when . (3) Monte Carlo needs a way to draw from the distribution , which is the next topic.
Where random numbers come from
A computer is deterministic, so it cannot throw dice. A pseudo-random number generator (PRNG) is a formula that, from a starting number called the seed, produces a long sequence that behaves like independent random numbers. Start from the same seed and you get the same sequence. NumPy’s default_rng(0) gives every time. Start from a new seed and you get a different one.
The basic output is a number uniform on : every stretch of the same length is equally likely, with density (P1.D3). Everything else is built from it, and the browser simulators in P1.D1 and in this lesson use a small seeded generator.
Why this matters. A seed makes a run reproducible: record it and anyone can replay your experiment, which is why the widget above shows its seed. It does not make the numbers less random in a statistical sense. Two warnings: do not choose the seed that gives the answer you like, and the same seed is only guaranteed to reproduce the same numbers with the same library version. P1.G3 covers generators, seeding and why GPU runs can differ.
Sampling from other distributions
We now have uniform numbers. Four tools turn them into draws from other distributions.
Discrete: table lookup in the cumulative sum
Suppose a variable takes the values with probabilities . Lay the probabilities end to end on : the stretch belongs to value , to value , and to value . The cumulative sums are the right ends of the stretches. Draw uniform on and return the first value whose cumulative sum is above . For the answer is value . Each value is returned with probability equal to the length of its stretch, which is its probability.
A language model does exactly this. For logits the softmax (P3.A8) gives probabilities and cumulative sums . A draw returns the second token. Always taking the largest probability (greedy decoding) would always return the first, while sampling returns the first about of the time. Temperature divides the logits before the softmax: for the probabilities become , sharper, and for they become , flatter. Top- keeps only the largest probabilities and renormalizes. In all cases the draw is the same table lookup (P10.A5).
Continuous: the inverse CDF
P1.D2 showed that if is a strictly increasing continuous CDF and is uniform on , then has CDF . The proof is one line: . For the exponential with rate , . Solving gives
For and this is , the median; for it is . Because is uniform too, works as well (for ). Move in the widget and read off the curve. Then draw many: equal steps of land on the curve at values that crowd together where the CDF is steep, which is where the density is high.
Gaussian: Box–Muller, or the library
The Gaussian CDF has no formula and so no formula for (P1.D2). In practice call the library (rng.normal(mu, sigma)). One classical recipe is Box–Muller: take two independent uniform numbers and , and set
Then and are independent standard Gaussians. For and they are and . To get , use , which is the recipe a variational autoencoder uses for its latent code (P8.3).
Rejection sampling
Sometimes you can evaluate the density but cannot invert its CDF. Rejection sampling needs only a ceiling with on an interval. Throw a dart at the rectangle: uniform on the interval and uniform on . Keep if the dart is under the curve (), otherwise throw it away and try again. The kept values have density : at each , the dart lands under the curve with a chance proportional to . The acceptance rate is the area under the curve divided by the area of the rectangle, for a density.
Example: the density on has its largest value at , so use . The acceptance rate is , so on average proposals per kept sample. The kept samples have mean and , as the third code cell checks.
The darts are rejection sampling. Draw points uniformly in the square and keep those inside the quarter circle: the kept ones are uniform on the quarter circle, and the acceptance rate is . In dimensions the same idea, a ball inside the cube around it, has acceptance rate , where is the volume of the unit ball: at , at , at , at , and at . A poor ceiling or a high dimension makes rejection hopeless.
Go deeper When you cannot sample from the distribution directly: importance sampling and MCMC
Importance sampling draws from an easier distribution and corrects with weights: , valid when is positive wherever is not zero. The average of over draws is an unbiased estimate. It shines for rare events. Take the standard Gaussian chance . Plain sampling with draws sees about hits, a relative error of . Sampling instead from , where the event is common, with weights , gives a relative standard error of with only draws; plain sampling with draws would expect only hits. A poor can make the variance infinite, so needs tails at least as heavy as where it counts.
Markov chain Monte Carlo (MCMC) is for the case where is known only up to a constant (as in Bayesian posteriors). It builds a chain of dependent samples whose long-run distribution is . Because consecutive samples are correlated, they count for fewer than independent ones (see the pitfalls below).
With or without replacement, and shuffling
Drawing with replacement makes the draws independent, so every formula above applies. Drawing without replacement from a finite population of items makes them slightly dependent: after you draw one, it cannot appear again. The variance of the sample mean becomes , where is the population variance. It is smaller, so the with-replacement formula is a little pessimistic: the factor is for of , and for of . When is tiny compared with , the difference vanishes.
To shuffle is to put the items in a uniformly random order (a random permutation). Shuffling the training set and cutting it into mini-batches draws batches without replacement within an epoch (P1.F4). The factor above shows that the formula is then a good, slightly pessimistic, approximation while is small compared with the data set.
Go deeper The bootstrap: resampling your own data
You have one data set of examples and want to know how much an estimate (an average, an accuracy) would vary on a fresh data set, which you cannot collect. The bootstrap draws examples with replacement from your data, recomputes the estimate, and repeats many times. The spread of the recomputed values stands in for the real sampling spread. One fact: each resample leaves out about of the examples, because the chance that a given example is never drawn in tries is , which is for and tends to . Bagging (P3.B4) trains each model of an ensemble on one bootstrap sample.
When Monte Carlo goes wrong
Rare events. To estimate a probability from samples, the standard error is , which is small in absolute terms for small . What matters is the relative error, the standard error divided by :
It depends on the expected number of hits, . With and you expect hits and the relative error is . With and you expect one hit, the relative error is about , and the chance of no hit at all is . To get at you need about samples. A nasty trap: with zero hits the estimate is and the formula also says , a confident but wrong answer. Rare failures of a very reliable model are hard to measure for this reason.
Correlated samples. The error assumes independent draws. If each sample resembles the previous one, as in MCMC or in a simulation that reuses its state, the samples carry less information than . Reusing one seed for several “independent” runs gives identical, not independent, runs.
Go deeper Correlated samples and the effective sample size
Suppose the samples form a sequence in which neighbouring values have correlation and the correlation fades geometrically (an AR(1) process). For a long run the variance of the average is about , so the run is worth only independent samples. For the factor is : correlated samples are worth about independent ones, and the true standard error is times the naive . A simulation of this chain (4000 repeats of 1000 steps) measured an average with standard deviation , against from the naive formula and from the one above.
Heavy tails. The standard error needs a finite variance. For a population like the Cauchy (P1.D8) the standard error is not defined and the average never settles.
Slow progress. The rate is slow: a thousand times fewer errors costs a million times more samples. Methods that reduce itself (variance reduction) exist, but this lesson does not cover them.
Where this shows up in machine learning
The expected loss over a data distribution is . Sampling and averaging appear in many places:
- Mini-batches. A mini-batch of examples drawn from the data gives , a Monte Carlo estimate with standard error , which is why batch size trades noise for cost (P1.D8, P1.F4).
- Test sets. A test set is another sample: its accuracy has standard error (P1.D8).
- Randomness inside training. Dropout draws a fresh random mask at every step (P4.17), data augmentation draws a random transformation of each image (P4.18), random initialization draws weights from a uniform or Gaussian distribution (P4.12), and random hyperparameter search draws settings from ranges (P4.23).
- Generation. A language model samples its next token (P10.A5), and a variational autoencoder samples its latent code (P8.3).
- Reinforcement learning. An agent can estimate the value of a state by averaging returns from sampled episodes; P9.3 explains what a value is.
Each case is a draw from a distribution, or an average over such draws, and the rules above say how much to trust it.
Intuition
Monte Carlo is a poll. To learn what a huge population thinks you do not ask everyone; you ask a random sample and report the share, with a margin of error that depends on the sample size, not on how large the population is. A function averaged over a huge space is answered the same way: sample it at random points and average. The analogy breaks in two places: a poll can fail by bias in how people are picked, while a program draws from the distribution it is given; and a pollster cannot ask the same person a thousand times, while a program can call the function as often as it likes.
Math
Estimator. For i.i.d. , has and , so the standard error is . The sample variance is an unbiased estimate of .
Probability. With , , so the standard error is and the relative error is . For the darts, and .
Integral. for . The estimate has standard error .
Inverse CDF. . For the exponential, .
Rejection. With a proposal on an interval of width and , a point is accepted with probability given . Overall acceptance is , and the accepted have density , which is itself.
Box–Muller. is exponential with rate and the angle is uniform and independent. A pair of independent standard Gaussians has exactly this radius and angle distribution, because its joint density depends only on the radius.
Code
Categorical sampling and the exponential inverse CDF in NumPy. np.searchsorted(cum, u, side="right") returns the index of the first cumulative value above .
import numpy as np
rng = np.random.default_rng(0)
cum = np.cumsum([0.5, 0.3, 0.2])
u = rng.random(100_000)
print(np.bincount(np.searchsorted(cum, u, side="right")) / len(u)) # near 0.5, 0.3, 0.2
x = -np.log(1 - rng.random(100_000)) / 2.0 # exponential, rate 2
print(x.mean()) # near 1/2
print(rng.choice(3, size=5, p=[0.5, 0.3, 0.2])) # the library does the lookup for youTry it: Monte Carlo in code
The first cell throws darts with a fixed seed for up to and prints the estimate, the error and the band. It then repeats the -dart experiment times and checks the share of runs inside the band and the spread of the estimates against the formula. The second cell estimates and compares it with the midpoint rule, then runs the dimension example. The third cell tests the sampling tools: the cumulative-sum lookup, the exponential, Box–Muller, rejection and a rare event.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
With seed the cell prints hits for darts (estimate ), hits for darts (estimate , error , outside the band, which happens in about one run in twenty) and hits for darts (estimate , error ). The share of repeated runs inside the band is , near , and the spread of the estimates is against the formula .
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The first line gives against the exact (the theoretical standard deviation is ). In the second part the standard errors , and match from the table above, even in dimensions. Challenge: change to and check that the standard error drops by a factor of .
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Each printed estimate sits close to its exact value: the cumulative-sum lookup returns of the time, the exponential has mean and of its mass below (exact ), Box–Muller gives standard deviation and uncorrelated pairs, rejection accepts of the points, and the rare event shows a measured relative error of against the formula . The last line is the chance of seeing no hit at all.
Common mistakes
Check your understanding
You want the average of a function over a cube in dimensions. A grid with points per axis, or independent random points? Which statement is correct?
A grid has cells. The Monte Carlo error depends on the number of samples and on , and the dimension affects it only through . The claim that both need evaluations ignores that Monte Carlo spends only evaluations. The error of the random points does not grow like for every function: it depends on the function through . Random points work in high dimension, which is where they are used.
A Monte Carlo estimate has a standard error of with samples. About how many samples give a standard error of ?
The standard error is proportional to . Dividing it by needs to be times bigger, so must be times bigger: . The value treats the error as proportional to . The value is times more, which would divide the error by about . The value is a guess based on and ignores the square root.
To sample from the exponential distribution with rate using the inverse CDF, you draw . Which value of do you return?
Solve for : . The value is , which uses where belongs; it is the answer for . The value is without dividing by the rate. The value is , which has no basis in the formula.
You use rejection sampling for the density on , with uniform on and a ceiling . What fraction of the proposed points is accepted?
The area under the density is and the rectangle has area , so the acceptance rate is . The value would need a ceiling of . The value would need a ceiling of . The value is the reciprocal, the expected number of proposals per accepted sample, and a fraction cannot exceed .
A rare event has probability . You draw independent samples and count the hits. About how likely is it that you see no hit at all?
Each sample misses with probability , so none of hits with probability . The value is the chance of a hit in one sample. The value has no basis in the numbers. The value is the chance that two particular samples are both hits.
Exercises
- A run of darts gives hits. Give the estimate of , its error, and the standard error computed from the data.
Show answer
The estimate is , which is above . The data give and standard error , so the error is about standard errors, an ordinary size. - How many darts make the estimate of lie within with about probability?
Show answer
. For it is a hundred times more, about . - Use the four uniform points on to estimate , and compare with the exact value.
Show answer
The values of are , with mean . Times the length : . The exact value is . Four points give a rough answer, with a large error. - A variable takes values with probabilities . Which value does each draw return: , , ?
Show answer
The cumulative sums are . So returns , returns , and returns . - Sample from the exponential with rate using . What is the mean of this distribution?
Show answer
. The mean is . - The density on is sampled by rejection with a uniform proposal. What ceiling and acceptance rate result? Is there a cheaper way?
Show answer
The largest value is at , so and the acceptance rate is : two proposals per kept sample on average. The inverse CDF is cheaper: , so needs one uniform number per sample and rejects nothing. - You estimate a probability and want a relative error of . How many samples?
Show answer
gives , about samples, which means about expected hits. - Out of samples, no hit occurs. What does the standard error from the data say, and why is it misleading?
Show answer
With it says . But a true gives no hit in samples with probability , about one time in twenty. Zero hits only says that is probably below a few percent, not that it is zero. - A sample of is drawn without replacement from a population of . By what factor is the variance of the mean smaller than the with-replacement value, and the standard deviation?
Show answer
The factor is for the variance, and its square root for the standard deviation. - Apply Box–Muller with and , then turn into a draw from .
Show answer
and . The draw is . - You report a Monte Carlo result of from a run with seed , and your colleague gets with seed . Is something wrong? What should you do?
Show answer
Not necessarily: different seeds give different estimates, scattered by about the standard error. Compare the difference with the standard errors. Record the seeds, and report the estimate with its standard error, or the mean and spread over several seeds. - Why does a heavy-tailed function make the standard error unreliable even when is large?
Show answer
The formula needs a finite variance. With very heavy tails the sample standard deviation is dominated by a few huge draws, can keep growing with , and the average itself may not settle (the Cauchy case of P1.D8).
Next: P1.D10 asks the reverse question: given data, which parameters make them most probable (maximum likelihood). P1.G3 explains pseudo-random generators and seeds in depth, P1.F4 uses random mini-batches as Monte Carlo estimates of the gradient, and P10.A5 shows temperature and top- sampling of the next token.