Importance sampling: correct the sampling distribution
重要性采样
Enumerate four samples to distinguish unbiased importance weighting, self-normalization, MSE and misleading weight ESS.
importance-samplingChange where you look, then correct the weights
Imagine checking two kinds of parcels. Under the target population, three quarters belong to class 1, but your sampling process selects each class with equal probability. The raw sample average answers a question about the sampling process. Importance weights let it answer the target-population question instead.
Write the target probabilities as p=(1/4,3/4), the proposal as q=(1/2,1/2), and the quantity of interest as h=(0,1). The target mean is 3/4. A class 0 draw receives weight 1/2; a class 1 draw receives weight 3/2. No learning algorithm is needed to understand this correction. Start with expectation and variance and Monte Carlo integration.
Two estimators, two finite-sample behaviors
For independent draws Xᵢ from q, ordinary importance sampling uses a known normalized target p:
The cancellation needs proposal support wherever p(x)h(x) contributes; requiring q>0 throughout target support is a convenient sufficient condition. In a continuous space, replace the sum with an integral and require integrability. Finite variance of wh gives variance Var_q(wh)/N. Unbiasedness does not require small variance.
If only an unnormalized target is available, its unknown constant can cancel between two estimated sums:
This self-normalized estimator is generally biased for finite N. Under support coverage and the relevant law-of-large-numbers conditions, numerator and denominator averages converge to their expectations, giving consistency when the denominator limit is positive. Ratios of unbiased estimates need not be unbiased. Owen, Chapter 9, Sections 9.1–9.2, develops both estimators and their assumptions.
Exhaust all four possible samples
For N=2, the ordered samples 00,01,10,11 each have probability 1/4. Ordinary estimates are 0,3/4,3/4,3/2. Their mean is 3/4. The last estimate exceeds the largest h value: ordinary IS does not force its realized weights to average to one.
Self-normalized estimates are 0,3/4,3/4,1, averaging 5/8. The bias is−1/8. Its variance is 9/64 and its mean squared error is 5/32; ordinary IS has variance and MSE 9/32. In this example, a biased estimator has smaller MSE. That is a calculated comparison for these p,q,h,N, not a universal ranking.
Enumerate the sampling distribution exactly
The complete Python 3.12 program uses rational arithmetic and enumerates every ordered IID proposal sample. It reports expectations over the sampling distribution, not estimates of those expectations from another random run. The API deliberately requires positive probabilities in every listed state, a stronger contract than the most general support condition.
from fractions import Fraction as F
from itertools import product
from math import prod
def inputs(p, q, h):
p,q,h=map(list,(p,q,h));n=len(p)
if not 1<=n<=6 or len(q)!=n or len(h)!=n:
raise ValueError('one to six states and matching vectors required')
for v in (p,q):
if any(type(x) not in (int,F) or not 0<x<=1 for x in v) or sum(v,F(0))!=1:
raise ValueError('strictly positive rational probabilities summing to one required')
if any(type(x) not in (int,F) or abs(x)>1000000 for x in h):
raise ValueError('bounded rational function values required')
return list(map(F,p)),list(map(F,q)),list(map(F,h))
def path_estimates(p, q, h, path):
p,q,h=inputs(p,q,h);path=list(path)
if not 1<=len(path)<=6 or any(type(i) is not int or not 0<=i<len(p) for i in path):
raise ValueError('one to six valid integer state indices required')
w=[p[i]/q[i] for i in path];weighted=sum((v*h[i] for v,i in zip(w,path)),F(0))
return weighted/len(path),weighted/sum(w),sum(w)**2/sum(v*v for v in w)
def sampling_distribution(p, q, h, draws=2):
p,q,h=inputs(p,q,h);n=len(p)
if type(draws) is not int or not 1<=draws<=6 or n**draws>10000:
raise ValueError('one to six draws and at most10000 paths required')
mu=sum((a*b for a,b in zip(p,h)),F(0));rows=[]
for path in product(range(n),repeat=draws):
ordinary,normalized,ess=path_estimates(p,q,h,path)
rows.append((path,prod(q[i] for i in path),ordinary,normalized,ess))
moments={}
for label,col in [('ordinary',2),('normalized',3)]:
mean=sum((r[1]*r[col] for r in rows),F(0))
var=sum((r[1]*(r[col]-mean)**2 for r in rows),F(0))
moments[label]=(mean,mean-mu,var,var+(mean-mu)**2)
return mu,rows,moments
if __name__=='__main__':
p=[F(1,4),F(3,4)];q=[F(1,2),F(1,2)];h=[0,1]
mu,rows,moments=sampling_distribution(p,q,h)
print('target mean:',mu)
print('path; probability; ordinary; normalized; weight ESS')
for row in rows:print(row[0],*[str(x) for x in row[1:]],sep='; ')
print('mean; bias; variance; MSE')
for label,values in moments.items():print(label,*map(str,values),sep='; ')
bad=[F(99,100),F(1,100)]
print('rare-event proposal ordinary variance:',sampling_distribution(p,bad,h)[2]['ordinary'][2])
print('all-zero path normalized estimate and ESS:',*[str(x) for x in path_estimates(p,bad,h,[0,0])[1:]])
Output:
target mean: 3/4
path; probability; ordinary; normalized; weight ESS
(0, 0); 1/4; 0; 0; 2
(0, 1); 1/4; 3/4; 3/4; 8/5
(1, 0); 1/4; 3/4; 3/4; 8/5
(1, 1); 1/4; 3/2; 1; 2
mean; bias; variance; MSE
ordinary; 3/4; 0; 9/32; 9/32
normalized; 5/8; -1/8; 9/64; 5/32
rare-event proposal ordinary variance: 891/32
all-zero path normalized estimate and ESS: 0 2
The four moment columns are mean, bias, variance and MSE. Enumeration costs O(nᴺ(N+n)) rational operations in this implementation, including repeated input validation; storing all rows costs O(nᴺN). Large rational numerators and denominators add bit costs. The 10000-path cap makes the example finite and inspectable. Actual IS stores a running sum and requires O(N) target/proposal evaluations, with their evaluation costs counted separately.
Balanced observed weights can hide missing mass
Now use q=(99/100,1/100). Class 1 is rare under the proposal but common under the target; its weight becomes 75. Ordinary IS with two draws has variance 891/32, far above 9/32. The chance of seeing no class 1 is(99/100)²=9801/10000. That sample gives a normalized estimate of zero.
A common weight diagnostic is:
On the all-zero path, the two weights are identical, so ESS_w=2, its maximum. Yet the estimate misses the target mean 3/4. This diagnostic sees observed weight concentration, not regions never visited. Owen, Section 9.3, explicitly discusses this limitation. It is also independent of h, although estimation difficulty depends on h.
In high dimensions, modest mismatches across coordinates can multiply into severe weight concentration. Hastings’s 1970 introduction discusses this difficulty as motivation for alternative sampling strategies; it does not establish a universal dimensional cutoff. Better proposals, mixtures and adaptation can help, but adaptation changes the sampling design and needs an appropriate analysis. Clipping weights changes bias and must be disclosed.
Separate bias, variance and coverage
- Why can ordinary IS return 3/2 when h only takes 0 and 1?
Answer 1: It divides by the draw count, not the realized sum of weights. Both sampled h values can receive weight 3/2.
- What is the self-normalized estimator’s finite-sample bias in the four-path example?
Answer 2: 5/8−3/4=−1/8.
- Does ESS_w=N certify accuracy?
Answer 3: No. The bad proposal’s 00 path has ESS_w=2 but estimate 0 instead of 3/4.
- If p=q, how do the two estimators compare?
Answer 4: All weights are one, so both equal the ordinary sample mean. Sampling variability can still remain.
Choose a proposal for the quantity you need
Project: keep p fixed, vary the second proposal probability over 1/100,1/4,1/2,3/4,99/100 and compute both MSEs by enumeration. Repeat with a different h. A proposal’s quality belongs to a particular estimation task, not just to a visual resemblance between two distributions.
Importance weighting also appears in off-policy evaluation and distribution-shift correction. Those settings require justified probability ratios and overlap; weights cannot repair an unobserved outcome mechanism by themselves. Compare MCMC, where dependent transitions replace independent proposal reweighting, and sampling bias, where the sampling mechanism may itself be unknown.
Make a prediction, then check
What does a maximum weight ESS establish?
Learning objectives
- Derive the importance-weight identity and its support condition.
- Compute bias and MSE by exact finite-sample enumeration.
- Explain why a large weight ESS can miss target mass.
Prerequisites & connections
Explore related knowledge →References
- Monte Carlo theory, methods and examples — Chapter 9: Importance sampling
Art B. Owen · 2018 - Monte Carlo sampling methods using Markov chains and their applications
W. K. Hastings · 1970
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-agent authored technical review: cited primary-source scope, explicit assumptions, original calculations and counterexamples, runnable tests and bilingual review; not independent human or second-agent review.
- Single-agent authored technical review: bounded primary-source locations, assumptions, original derivations, exact/literal references and matching bilingual equations/examples/exercises. Not independent human or second-agent review.
- Four focused CPython3.12.4 tests passed per chapter. IS and decisions use exact fractions; VI and GP use floating-point calculations checked against analytic constants, invariance and meaningful boundaries. NumPy1.26.4 used for GP.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
Source locations checked:
- Monte Carlo theory, methods and examples — Chapter 9: Importance sampling · Chapter9 physical pages4–5,8–9,11–12: ordinary and self-normalized IS, support, weight diagnostics; observed chapter copyright2009–2013,2018, not a guessed publication day. Original finite-state example independently derived.
- Monte Carlo sampling methods using Markov chains and their applications · Introduction on printed97: importance weights and high-dimensional concentration; not cited as invention of importance sampling.
Related topics