Importance Sampling

Plain sampling needs about 316,000 draws just to see ten days past 4 standard deviations. Draw from a shifted distribution, weight each draw by p/q, and 1,000 draws land within about 7% of the truth.

Pick a sampler, set the threshold, then press Draw 1,000. Watch where the draws land and what each sampler reports. Then we build, piece by piece, the weight, its variance, the best proposal, the health check and five places the idea runs today.

You need Monte Carlo (an average of random draws estimates an expectation; see the Monte Carlo lesson) and a little Python. We build the rest from zero.

Estimate a one-in-31,600 event

4.0

The target is the standard bell curve N(0,1) and the event is X > t. Importance sampling draws from q = N(t, 1). The truth is the exact normal tail. The draws are random, so each press gives a new run.

Chapter 0

The Event You Never See

Count how few plain draws land in a rare region, and measure how bad the estimate gets

An insurer asks: what is the chance that tomorrow's loss passes 4 standard deviations? You have a model of one day's loss, so you simulate a thousand days and count. The counter most likely stays at zero.

Call a day's standardized loss X, drawn from the standard bell curve N(0,1). The rare event is X > t for a threshold t. Crude Monte Carlo (plain sampling) estimates the event's probability as the share of draws that pass t. Most draws land in the bulk and tell you nothing.

Rain draws on the tail

Teal is the bell curve p. Each dot is one draw. Blue marks the threshold. Press Run, then push t to the right and watch the hit counter stall.

3.0

Draws come from N(0,1) through a seeded random generator. The truth is the exact normal tail.

How noisy is the share? Call the true probability p and the number of draws N. Each draw is a coin that lands 1 with chance p. The typical error of the share, divided by p itself, is the relative error.

Say it aloud

Rel equals the square root of one minus p, over p times N.

rel
rel the typical miss of the estimate, as a share of the true answer.
√
the square root of it turns a variance back into a typical distance.
p
p the true chance of the event, here the tail past t.
N
N the number of plain draws.
In plain words

Divide one minus p by p times N. Take the square root. A small p makes the bottom small, so rel grows.

With numbers

At t = 4, p = 0.0000317. With N = 1,000,000: rel = √(0.99997 / 31.7) = 0.18, an 18% error. With N = 1,000, rel = 5.6, and 97% of runs see no hit at all.

The failure. Symptom: the estimate is 0, or it jumps between 0 and a large value from run to run. Measure: count the hits. Fewer than 100 hits means more than 10% error. Fix: sample somewhere else. A one-in-a-million event needs about 100 million plain draws for 10% error.

So keep the same truth but change where you look. Draw from a distribution that visits the rare region often. Then multiply each draw by an honest correction, so the answer stays exact.

The road

  1. Reweight: the weight p/q and why the answer stays exact.
  2. Variance: why a bad proposal can have infinite variance.
  3. The best proposal: the shape that gives zero variance, and its catch.
  4. Effective sample size: how many draws your weights are worth.
  5. Self-normalized: when you know the target only up to a constant.
  6. Rare events: tilt q toward the tail. This is the hero's sampler.
  7. Off-policy: score a policy from another policy's logs.
  8. Rendering: sample light where the surface reflects it.
  9. Annealed: a ladder of small reweightings.
  10. Field guide: terms, numbers, code and links.
Plain sampling draws 1,000,000 values from N(0,1) to estimate P(X > 4), which is about 0.0000317. About how many draws land past 4?

Chapter 1

Sample Here, Answer There

Draw from a proposal you choose and correct each draw with the weight p/q

Call the distribution you care about the target p. Call the distribution you draw from the proposal q. You choose q, so you can make it visit the places that matter.

The draws now over-represent some places and under-represent others. Each draw x gets a correction, the importance weight: the target density at x divided by the proposal density at x. Where q over-produces, the weight is below 1. Where q under-produces, it is above 1.

The correction is exact. Multiply and divide by q inside the average:

Ep[f] = ∫ p(x) f(x) dx = ∫ q(x) · p(x)/q(x) · f(x) dx = Eq[w(x) f(x)]

