Course contents 21 / 22

21 / 22 · Random Processes and Sampling

Monte Carlo methods

Computing with random samples: plain Monte Carlo and its error bar, generating samples by inversion, transformation (Box–Muller) and rejection, why rejection sampling collapses in high dimensions, importance sampling for rare events and its effective sample size, and variance reduction with control variates, the idea behind baselines in policy gradients.

Prerequisites

Markov chains

On this page 6

The law of large numbers turned every expectation into a limit of averages: draw samples, average, and the error falls like 1/n1/\sqrt n. Two questions remain before that recipe is a method. How are samples from a given distribution produced at all, when a computer only supplies uniform random numbers? And what can be done when 1/n1/\sqrt n is too slow, as it is for rare events? This note answers both: inversion, transformation and rejection produce samples; importance sampling and variance reduction make each sample count for more.

Notation. The target is μ=Ep[g(X)]\mu = E_p[g(X)] for a density pp; μ^n=1n∑g(Xi)\hat\mu_n = \frac1n \sum g(X_i) with Xi∼pX_i \sim p. A proposal qq is a density that is easy to sample.

Plain Monte Carlo and its error#

With XiX_i independent from pp and Ep∣g(X)∣<∞E_p\lvert g(X) \rvert < \infty, μ^n\hat\mu_n is unbiased and converges to μ\mu. If moreover σ2=Var⁡p(g(X))\sigma^2 = \operatorname{Var}_p(g(X)) is finite, by the central limit theorem it is approximately N(μ,σ2/n)N(\mu, \sigma^2/n). A Monte Carlo estimate should always be reported with its error bar, μ^n±1.96 σ^/n\hat\mu_n \pm 1.96\, \hat\sigma/\sqrt n, computed from the same samples. The error depends on σ\sigma and nn and not directly on the dimension of XX, which is why Monte Carlo is the method of choice for high-dimensional integrals. Without a finite variance the error bar is meaningless, even when the estimate converges: heavy-tailed g(X)g(X), and importance weights with infinite variance below, need other diagnostics or robust estimators such as the median of means. Everything below either produces the samples or reduces σ\sigma.

Producing samples#

A random number generator supplies independent U(0,1)U(0, 1) numbers. The simplest map rescales them: X=a+(b−a)UX = a + (b - a)U is uniform on [a,b][a, b], because for xx in [a,b][a, b]

P(X≤x)=P(U≤x−ab−a)=x−ab−a,P(X \le x) = P\Big(U \le \frac{x - a}{b - a}\Big) = \frac{x - a}{b - a} ,

the CDF of U(a,b)U(a, b). In the same way μ+σZ\mu + \sigma Z is N(μ,σ2)N(\mu, \sigma^2) when ZZ is standard normal, by the linear-map rule. Three techniques turn uniforms into samples from other distributions.

  • Inversion. F−1(U)F^{-1}(U) has CDF FF, as shown in the functions of random variables note: −ln⁡(1−U)-\ln(1 - U) is exponential, and a lookup in cumulative sums samples any discrete distribution.
  • Transformation. When F−1F^{-1} has no formula, another map may. The Box–Muller transform takes two independent uniforms to a standard normal: Z=−2ln⁡(1−U1)cos⁡(2πU2)Z = \sqrt{-2\ln(1 - U_1)} \cos(2\pi U_2). It works because the pair (Z1,Z2)(Z_1, Z_2) of independent normals has a rotation-invariant density, so its angle is uniform and independent of the radius, and its squared radius, a sum of two squared standard normals, is exponential with mean 2.
  • Rejection. For a density known only up to a constant, or with no convenient sampling formula, propose and accept.

Why not let the central limit theorem make the normal? The sum of twelve uniforms minus six, X=U1+⋯+U12−6X = U_1 + \dots + U_{12} - 6, has mean 12⋅12−6=012 \cdot \tfrac12 - 6 = 0 and variance 12⋅112=112 \cdot \tfrac1{12} = 1, since Var⁡(Ui)=1/12\operatorname{Var}(U_i) = 1/12 and variances of independent terms add. Its histogram looks normal, but XX never leaves [−6,6][-6, 6], and its tails are too light well before that: P(X>4)=8.5⋅10−6P(X > 4) = 8.5 \cdot 10^{-6} against 3.17⋅10−53.17 \cdot 10^{-5} for a normal, and P(X>5)P(X > 5) is more than a hundred times too small. For tail probabilities, such as the rare event below, the approximation fails; Box–Muller is exact.

Rejection sampling#

