Monte Carlo and Importance Sampling

A neuron fires 4 spikes on one trial and 12 on the next, and a hidden drive you cannot record explains part of the gap. To score a model of it, you must average over every value that drive could take. Random samples do it, and a good proposal cuts the error 3.6 times.

Choose Importance sampling, then drag the sample count. Watch 14 independent runs close in on the green line, the true answer. Then we build, piece by piece, why the average works, how its error shrinks, and how to pick a proposal that makes it shrink faster.

You need what a probability density is (a curve whose area is 1) and what an average is. We build the rest from zero.

Based on Lecture 18 of Princeton NEU 560: Statistical Modeling and Analysis of Neural Data (Spring 2024, Jonathan Pillow), taught that day by Victor Geadah. Lecture slides. Every idea is re-taught here in our own words and devices.

Estimate the evidence

100

Illustrative toy, one hidden drive z with prior N(0, 1) and one recorded amplitude x = 3 with x given z distributed N(2z, 0.5²). The evidence p(x) = 0.0671 is known exactly, so the green line is exact. The importance proposal is N(1.4, 0.5²). The runs are real seeded random draws in your browser; the band is the exact standard error from numerical integration.

Chapter 0

Why a Hidden State Forces an Integral

See why a model with something unseen inside it must add up every value the unseen thing could take

An electrode sits in the motor cortex of a monkey that is waiting for a go cue. On every trial you count the spikes in one 100 ms bin. The cue is the same and the reach is the same, yet the counts come out as 4, 9, 6 and 12.

Some of that wobble is plain noise. But some of it comes from something you cannot record: how ready the animal was, how hard it was paying attention, how much drive the circuit was getting. You never see that quantity. You only see its footprint in the spikes.

A quantity that shapes the data but is never observed has a name. It is a latent variable, written z. The spikes you do record are the data, written x. A model built around this split is a latent variable model, and most of modern neural data analysis uses one.

Adding up over what you cannot see

Start with the simplest case. Say the hidden state z has just two values: ready with probability 0.3, and drowsy with probability 0.7. The data x is whether the bin holds a spike. When ready, a spike has probability 0.6. When drowsy, 0.1.

How likely is a spike, if you do not know the state? Take each way a spike can happen and add them up. A ready bin with a spike: 0.3 × 0.6 = 0.18. A drowsy bin with a spike: 0.7 × 0.1 = 0.07. The total is 0.25.

That step has a name: marginalization. You remove z from the picture by adding up the joint probability over every value z could take. The lecture opens with this idea and calls it essential to probabilistic modelling.

P(x)
How likely the data is, with the hidden state averaged out. The lecture calls this the marginal.
∫
A sum over a continuous range. It is the two-state sum above, with infinitely many states squeezed together.
P(x, z)
The joint probability: how likely this data and this hidden value are together. It splits into P(z) × P(x | z): first draw the state, then draw the data from it.
dz
A thin slice of z. Each slice gets its own term, and the integral adds them all.

Real hidden states are not two-valued. Attention varies smoothly, and so does the drive to a circuit. When z is continuous, the sum becomes an integral: the area under a curve, found by adding infinitely thin slices. The lecture's picture is an arrow from latents z down to data x, with a density p(z) on top and p(x | z) below. First nature picks z, then it generates x.

Why not slice the curve finely?

For one hidden number you can. Lay a grid of 10 points along z, evaluate the curve at each, and add. For two hidden numbers you need a 10 by 10 grid, which is 100 points. For three, 1,000. Each new hidden dimension multiplies the count by 10.

A real population model has tens of hidden dimensions, one for each latent factor. Ten points per axis then gives 10 to the power of the dimension, and that number leaves any computer behind. This is the curse of dimensionality: the cost of a grid grows exponentially with the number of unknowns.

There is a different way. Instead of visiting every grid point, visit a few hundred random points and average. Its cost does not multiply with each dimension. The lecture is about that idea, Monte Carlo integration, and one improvement to it, importance sampling. Drag the dimension below and compare the two bills.

Count the bill for a grid

Each bar is a number of function evaluations on a log scale: every tick to the right is ten times more. Yellow is a grid with 10 points per hidden dimension. Warm is a fixed budget of random samples. Drag the number of hidden dimensions.

3
1,000

The grid count is exact: 10 to the power d. The time line assumes an illustrative one million evaluations per second. The accuracy of a Monte Carlo estimate does not depend on d in the way a grid does, but it does depend on how spread out the function is; Chapters 3 and 5 make that precise.

At 3 dimensions the grid needs 1,000 evaluations, the same as the random budget. At 6 it needs 1,000,000. At 12 it needs a trillion, which takes about 11.6 days at a million evaluations a second. The random budget did not move.

A word on the course

This is Lecture 18 of Princeton NEU 560, Statistical Modeling and Analysis of Neural Data, from Spring 2024. Jonathan Pillow runs the course. This lecture, dated April 9, was given by Victor Geadah. Its opening slides say why it matters: marginalization is essential in latent variable models, and this lecture teaches the integration tool those models need. The slides carry no reading list, so every idea here is taught inside the chapter that needs it.

The road

  1. One shape: evidence, posterior, ELBO and prediction are all one kind of integral.
  2. Monte Carlo: average the function at random samples.
  3. The error: why the average is right, and why its error falls as one over the square root of m.
  4. The linear Gaussian: a test with a known answer.
  5. When it struggles: peaked functions and densities you cannot sample.
  6. Importance sampling: draw elsewhere, then reweight.
  7. In code: three lines of JAX and a head-to-head test.
  8. The proposal: which q is best, and how to get near it.
  9. Normalising: what to do when densities have unknown constants.
  10. Field guide: numbers, checklist, code, and where this leads.
A population model has 8 hidden dimensions. You slice each into 10 grid points to compute the marginal. How many evaluations does the grid need?

Chapter 1

Four Integrals That Are One Integral

Spot the single shape, an average of h under p, hiding inside evidence, posterior, ELBO and prediction

You have recorded one trial from a model neuron and counted 12 spikes. You believe a hidden drive z pushes the firing rate up and down. You have a model: z comes from a bell curve centred on zero, and given z the spike count follows a Poisson law (the standard model for counts of rare, independent events) with rate e1.5 + 0.8z. What do you now want to know?

