Elements of Statistical Computation

Importance Sampling

Longhai Li

2026-11-27

1. Goal and Idea

The Goal

Rejection sampling turns draws from an envelope g(\theta)\ge f(\theta) into exact draws from f(\theta), but every rejected proposal is wasted — and in the tails of a poor envelope, almost every proposal is rejected.

Two integrals with respect to an unnormalized function f(\theta), e.g. f(\theta) = \pi(\theta)L(\theta):

  1. The normalizing constant (marginal likelihood). C_f = \int f(\theta)\,d\theta.

  2. A posterior expectation. A = \frac{\int a(\theta)\,f(\theta)\,d\theta}{\int f(\theta)\,d\theta} = E_f\big[a(\theta)\big], \qquad \theta\sim\frac{f(\theta)}{C_f}

Plain Monte Carlo needs draws from f(\theta)/C_f, which we cannot produce. Rejection sampling needs an envelope g(\theta)\ge f(\theta), which may be hard to find or very wasteful.

The Idea: Reweighting

Importance sampling keeps every proposal instead of discarding most of them: draw from an easier function g(\theta) and attach a weight that corrects for sampling from the wrong distribution. Nothing is ever thrown away, and no envelope condition g(\theta)\ge f(\theta) is required — the price is that the sample is no longer an exact iid sample from f(\theta), only a weighted one.

  • Draw \theta\sim g(\theta)/C_g, where g(\theta) is another (possibly unnormalized) function we can sample from

  • Attach the importance weight, w(\theta) = \frac{f(\theta)}{g(\theta)}

  • Hope that w(\theta)\approx constant, i.e. g(\theta) has roughly the shape of f(\theta)

Requirement on g(\theta): wherever f(\theta) is positive, g(\theta) must be positive too, \{\theta: g(\theta)>0\}\ \supseteq\ \{\theta: f(\theta)>0\}.

Otherwise part of f(\theta) is never visited and the estimate is biased (Example 3).

Picture: Areas and Weights

Figure 1

Draws \theta_i come from g(\theta) (blue); each carries weight w(\theta_i)=f(\theta_i)/g(\theta_i) (green). Where f(\theta) rises above g(\theta) the weights are large, where g(\theta) dominates they are small; the average weight estimates the area ratio C_f/C_g.

2. The Importance Reweighting Formula

Derivation

Let C_f = \int f(\theta)\,d\theta, C_g = \int g(\theta)\,d\theta, and w(\theta) = f(\theta)/g(\theta).

The ratio of normalizing constants: \frac{C_f}{C_g} = \frac{\int f(\theta)\,d\theta}{\int g(\theta)\,d\theta} = \int\frac{f(\theta)}{g(\theta)}\cdot\frac{g(\theta)}{C_g}\,d\theta = E_g\big[w(\theta)\big].

The expectation of a(\theta): \begin{aligned} E_f\big[a(\theta)\big] &= \frac{\int a(\theta)\,f(\theta)\,d\theta}{C_f} = \frac{\displaystyle\int a(\theta)\,\frac{f(\theta)}{g(\theta)}\cdot\frac{g(\theta)}{C_g}\,d\theta}{C_f/C_g} \\[6pt] &= \frac{E_g\big[a(\theta)\,w(\theta)\big]}{C_f/C_g} = \frac{E_g\big[a(\theta)\,w(\theta)\big]}{E_g\big[w(\theta)\big]}. \end{aligned}

The division by g(\theta) is legitimate only on \{\theta: g(\theta)>0\}, hence the support requirement.

The Estimators

Draw \theta_1,\ldots,\theta_n \overset{iid}{\sim} g(\theta)/C_g and compute w_i = w(\theta_i) = f(\theta_i)/g(\theta_i).

Ratio of normalizing constants, and C_f itself when C_g is known \widehat{\frac{C_f}{C_g}} = \frac1n\sum_{i=1}^n w_i, \qquad \hat C_f = C_g\cdot\widehat{\frac{C_f}{C_g}} = C_g\frac{1}{n}\sum_{i=1}^n \frac{f(\theta_i)}{g(\theta_i)}.

Both are unbiased; with a normalized proposal (C_g=1), \hat C_f is just the average weight — e.g. the marginal likelihood.

Self-normalized expectation \hat A = \frac{\frac1n\sum_i a(\theta_i)\,w_i}{\frac1n\sum_i w_i} = \frac1n\sum_{i=1}^n a(\theta_i)\,\hat w^\star_i, \qquad \hat w^\star_i = \frac{w_i}{\frac1n\sum_{j=1}^n w_j}, \quad \frac1n\sum_i\hat w^\star_i = 1

\hat w^\star_i estimates the normalized weight w^\star(\theta_i) (below) and turns the proposal sample into a weighted sample from f(\theta); unknown constants in f(\theta) and g(\theta) cancel. It is a ratio of two averages, so it is biased with bias O(1/n), but consistent.

Effective Sample Size

How many “equally informative” draws is a weighted sample worth?. n_{\text{eff}} = \frac{n}{\frac1n\sum_{i=1}^n (\hat w^\star_i)^2} = \frac{\left(\sum_i w_i\right)^2}{\sum_i w_i^2}.

