Monte Carlo Methods
Monte Carlo Methods are a broad family of computational algorithms that use repeated random sampling to obtain numerical estimates of quantities that are difficult or impossible to compute analytically — integrals, expectations, probabilities, and optimum values alike. They matter enormously in modern AI because virtually every Bayesian inference procedure, reinforcement learning algorithm, and generative model relies on Monte Carlo estimation at its core. The counterintuitive fact: you can estimate the volume of an arbitrarily complex high-dimensional region to reasonable precision using nothing but a random number generator and a yes/no membership test.
Every Monte Carlo method rests on a single insight: an expectation under a distribution is just an average, and averages can be approximated by sampling. If you want to compute and you cannot solve the integral analytically, draw samples from and average over them — the law of large numbers guarantees convergence. The "aha moment" is realizing that this works in any number of dimensions, while deterministic grid-based integration blows up exponentially with dimension, making Monte Carlo the only practical integration method in the high-dimensional regimes that define modern ML.
The most common mistake is believing that more samples always means faster convergence, and therefore that Monte Carlo is simply "slow but reliable." What practitioners actually get wrong is conflating the statistical convergence rate (which is regardless of dimension — a feature) with the effective convergence rate, which collapses catastrophically when the proposal distribution is poorly matched to the target. In high dimensions, almost all samples land in regions of negligible probability mass, so your estimator has astronomically high variance despite technically being unbiased. The correct mental model is: Monte Carlo convergence depends not on alone but on the effective sample size — the number of samples that actually carry probability mass — and designing good samplers (importance sampling, MCMC, etc.) is the art of keeping that number large.
How It Works
Basic Monte Carlo Integration
The foundation is the Monte Carlo estimator of an expectation. Suppose we want to compute:
Explanation: This says we want the average value of some function when its input is drawn from distribution — a quantity that appears everywhere in ML as a loss, a likelihood, or a reward. Here is a random variable, is its probability density, and is any measurable function (a loss, a reward, a likelihood ratio). We approximate with the sample mean estimator:
Explanation: Draw independent samples from , evaluate at each, and average — this is the entire Monte Carlo estimator in one line. By the Strong Law of Large Numbers, almost surely as . The convergence rate is given by the Central Limit Theorem:
Explanation: The estimation error shrinks as regardless of dimension , which is why Monte Carlo beats deterministic quadrature once is large.
Importance Sampling
When sampling directly from is hard or inefficient, we use a tractable proposal distribution and reweight:
Explanation: Each sample drawn from is given an importance weight that corrects for the mismatch between where we sampled and where we should have sampled. The self-normalized importance sampling (SNIS) estimator — used when is only known up to a normalizing constant — normalizes the weights:
Explanation: When the normalizing constant of is unknown (common in Bayesian posteriors), we divide by the sum of unnormalized weights , which cancels the constant at the cost of introducing a small bias that vanishes as .
Markov Chain Monte Carlo (MCMC)
When is large and no good global proposal exists, we construct a Markov chain whose stationary distribution is . The Metropolis-Hastings acceptance ratio ensures detailed balance:
Explanation: A proposed move from to is accepted with probability — if the proposed state has higher target density it is always accepted; if lower, it is accepted probabilistically to ensure the chain mixes correctly. ```python import torch def metropolis_hastings(log_p, x_init, n_samples, step_size=0.1): """Minimal Metropolis-Hastings sampler in PyTorch.""" x = x_init.clone() samples = [] log_p_x = log_p(x) for _ in range(n_samples):
# Gaussian random walk proposal x_prop = x + step_size * torch.randn_like(x) log_p_prop = log_p(x_prop)
# Log acceptance ratio (works with unnormalized log densities) log_alpha = log_p_prop - log_p_x accept = torch.log(torch.rand(1)) < log_alpha if accept: x, log_p_x = x_prop, log_p_prop samples.append(x.clone()) return torch.stack(samples)
Example: sample from a 2D Gaussian mixture
def log_target(x): c1 = torch.distributions.MultivariateNormal( torch.tensor([2.0, 2.0]), torch.eye(2) 0.5 ) c2 = torch.distributions.MultivariateNormal( torch.tensor([-2.0, -2.0]), torch.eye(2) 0.5 ) return torch.log(0.5 c1.log_prob(x).exp() + 0.5 c2.log_prob(x).exp()) x0 = torch.zeros(2) samples = metropolis_hastings(log_target, x0, n_samples=5000) print(f"Sample mean: {samples[1000:].mean(0)}") # discard burn-in ```
Variance Reduction Techniques
Raw Monte Carlo can be slow to converge. Key variance reduction strategies:
- Control Variates: Replace with where is a correlated function with known expectation; choose to minimize variance.
- Antithetic Variates: Pair each sample with its "opposite" to introduce negative correlation and reduce variance.
- Stratified Sampling: Partition the domain and sample proportionally from each region to ensure coverage.
- Quasi-Monte Carlo (QMC): Replace pseudo-random sequences with low-discrepancy sequences (Halton, Sobol), achieving convergence rather than for smooth integrands.
Ulam was a Polish-American mathematician who worked on the Manhattan Project at Los Alamos, where he co-invented the Monte Carlo method in 1946 while recovering from encephalitis — he reputedly conceived the idea while playing solitaire and wondering about the probability of a successful game. His specific contribution was recognizing that statistical sampling could solve the neutron diffusion equations that were analytically intractable, and together with John von Neumann he formalized the algorithmic framework. The method was codenamed "Monte Carlo" after the casino in Monaco, a name suggested by fellow Manhattan Project physicist Nicholas Metropolis as a secret reference to their use of random chance.
Intuition
Imagine you want to measure the area of a bizarre, hand-drawn blob drawn on a piece of paper. Instead of trying to trace its boundary mathematically, you pick up a handful of rice, toss it randomly across the paper, and count how many grains land inside the blob versus outside it. The ratio times the total paper area gives you an estimate of the blob's area. This is Monte Carlo integration in its purest form. Now imagine the paper has 1000 dimensions — you literally cannot draw a grid fine enough to cover it (there are too many grid points), but you can still throw rice randomly and count. That is the decisive advantage. The art of Monte Carlo is choosing where to throw the rice: if the blob is tiny relative to the paper, most grains miss it and you need an enormous number of grains for a good estimate — this is the high-variance problem that importance sampling and MCMC solve by concentrating samples where they matter.
Historical Development
Why It Matters
Prerequisites
What This Leads To
See Also
Bayesian Inference · Importance Sampling · Variational Autoencoders · Stochastic Gradient Descent · Sequential Monte Carlo