Four questions come up every time. How well does this model explain the data? Where was the hidden drive on this trial? How should the parameters change so the model fits better? What will the next trial look like? The lecture gives each one a name, and each one is an integral over z.

Four questions, four integrals

The first is the marginal likelihood, also called the evidence. It scores the whole model against the data, and you use it to fit or compare models. It is the marginalization of Chapter 0, written with the model's parameters θ added.

p(x | θ)
The evidence: the probability the model gives to the data you saw. A better model gives a bigger number.
p(x | z, θ)
The likelihood: how well one particular hidden value z explains the spikes. For our example, the Poisson probability of 12 spikes at the rate that z sets.
p(z | θ)
The prior: how likely each z is before you look at the data. For our example, the bell curve centred on zero.

The second is the posterior, which the lecture also calls the recognition distribution. It says where z probably was, given the spikes. Bayes’ rule builds it from the same two pieces, divided by the evidence. Every quantity you read off it, such as the average value of z, is an integral against it.

The third is the evidence lower bound, or ELBO. Often the evidence is too hard to compute, so you maximise a cheaper stand-in that always sits below it. The ELBO, F, is an integral against a guess q of the posterior, and the expectation-maximisation (EM) algorithm is built on the same integral. The fourth is the posterior predictive: the chance of a new trial x′, found by averaging the likelihood of x′ over the posterior.

One shape under all four

Look at the four formulas again. Each has a curve inside the integral that we can write down, multiplied by a density that tells us where z is likely. The lecture names the general problem with one line.

∫ … dz
Add up the thin slices over all z.
h(z)
The function whose average you want. You can evaluate it at any z.
p(z)
The density that weights each z. You will need to draw random z from it.
Ep[h(z)]
The expectation: the average of h(z) if you draw z from p, over and over, forever.

An expectation is a long-run average, so the integral is secretly an average. Hold that thought. It is the whole reason Monte Carlo works. The only job left is to name h and p for each question.

Try it on the Poisson example. Pick a question below. The pink curve is p, the blue curve is h, and the dashed curve is their product. The integral is the area under the dashed curve, taken with sign.

Name h and p

Choose a question. The pink curve is p(z), the blue curve is h(z), each scaled to fit. The dashed curve is h times p. The read-out tells you which is which and gives the value of the integral.

Illustrative Poisson model: prior z ~ N(0, 1), rate e^(1.5 + 0.8 z), 12 spikes observed. Prediction asks for the chance that the next trial also holds 12 spikes. The ELBO uses a made-up guess q = N(0.8, 0.5²) for the posterior. Every value comes from numerical integration in your browser.

For the evidence, the prior is p and the likelihood of 12 spikes is h. Their integral comes to 0.0211. No formula gives this number, because z sits inside an exponential inside a Poisson. That is the usual case. The lecture says these integrals are almost always intractable: no neat algebra solves them, so we estimate them numerically.

The lecture then sets its plan. First, Monte Carlo integration. Second, importance sampling. They differ in one thing only, which is where the random z values come from, and that choice decides the variance of the answer.

You want the chance that the next trial shows 12 spikes, given the spikes you already saw. In the shape ∫ h(z) p(z) dz, what are h and p?

Chapter 2

Monte Carlo: Average Random Samples

Replace the integral with the plain average of h at samples drawn from p, and read it as code

You want the average height of everyone in a stadium. Measuring 60,000 people is slow. So you pick 100 seats at random, measure those people, and take the mean. You will be a little off, but you will be close, and you never visited the other 59,900 seats.

That is the whole idea of Monte Carlo integration, named after the casino because it runs on chance. The integral from Chapter 1 is an average of h over the density p. So do what you did in the stadium: draw random z values from p, evaluate h at each, and average.

The estimator

Write the draws as z(1), z(2), up to z(m). The raised numbers in brackets only label which draw it is. The lecture asks that the draws be i.i.d., short for independent and identically distributed: each one comes from the same p, and no draw affects another. Then the estimate is the plain mean.

Ep[h(z)]
The true value you want: the integral of h times p.
1/m
Divide by the number of draws. This turns a sum into a mean.
∑ h(z(i))
Evaluate h at each draw and add the m results.
ĥm
The name for this estimate. The small m reminds you it depends on how many draws you took.

Here it is on the Poisson example, with five draws that I chose by hand for the arithmetic. The drive z takes the values −0.4, 1.1, 0.3, −1.2 and 0.8. For each one the rate is e1.5 + 0.8z, and h is the Poisson chance of exactly 12 spikes at that rate.

z = −0.4: rate 3.25, h = 0.0001   z = 1.1: rate 10.80, h = 0.1073   z = 0.3: rate 5.70, h = 0.0082   z = −1.2: rate 1.72, h ≈ 0.0000   z = 0.8: rate 8.50, h = 0.0604 (illustrative draws)

The five values add to 0.1760, and the mean is 0.1760 / 5 = 0.0352. The true evidence is 0.0211, so five draws overshoot by about two thirds. Look at why. Only two of the five draws landed where a rate near 12 is likely, and those two carried nearly all the sum. With so few draws, luck decides how many land there.

Now let the machine draw more. The device below samples z from the prior, shows each h value, and keeps a running mean. Press Draw 10 a few times and then Draw 100.

Sample and average

Top: the prior curve in pink, the likelihood h in blue, and your draws as teal ticks on the z axis. Bottom: the running mean of h in warm, and the true value 0.0211 as a green line. Draw some samples, then start over to see a different run.

Illustrative Poisson model: z ~ N(0, 1), rate e^(1.5 + 0.8 z), 12 spikes observed, true evidence 0.0211 by numerical integration. The draws are real seeded random numbers in your browser; each start over uses a new seed.

Early on the line jumps around, because each new draw is a big share of the sum. As draws pile up, each new one moves the mean less, and the line flattens onto the green one. Nothing guides it there. The settling is a property of averages, and the next chapter says exactly how fast.

The same thing as code

