Overview
Many quantities are averages in disguise: an integral is the average height of a function times the width of its range. So draw random points, evaluate the function and take the mean. The answer is noisy, but the noise shrinks in a known way as you draw more, and it does not get worse in high dimensions the way grids do. When you cannot sample from the distribution you care about, three tricks help. Importance sampling draws from an easier distribution and reweights. Rejection sampling draws from an easier one and throws some draws away. Markov chain Monte Carlo, or MCMC, takes a random walk that visits each region in proportion to its probability.
A short history
Stanislaw Ulam and John von Neumann developed the method at Los Alamos in the 1940s to study neutron diffusion, and Nicholas Metropolis named it after the casino. Metropolis and Ulam published the idea in 1949. In 1953 Metropolis and colleagues gave the first Markov chain sampler, which W. K. Hastings generalised in 1970. These samplers later made Bayesian statistics practical for models with no closed-form answer.
How it works
- Write the quantity you want as an expectation: the average of some function under some distribution.
- Plain Monte Carlo: draw samples, evaluate the function at each, and average. Report the standard error alongside the estimate.
- Importance sampling: draw from a proposal that you can sample, and weight each draw by target density over proposal density.
- Rejection sampling: draw from and keep each draw with probability equal to the target divided by a scaled proposal that sits above it everywhere.
- Metropolis-Hastings: from the current point propose a small random move. Accept it if the target is higher there, and otherwise accept with probability equal to the ratio of target values.
- Discard the first steps of the chain (the burn-in), then treat the remaining points as correlated samples of the target.
- Check quality with the effective sample size, which says how many independent draws your weighted or correlated samples are worth.
Watch out for
- The error falls like . One more correct digit costs a hundred times more samples.
- Importance sampling fails quietly when the proposal has lighter tails than the target. A few huge weights then carry the estimate, and the effective sample size collapses.
- Rejection sampling needs a bound that holds everywhere, and its acceptance rate drops quickly as the dimension grows.
- Metropolis-Hastings samples are correlated, so 20000 steps may be worth only a few hundred independent draws. A proposal scale that is too small or too large makes this worse.
- A chain started far from the bulk of the target, or one that never crosses between separated peaks, can look settled while being wrong. Run several chains from different starts.
Use cases
When to use it
Integrals with no closed form, especially in many dimensions, and sampling from a distribution known only up to a constant, which is the usual situation for a Bayesian posterior.
In industry
- Finance
- Banks price path-dependent options and estimate value at risk by simulating many market scenarios and averaging the outcomes.
- Physics and engineering
- Particle transport codes simulate individual particles through matter to design reactor shielding and radiation therapy plans.
- Computer graphics
- Film renderers use path tracing, which averages random light paths per pixel to estimate the lighting integral.
- Bayesian statistics
- Tools such as Stan and PyMC draw posterior samples with Markov chain Monte Carlo when no formula for the posterior exists.
Choosing it: what must hold
- A quantity that can be written as an expectation or integral over a distribution.
- A way to draw samples from that distribution, or a density you can evaluate up to a constant for MCMC.
- A compute budget for many samples: the error shrinks only with the square root of the sample count.
- For MCMC, checks that the chain has converged and mixed before its samples are used.
When to choose something else
| If | Use instead |
|---|---|
| The integral has a closed form or the problem has one or two dimensions | The exact formula, or numerical quadrature |
| The prior is conjugate to the likelihood | Bayesian inference in closed form |
| You need a fast approximate posterior for a very large model | Variational inference |
Math foundations
The Monte Carlo estimate
Replace an expectation by an average over samples. For an integral over , draw uniformly and multiply the average by . The law of large numbers says this converges.
Its standard error
The spread of the estimate, measured from the same samples. It depends on the number of samples and the variability of , not on the dimension of .
Importance sampling
Draws from are corrected by weights that say how much more or less likely each point is under the target. Dividing by the sum of weights means only needs to be known up to a constant.
Effective sample size of weights
Equal weights give . If one weight dominates, is close to 1 and the estimate rests on a single draw.
Rejection sampling
Accepted draws are exact samples of the target. The overall acceptance rate is the area under divided by , so a loose bound wastes most proposals.
Metropolis-Hastings acceptance
For a symmetric proposal such as a Gaussian step. Uphill moves are always taken and downhill moves sometimes, which makes the target the stationary distribution of the chain. Only a ratio appears, so the normalizing constant is never needed.
Effective sample size of a chain
Positive autocorrelation between samples steps apart reduces the information in the chain. The template truncates the sum at the first lag where is not positive.
Symbols
- the function whose average is wanted
- the target distribution
- the target density, possibly without its normalizing constant
- the proposal distribution, which is easy to sample from
- the -th sample
- the number of samples (n_samples in the config)
- the Monte Carlo estimate from samples
- the sample standard deviation of the values
- the importance weight of sample
- the constant with everywhere (bound in the code)
- the current point of the chain and the proposed point
- the probability of accepting a proposed move
- the autocorrelation of the chain at lag
- the effective sample size
Worked by hand
Estimate by dropping points uniformly in the unit square and counting those inside the quarter circle of radius 1, whose area is . Suppose 10 points are drawn and 8 fall inside.
Ten points give 3.2, give or take about 0.5. Each point contributes 4 or 0, and that spread is about 1.64 at the true value, so two reliable decimal places already need roughly 27000 points.
Visual example
Loading the example.
Try this
- With Metropolis-Hastings, drop the proposal width to 0.3: the chain stays in one hump and the estimate is badly off.
- Switch to rejection sampling and widen the proposal. The envelope rises and the acceptance rate falls.
- Use importance sampling with a width of 0.8 and read the effective sample size.
Code sample
import numpy as np
from impl import MonteCarlo
from config import MonteCarloConfig
mc = MonteCarlo(MonteCarloConfig(n_samples=20000, proposal_scale=2.5))
value, err = mc.integrate(lambda x: x**2, 0.0, 1.0) # about 1/3, with its standard error
log_target = lambda x: float(-0.5 * ((x[0] - 3.0) / 2.0) ** 2) # N(3, 2^2) up to a constant
samples, rate = mc.metropolis_hastings(log_target, x0=0.0) # samples (20000, 1), mean near 3, std near 2Read the implementation (133 lines)
"""Monte Carlo methods.
Plain Monte Carlo integration with a standard error, importance sampling, rejection sampling, and
random-walk Metropolis-Hastings MCMC. All four turn random draws into estimates of integrals or into samples
of a distribution known only up to a constant.
"""
from __future__ import annotations
import math
import numpy as np
try:
from .config import MonteCarloConfig
except ImportError: # run from the template's own folder
from config import MonteCarloConfig
class MonteCarlo:
"""Sampling-based estimators that share one seeded random generator (`self.rng`)."""
def __init__(self, config: MonteCarloConfig | None = None) -> None:
self.config = config or MonteCarloConfig()
self.rng = np.random.default_rng(self.config.seed)
def integrate(self, func, low: float, high: float) -> tuple[float, float]:
"""Estimate the integral of func over [low, high] from uniform draws.
func takes and returns an array (n,). Returns (estimate, standard error of the estimate).
"""
if not high > low:
raise ValueError("high must be greater than low")
n = self.config.n_samples
values = (high - low) * np.asarray(func(self.rng.uniform(low, high, size=n)), dtype=float)
return float(values.mean()), float(values.std(ddof=1) / math.sqrt(n)) if n > 1 else math.inf
def estimate_pi(self) -> float:
"""4 times the share of uniform points in the unit square that fall inside the quarter circle."""
points = self.rng.random((self.config.n_samples, 2))
return float(4.0 * np.mean((points**2).sum(axis=1) <= 1.0))
def importance_sampling(self, func, log_target, sample_proposal, log_proposal,
self_normalized: bool = True) -> tuple[float, float]:
"""Estimate E_target[func(x)] with draws from a different (proposal) distribution.
func: array (n, ...) -> array (n,), the quantity to average.
log_target: array -> array (n,), log density of the target; may lack its normalizing constant
when self_normalized is True.
sample_proposal: (rng, n) -> array of n draws from the proposal.
log_proposal: array -> array (n,), log density of the proposal.
Returns (estimate, effective sample size). An effective sample size far below n means the proposal
is a poor match and the estimate rests on a handful of draws.
"""
n = self.config.n_samples
x = sample_proposal(self.rng, n)
log_w = np.asarray(log_target(x), dtype=float) - np.asarray(log_proposal(x), dtype=float)
values = np.asarray(func(x), dtype=float)
if self_normalized:
w = np.exp(log_w - log_w.max())
estimate = float((w * values).sum() / w.sum())
else:
w = np.exp(log_w)
estimate = float((w * values).mean())
return estimate, float(w.sum() ** 2 / (w**2).sum())
def rejection_sampling(self, target_pdf, sample_proposal, proposal_pdf, bound: float) -> tuple[np.ndarray, float]:
"""Exact samples of the target, using a proposal with target_pdf(x) <= bound * proposal_pdf(x) everywhere.
target_pdf may be unnormalized. A draw x is kept with probability target_pdf(x) / (bound * proposal_pdf(x)).
Returns (samples with n_samples entries along axis 0, acceptance rate).
"""
if bound <= 0:
raise ValueError("bound must be positive")
n = self.config.n_samples
kept, n_kept, n_tried = [], 0, 0
while n_kept < n:
x = sample_proposal(self.rng, n)
ratio = np.asarray(target_pdf(x), dtype=float) / (bound * np.asarray(proposal_pdf(x), dtype=float))
if np.any(ratio > 1.0 + 1e-9):
raise ValueError("bound is too small: the target exceeds bound * proposal somewhere")
accepted = x[self.rng.random(n) < ratio]
kept.append(accepted)
n_kept += len(accepted)
n_tried += n
if n_tried >= 1000 * n and n_kept == 0:
raise ValueError("no proposal was accepted, check the densities and the bound")
return np.concatenate(kept)[:n], n_kept / n_tried
def metropolis_hastings(self, log_target, x0) -> tuple[np.ndarray, float]:
"""Random-walk Metropolis-Hastings.
log_target: array (d,) -> float, log density up to an additive constant.
x0: starting point, scalar or array (d,).
Returns (samples array (n_samples, d), acceptance rate over all steps including burn-in).
Consecutive samples are correlated, so they carry less information than independent draws.
"""
x = np.atleast_1d(np.asarray(x0, dtype=float)).copy()
log_p = float(log_target(x))
if not math.isfinite(log_p):
raise ValueError("the starting point has zero target density")
total = self.config.burn_in + self.config.n_samples
steps = self.rng.normal(0.0, self.config.proposal_scale, size=(total, x.size))
log_u = np.log(self.rng.random(total))
samples = np.empty((self.config.n_samples, x.size))
accepted = 0
for t in range(total):
candidate = x + steps[t]
log_p_candidate = float(log_target(candidate))
if log_u[t] < log_p_candidate - log_p: # symmetric proposal: the ratio of targets decides
x, log_p = candidate, log_p_candidate
accepted += 1
if t >= self.config.burn_in:
samples[t - self.config.burn_in] = x
return samples, accepted / total
def effective_sample_size(chain, max_lag: int = 1000) -> float:
"""Effective number of independent samples in a correlated 1-D chain, array (n,).
n / (1 + 2 * sum of autocorrelations), with the sum cut at the first non-positive autocorrelation.
"""
x = np.asarray(chain, dtype=float).ravel()
n = x.size
x = x - x.mean()
var = float(np.dot(x, x) / n)
if var == 0:
return float(n)
tau = 1.0
for lag in range(1, min(max_lag, n - 1)):
rho = float(np.dot(x[:-lag], x[lag:]) / (n * var))
if rho <= 0:
break
tau += 2.0 * rho
return n / tau- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 9, run with
python3 -m unittest -v
Practice
Create MonteCarlo with the default config. Call estimate_pi, then integrate(np.sin, 0, np.pi) and compare the error with the reported standard error (the exact value is 2). Run metropolis_hastings on a standard normal log density, lambda x: -0.5 * float(x @ x), from x0 = 0, with proposal_scale 0.1, 2.4 and 50, and compare acceptance rates and effective_sample_size of the first column.
Check on learning
- A grid with 10 points per axis needs evaluations in dimensions. Why does the Monte Carlo standard error not suffer in the same way?
A way to think about it
Look at what the standard error formula contains. The dimension enters only through how variable is, not through the count of points.
- You use a standard normal proposal to estimate an expectation under a heavier-tailed target. What will the weights look like, and why is the result untrustworthy even if it looks stable?
A way to think about it
Far out in the tail the ratio of target to proposal is enormous, but such draws are rare. Think about what happens on the run where one finally appears.
- With a tiny proposal scale almost every Metropolis-Hastings move is accepted. Why is a very high acceptance rate a bad sign?
A way to think about it
Accepted steps that barely move leave consecutive samples almost identical. Relate that to the autocorrelations in the effective sample size formula.
- Rejection sampling of a standard normal target from a wide uniform box wastes most draws. What happens to the acceptance rate when the target is a product of 20 such normals in 20 dimensions?
A way to think about it
The acceptance rate in one dimension is a fraction below 1. Independent dimensions multiply, so raise it to the 20th power.
- Why can Metropolis-Hastings work with a density known only up to a constant, and why does that matter for Bayesian inference?
A way to think about it
The acceptance rule uses a ratio of target values. Recall which part of Bayes' theorem is the hard integral.