If w_i\approx constant (proposal shaped like the target), \hat w^\star_i = 1 and n_{\text{eff}} = n: full efficiency. If one weight dominates, n_{\text{eff}}\approx1: only one draw is doing any work.

Variance heuristic: \operatorname{Var}_g(\hat A)\approx\operatorname{Var}_f(a(\theta))/n_{\text{eff}}, the same form as for an iid sample of size n_{\text{eff}} from f(\theta) itself. n_{\text{eff}} estimates the population quantity n_{\text{eff}}^\star = n/E_g[w^\star(\theta)^2], where w^\star(\theta) = \frac{f(\theta)/C_f}{g(\theta)/C_g} is the weight normalized so that E_g[w^\star(\theta)]=1.

The catch, central to this lecture: n_{\text{eff}} is computed only from the weights actually observed. A proposal that never visits the part of \theta-space where f(\theta) and g(\theta) disagree most will report a reassuring n_{\text{eff}} while being badly wrong.

Derivation of ESS

Constants cancel in \hat A, so assume f,g normalized: w=w^\star, E_g[w]=1, and E_g[w\,h]=E_f[h] for any h. \begin{aligned} &\text{1. Error as a ratio:} && \hat A - A = \frac{\frac1n\sum_i w_i\,(a(\theta_i)-A)}{\frac1n\sum_i w_i} \\[2pt] &\text{2. Delta method } \big(\tfrac1n\textstyle\sum_i w_i\to 1\big)\text{:} && \hat A - A \approx \frac1n\sum_{i=1}^n Z_i,\quad Z_i = w_i\,(a(\theta_i)-A) \text{ iid, mean } 0 \\[2pt] &\text{3. Variance of an iid mean:} && \operatorname{Var}(\hat A)\approx\frac1n E_g\big[w^2(a-A)^2\big] = \frac1n E_f\big[w\,(a-A)^2\big] \\[2pt] &\text{4. If } w \perp (a-A)^2 \text{ under } f\text{:} && E_f\big[w\,(a-A)^2\big]\approx E_f[w]\operatorname{Var}_f(a) = E_g[w^2]\operatorname{Var}_f(a) \\[2pt] &\text{5. Match iid sampling from } f\text{:} && \operatorname{Var}(\hat A)\approx\frac{\operatorname{Var}_f(a)}{n/E_g[w^2]} \;\Longrightarrow\; n_{\text{eff}}^\star = \frac{n}{E_g[w^{\star 2}]} \end{aligned}

E_g[Z]=E_f[a-A]=0 in step 2. Since E_g[w^{\star 2}]=1+\operatorname{Var}_g(w^\star), n_{\text{eff}}^\star\le n; plugging in the sample weights gives \widehat{n_{\text{eff}}} = n\big/\tfrac1n\sum_i\hat w^{\star 2}_i. Step 4 (“uncorrelated”) is the only real approximation; it fails in the example on the next slide.

Limitations of the ESS Diagnostic

The variance heuristic is not uniformly precise. With f(\theta) the N(0,1) density, g(\theta) the N(0,2^2) density, a(\theta)=\theta^2, n=4000:

  • empirical \operatorname{Var}(\hat A)\approx 3.15\times10^{-4}, matching exact delta-method calculations

  • but \operatorname{Var}_f(a(\theta))/n_{\text{eff}}^\star \approx 7.56\times10^{-4} — over twice as large, because w(\theta) and (a(\theta)-A)^2 are negatively correlated here

More critically: \widehat{n_{\text{eff}}} is computed only from the observed weights. If the proposal never explores where f(\theta) and g(\theta) disagree most, the estimator reports a falsely reassuring \widehat{n_{\text{eff}}} and masks a severe sampling inadequacy — the subject of Examples 1 and 2 below.

3. Example 1: The Volume of a Set

Example 1: The Volume of a Set

Take two indicator functions with A\subseteq B\subset\mathbb{R}^d: f(\theta) = I_A(\theta), \qquad g(\theta) = I_B(\theta), \qquad C_f = \int I_A(\theta)\,d\theta = |A|, \qquad C_g = |B|.

The target f(\theta)/C_f is the uniform distribution on A; the proposal g(\theta)/C_g is the uniform distribution on B, which is easy to sample when B is a box. Problem: estimate the volume C_f=|A|, with |B| known.

Draw \theta_1,\ldots,\theta_n\overset{iid}{\sim}\mathrm{Unif}(B). The weight is an indicator variable, w_i = \frac{f(\theta_i)}{g(\theta_i)} = I_A(\theta_i) = \begin{cases} 1, & \theta_i\in A,\\ 0, & \theta_i\in B\setminus A,\end{cases} \qquad w_i\sim\mathrm{Bernoulli}(p),\quad p = \frac{|A|}{|B|}.

So the importance sampling estimator is “hit-or-miss” Monte Carlo: \widehat{C_f} = |B|\cdot\frac1n\sum_{i=1}^n I_A(\theta_i) = |B|\,\frac{N_A}{n}, \qquad N_A = \#\{i:\theta_i\in A\}\sim\mathrm{Binomial}(n,p).

Example 1 (Continued): The Picture

Figure 2