The lecture shows the method in JAX, a Python library for fast numerical computing. It reads like NumPy, the common array library, and adds three tools built on composable function transformations. jit compiles a function once with XLA, a compiler for array maths, so repeated calls run fast. grad gives the derivative of a function automatically. vmap turns a function written for one input into one that handles a whole batch. The lecture also uses TensorFlow Probability, which supplies ready-made distributions that can sample and score.

python
import jax, jax.numpy as jnp
from tensorflow_probability.substrates import jax as tfp
tfd = tfp.distributions

def monte_carlo(h, p_dist, m, key):
    z = p_dist.sample(m, seed=key)   # shape (m,): m draws from p
    return jnp.mean(h(z))            # h(z) has shape (m,); mean is one number

p = tfd.Normal(loc=0., scale=1.)                       # the prior over z
def h(z):                                          # Poisson likelihood of 12 spikes
    return tfd.Poisson(log_rate=1.5 + 0.8 * z).prob(12.)
est = monte_carlo(h, p, 1000, jax.random.PRNGKey(0))   # about 0.021

Follow the data. The input is a function h, a distribution p, a count m and a random key. p_dist.sample returns an array of m numbers, one per draw. h(z) returns another array of m numbers. jnp.mean reduces that array to one number. The key makes the randomness repeatable: the same key gives the same draws.

Notice what the method asks of you. You must be able to sample from p and to evaluate h(z) at any z. Nothing else. You do not need a formula for the integral, and you do not need p to have a neat shape.

Your colleague wants the Monte Carlo estimate of Ep[h(z)]. Which two abilities must you have?

Chapter 3

Why the Average Works, and How Fast

Show that the estimate is unbiased and consistent, and derive its error of sigma over root m

Suppose you ran the stadium survey ten times, each time with a fresh random set of 100 seats. You would get ten slightly different averages. Some come out high and some low. Two questions matter. Are they centred on the right answer? And how widely do they scatter?

The lecture answers both, and the slides leave the algebra for the board. Here is that algebra, slowly. It rests on one fact: an estimate is itself a random number, because it depends on random draws. Run it again and you get a different value.

Unbiased: centred on the truth

An estimator is unbiased if its average over many repeated runs equals the true value. The proof takes three steps. Start with the average of the estimate, written E[…]. The expectation of a sum is the sum of the expectations, so the 1/m and the sum pass outside. Every draw z(i) comes from the same p, so each h(z(i)) has the same average, which is the true value.

E[ĥm]
The average of the estimate over infinitely many repeated runs, each with m fresh draws.
1/m ∑ E[…]
The expectation moves inside the sum. Each of the m terms has the same average, because the draws are identically distributed.
Ep[h(z)]
That shared average is the true integral. So the estimate is unbiased for any m, even m = 1.

Unbiased does not mean any single run is close. A run with m = 1 is unbiased and still wild. It means the errors do not lean in one direction.

Consistent: it converges

An estimator is consistent if it homes in on the truth as m grows. For Monte Carlo this is the law of large numbers, a classic theorem: the mean of many i.i.d. draws converges to their expectation. The slide writes it with the arrow “a.s.”, for almost surely, meaning with probability 1. A run that fails to converge exists in theory but has probability zero.

The error: sigma over root m

Now the spread. The variance of a random number is the average squared distance from its own average, and its square root is the standard deviation. Two facts do the work. The variance of a sum of independent numbers is the sum of their variances. And pulling a constant c out of a variance gives c².

Var[ĥm]
How much the estimate scatters from run to run.
1/m² ∑ Var
The constant 1/m comes out as 1/m². The variances of independent draws add.
σh² / m
All m draws share one variance, σh², the variance of h(z) when z comes from p. The m terms cancel one m, leaving a single division.
σh / √m
The standard deviation of the estimate: its typical error. The lecture calls it the estimation error.

Work a number from the Poisson example. Under the prior, h has mean 0.0211 and standard deviation σh = 0.0346, by numerical integration. At m = 100 the error is 0.0346 / 10 = 0.0035, which is 16% of the answer. At m = 10,000 it is 0.0346 / 100 = 0.00035, which is 1.6%. A hundred times the draws bought only ten times the accuracy.

You will not know σh in practice, since it is another integral. The lecture notes that Monte Carlo estimates it too: take the spread of your own h values. That gives a usable error bar from the same draws. The lecture points to Robert and Casella (2004, section 3.2) for the details.

Now see all three facts at once. The device repeats the whole experiment 300 times at the sample count you choose and stacks the 300 estimates into a histogram.

Repeat the experiment 300 times

Each bar counts how many of 300 independent runs landed in that range. The green line is the truth. The warm line is the mean of the 300 runs. The dashed curve is the bell that sigma over root m predicts. Drag the sample count.

100

Illustrative Poisson model (z ~ N(0, 1), rate e^(1.5 + 0.8 z), 12 spikes, true evidence 0.0211, σh = 0.0346). The 300 runs use real seeded draws; at the smallest sample counts a few runs land beyond the right edge and are drawn in the last bar.

At m = 10 the histogram is wide and lopsided. At m = 100 it is tighter. At m = 10,000 it is a narrow spike. Through every change the warm line stays on the green one. That is unbiasedness. The spike narrowing is σh / √m.

One more reading of the formula matters later. The error has two parts: σh, which belongs to the problem, and √m, which you buy with computer time. The second is a slow purchase. The next chapters ask whether we can shrink the first.

Your Monte Carlo estimate has a standard error of 0.02 at m = 400. About how many samples give a standard error of 0.005?

Chapter 4

Your First Estimate: The Linear Gaussian

Choose h and p yourself, then check a Monte Carlo estimate against an answer you can compute exactly

The lecture now stops and asks you to do something. Take two integrals from Chapter 1 and say how you would estimate each by Monte Carlo. The hard part is not the method. It is spotting which piece is h and which is p. Try it before you read on.

The in-class exercise

The evidence. The integral is ∫ p(x | z, θ) p(z | θ) dz. The likelihood p(x | z, θ) is a function we can evaluate at any z, so it is h. The prior p(z | θ) is a density we can draw from, so it is p. Procedure: draw m values of z from the prior, compute the likelihood of the data at each, and average.