The only condition: q must be above zero wherever p times f is not zero. You cannot reweight a place you never sample.

Now the estimator. Call the function you average f. Draw N values x1 to xN from q. Call the estimate μ̂ (mu-hat).

Say it aloud

Mu-hat equals one over N times the sum over i of w of x-i times f of x-i, where w of x is p of x over q of x.

μ̂
mu-hat the estimate of the average of f under the target p.
1/N
one over N divide by the number of draws, to make an average.
Σi
the sum over i add one term for each draw, i from 1 to N.
w(xi)
w of x-i the weight of draw i.
f(xi)
f of x-i the function at draw i, here x squared.
p(x)/q(x)
p of x over q of x the target density over the proposal density at x.
In plain words

Draw each x-i from q. Multiply f of x-i by its weight w of x-i. Average the products. That is mu-hat.

With numbers

Target p = N(0,1), proposal q = N(0, 1.5), f(x) = x², truth 1. Three draws: 0.5, −2.0, 1.0. Weights 1.40, 0.49, 1.14. Products 0.35, 1.98, 1.14, total 3.46, so μ̂ = 1.15. The plain average of x² over the same draws is 1.75.

Move the proposal, keep the answer

Teal is p, pink is q. Dots are draws from q, sized by their weight. Drag q's centre and width. The orange running estimate of Ep[x²] heads for the yellow truth unless q is a poor match.

1.00
1.50

Each setting draws 3,000 values from q with a fixed seed. The truth Ep[x²] = 1 is exact.

You can write the weights by hand when both densities are bell curves. With p = N(0,1) and q = N(3,1), the √(2π) factors cancel:

w(x) = exp(−x2/2 + (x − 3)2/2) = exp(4.5 − 3x)
w(2.5) = e−3 = 0.050,   w(3.5) = e−6 = 0.0025

The failure. Symptom: the estimate settles, but on the wrong value. Take q uniform on [−2, 2]: it never draws the tails, so μ̂ converges to 0.74, not 1. Measure: check that q covers every place where p times f is large. Fix: widen q or give it heavier tails.

You draw x from q = N(3,1) but want an average under p = N(0,1). What weight does a draw at x = 2.5 carry, and why?

Chapter 2

Unbiased Is Not Accurate

Find where the variance comes from, and see a narrow proposal make it infinite

Run the same estimator twice, same target, same N, two proposals. One settles in a few hundred draws. The other sits still for thousands of draws, then jumps. Both are unbiased. The difference is the variance: how far one estimate tends to land from the truth.

The variance of μ̂ is the variance of one product w·f under q, divided by N. Call the per-draw variance σ²IS and the true answer μ.

Say it aloud

Sigma squared I-S equals the integral over x of p of x squared, times f of x squared, over q of x, minus mu squared.

σ²IS
sigma squared I-S the variance of one weighted draw w·f.
∫ … dx
the integral over x add up the term at every x.
p(x)²
p of x squared the target density, squared.
f(x)²
f of x squared the function, squared.
q(x)
over q of x the proposal density, in the denominator.
μ²
mu squared the true answer, squared.
In plain words

At every x, square p times f and divide by q. Add it all up. Subtract the true answer squared. Where q is tiny but p times f is not, the division blows up.

With numbers

p = N(0,1), f = x², μ = 1. With q = p the integral is 3, so σ²IS = 2. With q = N(0, 1.5) it is 1.49, so σ²IS = 0.49, four times better. With q = N(0, 0.8) it is 18.

For a bell-curve q of width σq, the ratio p²/q shrinks in the tails only while σq is above 1/√2 = 0.707. Below that it grows without end, so the integral is infinite. The estimate stays unbiased. Its variance is infinite.

Narrow the proposal until it breaks

Top: the variance per draw against q's width, with the red wall at 0.707. Bottom: one run of 4,000 draws. Slide the width below 0.7 and watch the run lurch.

0.60

Target N(0,1), f = x², q = N(0, width). The curve is exact: σ² = 3s / (4√2 · a2.5) − 1 with a = 1 − 1/(2s²). The run is a seeded simulation.

