§17.1–17.2Sampling and Monte Carlo Methods · Importance Sampling

Part III DL pp. 590–594 · ~6 min read

  • monte carlo algorithm
  • las vegas algorithm
  • monte carlo sampling
  • importance sampling
  • optimal importance sampling
  • biased importance sampling

§17.1 Two kinds of randomized algorithm

Randomized algorithms split into two families, and the difference decides which one machine learning can use:

Las Vegas vs Monte Carlo. Click a row for detail.
FamilyAnswerWhat is random
Las VegasLas Vegasalways exactthe resources (time/memory)
Monte CarloMonte Carloapproximate (random error)the error (shrinks with compute)
Dotted-underlined cells have explanations — click one.

Because most machine-learning problems admit no precise answer — ruling out exact methods and Las Vegas algorithms — we lean on Monte Carlo approximations. Why sample at all? Three recurring reasons: to speed up a tractable-but-costly sum (minibatches subsample the full training cost); to approximate an intractable sum or integral (the gradient of an undirected model’s log partition function, chapter 18); and sometimes because sampling is the goal — we want a model that generates data like the training set.

§17.1.2 The basics: sums as expectations

The trick of Monte Carlo sampling is to view an intractable sum or integral as an expectation, then approximate it by an average of samples:

Sum/integral as an expectation, then an average (eqs 17.1–17.3)

s=xp(x)f(x)=Ep[f(x)],s^n=1ni=1nf(x(i)),x(i)ps = \sum_{\boldsymbol{x}} p(\boldsymbol{x}) f(\boldsymbol{x}) = \mathbb{E}_p[f(\mathrm{x})], \qquad \hat{s}_n = \frac{1}{n}\sum_{i=1}^{n} f(\boldsymbol{x}^{(i)}), \quad \boldsymbol{x}^{(i)} \sim p
s=Ep[f(x)]s = \mathbb{E}_p[f(\mathrm{x})]the target: rewrite the (maybe exponentially large) sum/integral as an expectation of f under a distribution pscalar
s^n\hat{s}_nthe Monte Carlo estimate: just the average of f over n samples drawn from pscalar
x(i)p\boldsymbol{x}^{(i)} \sim pn independent samples from p — the whole method rests on being able to draw thesen samples

This estimate is trustworthy for three reasons. It is unbiased, E[s^n]=s\mathbb{E}[\hat{s}_n] = s (eq 17.4). By the law of large numbers it converges almost surely, limns^n=s\lim_{n\to\infty}\hat{s}_n = s (eq 17.5), provided Var[f]\mathrm{Var}[f] is finite. And its own variance falls off as

The 1/n variance law (eqs 17.6–17.7)

Var[s^n]=Var[f(x)]n\mathrm{Var}[\hat{s}_n] = \frac{\mathrm{Var}[f(\mathrm{x})]}{n}
Var[s^n]\mathrm{Var}[\hat{s}_n]the variance of the estimate — how much it wobbles run to runscalar
/n/\,ndividing by n means the standard error falls like 1/√n: to halve the error you need 4× the samples, to shrink it 10× you need 100×the Monte Carlo price

The central limit theorem adds that s^n\hat{s}_n is approximately Gaussian around ss, so we can put confidence intervals on it. See all of this at once — estimate π\pi by throwing darts, and watch the error track the 1/n1/\sqrt{n} line:

Monte Carlo estimation of π. Each dart lands uniformly in the unit square; the fraction inside the quarter-circle times 4 estimates π. The estimate is unbiased and converges (law of large numbers), and its error follows the dashed 1/√n reference — 100× the darts for 10× the accuracy.
64 dartssamples n (log)|error| (log)∝ 1/√n
π̂ = 4·(57/64)
= 3.5625
true π = 3.1416
|error| = 0.4209

The estimate is unbiased and converges to π by the law of large numbers; its error shrinks like 1/√n (the dashed reference). So 100× the samples buys only ~10× the accuracy — the price of Monte Carlo.

Worked example — how many samples?

Suppose ff has variance Var[f]=1\mathrm{Var}[f] = 1. To reach a standard error of 0.010.01 we need Var[f]/n=0.012\mathrm{Var}[f]/n = 0.01^2, i.e. n=10,000n = 10{,}000 samples. Want 0.0010.001 instead? That is n=1,000,000n = 1{,}000{,}000 — a hundred times more samples for a ten-times smaller error. This 1/n1/\sqrt{n} wall is exactly why a well-chosen sampling distribution (next) can be worth so much.

§17.2 Importance sampling

Everything above assumed we can sample from pp. When we cannot — or when sampling from pp is wasteful — importance sampling exploits a freedom in the setup. The product p(x)f(x)p(\boldsymbol{x})f(\boldsymbol{x}) can be re-split around any distribution qq:

The importance-sampling identity (eqs 17.8, 17.10)