The EM update. EM is the algorithm that fits a latent variable model by alternating two steps. Its second step maximises a quantity the lecture calls Q, an integral of the form ∫ p(z | x, θ′) log p(x, z | θ) dz. The log joint probability is h. The posterior under the old parameters θ′ is p. Procedure: draw z from that posterior, compute the log joint at each, and average. Our EM and Gaussian mixture lesson teaches the full algorithm.

The lecture ends the exercise with a rule that you should keep. In practice we identify h and p ourselves, and the method requires only that you can sample from p and evaluate h(z). Notice the catch hiding in the second example. The posterior is a harder thing to sample than the prior. Chapter 5 returns to this.

A test with a known answer

To trust a method, test it on a problem whose answer you know. The lecture picks the linear Gaussian model. It is the simplest latent variable model that still has the right structure: a hidden number, and a recording that depends linearly on it plus noise. In neural terms, z is a hidden drive and x is one channel’s amplitude.

z ~ N(μz, σz²)    x | z ~ N(A z, σx²) (the lecture uses vectors and matrices; we use single numbers)

Here N(μ, σ²) means a bell curve with centre μ and spread σ. A is a gain: how strongly the drive shows up in the recording. The lecture says the evidence p(x) is Gaussian and known. The reason is short. The recording is A times a Gaussian plus an independent Gaussian, and a sum of independent Gaussians is Gaussian, with variances that add.

p(x)
The evidence at the observed x. This is the exact answer we will test against.
Aμz
The centre. If the drive averages μz, the recording averages A times that.
A²σz² + σx²
The variance. Drive uncertainty gets multiplied by A twice (it is squared), and the recording noise adds on top.

Pick numbers. Let μz = 0, σz = 1, A = 2, σx = 0.5, and suppose you observe x = 3. The variance is 4 × 1 + 0.25 = 4.25, so the spread is 2.06. The Gaussian density at 3 is 0.0671. That is the target.

Now the Monte Carlo recipe, step by step. Draw z from N(0, 1). For each, compute h(z) = N(3; 2z, 0.5²), the chance of seeing 3 if the drive were z. That function peaks at z = 1.5, because 2 × 1.5 = 3. Average the m results. The code carries the shapes.

python
key = jax.random.PRNGKey(1)
z  = jax.random.normal(key, (m,))                 # shape (m,): draws from the prior N(0, 1)
hz = tfd.Normal(loc=2. * z, scale=0.5).prob(3.)  # shape (m,): likelihood of x = 3 at each z
est = hz.mean()                                   # one number, near 0.0671
err = hz.std() / jnp.sqrt(m)                      # the error bar, from the same draws

The last line is the slide’s remark about estimating σh with the draws themselves. You get the answer and a measure of how much to trust it, for free.

Now the experiment the lecture plots. For many sample counts, run the method 200 times and measure how far the estimates scatter. The device shows that scatter as a percentage of the true answer, on log axes, beside the line that σh / √m predicts. You can also change how sharply the measurement pins down z, using the noise σx.

Measure the error line

Both axes are logarithmic. Warm dots are the measured error from 200 runs at each sample count. The dashed line is the formula. A straight line sloping down means error shrinks as a power of m. Move the noise slider and watch the whole line shift.

0.50

Illustrative linear Gaussian model: z ~ N(0, 1), x | z ~ N(2z, σx²), x = 3 observed. The evidence is known exactly for every σx, and σh comes from numerical integration. The dots are real seeded Monte Carlo runs in your browser; each press of the button uses a new seed.

Two things show. The dots follow the dashed line: the measured scatter matches the theory, and it falls with slope −1/2, so each decade of samples cuts the error by a factor of 3.16. And the height of the line depends on σx. When the measurement is sharp, with a small σx, the likelihood h is a narrow spike in z. Few prior draws land on the spike, so σh is large relative to the answer. At σx = 0.5 and m = 1,000 the relative error is 8.5%. That hint of trouble is the topic of Chapter 5.

For the EM update, Q = ∫ p(z | x, θ′) log p(x, z | θ) dz. Which choice of h and p fits the Monte Carlo shape?

Chapter 5

When Plain Sampling Struggles

Find out why a peaked h and a p you cannot sample make plain Monte Carlo slow, and why more samples is a poor fix

Monte Carlo sounds like a free lunch: draw, evaluate, average. The lecture now lists where it goes wrong. It names two troubles on one slide. You may not be able to sample from p. And even when you can, the error may be too big. Each has a cause you can see.

Trouble one: p is out of reach

Return to the EM integral from Chapter 4. Its density p is the posterior, p(z | x, θ′), and the lecture highlights it in red. The posterior is the prior reweighted by how well each z explains the data, then rescaled to area 1. For a Gaussian model that gives another Gaussian, and you can sample it. For our Poisson neuron it gives no named curve at all.

You can evaluate the posterior up to a constant: the prior times the likelihood is easy to compute at any z. But a recipe that turns random numbers into draws from it does not exist. The one requirement of Monte Carlo, “you can sample from p”, fails. In real latent variable models for spikes, this is the usual case.

Trouble two: the draws land in the wrong place

Even when p is easy, the error σh / √m can be large. Look at the prior draws in the Poisson example. The likelihood h of 12 spikes is large only for z near 1, where the rate is near 12. The prior bell curve puts most of its draws at z between −1 and 1, so a good share land far from the bump. Those draws contribute almost nothing: h is near zero there.

So the sum is carried by the few draws that happened to land near the bump. The estimate depends on how many of those you got, and that number is itself random. This is why the estimate jumped around in Chapter 2.

The failure has three parts. The symptom is that estimates from different runs disagree and one or two draws dominate the sum. The measurement is the effective sample size: the number of equal-weight draws that would give the same accuracy. For h values h1 to hm it is (∑ hi)² / ∑ hi². If all draws count equally it equals m. If one draw carries everything it equals 1. The fix is the subject of the next chapter.

The more informative the data, the sharper the bump. Ten spikes tell you the rate far better than one spike does. So the more spikes you record, the worse plain Monte Carlo gets. Slide the spike count and watch.