The failure. Symptom: a running mean that sits flat, then leaps when one draw arrives. Measure: the largest weight over the sum of weights. In one run of 200,000 draws with width 0.5, one weight reached 726 and the sample variance was 209. Fix: give q heavier tails than p times |f|. Here the best bell width is √3 = 1.73, with σ²IS = 0.45.

Your estimate sits near 0.3 for thousands of draws, then leaps to 8 when one new draw arrives. What does that mean?

Chapter 3

The Proposal That Beats Noise

Shape q like p times |f| and every weighted draw returns the same number

If q sets the variance, which q is best? Put draws where p times |f| is large and none where it is zero. Push that idea to its limit.

Call the area under p times |f| Z. Dividing by Z makes the shape a proper distribution, one that adds up to 1. Call that distribution q* (q-star).

Say it aloud

Q-star of x equals the absolute value of f of x, times p of x, over Z.

q*(x)
q-star of x the proposal with the smallest variance.
|f(x)|
the absolute value of f of x the size of the function, sign dropped.
p(x)
p of x the target density.
Z
Z the area under |f| times p, so q* adds up to 1. Z equals the average of |f| under p.
In plain words

Multiply |f| by p at every x. Scale the curve by Z so its area is 1. Draw from that shape. When f is never negative, every product w times f then equals Z.

With numbers

p = N(0,1) and f = x², so Z = 1 and q* = x² p(x). At x = 2: w = p/q* = 1/4, and w·f = 1/4 × 4 = 1. At x = 0.5: w = 4, and w·f = 4 × 0.25 = 1. Every draw returns 1, the exact answer, so the variance is 0.

Blend toward q*

Top: p (teal), q* (blue) and your blend q (pink). Bottom: w·f at ten fixed points. Slide the blend toward q* and watch the bars level at the yellow line, Z = 1.

0.00

q = (1 − blend) · p + blend · q*. The variance is a numerical integral on a fine grid: 2 at blend 0, 0.31 at 0.5, 0.028 at 0.9, 0 at 1.

Now the catch. Z is the average of |f| under p. For f that is never negative, Z is the answer you want. If you could write q*, you would not need to sample. So q* is a direction, not a recipe: shape q like |f| times p, and keep its tails heavy (Chapter 2).

The failure. Symptom: a q shaped like |f|·p still leaves variance when f changes sign. For f = x, q* = |x| p / Z gives w·f = +Z or −Z, a variance of Z² = 0.64. Measure: look at the sign of the w·f values. Fix: split f into its positive and negative parts, and give each part its own proposal.

Why can you not use the optimal proposal q*(x) = |f(x)| p(x) / Z in practice?

Chapter 4

How Many Draws Your Weights Are Worth

Turn a list of weights into a count of plain draws

You drew 1,000 weighted draws. One weight is 100 and the rest are 1. The weighted average mostly repeats that one draw. How many plain draws is the set worth?

Call the weights w1 to wN. The effective sample size (ESS) is the number of equal-weight draws that would carry the same information. This form is Kish's, from survey sampling.

Say it aloud

E-S-S equals the sum over i of w-i, squared, divided by the sum over i of w-i squared.

ESS
E-S-S the effective sample size, between 1 and N.
(Σi wi)²
the sum over i of w-i, squared add the weights, then square the total.
Σi wi²
the sum over i of w-i squared square each weight, then add.
In plain words

Add the weights and square the total. Square each weight and add those. Divide the first by the second. Equal weights give N. One dominant weight gives about 1.

With numbers

Weights 1, 1, 1, 1, 100. The sum is 104, squared 10,816. The squares add to 10,004. ESS = 10,816 / 10,004 = 1.08. Five draws are worth about one. Weights 0.1, 0.2, 0.05, 4.0, 0.3 give 21.62 / 16.14 = 1.34.

Skew the weights, read the dial

Twelve purple bars show the normalized weights. Drag the skew to pile weight onto fewer draws and watch ESS fall from 12 toward 1.

0.20

Illustrative weights: wi = ri for i = 0 to 11, with r = eskew · 1.2.