Draws are uniform on B; each one either lands in A (weight 1) or not (weight 0). The fraction of hits estimates p=|A|/|B|, and multiplying by the known |B| gives \widehat{C_f}=|B|\,N_A/n.

Example 1 (Continued): Variance

\widehat{C_f}=|B|\,N_A/n is unbiased. With N_A\sim\mathrm{Binomial}(n,p) and |B| = C_f/p, \begin{aligned} \operatorname{Var}\bigl(\widehat{C_f}\bigr) &= \frac{|B|^2}{n^2}\operatorname{Var}(N_A) = \frac{|B|^2}{n^2}\,n\,p(1-p) = |B|^2\,\frac{p(1-p)}{n} \\[4pt] &= \frac{C_f^2}{p^2}\cdot\frac{p(1-p)}{n} = C_f^2\times\frac1n\cdot\frac{1-p}{p}. \end{aligned}

For a fixed target (C_f fixed), (1-p)/p decreases in p: the larger p=|A|/|B|, i.e. the tighter the proposal B fits A, the smaller the variance.

Example 1 (Continued): ESS

The normalized weights and their moments are w^\star(\theta) = \frac{f(\theta)/C_f}{g(\theta)/C_g} = \frac{I_A(\theta)}{p}, \qquad E_g[w^\star(\theta)] = 1, \qquad E_g[w^\star(\theta)^2] = \frac{1}{p}, so n_{\text{eff}}^\star = \frac{n}{E_g[w^\star(\theta)^2]} = n\,p = n\,\frac{|A|}{|B|}, \qquad \widehat{n_{\text{eff}}} = \frac{\left(\sum_i w_i\right)^2}{\sum_i w_i^2} = \frac{N_A^2}{N_A} = N_A .

  • The ESS is exactly the number of hits in A, and E(N_A) = np = n_{\text{eff}}^\star.

Example 1 (Continued): What n_{\text{eff}} Means