Count the draws that count

The pink curve is the prior. The blue curve is the likelihood of the spike count you pick, scaled to fit. Below the axis are 1,000 prior draws, drawn bright where h is large and faint where it is near zero. Drag the number of spikes.

12

Illustrative Poisson model: z ~ N(0, 1), rate e^(1.5 + 0.8 z). The relative error per draw and the samples needed come from numerical integration. The effective size of the 1,000 drawn points is measured from the drawn h values, so it jitters around the formula 1,000 / (1 + relative error²).

At 3 spikes the likelihood sits in the heart of the prior. The relative error per draw is 0.71, and about 201 draws give a 5% error. At 12 spikes it is 1.64, and you need 1,078 draws. At 20 spikes the bump is far out in the prior’s tail, the relative error is 3.26, and you need 4,257 draws. With 0 spikes the data is also surprising, because the model expects about 4.5, and the error is high again. The worst cases are the data the prior finds surprising.

Why not just add samples?

The lecture asks the question outright: how can we make our estimates better? The formula has two knobs. The error is σh / √m. One answer is to increase m. But the square root punishes you. To halve the error you need four times the samples, and to cut it by 10 you need 100 times. For the 20-spike case, an error of 1% needs about 106,000 draws instead of 4,257.

The other knob is σh. The lecture points an arrow at it with the question: can we get a better variance? That is the better lever. Shrinking σh by 10 gives the same gain as 100 times the samples, at no cost per draw. Importance sampling is a way to turn that knob. It also solves trouble one, because it removes the need to sample from p.

A colleague records many more spikes per trial and finds that Monte Carlo from the prior has become much noisier. Why?

Chapter 6

Importance Sampling: Draw Elsewhere, Reweight

Sample from a proposal q instead of p, then correct each draw with the weight p over q

A pollster wants the average income of a city. Most people earn near the middle, but a few neighbourhoods are very rich and decide the answer. A plain random sample may miss them entirely. So the pollster does something sensible: visit the rich neighbourhoods more often, then count each answer with a weight that undoes the extra visits.

That is importance sampling. The lecture calls it a generalisation of Monte Carlo integration. You still average h, but you draw the points from a density of your own choosing, and you correct for the choice.

The trick: multiply by one

Introduce a proposal distribution q. It is any density you can sample from and evaluate, and it should put its mass where h times p is large. Now do one small piece of algebra. Multiply and divide the integrand by q(z). Nothing changes, since you multiplied by 1. But the integral now looks like an expectation under q.

Ep[h(z)]
The answer you want, an average under p.
p(z) / q(z)
The importance weight, written w(z). It is the ratio of how likely z is under the target to how likely it is under your proposal.
Eq[ h w ]
An average of h times the weight, under q. Now you draw z from q, which you can do, and p only needs to be evaluated.

The estimator follows at once. Draw z(1) to z(m) from q. Compute each weight w(i) = p(z(i)) / q(z(i)). Then average h(z(i)) times w(i). This is plain Monte Carlo, applied to the new function h times w, with samples from q.

ĥmIS
The importance sampling estimate from m draws.
1/m ∑ h w
The plain average, but each h value is first multiplied by its draw’s weight.
w(i)
Small where q over-visits (q larger than p), large where q under-visits. It restores the right balance.

One condition keeps this honest: q must not be zero anywhere that h times p is not zero. If q never visits a region that matters, no weight can bring it back.

A worked example with five draws

Use the linear Gaussian model again: prior N(0, 1), recording x = 3, and the true evidence 0.0671. Take the proposal q = N(1.4, 0.5²), a bell centred where h peaks. Say the five draws from q are z = 1.0, 1.5, 2.0, 0.8 and 1.3 (illustrative). Each row gives p(z), q(z), the weight, h(z), and the product.

z = 1.0: p 0.2420, q 0.5794, w 0.4176, h 0.1080, h·w = 0.0451
z = 1.5: p 0.1295, q 0.7821, w 0.1656, h 0.7979, h·w = 0.1321
z = 2.0: p 0.0540, q 0.3884, w 0.1390, h 0.1080, h·w = 0.0150
z = 0.8: p 0.2897, q 0.3884, w 0.7459, h 0.0158, h·w = 0.0118
z = 1.3: p 0.1714, q 0.7821, w 0.2191, h 0.5794, h·w = 0.1270

The products add to 0.3310, and the mean is 0.3310 / 5 = 0.0662. The truth is 0.0671, so five draws land within 1.4%. Plain Monte Carlo with five draws from the prior would be nearly always far off. The reason is in the weights: every draw landed near the bump of h, and the weights, all below 1, scaled them down to the right size.

Now try your own proposal. The device shows p, h, and q, with 40 draws from q whose dot size shows how much each contributes. Move the centre and the width of q. The read-out gives the exact error at 100 draws.

Shape the proposal

Pink is the prior p, blue is h, scaled to fit, and purple is your proposal q. The dots are 40 draws from q, bigger where h times the weight is bigger. Drag the centre onto the blue bump, then try narrowing q too far.

0.00
1.00

Illustrative linear Gaussian model: z ~ N(0, 1), x | z ~ N(2z, 0.5²), x = 3, true evidence 0.0671. Centre 0 and width 1 is plain Monte Carlo. Exact errors come from numerical integration. The 40 draws use fixed random numbers, so they move smoothly with the sliders.

At centre 0 and width 1, q equals p, every weight is 1, and you have plain Monte Carlo with an error of 0.0181 at m = 100. Slide the centre to 1.4 and the width to 0.25, and it falls to about 0.0004, forty times smaller. Go below a width of 0.17 and the read-out turns to “unbounded”. That cliff is the lesson of the properties below.

What it keeps, and what it changes

Importance sampling is Monte Carlo on h times w, so it inherits everything from Chapter 3. It is unbiased and consistent. The change is the variance. The error is still the standard deviation of one term divided by √m, but the term is now h times w, and its spread depends on your proposal. A well-placed q shrinks the spread and a badly placed one inflates it.

The cliff has a plain cause. If q has thin tails, then far from its centre q is tiny while h times p is not. The weight p / q becomes huge there. A rare draw out there gets a gigantic weight and wrecks the average. Keep q at least as wide as the product h times p, and a little wider is safer.