The failure. Symptom: ESS/N far below 1. Measure: compute ESS every run. As a rule of thumb, ESS/N under 0.1 is a stop sign. Fix: re-centre or widen q, or add rungs between q and p (Chapter 9).

ESS has a blind spot. It judges the weights of the draws you have, never the places you did not draw. The uniform proposal on [−2, 2] from Chapter 1 scores a healthy ESS/N of 0.81 and still converges to 0.74 instead of 1.

Five weighted draws have weights 1, 1, 1, 1 and 100. What is the effective sample size, and what does it mean?

Chapter 5

When You Know the Target Only Up to a Constant

Divide by the sum of the weights so an unknown scale cancels, and pay a small bias

In Bayesian inference the posterior is the likelihood times the prior, divided by the evidence. The evidence is an integral you usually cannot compute. So you know the target's shape, p̃ (p-tilde), but not its scale: p̃(x) = c · p(x) for an unknown constant c.

Plain importance sampling with p̃ in the weight returns c times the answer. The fix is to divide by the sum of the weights. The constant c sits in the top and the bottom, so it cancels. This is self-normalized importance sampling (SNIS).

Say it aloud

Mu-hat S-N equals the sum over i of w-tilde-i times f of x-i, divided by the sum over i of w-tilde-i, where w-tilde-i is p-tilde of x-i over q of x-i.

μ̂SN
mu-hat S-N the self-normalized estimate.
Σi w̃i f(xi)
the sum over i of w-tilde-i times f of x-i the weighted total of f.
Σi w̃i
the sum over i of w-tilde-i the total weight.
w̃i
w-tilde-i the weight built from the unscaled target p-tilde. It equals c times the true weight.
In plain words

Weight each draw by p-tilde over q. Take the weighted total of f. Divide by the total weight. As a bonus, the average w-tilde estimates the hidden scale c.

With numbers

Target N(1,1), known only as p̃(x) = exp(x − x²/2), and proposal q = N(0,1). Drop the constants: w̃ = ex. Draws −1, 0, 1, 2 give w̃ = 0.37, 1, 2.72, 7.39, total 11.48. The weighted total of x is 17.13. So μ̂SN = 17.13 / 11.48 = 1.49. The truth is 1.

Hide a constant, then cancel it

The target is known only up to c. Drag c: the pink plain estimate moves with it, the purple self-normalized one stays put. Pick N to see the small-N bias.

1.00

Each histogram is 600 repeated runs with a fixed seed. Target N(1,1), proposal N(0,1), f = x.

The failure. Symptom: small runs sit off the truth on average. SNIS divides one random sum by another, and that ratio is biased. In this example the average over many runs is 0.61 at N = 4 and 0.97 at N = 100. Measure: run at two sizes of N and compare. Fix: use more draws, and report the ESS with the answer.

Self-normalized IS divides the weighted total by the total weight. What does that buy, and what does it cost?

Chapter 6

Tilt Toward the Rare Event

Shift the proposal onto the threshold, weight the hits, and find the best shift

Back to the tail of Chapter 0: P(X > 3) = 0.00135 for X from N(0,1). Shift the proposal to q = N(μ, 1), so many draws pass the threshold t = 3. Then weight each draw to undo the shift. This is exponential tilting, and it is the hero's sampler.

For this pair the weight has a closed form, because the √(2π) factors cancel. The estimate is the average of w(x) times 1{x > t}, a mark that is 1 if the draw passes t and 0 if not.

w(x) = exp(−x2/2 + (x − μ)2/2) = exp(μ2/2 − μx)
P̂ = (1/N) Σi w(xi) · 1{xi > t}

By hand, with μ = 3 and four draws 2.5, 3.2, 3.5, 4.0: the first misses, so its term is 0. The others give 0.00610, 0.00248 and 0.00055. The average is 0.00228. Four draws already reach the right order of magnitude.

Slide the tilt, find the sweet spot

Top: p, the tilted q and the rare region past t = 3. Bottom: relative error per draw against the shift, on a log scale. Slide the shift, then press Draw 1,000.

3.00

