Densities and importance sampling

Julia Fukuyama

Simulation-Based Inference ยท Lecture 16

Today

Cumulative distribution functions, probability mass functions, probability density functions.

Importance sampling.

Review

So far, we have said:

  • Probability distributions in some way describe the chance a random variable falls in various intervals
  • For a discrete distribution (finite or countable number of possible outcomes), we can describe a distribution using the probability of value individually.

Today, we generalize to distributions for random variables that can take any value in a continuous range.

Recall: Probability mass function for the discrete case

For a discrete variable \(X\), its probability mass function (PMF) is

\[ p(x)=P(X=x). \]

For a fair die, \(p(1)=\cdots=p(6)=1/6\). We add masses to find the probability of a set:

\[ P(X\in\{2,3\})=p(2)+p(3)=2/6. \]

Each possible value can carry positive probability, and the sum of the probabilities of all possible outcomes adds to 1.

Cumulative distribution functions

Every real-valued random variable \(X\) has a cumulative distribution function, or CDF:

\[ F(x)=P(X\leq x). \]

A function \(F\) is the CDF of a random variable if and only if:

  • \(F\) is nondecreasing.
  • \(F(x)\to 0\) as \(x\to-\infty\) and \(F(x)\to 1\) as \(x\to\infty\).
  • \(F\) is right-continuous: approaching \(x\) from above, \(F(x+h)\to F(x)\) as \(h\downarrow 0\).

Thus, we can either calculate a CDF from a known distribution or choose a valid CDF to specify a distribution.

Two ways to use a CDF

Start with probabilities and calculate the CDF.

For a discrete random variable with PMF \(p\),

\[ F(x)=\sum_{t\leq x}p(t). \]

Start with a valid CDF and calculate probabilities.

For any \(a<b\),

\[ P(a<X\leq b)=F(b)-F(a). \]

This second approach works even when we cannot describe the distribution by assigning probabilities to individual values.

Example: The CDF of a fair die

Let \(X\) be the result of rolling a fair six-sided die.

The CDF adds the probabilities of all outcomes at or below the threshold:

\[ F(3)=P(X\leq 3)=p(1)+p(2)+p(3)=\frac{3}{6}. \]

The threshold does not have to be a possible outcome:

\[ F(3.5)=P(X\leq 3.5)=P(X\in\{1,2,3\})=\frac{3}{6}. \]

There are no possible outcomes between 3 and 4, so the CDF stays constant between those values.

The fair-die CDF: a step function that jumps by 1/6 at each of 1 through 6. Closed dots mark the value at each jump.

The CDF jumps at each possible outcome.

The size of the jump is the probability of that outcome.

Recovering interval probabilities

\(F(b)\) gives the probability for all outcomes at or below \(b\).

Subtracting \(F(a)\) removes the probability for those at or below \(a\).

Therefore, for \(a<b\),

\[ P(a<X\leq b)=F(b)-F(a). \]

For the die,

\[ P(2<X\leq 4)=F(4)-F(2)=\frac{4}{6}-\frac{2}{6} =\frac{2}{6}. \]

These are the outcomes 3 and 4.

The same subtraction rule works for continuous random variables.

Small-interval probabilities for continuous random variables

To understand how concentrated the probability is near a value \(x\), we can examine a small interval around it:

\[ P(x-\epsilon<X\leq x+\epsilon) = F(x+\epsilon)-F(x-\epsilon). \]

Probability density function: motivation

The idea of the probability that a draw from a random variable lands in a little window around the value \(x\) is useful enough that we formalize it.

The probability in a window depends on its width. To measure concentration near \(x\), divide by the width and let the window shrink:

\[ \lim_{\epsilon\to0^+} \frac{P(x-\epsilon<X\leq x+\epsilon)}{2\epsilon} = \lim_{\epsilon\to0^+} \frac{F(x+\epsilon)-F(x-\epsilon)}{2\epsilon} = F'(x). \]

Probability density function: definition

For a distribution with a continuously differentiable CDF, we define its probability density function (PDF) by

\[ f(x)=F'(x). \]

The density describes probability per unit width near \(x\), without choosing a particular window size.

For a small \(\epsilon\),

\[ P(x-\epsilon<X\leq x+\epsilon)\approx 2\epsilon f(x). \]

Example: Uniform distribution

Suppose \(X\sim\operatorname{Uniform}(0,1)\).

Within \([0,1]\), the probability below a threshold is the threshold itself:

\[ F(x)=x,\qquad 0\leq x\leq 1. \]

The CDF has constant slope 1 inside this interval, so

\[ f(x)=1,\qquad 0<x<1. \]

Outside \([0,1]\), the CDF is constant and the density is zero.

Uniform(0, 1) CDF and PDF with the intervals from 0.2 to 0.3 and from 0.7 to 0.8 highlighted.

Both intervals have probability 0.1: equal widths give equal increases in the CDF and equal areas under the PDF.

Example: Normal distribution

Suppose \(X\sim N(0,1)\).

Standard normal CDF and PDF, with -2, 0, and 2 marked.

The CDF increases most rapidly near 0, where the density is highest.

In either tail, the CDF changes slowly and the density is low.

The CDF keeps increasing even after the density starts decreasing: we are still accumulating probability, but at a slower rate.

Normal example: Comparing small windows

Consider windows of the same width around \(-2\), \(0\), and \(2\).

Windows of width 0.2 at -2, 0, and 2. The CDF rises by about 0.011, 0.080, and 0.011 across them; these are the shaded areas under the PDF.

For each window,

\[ P(x-0.1<X\leq x+0.1) = F(x+0.1)-F(x-0.1) \approx 0.2f(x). \]

The central window contains more probability than either tail window.

Example: A mixture of two normals

Generate \(X\) in two steps:

  1. Choose one of two groups, each with probability \(1/2\).
  2. If you chose the first group, draw \(X\sim N(-2,1)\). If you chose the second, draw \(X\sim N(2,1)\).

CDF and PDF of the equal mixture of N(-2, 1) and N(2, 1).

Probability is concentrated near two different locations.

The CDF increases rapidly near each concentration and more slowly in the region between them.

Mixtures: Combining the two distributions

Let \(F_1\) and \(F_2\) be the CDFs of the two groups.

To fall below a threshold \(x\), we must choose a group and then draw a value below \(x\) within that group:

\[ F(x)=\frac12F_1(x)+\frac12F_2(x). \]

Taking derivatives gives the mixture density:

\[ f(x)=\frac12f_1(x)+\frac12f_2(x). \]

The two component densities, each multiplied by 1/2, and their sum.

Building a distribution from a density

In the same way that we can specify random variables directly via their CDFs, we can also specify random variables by their pdfs.

Choose a nonnegative function \(g(x)\) whose total area is finite and greater than zero:

\[ 0<Z=\int_{-\infty}^{\infty}g(x)\,dx<\infty. \]

Dividing by the total area gives a probability density function:

\[ f(x)=\frac{g(x)}{Z}. \]

This is called normalizing the function. It preserves the shape and makes the total area equal to 1.

Recall: Joint distributions for discrete random variables

For two discrete random variables, the joint PMF assigns a probability to each pair of possible values:

\[ p(x,y)=P(X=x,\ Y=y). \]

Suppose \(X\) and \(Y\) indicate rain on two consecutive days, with 1 meaning rain and 0 meaning no rain.

\(Y=0\) \(Y=1\)
\(X=0\) 0.4 0.1
\(X=1\) 0.1 0.4

The entries are nonnegative and sum to 1.

To find the probability of an event, add the entries for the pairs that belong to it. For example,

\[ P(X=Y)=p(0,0)+p(1,1)=0.8. \]

Densities for continuous random vectors

Suppose our outcome is a pair \((X,Y)\), where \(X\) and \(Y\) are both continuous.

A joint probability density function \(f(x,y)\) describes probability per unit area near \((x,y)\).

For a small rectangle centered at \((x,y)\), with side lengths \(\Delta x\) and \(\Delta y\),

\[ P\left( x-\frac{\Delta x}{2}<X\leq x+\frac{\Delta x}{2},\ y-\frac{\Delta y}{2}<Y\leq y+\frac{\Delta y}{2} \right) \approx f(x,y)\,\Delta x\,\Delta y. \]

At a point where the density is continuous, dividing the rectangleโ€™s probability by its area and shrinking the rectangle gives \(f(x,y)\).

Heatmap of a joint density with two bumps, with equal-area squares in a high-density and a low-density region.

Equal-area rectangles can have different probabilities: the density tells us how concentrated the probability is locally.

Higher dimensions

The same idea extends to a random vector \(\mathbf X=(X_1,\ldots,X_d)\).

Outcome Small neighborhood Approximate probability
One number Interval of width \(\Delta x\) \(f(x)\,\Delta x\)
Two numbers Rectangle of area \(\Delta x\,\Delta y\) \(f(x,y)\,\Delta x\,\Delta y\)
\(d\) numbers Box of volume \(V\) \(f(\mathbf x)\,V\)

A density describes probability per unit volume near a point.

For example, if \((X,Y)\) is uniform on the unit square, its density is 1 inside the square. A rectangle inside it with side lengths 0.1 and 0.2 has probability

\[ 1\times 0.1\times 0.2=0.02. \]

For a pair of unknown parameters, the joint density describes which combinations of parameter values are plausible.

Example: A bivariate normal distribution

A bivariate normal distribution describes a pair of continuous random variables \((X,Y)\).

Heatmap of a bivariate normal density with correlation 0.6.

The joint density describes which pairs of values are likely to occur together.

Interpreting the joint density

The same bivariate normal density, with equal-area squares at the center and in a low-density region.

For a small rectangle near \((x,y)\),

\[ P((X,Y)\text{ falls in the rectangle}) \approx f(x,y)\times\text{area of the rectangle}. \]

The rectangle near the center has higher probability because the density there is higher.

Importance sampling: motivation

Suppose we want to study a distribution with density \(p\).

We can evaluate \(p(x)\), or a function proportional to it, but we do not have a convenient way to draw samples from it.

If we have another distribution with density \(q\) that we can easily draw samples from, importance sampling tells us how to โ€œcorrectโ€ draws from \(q\) so that thep represent \(p\).

Importance sampling: algorithm

Let \(p\) be the target density and \(q\) the proposal density such that \(q > 0\) whenever \(p > 0\)

  1. Draw \(X_1,\ldots,X_N\) independently from \(q\).

  2. Calculate an importance weight for each draw: \[ w_i=\frac{p(X_i)}{q(X_i)}. \]

  3. Normalize the weights so they sum to 1: \[ W_i=\frac{w_i}{\sum_{j=1}^N w_j}. \]

Then (Theorem): If \(E_p[|g(X)|]<\infty\), then, as \(N\to\infty\),

\[ \sum_{i=1}^N W_i g(X_i) \longrightarrow E_p[g(X)] \qquad\text{almost surely}. \]

Notes

The points \(X_i\), with probability weights \(W_i\), approximate the target distribution.

We can replace \(p\) by a function proportional to it, which is called self-normalized importance sampling.

Requirement: \(q\) must assign positive density wherever \(p\) does, apart from sets of probability zero.

Why the density ratio?

Consider a small neighborhood \((x-\epsilon,x+\epsilon]\).

Under the target, its probability is approximately \(2\epsilon p(x)\). Under the proposal, its probability is approximately \(2\epsilon q(x)\).

The ratio is

\[ \frac{\text{probability we want in this neighborhood}} {\text{probability of drawing from this neighborhood}} \approx \frac{2\epsilon p(x)}{2\epsilon q(x)} = \frac{p(x)}{q(x)}. \]

This tells us how to weight draws near \(x\):

  • If \(q(x)=2p(x)\), we draw from this neighborhood about twice as often as we want. Each draw receives weight \(1/2\).
  • If \(q(x)=p(x)/2\), we draw from it about half as often as we want. Each draw receives weight \(2\).

The weights correct how much each neighborhood contributes. Normalizing makes the total weight equal to 1.

What if we only know the target up to a constant?

Suppose we can evaluate

\[ \widetilde p(x)=c\,p(x), \]

but do not know the positive constant \(c\).

Using \(\widetilde p\) gives normalized weights

\[ W_i = \frac{c\,p(X_i)/q(X_i)} {\sum_j c\,p(X_j)/q(X_j)} = \frac{p(X_i)/q(X_i)} {\sum_j p(X_j)/q(X_j)}. \]

The constant cancels.

We need the targetโ€™s relative density heights, not its normalizing constant.

Using the weighted sample

The weighted sample is analogous to a standard, unweighted sample from a distribution.

You can use the weighted sample to estimate set probabilities, means, draw histograms, you just have to incorporate the weights.

Estimating set probabilities

With an unweighted sample from the target, estimate \(P(X\in A)\) by the fraction of points in \(A\):

\[ \widehat P(X\in A) = \frac{\text{number of points in }A}{N} = \sum_{i:X_i\in A}\frac{1}{N}. \]

With a weighted sample, add the weights of the points in \(A\):

\[ \widehat P(X\in A) = \sum_{i:X_i\in A}W_i. \]

Each point in the set contributes its share of the total probability.

Estimating means

With an unweighted sample from the target, estimate \(E[X]\) by the sample mean:

\[ \widehat E[X] = \frac{1}{N}\sum_{i=1}^N X_i = \sum_{i=1}^N\frac{1}{N}X_i. \]

With a weighted sample, use a weighted mean:

\[ \widehat E[X] = \sum_{i=1}^N W_iX_i. \]

The same idea estimates the average of any function \(g(X)\): replace \(X_i\) by \(g(X_i)\).

Drawing histograms

A density histogram represents the probability in each bin by the area of its bar.

For a bin \(B\) of width \(h\):

Estimated probability in the bin Bar height
Unweighted sample \(\displaystyle \frac{\#\{i:X_i\in B\}}{N}\) \(\displaystyle \frac{\#\{i:X_i\in B\}}{Nh}\)
Weighted sample \(\displaystyle \sum_{i:X_i\in B}W_i\) \(\displaystyle \frac{1}{h}\sum_{i:X_i\in B}W_i\)

The same 1,500 points shown as an unweighted and a weighted density histogram, with identical bins and axes.

The points remain in the same bins. Weighting changes how much each point contributes to its bar.

Importance sampling example 1

Suppose we want a distribution on \([0,1]\) with density proportional to

\[ \widetilde p(x)=1+\sin^2(3\pi x). \]

The density is zero outside \([0,1]\).

To obtain a PDF, we would divide by the total area:

\[ p(x)=\frac{\widetilde p(x)}{Z}, \qquad Z=\int_0^1\widetilde p(x)\,dx. \]

The unnormalized density 1 + sinยฒ(3ฯ€x) on [0, 1]: three broad peaks of height 2.

Choose an easy proposal

Use a uniform proposal:

\[ q:\ \operatorname{Uniform}(0,1). \]

Its density is \(q(x)=1\) throughout the targetโ€™s range.

Draw \(X_1,\ldots,X_N\) independently from this proposal.

R

p_tilde <- function(x) {
  ifelse(x >= 0 & x <= 1,
         1 + sin(3 * pi * x)^2,
         0)
}

set.seed(681)
N <- 2000
x <- runif(N)  # proposal draws

Python

import numpy as np
rng = np.random.default_rng(681)

def p_tilde(x):
    inside = (x >= 0) & (x <= 1)
    return np.where(inside,
        1 + np.sin(3*np.pi*x)**2, 0)

N = 2000
x = rng.uniform(0, 1, N)

Density histogram of the 2,000 uniform proposal draws.

These draws cover the interval, but give equal weight to regions where the target has different densities.

Calculate the weights

Using the unnormalized target, each draw receives weight

\[ w_i=\frac{\widetilde p(X_i)}{q(X_i)} =1+\sin^2(3\pi X_i). \]

Then normalize:

\[ W_i=\frac{w_i}{\sum_jw_j}. \]

R

w <- p_tilde(x) / dunif(x)
W <- w / sum(w)
range(w)  # between 1 and 2

Python

w = p_tilde(x) / np.ones(N)
W = w / w.sum()
print(w.min(), w.max())

Draws near the peaks receive about twice as much weight as draws near the troughs.

We did not need to calculate \(Z\).

Before and after weighting

Unweighted and weighted density histograms of the same 2,000 draws, with the normalized target density overlaid.

The unweighted histogram approximates the uniform proposal.

The weighted histogram approximates the wavy target.

The points have not moved. The peaks appear because points in those regions contribute more weight.

Estimate a probability

What is the target probability of falling between 0.4 and 0.6, around the central peak?

With the proposal draws, the unweighted fraction

\[ \frac{\#\{i:0.4<X_i<0.6\}}{N} \]

estimates the proposal probability, which is 0.2.

To estimate the target probability, add the weights instead:

\[ \widehat P_p(0.4<X<0.6) = \sum_{i:0.4<X_i<0.6}W_i. \]

R

in_A <- x > 0.4 & x < 0.6
mean(in_A)    # proposal: 0.208
sum(W[in_A])  # target:   0.242

Python

in_A = (x > 0.4) & (x < 0.6)
print(in_A.mean())    # proposal
print(W[in_A].sum())  # target

Check against the target

For this example, we can calculate the normalizing constant:

\[ Z=\frac32, \qquad p(x)=\frac23\left[1+\sin^2(3\pi x)\right], \quad 0\leq x\leq1. \]

The target probability of the central interval is approximately

\[ P_p(0.4<X<0.6)\approx 0.234. \]

Importance sampling example 2

Continue using a uniform proposal on \([0,1]\).

Now consider a target with a narrow, smooth peak:

\[ \widetilde p(x)=0.01+b(x), \]

where

\[ b(x)= \begin{cases} \left[1-\left(\dfrac{x-0.5}{0.02}\right)^2\right]^2, & |x-0.5|<0.02,\\ 0,&\text{otherwise}. \end{cases} \]

The target is zero outside \([0,1]\).

The normalized narrow-peak target (peak height about 32, background about 0.3) and the uniform proposal.

The proposal spreads draws evenly across the interval. The target puts most of its probability near the center.

Most draws receive very little weight

Since \(q(x)=1\), the importance weights are

\[ w_i=\widetilde p(X_i)=0.01+b(X_i). \]

All proposal draws receive positive weight, but draws near the center receive much more.

R

p_narrow <- function(x) {
  u <- (x - 0.5) / 0.02
  b <- ifelse(abs(u) < 1,
              (1 - u^2)^2, 0)
  ifelse(x >= 0 & x <= 1,
         0.01 + b, 0)
}

N <- 200
x <- runif(N)
w <- p_narrow(x) / dunif(x)
W <- w / sum(w)

Python

def p_narrow(x):
    u = (x - 0.5) / 0.02
    b = np.where(np.abs(u) < 1,
        (1 - u**2)**2, 0)
    inside = (x >= 0) & (x <= 1)
    return np.where(inside,
                    0.01 + b, 0)

N = 200
x = rng.uniform(0, 1, N)
w = p_narrow(x) / np.ones(N)
W = w / w.sum()

200 uniform proposal draws beneath the target curve, with dot area proportional to weight; a handful of draws inside the peak dominate.

Outside the peak, weights are 0.01. At the center, the weight is 1.01.

A few draws determine the result

The peak occupies the interval \((0.48,0.52)\), only 4% of the proposalโ€™s range.

With 200 proposal draws, we expect about eight in this interval.

Their weights depend strongly on where they land: a draw near the center contributes much more than one near the edge.

Weighted histograms near the peak from four independent runs of 200 draws, with the target density overlaid.

The approximation can change substantially between runs, even though the target and proposal stay the same.

A proposal shaped like the target

Suppose that instead of a uniform proposal, we use one that looks more like the target:

\[ q:\ 0.3\,\operatorname{Uniform}(0,1)+0.7\,\operatorname{Uniform}(0.48,0.52), \]

\[ q(x)= \begin{cases} 0.3+\dfrac{0.7}{0.04}=17.8, & 0.48<x<0.52,\\ 0.3, & \text{otherwise in } [0,1]. \end{cases} \]

The narrow-peak target and the mixture-of-uniforms proposal: a flat density of 0.3 on [0, 1] with a block of height 17.8 over the peak.

To draw from \(q\): with probability 0.7 draw from \(\operatorname{Uniform}(0.48,0.52)\), otherwise from \(\operatorname{Uniform}(0,1)\).

R

q_mix <- function(x)
  0.3 * dunif(x) +
  0.7 * dunif(x, 0.48, 0.52)

r_mix <- function(N) {
  peak <- runif(N) < 0.7
  ifelse(peak,
         runif(N, 0.48, 0.52),
         runif(N))
}

estimate_peak_mix <- function(N) {
  x <- r_mix(N)
  w <- p_narrow(x) / q_mix(x)
  W <- w / sum(w)
  sum(W[x > 0.48 & x < 0.52])
}

sd(replicate(500,
  estimate_peak_mix(200)))
# about 0.035 (uniform: 0.11)

Python

def q_mix(x):
    inside = (x >= 0) & (x <= 1)
    pk = (x > 0.48) & (x < 0.52)
    return (np.where(inside, 0.3, 0)
            + np.where(pk, 0.7 / 0.04, 0))

def r_mix(N):
    peak = rng.uniform(size=N) < 0.7
    return np.where(peak,
        rng.uniform(0.48, 0.52, N),
        rng.uniform(0, 1, N))

def estimate_peak_mix(N):
    x = r_mix(N)
    w = p_narrow(x) / q_mix(x)
    W = w / w.sum()
    pk = (x > 0.48) & (x < 0.52)
    return W[pk].sum()

est = [estimate_peak_mix(200)
       for _ in range(500)]
print(np.std(est))

200 draws from the mixture proposal beneath the target curve, with dot area proportional to weight. Left, full range: draws outside the peak have fairly large weights, and most draws are crowded into the peak. Right, zoomed on the peak: about 140 draws spread across it, with weights following the shape of the bump.

Outside the peak, weights are \(0.01/0.3\approx0.033\). Inside, they are \((0.01+b(x))/17.8\): about 0.057 at the center, falling toward 0.0006 at the edges of the peak.

Now about 140 of the 200 draws land in the peak, so no handful of draws determines the result.

Histograms of 500 estimates of P(0.48 < X < 0.52), each from 200 draws: with the uniform proposal the estimates spread from about 0.2 to 0.85; with the mixture proposal they fall between about 0.6 and 0.78. The true probability 0.694 is marked.

Top panel: Importance sampling based estimates of \(P(.48 < X < .52)\) using a uniform proposal distribution.

Bottom panel: Importance sampling based estimates of \(P(.48 < X < .52)\) using a proposal distribution that looks more like the target.

Orange line: True probability.

What makes a good proposal?

A good proposal depends on what we want to learn.

To represent the whole target distribution:

  • The proposal should visit all regions with substantial target probability, so you want \(p\) and \(q\) to be similar.

To estimate a particular expectation \(E_p[g(X)]\):

  • The proposal should give enough attention to regions that contribute strongly to that expectation (e.g.ย to estimate a rare-event probability, you want the proposal to oversample the rare-event region).

Returning to ABC

Importance sampling lets us use draws from a convenient proposal to approximate a different target distribution.

For ABC, we would like to propose parameters more often where simulations are likely to match the observations.

But we generally cannot evaluate the posterior density, even up to a constant.

Next time: combine importance weighting with the ABC acceptance step, then use one weighted population to construct the next proposal.