In importance sampling, a draw lands where q is much larger than p. What does its weight w = p / q do to that draw?

Chapter 7

Importance Sampling in Code and in Practice

Write the estimator in three lines of JAX, and compare its error with plain Monte Carlo on the same model

Theory is cheap until it meets an array. You have a function h, a prior p, and a proposal q, and you want a single number out. This chapter is about writing that out and checking that it beats plain Monte Carlo on the one model where we know the answer.

Three lines of JAX

The lecture shows the importance sampling function right after the plain Monte Carlo one. Here is the same thing in our own variables. It takes h, the target p, the proposal q, a count m and a random key.

python
def importance_sampling(h, p_dist, q_dist, m, key):
    z = q_dist.sample(m, seed=key)                    # (m,)   draws from the PROPOSAL q
    log_w = p_dist.log_prob(z) - q_dist.log_prob(z)   # (m,)   log of the weight p(z) / q(z)
    return jnp.mean(h(z) * jnp.exp(log_w))              # (m,) times (m,) averaged to one number

q = tfd.Normal(loc=1.4, scale=0.5)                    # proposal near where h peaks
est = importance_sampling(h_lg, p, q, 1000, jax.random.PRNGKey(2))

Follow the arrays. Line one draws m numbers from q. Line two scores each draw under both densities and subtracts, giving m log-weights. Line three multiplies each h value by its weight and averages. Compare it with the plain version of Chapter 2: only the sampling line and the weight line differ. Setting q equal to p makes every weight 1, and the function returns the plain Monte Carlo answer.

Why work with log-weights? Densities can be tiny. A product of many small numbers, or a ratio of two of them, can underflow to zero in a computer’s fixed-size numbers. The difference of logs stays an ordinary number, and you exponentiate it only at the end. For high-dimensional z this habit separates working code from code that returns zeros.

A reality check on weights

After a run, look at the weights themselves. If a few weights are far larger than the rest, those draws dominate and the estimate is shaky. The same effective sample size from Chapter 5 now works on the weights: (∑ w)² / ∑ w². It equals m when all weights match, and 1 when one weight swallows the rest. A common habit is to report it beside the estimate. If it is a few percent of m, change q.

The head-to-head test

Now the lecture’s comparison. On the linear Gaussian model, run plain Monte Carlo and importance sampling many times, and plot how the scatter falls with m. The lecture’s plot shows the orange importance sampling curve running below the blue plain one. Here you pick the proposal. The ghost line is plain Monte Carlo, for reference.

Race four proposals

Both axes are logarithmic. The grey line is plain Monte Carlo from the prior. The purple dots are measured from 200 runs per sample count for the proposal you choose, and the dashed purple line is the exact prediction. Pick a proposal.

Illustrative linear Gaussian model: z ~ N(0, 1), x | z ~ N(2z, 0.5²), x = 3, true evidence 0.0671. Dots are real seeded runs in your browser (200 runs per point); the dashed lines are exact standard errors by numerical integration. The tight proposal has a width above the 0.17 cliff of Chapter 6, so its error is finite, though it is close to the edge.

With the prior as proposal the dots sit on the grey line, as they must. With the broad proposal, the line drops: at m = 1,000 the relative error falls from 8.5% to 4.4%. With the tuned proposal it is 2.4%. With the tight proposal it is 0.20%. Every line has the same slope, because every one is σ / √m. Importance sampling does not change the slope. It moves the whole line down.

That is worth saying plainly. A better proposal does the work of more samples. The tuned proposal at m = 1,000 matches the error that plain Monte Carlo reaches only near m = 13,000. Look at the tight proposal: it matches plain Monte Carlo with about 1.9 million draws.

The lecture ends this section with two questions. The variance of the estimate depends on q. How do we choose it? And what is the best possible q? Those are the next chapter.

In the code, why compute the weights as the exponential of log p minus log q, instead of dividing p by q directly?

Chapter 8

Choosing the Proposal

Find the proposal that minimises variance, see why it is circular, and use a Laplace approximation to get close

You have seen that the proposal matters a great deal. The tuned one cut the error by 3.6 times and the tight one by about 40 times. Naturally you ask: what is the best proposal of all? The lecture gives a clean answer, and then admits the answer is circular.

The best proposal

Think about what makes the estimate wobble. Each term is h(z) times the weight w(z). If every term had the same value, the average would have no spread at all, however few draws you took. So ask when h(z) p(z) / q(z) is constant. It is constant when q is proportional to h times p. That gives the lecture’s optimal proposal.

q*(z)
The proposal that gives the smallest variance of the importance sampling estimate, for the given h and p.
|h(z)| p(z)
The product, with h made positive. The proposal puts its mass where this product is big: where h is large and p is not tiny.
∫ |h| p dz′
The constant that makes q* a density with area 1. Without it the curve would not sum to 1.

Check the claim when h is positive. With q = q*, each weight is p / q* = (∫ h p) / h, so h times w equals ∫ h p, the very answer, for every draw. All terms agree and the variance is zero. The lecture sends the general proof, for any sign of h, to Robert and Casella (2004, Theorem 3.12).

Why the best is circular

Look at the denominator. To build q* you need the integral of h times p. That integral is the answer you wanted in the first place. If you had it, you would not need to sample. The lecture says so itself: quite circular. But the shape still teaches. Put your proposal where h times p is large, and the closer you get, the better.

The lecture asks a sharp question to show how this works. What is q* for the evidence, where h(z) = p(x | z)? The product h times p is the likelihood times the prior, which is the joint probability p(x, z). Seen as a function of z, the joint is the posterior up to a constant. So q* is the posterior, p(z | x). The best place to draw from, when estimating the evidence, is where the hidden state probably was, given the data.

Notice how neatly this connects. Chapter 5 said the posterior is the density you cannot sample. Here the posterior is the ideal proposal. You cannot use it exactly, but anything that resembles it will do well.

Getting close: the Laplace approximation