The curve is exact: relative variance per draw = eμ² · P(X > t + μ) / p² − 1. The draws are seeded.

The gain is precise. Per draw, the relative error is 27.2 for plain sampling and 1.84 at μ = 3. Square the ratio: one tilted draw is worth about 218 plain draws. The best shift is μ = 3.15, a little past t, where q* = 1{x > t}·p / Z piles its mass.

The failure. Symptom: the estimate wanders when q sits far past t. The few draws near t then carry huge weights. Measure: relative error per draw is 4.9 at μ = 5 and 16.3 at μ = 6. Fix: centre q at or just past the threshold.

To estimate P(X > 3) for X from N(0,1), why draw from q = N(3,1) instead of from p?

Chapter 7

Grade a Policy You Never Ran

Score a new policy from another policy's logs, and watch the product of ratios explode with the horizon

A clinic logged months of decisions made under its current rule, the behavior policy b. You designed a new rule, the target policy π. What would π score, without trying it on patients? This is off-policy evaluation.

A logged episode is a list of states st and actions at. Its chance under a policy is a product: one action probability per step, times the environment's transition probabilities. The environment terms are the same under π and b, so they cancel in the ratio. Call the episode's total reward, the return, G.

Say it aloud

V-hat equals G times the product over t of pi of a-t given s-t, over b of a-t given s-t.

V̂
V-hat one episode's estimate of the target policy's value.
G
G the return the logged episode earned.
Πt
the product over t multiply one factor for each step of the episode.
π(at | st)
pi of a-t given s-t the target's chance of the logged action in that state.
b(at | st)
b of a-t given s-t the behavior's chance of the same action.
In plain words

At each step, divide the target's chance of the logged action by the behavior's chance. Multiply the ratios; call the product rho. Multiply rho by G. Average V-hat over many episodes.

With numbers

On the logged actions, π gives 0.8, 0.5, 0.9 and b gives 0.4, 0.5, 0.3. The return is G = 2. Ratios 2, 1, 3, so rho = 6 and V̂ = 12. The target was six times as likely to produce this exact episode.

Why does length hurt? Take a toy with two actions. b picks each half the time; π picks one with chance 0.5 + m. Each step's ratio is 1 + 2m or 1 − 2m. Its mean is 1 and its mean square is 1 + 4m². Over H independent steps:

Var(ρ) = (1 + 4m2)H − 1  →  m = 0.5, H = 10: 210 − 1 = 1,023

Stretch the horizon

Purple bars count 4,000 episodes by their weight rho, on a log scale. The yellow line marks the mean, 1. Lengthen the episode or widen the gap and watch the mass slide left while a few episodes run far right.

6
0.40

The two-action toy above, simulated with a fixed seed. The variance in the read-out is exact.

The failure. Symptom: a few episodes decide the estimate. Measure: the share of total weight held by the top 1% of episodes. At m = 0.4 and H = 6 the median rho is 0.047 and the top 1% hold 34% of the weight. Fix: weighted IS (self-normalize the rho values, Chapter 5), and doubly robust estimators that add a learned value model (Jiang and Li, 2016).

The same ratio sits inside policy gradients and off-policy actor-critic, which reuse old data with clipped or truncated ratios.

Along one logged episode the per-step ratios π/b are 2.0, 1.0 and 3.0, and the return is 2.0. What is the importance-sampled estimate?

Chapter 8

Sample the Light That Matters

Pick light directions from the surface's reflection lobe and watch a noisy pixel go clean

You render a floor. Each pixel's brightness is an integral over every light direction on the half sphere above the point. The integrand is the incoming light L, times the surface's reflection function (the BRDF), times the cosine of the angle θ between the direction and the surface normal.

A path tracer estimates the integral one direction at a time with f/pdf: the integrand at a sampled direction, divided by the density that picked that direction. That is importance sampling, with q renamed pdf. For a matte surface under constant light, f = L·cos θ / π.

uniform: pdf = 1/(2π) → f/pdf = 2L cos θ = 1.6 at cos θ = 0.8, 0.4 at cos θ = 0.2
cosine: pdf = cos θ / π → f/pdf = L at every direction