Choose a proposal qq that is easy to sample and a constant MM with p(x)≤Mq(x)p(x) \le M q(x) everywhere. Draw X∼qX \sim q and U∼U(0,1)U \sim U(0, 1), and accept XX if UMq(X)≤p(X)U M q(X) \le p(X); otherwise discard it and try again. The point (X,UMq(X))(X, U M q(X)) is uniform under the envelope MqM q, so the accepted points are uniform under pp, and their xx-coordinates have density pp:

Figure

Rejection sampling

Envelope, points and accepted pointsA density hump under the envelope rectangle; 129 of 300 points lie under the hump.00.51envelope M · q, M = 2.46p, the Beta(2, 5) density12129 of 300 accepted3Envelope, points and accepted pointsA density hump under the envelope rectangle; 129 of 300 points lie under the hump.00.51envelope M · q, M = 2.46p, the Beta(2, 5) density12129 of 300 accepted3
The target is the Beta(2, 5) density; the uniform proposal q on [0, 1], times M = 2.4576, lies above it everywhere (1). Points uniform under the envelope (2) are kept if they fall under p (3): 129 of 300 are accepted. The accepted x-values are distributed as p, and the accepted share is 1/M = 0.41 on average.
Derivation: the acceptance rate and the density of accepted points

Given X=xX = x, the draw is accepted when U≤p(x)/(Mq(x))U \le p(x)/(M q(x)). This number lies in [0,1][0, 1] because p≤Mqp \le Mq, and a uniform UU falls below it with exactly that probability. We average over X∼qX \sim q, then apply Bayes’ rule for densities:

P(acc)=∫q(x) p(x)Mq(x) dx=1M∫p(x) dx=1M,f(x∣acc)=q(x) P(acc∣X=x)P(acc)=p(x)/M1/M=p(x).\begin{aligned} P(\text{acc}) &= \int q(x)\, \frac{p(x)}{M q(x)}\, dx \\ &= \frac1M \int p(x)\, dx = \frac1M, \\ f(x \mid \text{acc}) &= \frac{q(x)\, P(\text{acc} \mid X = x)}{P(\text{acc})} \\ &= \frac{p(x)/M}{1/M} = p(x) . \end{aligned}

The rounds are independent, so the accepted draws are independent samples from pp, and the number of rounds per sample is geometric with success probability 1/M1/M, hence mean MM.

The method needs pp only up to a constant factor. For p~=Zp\tilde p = Z p with an unknown ZZ and an envelope p~≤Mq\tilde p \le M q, the test UMq(X)≤p~(X)U M q(X) \le \tilde p(X) accepts with probability ∫q⋅p~/(Mq)=Z/M\int q \cdot \tilde p/(Mq) = Z/M, and the accepted draws still have density pp, by the derivation above with p~\tilde p in place of pp. The cost is set by the acceptance rate, 1/M1/M for a normalized target: on average MM proposals per accepted sample. That is 2.462.46 for the example, but it typically grows exponentially with the dimension, or faster. Sampling the unit ball by rejection from the surrounding cube accepts 79% of proposals in two dimensions, 0.25% in ten and 2.5⋅10−82.5 \cdot 10^{-8} in twenty: almost all the volume of a high-dimensional cube lies in its corners, as the multivariate Gaussian note found for the shell of a Gaussian. Rejection sampling is a tool for low dimensions and for the inner loops of other samplers.

The envelope must also cover the tails. For a standard Cauchy target, p(x)=1/(π(1+x2))p(x) = 1/(\pi(1 + x^2)), and a standard normal proposal, the ratio

p(x)q(x)=2π  ex2/21+x2\frac{p(x)}{q(x)} = \sqrt{\frac2\pi}\; \frac{e^{x^2/2}}{1 + x^2}

grows without bound as ∣x∣→∞\lvert x \rvert \to \infty (it is 8.2⋅1038.2 \cdot 10^3 at x=5x = 5), so no finite MM exists. The other way round works. A normal target under a Cauchy proposal has the ratio π/2 (1+x2) e−x2/2\sqrt{\pi/2}\,(1 + x^2)\, e^{-x^2/2}. The derivative of its logarithm, 2x/(1+x2)−x2x/(1 + x^2) - x, vanishes at x=0x = 0 and x=±1x = \pm 1, and the maximum is at ±1\pm 1: M=2π/2 e−1/2=1.52M = 2\sqrt{\pi/2}\, e^{-1/2} = 1.52, and 66% of proposals are accepted. A proposal needs tails at least as heavy as the target’s.

Importance sampling#