The lecture suggests one practical recipe, the Laplace approximation: fit a bell curve that sits on the peak of h times p and has the same curvature there. Three steps. First, find the peak z*: the point where the log of h times p is highest, using any optimiser. Second, measure how sharply the log curve bends at the peak, which is minus its second derivative. Third, take a Gaussian with centre z* and variance equal to one over that bend.

Try it on the linear Gaussian toy. The log of h times p is, up to a constant, minus half of 1 + 4 / 0.25 = 17 times the squared distance from 1.4118. Its peak is 1.4118, and its bend is 17. So the Laplace proposal is N(1.4118, 1/17), which has width 0.2425. It happens to be exact, because a Gaussian times a Gaussian is Gaussian. The weights are then all equal and the variance is zero.

Try the Poisson neuron with 12 spikes. The peak of the log product sits at z* = 1.08, and its bend gives a width of 0.358. The true posterior has mean 1.037 and width 0.362, found by numerical integration. The Laplace fit is close and not exact, because the true posterior leans to one side. A Gaussian cannot copy a lean, but it can still sit on the right spot.

One caution from Chapter 6 applies. A fitted Gaussian can have thinner tails than h times p. Inflating its width a little, say by a quarter, costs little and protects against the cliff.

Now see how forgiving or unforgiving the choice is. The map below colours every proposal, by its centre and width, by the exact error of importance sampling at m = 100. Bright means small error. Red means unbounded.

Map the proposals

Across is the proposal centre, up is its width. Bright purple is a small error and red is an unbounded one. The green mark is the best proposal, the posterior. The teal cross is yours. Drag the sliders or press a button.

0.00
1.00

Illustrative linear Gaussian model: z ~ N(0, 1), x | z ~ N(2z, 0.5²), x = 3, true evidence 0.0671. Every cell is the exact standard error at m = 100 by numerical integration, shown on a log colour scale from 0.003% to 100% of the answer; cells with width below 0.17 have infinite variance. The Laplace fit here equals the exact posterior, centre 1.412 and width 0.2425.

The map has a bright valley around the green mark and dark cells far from it. Two features stand out. Moving the centre away from 1.4 hurts quickly when the width is small, because a narrow proposal misses the bump. And the bottom strip, where the width is below 0.17, is red. Widening a proposal costs a bit of efficiency and buys safety. Narrowing it past the target is the one mistake that can ruin the estimate.

You estimate the evidence, where h(z) = p(x | z) and p is the prior. Which proposal q minimises the variance?

Chapter 9

Unnormalised Densities and Self-Normalising

Estimate with densities known only up to a constant by dividing by the sum of the weights

Everything so far assumed you could write p(z) down exactly, constant and all. For a neural model that is often untrue. Take the posterior over the hidden drive after 12 spikes. Its top is easy: the prior times the likelihood. Its bottom is the evidence, the very integral we are trying to estimate. So you can evaluate the posterior only up to a missing constant.

The lecture closes its methods with this problem. It asks what happens when neither p nor q is normalised, meaning neither integrates to 1. The answer is a small change to the estimator that makes it work, and the lecture says it is also more stable in general.

A density with a missing constant

An unnormalised density is a curve with the right shape but the wrong area. Write it with a tilde: p̃(z). The true density is p̃ divided by its area Zp. The same goes for q, with area Zq. You can compute p̃ and q̃ at any z, and you can sample from q. You do not know the two areas.

The plain importance weights p / q now cannot be computed. But the ratio of the unnormalised curves, w̃ = p̃ / q̃, can. It differs from the true weight by the fixed factor Zq / Zp. A fixed unknown factor is easy to cancel: divide by another quantity that carries the same factor.

The trick: divide by the sum of the weights

Take the average of the weights alone. By the same multiply-by-one argument as before, it estimates the ratio of the two areas, Zp / Zq. Take the average of h times the weights. It estimates Zp / Zq times the answer we want. Divide the second by the first. The unknown area ratio cancels, and the answer is left.

Ep[h(z)]
The answer, an average under the true, normalised p.
∑ h w̃
The top: the weighted sum of h. It is inflated by the unknown area ratio.
∑ w̃
The bottom: the plain sum of the weights. It carries the same area ratio, so dividing cancels it.
w̃(i)
The weight from the unnormalised curves, which you can compute with no constants.

This is the same thing as using normalised weights. Divide each w̃ by the sum of all of them, and the new weights add to 1. Then the estimate is a plain weighted average of the h values, with the normalised weights as the weights. The lecture writes it as the 1 over the sum of the weights, times the weighted sum of h, with a highlighted box on the sum.

A worked example, constants dropped

Estimate the posterior mean of z in the linear Gaussian toy, where h(z) = z. Pretend you do not know the evidence. Then p̃(z) is the likelihood times the prior, and the area under it is the unknown evidence. Take q̃(z) = exp(−(z − 1)²/2), a bell curve around 1 with its constant thrown away. Say the five draws from q are z = 0.9, 1.4, 1.6, 2.2 and 0.3 (illustrative).

z = 0.9: p̃ 0.0119, q̃ 0.9950, w̃ 0.0120, normalised 0.0520
z = 1.4: p̃ 0.1103, q̃ 0.9231, w̃ 0.1195, normalised 0.5185
z = 1.6: p̃ 0.0817, q̃ 0.8353, w̃ 0.0978, normalised 0.4245
z = 2.2: p̃ 0.0006, q̃ 0.4868, w̃ 0.0012, normalised 0.0050
z = 0.3: p̃ 0.0000, q̃ 0.7827, w̃ 0.0000, normalised 0.0000

The weights add to 0.2304. The estimate is the weighted average of the five z values: 0.0520 × 0.9 + 0.5185 × 1.4 + 0.4245 × 1.6 + 0.0050 × 2.2, which comes to 1.463. The true posterior mean is 1.412, so five draws land within 4%. Notice the weights. Two of the five carry 94% of the total. The effective sample size, (∑ w̃)² / ∑ w̃², is only 2.2 out of 5. The method works, and the diagnostic tells you honestly how much of your sample is pulling weight.

Now see why the division matters. In the device the target is the unnormalised curve multiplied by a hidden constant Z that you choose. The naive estimate, which uses the weights as they are, scales with Z and is wrong. The self-normalised estimate ignores Z.