n_{\text{eff}} compares with an iid sample from f(\theta)/C_f, which can estimate expectations E_f[a(\theta)] but not C_f. So use a simple a(\theta): take D\subseteq A and a(\theta)=I_D(\theta), with E_f[a(\theta)] = q = \frac{|D|}{|A|} \quad\text{(the fraction of $A$ lying in $D$).}

  • \hat q_A, iid sample of size m from \mathrm{Unif}(A) (direct sampling from f(\theta)/C_f): \hat q_A = \frac{\#\{\theta_i\in D\}}{m}, \qquad \operatorname{Var}(\hat q_A) = \frac{q(1-q)}{m}.

  • \hat q_B, importance sample of size n from \mathrm{Unif}(B): the normalized weights and the estimate are \begin{aligned} \hat w^\star_i &= \frac{w_i}{\frac1n\sum_{j=1}^n w_j} = \begin{cases} n/N_A, & \theta_i\in A,\\ 0, & \theta_i\notin A, \end{cases}\\[4pt] \hat q_B &= \frac1n\sum_{i=1}^n I_D(\theta_i)\,\hat w^\star_i = \frac{N_D}{N_A}, \qquad N_D = \#\{\theta_i\in D\}. \end{aligned}

Example 1 (Continued): \operatorname{Var}(\hat q_B)

Given N_A, the hits are iid \mathrm{Unif}(A), so N_D\mid N_A\sim\mathrm{Binomial}(N_A,q): E(\hat q_B\mid N_A) = q, \qquad \operatorname{Var}(\hat q_B\mid N_A) = \frac{q(1-q)}{N_A}.

By the law of total variance, with N_A\sim\mathrm{Binomial}(n,p) (conditioning on N_A\ge1), \begin{aligned} \operatorname{Var}(\hat q_B) &= E\big[\operatorname{Var}(\hat q_B\mid N_A)\big] + \operatorname{Var}\big[E(\hat q_B\mid N_A)\big] = q(1-q)\,E\Big[\frac{1}{N_A}\Big] + \underbrace{\operatorname{Var}(q)}_{=\,0} \\[4pt] &= q(1-q)\,E\Big[\frac{1}{N_A}\Big] \;\approx\; \frac{q(1-q)}{np}, \end{aligned} since E[1/N_A]\approx 1/(np) for large np. Compared with \operatorname{Var}(\hat q_A) = q(1-q)/m:

  • Given N_A, \hat q_B matches \hat q_A with m = N_A = \widehat{n_{\text{eff}}} exactly (misses contribute nothing).
  • On average, it matches \hat q_A with m = np = n_{\text{eff}}^\star = n/E_g[w^\star(\theta)^2].

Numerical Example: Area of a Crescent

A = D_1\setminus D_2: D_1 is the unit disk at the origin, D_2 a disk of radius r_2=0.9 centred at (0.3,0). Testing \theta\in A is one line of code, but areas of such Boolean combinations of shapes (constructive solid geometry, as in CAD software) have no elementary formula in general. Two circles still have a closed form, used only to check the estimates.

Two proposals B\supseteq A: a generous box [-2,2]^2 (p=|A|/16\approx0.056) and the disk D_1 itself (p=|A|/\pi\approx0.286).

Code
r1 <- 1; r2 <- 0.9; d <- 0.3
in_A <- function(x, y) (x^2 + y^2 <= r1^2) & ((x - d)^2 + y^2 > r2^2)
circle_intersection_area <- function(r1, r2, d) {          # exact, for checking only
    r1^2 * acos((d^2 + r1^2 - r2^2) / (2 * d * r1)) +
    r2^2 * acos((d^2 + r2^2 - r1^2) / (2 * d * r2)) -
    0.5 * sqrt((-d + r1 + r2) * (d + r1 - r2) * (d - r1 + r2) * (d + r1 + r2))
}
area_true <- pi * r1^2 - circle_intersection_area(r1, r2, d)
xlim <- c(-2, 2); ylim <- c(-2, 2)
crescent_is <- function(proposal, n, seed) {
    set.seed(seed)
    if (proposal == "box") {
        x <- runif(n, xlim[1], xlim[2]); y <- runif(n, ylim[1], ylim[2])
        Cg <- (xlim[2] - xlim[1]) * (ylim[2] - ylim[1])        # C_g = |B|
    } else {
        rr <- r1 * sqrt(runif(n)); th <- runif(n, 0, 2 * pi)
        x <- rr * cos(th); y <- rr * sin(th)
        Cg <- pi * r1^2                                        # C_g = |D_1|
    }
    w <- in_A(x, y)                                            # w = f/g = I_A(theta_i)
    list(x = x, y = y, hit = w,
         estimate = Cg * mean(w), me = 1.96 * Cg * sd(w) / sqrt(n), ess = ess(w))
}

Numerical Example (Continued): The Darts

Code
res_box_vis  <- crescent_is("box",  1500, seed = 1)
res_disk_vis <- crescent_is("disk", 1500, seed = 1)
theta_seq <- seq(0, 2 * pi, length.out = 200)
par(mfrow = c(1, 2))
plot(res_box_vis$x, res_box_vis$y, asp = 1, pch = 20,
     col = ifelse(res_box_vis$hit, "steelblue", "tomato"), xlab = "x", ylab = "y",
     main = paste(sum(res_box_vis$hit), "of 1500 hit A (box)"))
rect(xlim[1], ylim[1], xlim[2], ylim[2], border = "black", lwd = 2)
lines(r1 * cos(theta_seq), r1 * sin(theta_seq), lwd = 2)
lines(d + r2 * cos(theta_seq), r2 * sin(theta_seq), lwd = 2)
plot(res_disk_vis$x, res_disk_vis$y, asp = 1, pch = 20,
     col = ifelse(res_disk_vis$hit, "steelblue", "tomato"), xlab = "x", ylab = "y",
     xlim = xlim, ylim = ylim, main = paste(sum(res_disk_vis$hit), "of 1500 hit A (disk)"))
lines(r1 * cos(theta_seq), r1 * sin(theta_seq), lwd = 2)
lines(d + r2 * cos(theta_seq), r2 * sin(theta_seq), lwd = 2)
par(mfrow = c(1, 1))

Figure 3

Blue darts land in A (weight |B|), red darts miss (weight 0).

Numerical Example (Continued): Results

Code
n <- 5000
res_box  <- crescent_is("box",  n, seed = 1)
res_disk <- crescent_is("disk", n, seed = 1)
knitr::kable(data.frame(
    proposal = c("Bounding box (naive)", "Disk $D_1$ (importance)"),
    truth    = rep(area_true, 2),
    estimate = c(res_box$estimate, res_disk$estimate),
    ME       = c(res_box$me, res_disk$me),
    ess_pct  = 100 * c(res_box$ess, res_disk$ess) / n
), digits = 4, col.names = c("Proposal $g$", "True area", "Estimate", "M.E.", "ESS %"))
Table 1
Proposal g True area Estimate M.E. ESS %
Bounding box (naive) 0.8984 0.9056 0.1025 5.66
Disk D_1 (importance) 0.8984 0.8891 0.0392 28.30
  • Both proposals are unbiased: importance sampling never needs A’s shape, only a B that covers it.
  • The ESS % is the hit rate \approx p=|A|/|B|, exactly as the general formula predicts: about 5.6% for the box and 28.6% for D_1.
  • The relative variance (1-p)/(np) is about 6.7 times smaller for the disk, so the margin of error drops by \sqrt{6.7}\approx2.6 (0.103 vs 0.039). A box that is too generous costs precision, not correctness.

Example 1 (Continued): What If B\subset A?

The proposal is too small: f(\theta)=I_A(\theta), g(\theta)=I_B(\theta) with B\subset A, so g(\theta)=0 on A\setminus B. Every draw \theta_i\sim\mathrm{Unif}(B) lies in A: \begin{aligned} &w_i = \frac{I_A(\theta_i)}{I_B(\theta_i)} = 1, && \frac1n\sum_{i=1}^n w_i = 1 = E_g[w(\theta)] \;\ne\; \frac{C_f}{C_g} = \frac{|A|}{|B|}; \\[2pt] &\widehat{C_f} = |B|\cdot\frac1n\sum_{i=1}^n w_i = |B|, && \text{biased: } |B| < |A| = C_f; \\[2pt] &w^\star(\theta) = \frac{I_A(\theta)/|A|}{I_B(\theta)/|B|} = \frac{|B|}{|A|} \text{ on } B, && E_g[w^\star(\theta)] = \frac{|B|}{|A|} < 1; \\[2pt] &\hat w^\star_i = \frac{w_i}{\frac1n\sum_j w_j} = 1, && \widehat{n_{\text{eff}}} = \frac{\left(\sum_i w_i\right)^2}{\sum_i w_i^2} = \frac{n^2}{n} = n. \end{aligned}

  • Zero variance and a perfect \widehat{n_{\text{eff}}}=n: nothing computed from the draws reveals the bias.
  • E_g[w^\star]<1 would, but \hat w^\star_i averages to 1 by construction. Ensure support by design.

Example 1 (Continued): Picture of B\subset A

Figure 4

The draws fill B evenly and every weight is 1, so the sample looks perfect, yet the red region A\setminus B contributes nothing: \widehat{C_f}=|B|, not |A|.

4. Example 2: Tail Probability of a Student-t Distribution

Example 2: Tail Probability of a Student-t Distribution

The target is a standard Student-t_\nu: \nu=1 is the Cauchy, \nu\to\infty recovers the normal — \nu is a tuning parameter of the target’s tail weight. Goal: P(c_1<X<c_2) for a finite interval (c_1,c_2), from a truncated-normal proposal sampled by adaptive rejection sampling (ARS).

\log\varphi is concave, and restricting to (c_1,c_2) preserves concavity, so the ars package applies directly to the proposal.

Code
rtnorm_ars <- function(n, mu = 0, sigma = 1, lo = 0, hi = Inf) {
    logf   <- function(x) dnorm(x, mu, sigma, log = TRUE)
    fprima <- function(x) -(x - mu) / sigma^2
    if (is.finite(hi)) {
        x0 <- lo + (hi - lo) * c(0.1, 0.5, 0.9)
    } else {
        right <- max(mu, lo) + 3 * sigma
        x0 <- sort(unique(c(lo + 0.1 * sigma, max(lo + 0.2 * sigma, mu + 1e-6), right)))
    }
    ars(n, f = logf, fprima = fprima, x = x0,
        lb = TRUE, xlb = lo, ub = is.finite(hi), xub = if (is.finite(hi)) hi else 0)
}

The target \log f_{t_\nu} is not concave at any finite \nu — convex out in the tails, concave everywhere only in the \nu\to\infty limit — so ARS cannot sample it directly. The truncated-normal proposal is a substitute, which is exactly why the sample needs importance weights.

Example 2 (Continued): The Estimator

Target and proposal, both unnormalized — the t_\nu and N(\mu,\sigma^2) densities cut off outside (c_1,c_2): f(x) = \begin{cases} f_{t_\nu}(x), & c_1<x<c_2,\\ 0, & \text{otherwise,}\end{cases} \qquad g(x) = \begin{cases} \dfrac{1}{\sigma\sqrt{2\pi}}\,e^{-(x-\mu)^2/(2\sigma^2)}, & c_1<x<c_2,\\ 0, & \text{otherwise,}\end{cases} with normalizing constants (C_g is known): C_f = \int f(x)\,dx = P(c_1<X<c_2), \qquad C_g = \int g(x)\,dx = \Phi\!\left(\tfrac{c_2-\mu}{\sigma}\right)-\Phi\!\left(\tfrac{c_1-\mu}{\sigma}\right). Draw X_1,\ldots,X_{n}\sim g(x)/C_g (the truncated normal), weight by w(x)=f(x)/g(x), and scale by C_g: \widehat{C_f} = C_g\cdot\frac1n\sum_{i=1}^n w(X_i), unbiased for C_f for any g(x) positive wherever f(x) is — regardless of c_1,c_2,\mu,\sigma,\nu.

Example 2 (Continued): The Picture

Figure 5

Here \nu=1 (Cauchy), \mu=0, \sigma=1. The shaded areas are C_f (red) and C_g (blue); outside (c_1,c_2) both are cut off (dotted). Green: 10 draws from g(x)/C_g and their weights w(x) — draws are dense near c_1 where g is high and get small weights there; the rare draws on the right carry large weights.

Example 2 (Continued): is_t_interval()

Code
is_t_interval <- function(n, df, c1, c2, mu, sigma, seed = NULL) {
    if (!is.null(seed)) set.seed(seed)
    X <- rtnorm_ars(n, mu, sigma, c1, c2)

    Cg   <- pnorm(c2, mu, sigma) - pnorm(c1, mu, sigma)    # known C_g
    logw <- dt(X, df, log = TRUE) - dnorm(X, mu, sigma, log = TRUE)   # f/g, unnormalized g

    m    <- max(logw); v <- exp(logw - m)
    Chat <- Cg * mean(v) * exp(m); se <- Cg * sd(v) / sqrt(n) * exp(m)
    wn   <- v / mean(v)                                    # hat w*_i, mean 1

    list(X = X, wn = wn, Chat = Chat, se = se, ess = n / mean(wn^2),
         truth = pt(c2, df) - pt(c1, df))
}
Code
settings <- data.frame(df = c(1, 10, 1, 10), c1 = c(1, 1, -1, -1), c2 = c(3, 3, 2, 2))
res <- lapply(seq_len(nrow(settings)), function(i) with(settings[i, ],
    is_t_interval(n = 5000, df = df, c1 = c1, c2 = c2, mu = 0, sigma = 1, seed = 1)))

knitr::kable(data.frame(
    df = settings$df, c1 = settings$c1,
    c2 = settings$c2,
    truth = sapply(res, `[[`, "truth"), estimate = sapply(res, `[[`, "Chat"),
    se = sapply(res, `[[`, "se"), ess_pct = 100 * sapply(res, `[[`, "ess") / 5000
), digits = 4, col.names = c("df", "c1", "c2", "truth", "estimate", "s.e.", "ESS %"))
Table 2
df c1 c2 truth estimate s.e. ESS %
1 1 3 0.1476 0.1490 0.0014 68.7656
10 1 3 0.1638 0.1642 0.0004 96.8918
1 -1 2 0.6024 0.6025 0.0008 99.1570
10 -1 2 0.7929 0.7930 0.0002 99.9562

Every estimate is within a couple of standard errors of the truth, at heavy (\nu=1) and light (\nu=10) tails alike.

Example 2 (Continued):Observations

  • Default settings: raising n improves the estimate at the usual 1/\sqrt n rate, and the 95% interval covers about as often as claimed

  • Small \sigma, or \mu far outside (c_1,c_2): draws pile up wherever the proposal has mass, weights nearly equal, n_{\text{eff}} stays high, estimate can still miss badly

  • Large \sigma: one draw’s weight can dominate, n_{\text{eff}} collapses toward 1 — visibly unreliable, an improvement on invisibly unreliable

5. Example 3: Same Support, but a Mode Is Missed

Example 3: Same Support, but a Mode Is Missed,

f(\theta) = \tfrac12\varphi(\theta+d) + \tfrac12\varphi(\theta-d), \qquad g_{\sigma}(\theta) = \tfrac{1}{\sigma}\varphi\!\left(\tfrac{\theta+d}{\sigma}\right), \qquad d = 5.

Both are positive on all of \mathbb{R}, so the support requirement holds. But for \sigma of order one the proposal concentrates around -d and never produces draws near the second mode at +d.

For \theta near -d and \sigma=1, w(\theta) = \tfrac12 + \tfrac12\,\frac{\varphi(\theta-d)}{\varphi(\theta+d)} = \tfrac12 + \tfrac12 e^{2d\theta} \;\approx\; \tfrac12,

so every observed weight is nearly equal, \hat w^\star_i\approx1 and n_{\text{eff}}\approx n, while \widehat{C_f/C_g}\approx\tfrac12 (truth 1) and \hat E_f(\theta)\approx-d (truth 0). The draws that would expose the error carry w(\theta)\approx\tfrac12e^{2d\theta}\gg1 near \theta=+d and have probability \Phi(-2d)\approx10^{-23} under g_1: they never appear.

Example 3 (Continued): The Figure

Figure 6

The observed effective sample size reports near-perfect efficiency. The exact effective fraction 1/E_g(w(\theta)^2) is smaller by forty orders of magnitude — a property of f(\theta),g(\theta) alone, invisible to any single sample. The variance is finite at \sigma=1 (it diverges only for \sigma\le1/\sqrt2), so the estimator is consistent — it would just need n\sim10^{43} to look normal.

6. Example 4: Marginal Likelihood via Importance Sampling

Example 4: Marginal Likelihood via Importance Sampling

Data y_1,\ldots,y_m\sim N(\mu,\sigma^2), \theta=(\mu,w) with w=\log\sigma^2, independent normal priors. The target is prior \times likelihood, with C_f=P(y), the marginal likelihood: f(\mu,w) = N(\mu\mid\mu_0,\sigma_\mu^2)\;N(w\mid w_0,\sigma_w^2)\;\prod_{k=1}^m N\big(y_k\mid\mu,\,e^{w}\big). The proposal is the Gaussian (Laplace) approximation at the mode (\hat\mu,\hat w) of f, with H = -\nabla^2\log f(\hat\mu,\hat w): g(\mu,w) = N_2\big((\mu,w)\,\big|\,(\hat\mu,\hat w),\,H^{-1}\big). Since C_g=1, \;\widehat{P(y)} = \frac1n\sum_{i=1}^n f(\theta_i)/g(\theta_i) with \theta_i\sim g(\theta). Contrast: the prior as proposal, g(\theta)=\pi(\theta), gives weights L(\theta_i).

Example 4 (Continued): The Contours of f and g

Figure 7

With m=5 observations the posterior is skewed in w=\log\sigma^2 (long upper tail), so its contours are not the ellipses of the quadratic approximation g(\theta). The weights f/g correct for that difference; as m grows, f becomes more Gaussian and g fits better.

Example 4 (Continued): Implementation

log_lik   <- function(x, mu, w) sum(dnorm(x, mu, exp(w / 2), log = TRUE))
log_prior <- function(mu, w, mu_0, sigma_mu, w_0, sigma_w) {
    dnorm(mu, mu_0, sigma_mu, log = TRUE) + dnorm(w, w_0, sigma_w, log = TRUE)
}
neg_log_post <- function(theta, x, mu_0, sigma_mu, w_0, sigma_w) {
    -log_lik(x, theta[1], theta[2]) -
        log_prior(theta[1], theta[2], mu_0, sigma_mu, w_0, sigma_w)
}
log_dmvnorm_batch <- function(Theta, mu, A) {           # log N(mu, A^-1) at every column at once
    Tc <- Theta - mu
    quad <- colSums((A %*% Tc) * Tc)
    0.5 * (-nrow(Theta) * log(2 * pi) + sum(log(svd(A)$d)) - quad)
}
log_marlik_imps <- function(x, mu_0, sigma_mu, w_0, sigma_w, n) {
    fit <- nlm(neg_log_post, c(mean(x), log(stats::var(x))), hessian = TRUE,
               x = x, mu_0 = mu_0, sigma_mu = sigma_mu, w_0 = w_0, sigma_w = sigma_w)
    mu_hat <- fit$estimate; H <- fit$hessian
    L <- t(chol(solve(H)))
    Theta <- L %*% matrix(rnorm(2 * n), 2, n) + mu_hat
    log_g <- log_dmvnorm_batch(Theta, mu_hat, H)
    log_f <- -apply(Theta, 2, neg_log_post, x = x, mu_0 = mu_0, sigma_mu = sigma_mu,
                     w_0 = w_0, sigma_w = sigma_w)
    lw <- log_f - log_g
    m  <- max(lw); v <- exp(lw - m)
    structure(log_sum_exp(lw) - log(n), ess = log_ess(lw), se = sd(v) / (sqrt(n) * mean(v)))
}

Example 4 (Continued): Implementation (2)

log_marlik_prior <- function(x, mu_0, sigma_mu, w_0, sigma_w, n) {
    mus <- rnorm(n, mu_0, sigma_mu); ws <- rnorm(n, w_0, sigma_w)
    lw <- vapply(seq_len(n), function(i) log_lik(x, mus[i], ws[i]), numeric(1))
    m  <- max(lw); v <- exp(lw - m)
    structure(log_sum_exp(lw) - log(n), ess = log_ess(lw), se = sd(v) / (sqrt(n) * mean(v)))
}
log_marlik_grid <- function(x, mu_0, sigma_mu, w_0, sigma_w, n_grid = 400, width = 8) {
    n   <- length(x)
    fit <- nlm(neg_log_post, c(mean(x), log(stats::var(x))), hessian = TRUE,
               x = x, mu_0 = mu_0, sigma_mu = sigma_mu, w_0 = w_0, sigma_w = sigma_w)
    se  <- sqrt(diag(solve(fit$hessian)))
    mu_grid <- fit$estimate[1] + seq(-width, width, length.out = n_grid) * se[1]
    w_grid  <- fit$estimate[2] + seq(-width, width, length.out = n_grid) * se[2]
    SS <- sum(x^2) - 2 * mu_grid * sum(x) + n * mu_grid^2
    log_lik_grid   <- outer(SS, w_grid,
                             function(ss, w) -0.5 * n * log(2 * pi) - n * w / 2 - 0.5 * exp(-w) * ss)
    log_prior_grid <- outer(dnorm(mu_grid, mu_0, sigma_mu, log = TRUE),
                             dnorm(w_grid, w_0, sigma_w, log = TRUE), "+")
    h_mu <- diff(mu_grid[1:2]); h_w <- diff(w_grid[1:2])
    log_sum_exp(as.vector(log_lik_grid + log_prior_grid)) + log(h_mu) + log(h_w)
}

log_marlik_grid() supplies ground truth by quadrature — a midpoint grid centred and scaled by the Laplace fit, vectorized via the sufficient statistic \sum(x-\mu)^2.

Example 4 (Continued): Results Across Sample Sizes

Code
set.seed(4)
ms <- c(5, 20, 100, 400); n <- 2000

summarize_is <- function(fn, x, n) {
    est <- fn(x, 0, 5, 0, 5, n); se <- attr(est, "se")
    c(estimate = sprintf("%.2f", as.numeric(est)),
      ci       = sprintf("(%.2f, %.2f)", as.numeric(est) - 1.96 * se, as.numeric(est) + 1.96 * se),
      ess      = sprintf("%.1f", 100 * attr(est, "ess") / n))
}
merged_tbl <- do.call(rbind, lapply(ms, function(m) {
    x   <- rnorm(m)
    lap <- summarize_is(log_marlik_imps,  x, n)
    pri <- summarize_is(log_marlik_prior, x, n)
    data.frame(m = m, truth = sprintf("%.2f", log_marlik_grid(x, 0, 5, 0, 5)),
               lap_estimate = lap[["estimate"]], lap_ci = lap[["ci"]], lap_ess = lap[["ess"]],
               pri_estimate = pri[["estimate"]], pri_ci = pri[["ci"]], pri_ess = pri[["ess"]],
               row.names = NULL)
}))
names(merged_tbl) <- c("m", "truth", "Laplace: est.", "Laplace: 95% CI", "Laplace: ESS %",
                       "prior: est.", "prior: 95% CI", "prior: ESS %")
knitr::kable(merged_tbl, align = "r")
Table 3
m truth Laplace: est. Laplace: 95% CI Laplace: ESS % prior: est. prior: 95% CI prior: ESS %
5 -10.09 -10.16 (-10.21, -10.11) 43.3 -10.00 (-10.31, -9.69) 1.9
20 -37.29 -37.31 (-37.33, -37.29) 84.9 -36.86 (-37.32, -36.40) 0.9
100 -153.02 -153.01 (-153.02, -153.01) 96.3 -153.94 (-155.12, -152.76) 0.1
400 -531.18 -531.18 (-531.18, -531.18) 99.2 -534.74 (-536.43, -533.05) 0.1

Laplace-shaped: tight interval centred on truth at every m, n_{\text{eff}} near nominal. Prior sampling degrades monotonically as the posterior concentrates at rate m^{-1/2} while the prior stays put — n_{\text{eff}} falls to a fraction of one percent, and its (still sometimes-covering) interval is only as trustworthy as those few dominant draws.

7. Advanced Applications of Importance Sampling

Free Energy and the Marginal Likelihood

A system with energy U(x) at inverse temperature \beta has normalizing constant (partition function) and free energy Z(\beta) = \int e^{-\beta U(x)}\,dx, \qquad F(\beta) = -\frac1\beta\log Z(\beta). Importance sampling with g(x)=e^{-\beta_0U(x)}, f(x)=e^{-\beta_1U(x)}, w(x)=e^{-(\beta_1-\beta_0)U(x)} gives \frac{Z(\beta_1)}{Z(\beta_0)} = E_{\beta_0}\Big[e^{-(\beta_1-\beta_0)U(x)}\Big]. Bayesian analogue: U(\theta)=-\log L(\theta), g(\theta)=\pi(\theta) (\beta_0=0), f(\theta)=L(\theta)\pi(\theta) (\beta_1=1): P(y) = \frac{C_f}{C_g} = E_\pi\big[L(\theta)\big] \approx \frac1n\sum_{i=1}^n L(\theta_i), \qquad \theta_i\sim\pi(\theta). One jump from prior to posterior is the “prior sampling” of Example 4: almost all prior draws get negligible weight.

Stepping Stones: Many Small Jumps Instead of One Big One

Chain temperatures 0=\beta_0<\beta_1<\cdots<\beta_K=1 and estimate each factor by importance sampling from \beta_{k-1} to \beta_k: \frac{Z(1)}{Z(0)} = \prod_{k=1}^K \frac{Z(\beta_k)}{Z(\beta_{k-1})}.

Figure 8

Bayesian Leave-One-Out Cross-Validation

Goal: the leave-one-out predictive density p(y_j\mid y_{-j}) = \int p(y_j\mid\theta)\,p(\theta\mid y_{-j})\,d\theta for every j, without refitting the model once per observation.

With prior \pi(\theta) and independent observations y_1,\ldots,y_m, both posteriors are prior \times likelihood (unnormalized):

  • Target, the posterior without y_j: \;f(\theta) = \pi(\theta)\prod_{k\ne j} p(y_k\mid\theta).
  • Proposal, the full posterior, whose draws \theta_1,\ldots,\theta_n we already have: \;g(\theta) = \pi(\theta)\prod_{k=1}^{m} p(y_k\mid\theta).
  • Weight: w_j(\theta) = \frac{f(\theta)}{g(\theta)} = \frac{\pi(\theta)\prod_{k\ne j} p(y_k\mid\theta)}{\pi(\theta)\prod_{k=1}^{m} p(y_k\mid\theta)} = \frac{1}{p(y_j\mid\theta)}, so the estimate is a harmonic mean of the likelihood of y_j over the full-posterior draws: \hat p(y_j\mid y_{-j}) = \frac{\sum_i p(y_j\mid\theta_i)\,w_j(\theta_i)}{\sum_i w_j(\theta_i)} = \frac{n}{\sum_{i=1}^n 1/p(y_j\mid\theta_i)}.

Summary (1/2)

  • Importance sampling reweights draws from a proposal g(\theta) by w(\theta)=f(\theta)/g(\theta) instead of accepting/rejecting them: \widehat{C_f/C_g} = \frac1n\sum_i w_i, \qquad \hat A = \frac1n\sum_i a(\theta_i)\,\hat w^\star_i, \quad \hat w^\star_i = \frac{w_i}{\frac1n\sum_j w_j}, only the support condition \{\theta: g(\theta)>0\}\supseteq\{\theta: f(\theta)>0\} is required, not an envelope g(\theta)\ge f(\theta)

  • A good proposal shaped like the target on its support gives near-constant weights and n_{\text{eff}}\approx n (Examples 2 and 3), and a single weighted sample can answer several questions about the same target

Summary (2/2)

  • A proposal that misses a mode or part of the support fails silently (Example 3): observed weights look healthy while the estimate is badly wrong, and no amount of extra sampling fixes it — n_{\text{eff}} diagnoses only the noisy failure, never the silent one

  • The marginal likelihood: a Laplace-shaped proposal stays efficient as data accumulate and the posterior sharpens; the prior does not

  • Advanced uses: normalizing-constant ratios (free energy, marginal likelihood) via tempering/stepping-stones; leave-one-out cross-validation from full-posterior draws with w_j(\theta)=1/p(y_j\mid\theta)