Plain Monte Carlo spends its samples where pp is large, which may be far from where gg matters. Importance sampling draws from a proposal qq instead and corrects with weights:

Ep[g(X)]=∫g(x)p(x)q(x) q(x) dx=Eq[g(X) w(X)],w(x)=p(x)q(x),\begin{aligned} E_p[g(X)] &= \int g(x) \frac{p(x)}{q(x)}\, q(x)\, dx = E_q\big[g(X)\, w(X)\big], \\ w(x) &= \frac{p(x)}{q(x)} , \end{aligned}

valid whenever q>0q > 0 wherever gp≠0g p \ne 0. The estimator 1n∑g(Xi)w(Xi)\frac1n \sum g(X_i) w(X_i) with Xi∼qX_i \sim q is unbiased, and its variance depends on how well qq matches ∣g∣p\lvert g \rvert p; the ideal proposal is proportional to it.

The gain is largest for rare events. To estimate P(Z>4)=3.17⋅10−5P(Z > 4) = 3.17 \cdot 10^{-5} for a standard normal ZZ, a million plain samples see only 28 events, against the 31.731.7 expected: a relative standard error of about 18%, and a realized error of 12% in this run. Sampling from q=N(4,1)q = N(4, 1) puts half the draws in the event, each weighted by p/q=e8−4xp/q = e^{8 - 4x}:

Figure

Importance sampling for a rare event

Original density, proposal and the event regionThe normal curve at zero barely reaches the region beyond 4; the proposal curve centred at 4 lies half inside it.event Z > 4-4-202468p = N(0, 1): P_p = 3.17·10⁻⁵proposal q = N(4, 1): P_q = 0.50weight p/q = e^(8 − 4x)Original density, proposal and the event regionThe normal curve at zero barely reaches the region beyond 4; the proposal curve centred at 4 lies half inside it.event Z > 4-4-202468p = N(0, 1): P_p = 3.17·10⁻⁵proposal q = N(4, 1): P_q = 0.50weight p/q = e^(8 − 4x)
To estimate P(Z > 4) = 3.17·10⁻⁵ for a standard normal Z, plain sampling from p wastes almost every draw: one in 31,600 lands in the region. The proposal q = N(4, 1) lands there half the time, and every hit is weighted by p/q = e^(8 − 4x), which restores the right expectation. 10,000 draws from q give a relative standard error of about 2%, a million draws from p about 18%.

Ten thousand draws from qq estimate 3.27⋅10−53.27 \cdot 10^{-5} with a relative standard error of 2%, a hundred times fewer samples for eight times less error; the realized error of this estimate, known here because the exact value is, is 3.3%. The same weights are useless for other questions: their effective sample size (∑wi)2/∑wi2(\sum w_i)^2 / \sum w_i^2 is 5.15.1 out of 10,000, so estimating, say, the mean of ZZ with them would be hopeless. A proposal is good for a specific integrand, and a proposal with lighter tails than pp can have infinite variance.

When pp is known only up to a constant, p=p~/Zp = \tilde p / Z as for a posterior, the weights p/qp/q cannot be computed. The unnormalized weights vi=p~(Xi)/q(Xi)v_i = \tilde p(X_i)/q(X_i) can, and their average estimates ZZ, since Eq[p~(X)/q(X)]=∫p~(x) dx=ZE_q[\tilde p(X)/q(X)] = \int \tilde p(x)\, dx = Z. Dividing the estimate of ZμZ\mu by this estimate of ZZ cancels the unknown constant (self-normalized importance sampling):

μ^SN=∑ivi g(Xi)∑jvj=∑iwˉi g(Xi),wˉi=vi∑jvj.\begin{aligned} \hat\mu_{\mathrm{SN}} &= \frac{\sum_i v_i\, g(X_i)}{\sum_j v_j} = \sum_i \bar w_i\, g(X_i), \\ \bar w_i &= \frac{v_i}{\sum_j v_j} . \end{aligned}

By the law of large numbers the numerator divided by nn tends to Eq[gp~/q]=ZμE_q[g\tilde p/q] = Z\mu and the denominator divided by nn to ZZ, so the ratio is consistent. It is biased for finite nn, because the expectation of a ratio is not the ratio of expectations: with n=1n = 1 the estimate is g(X1)g(X_1), whose mean is Eq[g(X)]E_q[g(X)], not Ep[g(X)]E_p[g(X)]. The average of the viv_i alone is an unbiased estimate of ZZ; with the prior as qq, it is the estimate of a model’s evidence from prior draws.