Hide a constant in the target

Bars show the three estimates of the posterior mean of z. Green is the truth. Purple divides by the sum of weights. Red does not, so it is wrong. Raise or lower the hidden constant, then narrow the proposal to see the effective sample size fall.

1.00
1.00

Illustrative linear Gaussian model: z ~ N(0, 1), x | z ~ N(2z, 0.5²), x = 3, true posterior mean 1.412 (exact). The target p̃ is the likelihood times the prior times your constant Z. The proposal is N(1, width²), used unnormalised. 100 real seeded draws; the naive estimate is the plain mean of z times p̃ over q̃.

Move Z from 1 to 10, and the red bar leaps ten times higher. The purple bar does not move. That is the cancellation at work. Now narrow the proposal to 0.2 and look at the effective sample size in the read-out. It drops, because few draws land where the posterior has mass, and the estimate gets noisy. The weights are telling you something: change q.

There is a small price. A ratio of two random sums is slightly biased for finite m, though the bias shrinks as m grows and the estimate stays consistent. In practice this is a good deal. You gain the ability to work with unnormalised densities, and the estimate often has lower variance than the plain version.

You can evaluate p̃ and q̃ but not their areas. What makes the self-normalised estimator work?

Chapter 10

Field Guide

Keep the numbers, the checklist, the core code and the roads that lead onward

Here is the whole lecture in one breath. Many questions about a model with a hidden state come down to one integral, the average of h(z) under a density p(z). When you cannot do it by algebra, draw samples and average. The estimate is unbiased and its error falls as σh / √m. When p is awkward to sample, or h is a narrow spike, draw from a proposal q instead and weight each draw by p over q. The best q is proportional to |h| p. When the densities lack their constants, divide by the sum of the weights.

The numbers to remember

QuantityValueWhere it came from
Plain Monte Carlo errorσh / √mLecture slides 8 and 9, derived in Chapter 3
Cost of 10 times less error100 times the samplesFrom the square root, Chapter 3
Toy evidence, x = 30.0671, exactLinear Gaussian, Chapter 4 (illustrative numbers)
Plain error at m = 1000.0181 (27% of the answer)Exact, by numerical integration
Tuned proposal N(1.4, 0.5²)0.0050, 3.6 times smallerChapters 6 and 7
Tight proposal N(1.4, 0.25²)0.0004, 40 times smallerChapter 6
Width cliff for the toy0.17: below it, infinite varianceChapter 6, derived from the tails
Samples for a 5% error, 3, 12 and 20 spikes201, 1,078 and 4,257Poisson example, Chapter 5
Effective sample size(∑ w)² / ∑ w²Chapters 5, 7 and 9
Optimal proposalq* = |h| p / ∫ |h| pLecture slide 19, Chapter 8

Which estimator do I use?

Tell the device what you can do. It returns the recipe from this lecture that fits.

Pick your estimator

Switch each statement on or off to match your problem. The recommendation and the chapter to reread update at once.

A rule of thumb, not a theorem: it follows the lecture's requirements (sample from p, evaluate h; or sample from q and evaluate p and q) and the habit of checking the effective sample size.

The core as code

python
def monte_carlo(h, p_dist, m, key):                     # needs: sample p, evaluate h
    z = p_dist.sample(m, seed=key)                      # (m,)
    return jnp.mean(h(z))

def importance_sampling(h, p_dist, q_dist, m, key):     # needs: sample q, evaluate p, q, h
    z = q_dist.sample(m, seed=key)                      # (m,)
    log_w = p_dist.log_prob(z) - q_dist.log_prob(z)     # (m,) both densities normalised
    return jnp.mean(h(z) * jnp.exp(log_w))

def self_normalized_is(h, log_p_tilde, log_q_tilde, q_dist, m, key):
    z = q_dist.sample(m, seed=key)                      # (m,)
    log_w = log_p_tilde(z) - log_q_tilde(z)             # (m,) constants may be unknown
    w = jnp.exp(log_w - jnp.max(log_w))                 # shift by the max: same ratios, no overflow
    ess = jnp.sum(w) ** 2 / jnp.sum(w ** 2)           # effective sample size, out of m
    return jnp.sum(h(z) * w) / jnp.sum(w), ess

Subtracting the largest log-weight before exponentiating is safe, because dividing top and bottom of the ratio by the same number changes nothing. It is the last piece of numerical care this lecture needs.

Where it sits in the field

The lecture ends with four doors that open from here. Each answers a question this lesson leaves open.

Keep going with the maths this lecture borrows and the neural models it serves. The Monte Carlo simulation and importance sampling Gleams give a second telling. EM and Gaussian mixtures shows where the integral in the update comes from. Generalised linear models builds the Poisson model we used, and VAEs maximise the ELBO with a learned q. In the brain-computer interface series, point-process GLMs and latent variable models use these estimates to fit real recordings. For tracking a hidden state over time with Gaussians, see the Kalman filter and RTS smoothing.

The takeaway. A hard integral against a density is an average in disguise. Draw samples and average to estimate it; the error falls as one over root m. Draw from a proposal near h times p and reweight to cut the constant in front of that error. Divide by the sum of the weights when the constants are unknown.

Credit. This lesson re-teaches Lecture 18 of Princeton NEU 560, Statistical Modeling and Analysis of Neural Data (Spring 2024), taught by Jonathan Pillow, with this lecture given by Victor Geadah. The course site is pillowlab.princeton.edu/teaching/statneuro2024 and the slides are here. The lecture cites Robert and Casella, Monte Carlo Statistical Methods (2004). All numbers marked illustrative are our own toy models; all else is derived in the chapters.

Now press Teach and explain, from memory, why an integral over a hidden state is an average, how the error of a Monte Carlo estimate falls, and why a proposal near h times p helps. Then go back to the runs at the top, switch to importance sampling, and say why the spread shrinks.

Your estimate of a spiky integral has an effective sample size of 12 out of 1,000 draws. What is the best next step?
NEU 560 Lecture 18: Monte Carlo Integration and Importance Sampling
The course site · Lecture slides · Back to Gleams