The cosine in the pdf cancels the cosine in the integrand. One sample gives the exact pixel. That is Chapter 3's q*: the pdf has the integrand's shape, so the ratio is constant.

Match the sampler to the lobe

Left: the half sphere, with sampled directions drawn as rays whose length is f/pdf. Right: a patch of pixels that should all be the same grey. Change the sampler, sharpen the lobe and set the samples per pixel.

1
4

A toy lobe: the integrand is proportional to cosk θ, aimed along the normal, scaled so the true pixel is 1. k = 1 is a matte surface. The noise figures are exact; the patch is a seeded simulation.

LobeUniformCosineLobe-matched
matte, k = 10.5800
glossy, k = 112.291.510

The table gives the relative error of one sample. With 16 samples per pixel, the glossy floor keeps 57% noise under uniform sampling and 38% under cosine sampling.

The failure. Symptom: grain and bright speckles that survive many samples. Measure: the standard deviation of one pixel across frames. Fix: sample from the BRDF lobe, and from the light sources too, then combine the two by multiple importance sampling (Veach, 1997).

A matte surface sits under constant light. Why does cosine-weighted sampling render the pixel with zero noise?

Chapter 9

A Ladder of Small Reweightings

Replace one impossible reweighting with many small ones, and estimate a ratio of normalizers

Sometimes q and p barely overlap. One-step weights are either near 0 or huge, and the ESS stays near 1 for any number of draws. So build a ladder of in-between targets, from the easy start p0 to the hard target p̃1, and reweight one small step at a time. Radford Neal named this annealed importance sampling (AIS) in 2001.

The rungs are blends p̃β = p01−β · p̃1β, with β (beta) running from 0 to 1 over K rungs. A particle starts as a draw from p0. At each rung it picks up a small weight. Then an MCMC move (a random step that keeps the current blend as its target, see MCMC) carries it on. Call its position at rung k xk.

Say it aloud

W equals the product over k of p-tilde beta-k of x-k, over p-tilde beta-k-minus-one of x-k.

w
w the particle's weight after the last rung.
Πk
the product over k multiply one ratio per rung, k from 1 to K.
p̃βk(xk)
p-tilde beta-k of x-k the next blend, at the particle's position.
p̃βk−1(xk)
p-tilde beta-k-minus-one of x-k the current blend, at the same position.
In plain words

At each rung, divide the next blend by the current blend at the particle's position x-k. Multiply that ratio into w. Then move the particle. The average w over many particles estimates Z1/Z0, the ratio of the two normalizers.

With numbers

p0 = N(0,1) and p̃1 = exp(−x²/2 + μx), so each rung is N(βμ, 1) and each ratio is exp(Δβ · μ · xk). With μ = 1 and K = 2: start at 0.3, ratio e0.15 = 1.16; move to 0.9, ratio e0.45 = 1.57; w = 1.82. The truth, e0.5 = 1.65, is the average over many particles.

Add rungs, save the weights

Top: the rungs from p0 (teal) to the target (pink). Bottom: the final weights of 48 particles, sorted. Widen the gap, then add rungs and watch the weights even out.

1
3.00

The move here is an ideal one: a fresh draw from each rung. Real AIS uses a few MCMC steps. The ESS and the estimate use 4,000 seeded particles; the bars show the first 48.

With ideal moves the log-weight has variance μ²/K, so ESS/N ≈ e−μ²/K. For μ = 3: 0.0001 with one rung, 0.41 with 10, 0.74 with 30.

The failure. Symptom: one particle holds most of the weight and Z1/Z0 comes out low. With μ = 3, one rung and 20,000 particles, a run gave 71.5 against a truth of 90.0. Measure: the ESS of the final weights. Fix: more rungs, better moves, or resampling between rungs, which is Sequential Monte Carlo.

Annealed IS with a gap of μ = 3 has ESS/N near 0.0001 with one rung. What raises it to about 0.74?

Chapter 10

Field Guide

Keep the terms, the numbers, the checks and the code in one place