Importance weights appear throughout machine learning: off-policy evaluation in reinforcement learning reweights logged actions by the ratio of the new policy to the old, and the importance-weighted bound of variational autoencoders averages the importance weights of several samples inside the logarithm.

Variance reduction#

Even with the right distribution, the variance of the estimator can often be cut by using what is already known.

  • Control variates. If a quantity h(X)h(X) with known mean is correlated with g(X)g(X), estimate E[g(X)+c (h(X)−Eh(X))]E[g(X) + c\,(h(X) - E h(X))] instead, with c=−Cov⁡(g,h)/Var⁡(h)c = -\operatorname{Cov}(g, h)/\operatorname{Var}(h). To compute E[eU]=e−1E[e^U] = e - 1 for U∼U(0,1)U \sim U(0, 1), the control h(U)=Uh(U) = U with mean 1/21/2 cuts the variance per sample from 0.24460.2446 to 0.00400.0040, a factor of 60, for free. In policy-gradient reinforcement learning, subtracting a baseline from the reward is a control variate for the gradient estimate, and it is one of the main reasons such methods work in practice.
  • Antithetic pairs. Use UU and 1−U1 - U together: for monotone gg the two values are negatively correlated, and their average has lower variance than two independent samples.
  • Stratification and quasi-Monte Carlo. Spread the samples evenly over the space instead of at random; in low dimensions, low-discrepancy sequences reach errors close to 1/n1/n instead of 1/n1/\sqrt n.

Gradient estimation in machine learning is the same problem. The gradient of an expectation Eqθ[f(Z)]E_{q_\theta}[f(Z)] can be estimated by the score-function (REINFORCE) estimator, unbiased but high-variance, or by the reparametrization trick of the variational autoencoder, which writes Z=μθ+σθεZ = \mu_\theta + \sigma_\theta \varepsilon and usually has far lower variance.

What changed#

Plain Monte CarloMonte Carlo methods
Samples from ppassumed availableinversion, transformation, rejection
Errorσ/n\sigma/\sqrt n, reported with the estimatethe same rate, smaller σ\sigma
Rare eventsmost samples wastedimportance sampling from a proposal near the event
Known structureignoredcontrol variates, antithetic pairs, stratification
High dimensionsthe rate does not depend on ddbut rejection rates and importance weights degrade with dd

Limitations#

  • Good proposals are hard to find in high dimensions. Both rejection sampling and importance sampling need qq close to pp; in many dimensions a small mismatch in every coordinate compounds, and acceptance rates and effective sample sizes collapse exponentially.
  • Importance sampling can fail silently. A proposal with lighter tails than the target can give estimates whose variance is infinite: they look stable for a long time and then jump.
  • Exact samples from complicated distributions are rarely available. Posteriors of real models, energy-based models and distributions over structures need a different approach, the subject of the next note.

What you should remember#

  • Report a Monte Carlo estimate with its error bar ±1.96 σ^/n\pm 1.96\,\hat\sigma/\sqrt n, valid for independent draws when g(X)g(X) has a finite variance; the rate does not depend on the dimension.
  • Samples come from inversion (F−1(U)F^{-1}(U)), transformations (Box–Muller) or rejection (accept X∼qX \sim q with probability p(X)/(Mq(X))p(X)/(Mq(X)), acceptance rate 1/M1/M).
  • Rejection sampling needs pp only up to a constant but its acceptance rate collapses in high dimensions.
  • Importance sampling: Ep[g]=Eq[g p/q]E_p[g] = E_q[g\, p/q]; it can make rare events cheap; check the effective sample size (∑w)2/∑w2(\sum w)^2/\sum w^2.
  • Control variates subtract a correlated quantity with known mean; baselines in policy gradients are control variates.

Code#

Rejection sampling, Box–Muller, a rare event by importance sampling, a control variate, the twelve-uniform approximation, a Cauchy envelope and self-normalized weights:

import numpy as np, math
from scipy import stats

rng = np.random.default_rng(0)

# rejection sampling from Beta(2, 5) with a uniform proposal and M = max p = p(0.2)
p = stats.beta(2, 5).pdf
M = p(0.2)
x, u = rng.random(100_000), rng.random(100_000)
sample = x[u * M <= p(x)]
print(round(float(M), 4), round(len(sample) / 100_000, 3), round(float(sample.mean()), 3), round(2 / 7, 3))   # 2.4576 0.408 0.286 0.286

# the share of a cube taken by the inscribed ball: the acceptance rate of rejection sampling in d dimensions
print([f'{math.pi ** (d / 2) / math.gamma(d / 2 + 1) / 2 ** d:.2g}' for d in (2, 5, 10, 20)])   # ['0.79', '0.16', '0.0025', '2.5e-08']