p(x)f(x)=q(x)p(x)f(x)q(x),s^q=1ni=1np(x(i))f(x(i))q(x(i)),x(i)qp(\boldsymbol{x}) f(\boldsymbol{x}) = q(\boldsymbol{x})\,\frac{p(\boldsymbol{x}) f(\boldsymbol{x})}{q(\boldsymbol{x})}, \qquad \hat{s}_q = \frac{1}{n}\sum_{i=1}^{n} \frac{p(\boldsymbol{x}^{(i)}) f(\boldsymbol{x}^{(i)})}{q(\boldsymbol{x}^{(i)})}, \quad \boldsymbol{x}^{(i)} \sim q
q(x)q(\boldsymbol{x})the proposal / importance distribution — the one we actually sample from. Any q with support where pf ≠ 0 is validdistribution
p(x(i))f/q(x(i))p(\boldsymbol{x}^{(i)}) f / q(\boldsymbol{x}^{(i)})the importance weight × f: reweight each q-sample by how much more likely it was under p than under qscalar
s^q\hat{s}_qthe importance-sampling estimator — same target s, but sampled from qscalar

The remarkable part: the estimator’s mean does not depend on qq, Eq[s^q]=s\mathbb{E}_q[\hat{s}_q] = s (eq 17.11) — every qq is correct on average. But its variance is exquisitely sensitive to qq (eq 17.12), and there is a single best choice — optimal importance sampling :

The optimal proposal (eq 17.13)

q(x)=p(x)f(x)Zq^{*}(\boldsymbol{x}) = \frac{p(\boldsymbol{x})\,|f(\boldsymbol{x})|}{Z}
p(x)f(x)p(\boldsymbol{x})\,|f(\boldsymbol{x})|put sampling weight exactly where the integrand is large — where p·|f| has massunnormalized
ZZthe normalizer making q* a distribution. Computing it essentially solves the original problem, so q* is an ideal, not a recipescalar
qq^{*}the optimal proposal: when f has constant sign, Var[ŝ_{q*}] = 0 — a SINGLE sample suffices (in principle), because computing q* has already solved the problemdistribution

The payoff and the peril are both huge. A good qq concentrates samples where they matter; a bad qq — especially in high dimensions, where a simple qq matches pfp|f| poorly — gives an estimator that usually underestimates ss and rarely, wildly overestimates it. Estimate a rare-event probability and feel the difference:

Estimating a rare-tail probability s = P(x > 3) under p = N(0,1). At μ = 0 (naive Monte Carlo) samples almost never reach the tail, so the per-sample error is enormous. Shift the proposal q = N(μ,1) toward the tail and the variance collapses; the dashed q* ∝ p·|f| is the zero-variance ideal of eq 17.13. Overshoot and the error climbs back.
f = 1[x>3]p = N(0,1)q = N(μ,1)q\* ∝ p·f
s = P(x>3) = 0.00135
rel. error / sample:
= 27.4 (naive 27.4)
samples for 10% error ≈ 75,195
q: poor (naive-like)

At μ = 0 (naive Monte Carlo) almost no samples land in the tail, so the variance is enormous. Slide μtoward the tail and q overlaps p·f — the estimator's variance collapses. The dashed q\* ∝ p·|f| is the optimal (zero-variance) choice of eq 17.13; overshoot μ and the error creeps back up.

When pp and qq are only known unnormalized (the usual case for energy-based models), use biased importance sampling (eqs 17.14–17.16): divide the weighted sum of ff by the sum of the weights, using p~,q~\tilde{p}, \tilde{q} and needing no normalizers. It is biased — but asymptotically unbiased, since the denominator converges to 11 as nn \to \infty.

Why q matters so much in high dimensions

Look again at the weight p(x)f(x)/q(x)p(\boldsymbol{x})f(\boldsymbol{x})/q(\boldsymbol{x}). If some samples have qq tiny while pfp|f| is not small, that ratio explodes, and the variance with it. In high dimensions the dynamic range of joint probabilities is vast, so a simple qq almost always mismatches pfp|f| somewhere — collecting mostly near-useless samples punctuated by rare giant weights. Despite this, importance sampling is a workhorse in deep learning: accelerating large-vocabulary neural language models (§12.4), estimating partition functions (§18.7), scoring variational-autoencoder likelihoods (§20.10.3), and reducing gradient variance by sampling hard examples more often.

When even a good qq is out of reach, we give up on independent samples and build a sequence of samples that converges to pp — the Markov chain Monte Carlo approach.

Check yourself — Monte Carlo & importance sampling

1.What distinguishes a Monte Carlo algorithm from a Las Vegas algorithm?

2.The Monte Carlo estimate ŝ_n = (1/n)Σf(x⁽ⁱ⁾) has which key properties?

3.To cut a Monte Carlo estimate's standard error by a factor of 10, how many more samples do you need?

4.In importance sampling, how does the choice of proposal q affect the estimator?

5.Predict the outcome — in ImportanceSamplingLab you estimate P(x>3) under N(0,1) and slide the proposal mean μ from 0 up toward 3. What happens to the per-sample error?

5 questions