Draw from a q you can afford. Weight each draw by p/q. Shape q like p times |f|, keep its tails heavy, and read the ESS before you trust the answer. Every application on this page is that one move.

TermWhat it isNumber from this page
Weight wp(x)/q(x) for one draww(2.5) = 0.050 for p = N(0,1), q = N(3,1)
Estimate μ̂average of w·f over draws from q1.15 from three draws, truth 1
Variance σ²IS∫ p²f²/q dx − μ²2 for q = p; 0.49 for width 1.5; infinite below 0.707
Optimal q*|f|·p / Zvariance 0, but Z is the answer
ESS(Σw)² / Σw²1.08 for weights 1, 1, 1, 1, 100
SNISΣw̃f / Σw̃average 0.61 at N = 4, 0.97 at N = 100
Tiltingq = N(μ, 1) for a tail218 times fewer draws at μ = 3 for P(X > 3)
Off-policy ρproduct of π/b over stepsVar = 1,023 at m = 0.5, H = 10
BRDF samplingpdf shaped like the lobematte: 0.58 to 0 per-sample error
AISa ladder of reweightings with movesESS/N 0.0001 to 0.74 with 30 rungs

Checklist before you trust a number

  1. q is above zero wherever p times f is not zero.
  2. q has tails at least as heavy as p times |f|.
  3. ESS/N is above about 0.1, measured on w, or on w·f for a tail.
  4. The largest weight holds a small share of the total.
  5. Two runs with different seeds agree within their error bars.
  6. With an unscaled target, use SNIS and run at two sizes of N.

The core in code

pythonimport numpy as np
from scipy.stats import norm
rng = np.random.default_rng(0)

def importance_sample(f, log_p, log_q, sample_q, n):
    x = sample_q(n)                       # n draws from the proposal
    log_w = log_p(x) - log_q(x)            # log weights: safer than p/q
    w = np.exp(log_w - log_w.max())        # rescale; SNIS cancels the shift
    ess = w.sum()**2 / (w**2).sum()
    snis = np.sum(w * f(x)) / w.sum()
    return snis, ess / n

# tail P(X > 3) with an exact weight and a tilted proposal
x = rng.normal(3.0, 1.0, 10_000)
w = np.exp(4.5 - 3.0 * x)                  # p/q for p = N(0,1), q = N(3,1)
print(np.mean(w * (x > 3)), norm.sf(3))    # 0.00128 vs 0.00135

Where it sits

Monte Carlo, averages of random draws, is the root of this family. MCMC draws from p itself with a chain, at the cost of correlated draws. Hamiltonian Monte Carlo makes those chain steps long and cheap. Sequential Monte Carlo adds resampling to the ladder of Chapter 9. Quasi-Monte Carlo replaces random draws with evenly spread points. Monte Carlo tree search uses rollouts to choose moves.

Wall you hitWhat it looks likeWhere to go
Light-tailed qone weight dominates; the mean jumpswiden q, imitate q* (Chapters 2, 3)
q and p barely overlapESS near 1AIS, then SMC
Long horizonsVar(ρ) grows like (1 + 4m²)Hweighted IS, doubly robust
You need draws from pIS only reweightsMCMC
The takeaway. The weight keeps the answer exact for any q that covers the target. The choice of q decides only the variance, and the ESS tells you how much of it you bought.

Keep going

Monte Carlo (the family hub) · MCMC · Sequential Monte Carlo · Policy gradients · Off-policy actor-critic · NEU 560: Monte Carlo and importance sampling

Further reading: Art Owen, Monte Carlo theory, methods and examples, chapter 9.

Radford Neal, "Annealed Importance Sampling" (arXiv, 2001); Precup, Sutton and Singh, "Eligibility Traces for Off-Policy Policy Evaluation" (2000); Eric Veach, PhD thesis on robust Monte Carlo light transport (Stanford, 1997).

Now press Present or Teach and explain from memory: the weight, why the answer stays exact, where the variance comes from, and how ESS warns you. Then go back to the hero and estimate the tail at t = 6 both ways. Say why one sampler reports zero and the other lands within a few percent.

Importance Sampling
The Monte Carlo family · Back to Gleams