# Box-Muller: two uniforms give a standard normal
u1, u2 = rng.random((2, 500_000))
z = np.sqrt(-2 * np.log(1 - u1)) * np.cos(2 * np.pi * u2)
print(round(float(z.mean()), 3), round(float(z.std()), 3))           # 0.0 1.003

# a rare event, P(Z > 4): a million plain samples against 10,000 importance samples from N(4, 1)
true = stats.norm.sf(4)
plain = rng.normal(size=1_000_000) > 4
y = rng.normal(4, 1, 10_000)
w = np.exp(8 - 4 * y)                                                # p(y) / q(y)
terms = (y > 4) * w
print(f'{true:.3g}', int(plain.sum()), f'{terms.mean():.3g}', round(float(terms.std() / math.sqrt(1e4) / true), 3))   # 3.17e-05 28 3.27e-05 0.022
print(round(float(w.sum() ** 2 / (w ** 2).sum()), 1))               # 5.1: the effective sample size of these weights

# a control variate for E[e^U] = e - 1: the variance per sample without and with it
U = rng.random(10_000)
Y = np.exp(U)
c = -np.cov(Y, U)[0, 1] / U.var(ddof=1)
print(round(float(Y.mean()), 4), round(float(Y.var()), 4), round(float((Y + c * (U - 0.5)).var()), 4), round(math.e - 1, 4))   # 1.7181 0.2446 0.004 1.7183

# twelve uniforms minus six: mean 0 and variance 1, but exact tails (Irwin-Hall CDF) far below the normal's
s = rng.random((100_000, 12)).sum(axis=1) - 6
sf12 = lambda x: 1 - sum((-1) ** k * math.comb(12, k) * max(x + 6 - k, 0) ** 12 for k in range(13)) / math.factorial(12)
print(round(float(s.mean()), 3), round(float(s.var()), 3), [f'{sf12(t):.2g}' for t in (4, 5)], [f'{stats.norm.sf(t):.2g}' for t in (4, 5)])   # -0.005 0.999 ['8.5e-06', '2.1e-09'] ['3.2e-05', '2.9e-07']

# a normal target under a Cauchy envelope, M = max p/q at x = 1; a normal proposal under a Cauchy target has no M
M = 2 * math.sqrt(math.pi / 2) * math.exp(-0.5)
x = rng.standard_cauchy(100_000)
keep = x[rng.random(100_000) * M * stats.cauchy.pdf(x) <= stats.norm.pdf(x)]
print(round(M, 3), round(len(keep) / 100_000, 3), round(float(keep.std()), 3), round(float(stats.cauchy.pdf(5) / stats.norm.pdf(5))))   # 1.52 0.657 1.0 8235

# self-normalized importance sampling for the unnormalized p~(x) = exp(-x^2/2), Z = sqrt(2 pi), with the Cauchy draws
v = np.exp(-x ** 2 / 2) / stats.cauchy.pdf(x)
print(round(float(v.mean()), 3), round(math.sqrt(2 * math.pi), 3), round(float((v * x ** 2).sum() / v.sum()), 3))   # 2.499 2.507 0.997: Z and E_p[X^2] = 1

Next#

Rejection and importance sampling need a proposal close to the target, and in high dimensions there usually is none. The last note of the course builds instead a Markov chain whose stationary distribution is the target, using only the unnormalized density: the Metropolis–Hastings algorithm, Gibbs sampling, and Langevin dynamics, the bridge to diffusion models.

References#

  • C. P. Robert, G. Casella. Monte Carlo Statistical Methods, 2nd ed. Springer, 2004. Chapter 2 (random variable generation, rejection), Chapter 3 (Monte Carlo integration, importance sampling), Chapter 4 (variance reduction).
  • A. B. Owen. Monte Carlo Theory, Methods and Examples. 2013. Chapters 4, 8 and 9 (non-uniform random variables, variance reduction, importance sampling).
  • G. E. P. Box, M. E. Muller. A Note on the Generation of Random Normal Deviates. The Annals of Mathematical Statistics, 29(2), 1958.
  • J. von Neumann. Various Techniques Used in Connection with Random Digits. National Bureau of Standards Applied Mathematics Series, 12, 1951. The rejection method.
  • R. J. Williams. Simple Statistical Gradient-Following Algorithms for Connectionist Reinforcement Learning. Machine Learning, 8, 1992. REINFORCE and baselines.