The Laplace Approximation

You fit one neuron and get one number for its weight. The Laplace approximation adds the error bar: a bell curve whose width comes from how sharply your belief peaks.

Learn what a posterior is, why a peak alone hides how sure you are, and how one derivative turns any smooth peaked posterior into a Gaussian you can work with.

Drag Trials recorded from 1 up to 40 and watch the dashed purple bell hug the warm true posterior more tightly. Then raise the prior strength. After that we build every piece from zero: the prior, the evidence, the Gaussian posterior, the Taylor series and the Hessian.

You need a spike count (how many spikes a neuron fires in one short trial) and the idea of a slope. We build the rest from zero.

Based on Lecture 14 of Princeton NEU 560, Statistical Modeling and Analysis of Neural Data (Spring 2024), taught by Jonathan Pillow. Lecture slides. Every idea is re-taught here in our own words and devices. It follows Lecture 13, Model Selection and is a spine lesson of our BCI series.

Fit a neuron, see the error bar

4
0.20

Illustrative: one made-up neuron whose spike count in a trial is Poisson with mean e^(x · w), stimulus strength x between 0.2 and 1.5 and true weight 1.2, seeded so the same trials arrive in the same order every visit. The warm curve is the exact posterior computed on a 500-point grid. The purple curve is the Laplace approximation of Chapter 6.

Chapter 0

A Weight Without an Error Bar

See why the best-fit number for a neuron is not enough, and what the lecture builds to fix it

You record one neuron in visual cortex. On each trial you show a bar of light at some strength, and you count the spikes in the next 200 ms. After a handful of trials you fit a model that says: the stronger the light, the more spikes, scaled by one number, the weight. Your fitting code prints w = 1.31. Done?

Not quite. A colleague asks how sure you are. Could the weight be 1.0? Could it be 1.6? The single number cannot say. It is a point estimate: one best guess with no sense of how far the truth could lie from it. A pin on a map tells you where, but not whether the pin could be a mile off.

This lecture is about the missing half. We want the pin and the circle around the pin. In Bayesian statistics, that whole picture has a name: the posterior distribution.

The two pictures on the slide

Slide 18 draws the idea with two bell-shaped curves. Each curve answers one question: given the data and my prior beliefs, how plausible is each possible value of the weight? The horizontal axis holds the candidate weights. The height of the curve at a weight is the plausibility of that weight. The peak is the MAP estimate, short for maximum a posteriori: the single most plausible value.

The slide draws two curves with the peak in the same place. The left one is tall and thin. The right one is low and wide. The MAP estimate is identical, yet the two situations are very different. Thin means the data pins the weight down. Wide means many weights fit almost equally well.

Your neuron with 4 trials gives the wide curve. The same neuron after many more trials gives the thin one. The best-fit weight shifts only a little (in our toy, from 0.95 to 1.29 between 4 and 40 trials), but your right to trust it changes completely. Drag the number of trials below and watch the fitted tuning curve grow a fan of doubt around it.

Watch the doubt shrink

Blue dots are spike counts from the first trials. The warm line is the firing rate at the best-fit weight. The purple band is the rate at weights one standard deviation either side. Drag the trials and watch the band.

6

Illustrative: the same seeded neuron as the hero, spike count Poisson with mean e^(x · w). The band uses the Laplace standard deviation of Chapter 6 with a weak prior (precision 0.1), so it is a preview. The point to see now is that the band tightens as trials arrive, while the best-fit curve drifts only a little toward the true weight.

With 6 trials the band is wide: at the strongest stimulus it spans several spikes. With 60 trials it hugs the line. The model did not change. The data simply pinned the weight down. A number for that tightness is exactly what we want to compute.

What the lecture covers

The lecture begins with a short quiz on the lectures just before it, on regularization and MAP inference. Its five questions are worth knowing as a checklist. Why might the maximum likelihood estimator not exist? When you find the MAP estimate, you maximise the log-likelihood plus what? (The log prior.) What is the ridge penalty? (A cost on the squared size of the weights.) What do we call the denominator of Bayes’ rule? (The evidence, also called the marginal likelihood.) Those five terms return in this lecture, each one explained when we meet it.

Two more slides cover the course’s final project: you work alone or in a group of up to three, send a one-paragraph question first, give a 10 to 15 minute talk in reading week, and hand in a 3 to 5 page report by Dean’s date (May 7). That is all the logistics there are. The rest is mathematics.

Slide 5 sets the outline in three parts. First, a review of empirical Bayes, which is a way to choose how strong the prior should be. Second, the posterior itself, solved exactly when everything is Gaussian. Third, the Laplace approximation: what to do when the model is not Gaussian, as with spike counts.

Why do spike counts matter here? A count cannot be negative, and its spread grows with its mean. A Gaussian noise model is the wrong shape. So we use a Poisson model, the standard model for counts: the neuron has an average firing rate, and each trial's count scatters around that rate. With a Poisson model with a Poisson model the posterior is not a Gaussian. The Laplace approximation fits a Gaussian to it anyway, using one derivative. The Gaussian gives you the error bars. Our hero at the top of the page is that whole idea in one picture.

The road

  1. Picking the prior by cross-validation: hold some trials back and score the fits.
  2. Picking the prior by evidence: the area under likelihood times prior.
  3. The evidence in the Gaussian case: add Gaussians, get a Gaussian.
  4. Where the posterior comes from: Bayes’ rule, piece by piece.
  5. The Gaussian posterior: complete the square and read off the mean and covariance.
  6. The Laplace idea in one dimension: a parabola on the log curve.
  7. Worked exercise: one Poisson neuron, one trial, by hand.
  8. Many weights at once: gradient, Hessian and a covariance matrix.
  9. What to trust: credible intervals, exactness and concavity.
  10. Evidence by Laplace: scoring a prior when the model is not Gaussian.
  11. Field guide: numbers, checklist, code and where to go next.
Two fits of the same neuron give the same MAP weight, 1.3. Fit A has a tall, thin posterior. Fit B has a low, wide one. What is the right reading?

Chapter 1

Choose the Prior by Holding Data Back

Score each prior strength on trials the fit has never seen, and pick the one that predicts best

You want to predict a neuron’s response from 8 stimulus features, and you have only 14 trials. With 8 weights and 14 numbers to explain, a flexible fit can chase every wiggle of noise. It nails the 14 trials and then fails on the 15th. How do you stop it?

The usual cure is a prior: a belief, stated before the data, that the weights are probably small. A prior that says “small” pulls the fit toward zero and calms it down. The strength of that pull is one number, written λ (lambda). A hyperparameter is a number like this: it is not a weight of the model, it sets the rules for the weights. Slide 6 asks the question this lecture opens with: how do we choose λ?

Recap: what λ does

Lecture 11 showed that a Gaussian prior on the weights adds a cost to the fit: the sum of the squared weights, multiplied by λ. This is ridge regression. A large λ punishes big weights hard, so the fit is stiff and may miss real structure (underfitting). A tiny λ punishes nothing, so the fit is loose and may follow noise (overfitting). The best λ sits between. The weight vector that minimises the cost is the MAP estimate for that λ: the most plausible weights given the data and the prior.

Cross-validation: three steps

Slide 7 gives the recipe, named cross-validation. The idea is the one every student knows: do not mark your own homework. Split the trials into a training set (used to fit) and a test set (held back, used only to score). Then:

  1. Make a grid of λ values. Space them on a log scale, for example 0.001, 0.01, 0.1, 1, 10, 100, 1000, because the right strength can differ by factors of ten.
  2. For each λ, fit on the training trials. That gives one MAP weight vector per λ.
  3. Score that fit on the test trials. The score is the log-likelihood of the test responses: how probable the fit says the unseen data were.

Finally, pick the λ with the highest test score. The slide adds a last move: with the winning λ, refit on all the data to get the final estimate.

li
The score of the i-th prior strength, λi. Higher is better. It is a log-probability, so it is negative.
P(Ytest | Xtest, …)
How probable the held-back responses Ytest are, given the held-back stimuli Xtest and a weight vector. This is the likelihood from Lecture 9, evaluated on data the fit never saw.
ŵmap,i
The MAP weights found from the training trials with λi. The hat means “estimated”.

See both curves at once

Slide 8 is a hand sketch of the whole story, and the device below makes it real. It uses one toy neuron with 8 features, 14 training trials and 40 test trials. Slide λ from weak to strong. The blue line is the training score, the yellow line is the test score.

Slide the prior strength

Horizontal: λ from 0.001 to 1000 on a log scale. Vertical: average log-likelihood per trial, higher is better. The teal line is your λ. The green dot marks the best test score.

0.001

Illustrative toy: 8 features, true weights a smooth wave, Gaussian noise with standard deviation 1, 14 training trials and 40 test trials, all seeded. The MAP weights solve (XTX + λI) w = XTy by Gaussian elimination in your browser. The score is the average Gaussian log-likelihood per trial.

At λ = 0.001 the training score is the highest it ever gets and the test score is far lower. The gap is overfitting made visible: the fit knows the training trials by heart. As λ rises, the training score falls steadily, which is the price of a stiffer fit. The test score first rises, because a calmer fit generalises, then peaks, then falls again as the fit becomes too stiff.

A worked pick

Suppose a three-point grid gave these test scores per trial (illustrative): λ = 0.1 gives −1.9, λ = 1 gives −1.5 and λ = 10 gives −1.7. The maximum is −1.5, so λopt = 1. The recipe is only a loop and a comparison. Its cost is that it needs a held-out set, and it repeats the whole fit for every grid value.

That cost grows fast. With one hyperparameter, a grid of 8 values means 8 fits. With three hyperparameters, a grid of 8 per axis means 512 fits. This is why the lecture next offers a different route, in Chapter 2.

When it goes wrong

The symptom: your training score looks wonderful and your test score is poor. The measurement: the gap between the two curves, which here is large for small λ. The fix: raise λ until the test score peaks. A second symptom is a test score that is noisy from one random split to the next. With only 14 trials, one unlucky split can move the best λ by a factor of ten. Using more splits, or more data, steadies it.

Why do we score each λ on held-out trials instead of on the training trials?

Chapter 2

Choose the Prior by Its Evidence

Ask each prior how probable it made the data you saw, and keep the prior that did best

Three people each guess how big your neuron’s weight is. Ann says “about zero, give or take a third”. Bo says “somewhere within one of zero”. Cy says “anywhere within three”. Then your single measurement arrives: the weight looks like 1.0, give or take 0.5. Who made the better bet?

Ann bet narrowly on the wrong place and is surprised. Cy bet so widely that her probability was spread thin over a huge range, so any particular outcome got little. Bo bet on the right neighbourhood without spreading too far. The plain way to say it: the best prior is the one that made the data you saw least surprising. Slide 9 turns this into a number.

The denominator we ignored

Bayes’ rule says the posterior equals the likelihood times the prior, divided by a number that makes the area equal 1. Until now that number was a nuisance. Slide 9 points at it and gives it a job. The denominator is the evidence, also called the marginal likelihood: the probability of the data, averaged over every weight the prior allows.

P(Y | X, λ)
The evidence: how probable the observed responses Y are, for these stimuli X, under a prior of strength λ. It carries no weight w, because w has been averaged out.
∫
Add up over every possible weight. The curly S means a sum of infinitely many thin slices.
P(Y | X, w)
The likelihood: how well one particular weight w explains the data.
P(w | λ)
The prior: how plausible that weight was before the data, under strength λ.
dw
One thin slice of the weight axis. Likelihood times prior times slice width, added over all slices, is the area under the product curve.

The slide notes two readings. As a function of the weight, the numerator is what Bayes’ rule normalises. As a function of λ, the same quantity is a likelihood for λ itself: it says how well that prior setting explains the data. So choose λ by maximum marginal likelihood. The slide’s summary: “set hyperparameters using maximum (marginal) likelihood”.

Evidence is an area

Slide 10 shows the picture. A likelihood curve over the weight, three priors of different width, the product of likelihood and prior for each, and below it the area of each product plotted against the hyperparameter. The device below rebuilds it with our single measurement. The likelihood is a bump centred at 1.0 with spread 0.5. You choose the prior width.

Find the prior with the most evidence

Top: the blue likelihood, the pink prior, and the yellow product. The yellow area is the evidence. Bottom: log evidence for every prior width, with your choice as a dot. Slide the width.

0.32

Illustrative: one measurement y = 1.0 with noise 0.5, so the likelihood is a Gaussian bump in w, and the prior is a zero-centred Gaussian whose width (standard deviation) you set. The area is computed numerically on a grid. The slide labels its three priors with λ; here the same job is done by the width.

At width 0.32 the prior is a narrow spike at zero. The likelihood bump sits well off to the side, so the two barely overlap and the yellow area is small. At width 3 the prior is a low, wide hill. It overlaps the likelihood fully, but it is so low there that the product is small again. In between, around width 0.9, the product is tallest and the area is largest. That prior is the one that “expected” the data.

A worked comparison

For this Gaussian pair the area has a closed form: the evidence is a Gaussian bump in y with variance (prior width squared plus 0.25). For y = 1.0 that gives, at width 0.33: about 0.166. At width 1: 0.239. At width 3: 0.124. At width 0.87 the variance is almost exactly 1.0 and the evidence is 0.242, the maximum. The device shows the same values by numerical integration, which is how you would do it when no closed form exists.

Empirical Bayes: two steps

Slide 11 packages this as empirical Bayes. Step 1: estimate λ by maximising the evidence, which means fitting the hyperparameters that govern the prior. Step 2: with that λ, find the MAP weights as usual. The key difference from Chapter 1: no held-out set. The slide lists two advantages. You do not have to partition your data, and it is more practical with several λs, because you climb a smooth curve instead of searching a grid.

The catch, from slide 9: there is generally no closed-form maximum of the evidence, so you need numerical optimisation. The next chapter shows the case where the evidence has a formula. Chapter 10 shows what to do when it does not.

When it goes wrong

The symptom: the evidence curve is nearly flat. The measurement: the log evidence differs by less than about 1 between very different widths, here when the data are few or very noisy. The fix: nothing in the maths helps you, because the data truly do not distinguish the priors. Report that, and prefer the simpler (narrower) one.

Why does the evidence peak at a medium prior width instead of growing as the prior gets wider?

Chapter 3

The Evidence When Everything Is Gaussian

Add a Gaussian weight and Gaussian noise, and the data themselves come out Gaussian with a covariance you can write down

Chapter 2 computed an evidence by adding up thin slices. That works for one weight. With 100 weights it is hopeless: the integral has 100 dimensions. Is there a shortcut? For one special family of models there is, and the lecture spends five slides on it.

The family is the linear-Gaussian model. Two ingredients. The weights come from a Gaussian prior. The responses are the stimuli times the weights, plus Gaussian noise. In that family the evidence is itself a Gaussian, and you can write its covariance in one line.

Two facts about Gaussians

A Gaussian (a bell curve) is fixed by two things: its mean (where the centre is) and its covariance (how wide it is, and in several dimensions which way it leans). Slide 12 lists two “fun facts” and the whole derivation needs nothing else.

Fact 1, a linear map. Take a Gaussian vector x with mean μ and covariance Σ, and multiply by a matrix A. The result is Gaussian with mean Aμ and covariance AΣAT. Stretching the bell stretches its width, and the transpose handles the other side of each pair of coordinates.

Fact 2, a sum. Add two independent Gaussians. The means add and the covariances add. Two sources of independent doubt combine into one bigger doubt.

Derivation in three lines

Slides 12 to 15 reveal one line at a time. The prior says the weight vector w is Gaussian with mean 0 and covariance C. The encoding model says the responses are Y = Xw + ε, where X holds the stimuli, one row per trial, and the noise ε is Gaussian with covariance σ2I (the same independent noise on every trial). Now:

  1. Apply Fact 1. Xw is Gaussian with mean 0 and covariance XCXT. The prior on w, seen through the stimuli, becomes a prior on the responses.
  2. Apply Fact 2. Xw + ε adds a second Gaussian with covariance σ2I, so the covariances add: XCXT + σ2I.
  3. Name it. Y given X is Gaussian, mean 0, covariance XCXT + σ2I. That Gaussian is the marginal likelihood.
Y | X
The vector of all N responses, given the stimuli. We have averaged the weights out, so no w appears.
XCXT
Doubt that comes from not knowing the weights. Two trials move together when their stimuli are alike and the prior allows large weights.
σ2I
Doubt from noise in each trial. It sits on the diagonal only, because the noise is independent from trial to trial.

Check it by simulation

A derivation deserves a test. Take one weight and two trials with stimulus strengths 1.0 and 0.8. Draw many weights from the prior, make the two responses with noise, and plot each pair. The formula predicts the cloud’s shape. The yellow curve is the formula’s prediction; the dots are the simulation.

Test the marginal likelihood

Each blue dot is one simulated pair (response on trial 1, response on trial 2). The yellow ellipse is the 2-standard-deviation contour of N(0, XCXT + σ2I). Change the prior variance and the noise.

1.0
0.50

Simulation: 400 seeded draws of a weight from N(0, C) and of noise from N(0, σ2) for each trial, with stimulus strengths 1.0 and 0.8. The covariance printed from the dots is the sample covariance; the formula value is C · 1.0 · 0.8 for the off-diagonal. A sample of 400 agrees with the formula only to within a few percent.

At C = 1 and σ = 0.5 the cloud lies along a diagonal, because both trials share the same unknown weight. Raise the noise and the cloud puffs into a circle: independent noise dominates the shared weight. Raise C and the cloud stretches along the diagonal. In every setting the yellow ellipse hugs the dots, so the three-line derivation is right.

A worked number

With C = 1, σ2 = 0.25 and stimuli (1.0, 0.8), the covariance M = XCXT + σ2I is the 2 × 2 matrix with 1.25 and 0.89 on the diagonal and 0.80 off it. Its determinant is 1.25 × 0.89 − 0.802 = 0.4725. For observed responses Y = (1.0, 0.8), M−1Y = (0.529, 0.423), so YTM−1Y = 0.868. The Gaussian density gives log P(Y|X) = −½ ln(|2πM|) − ½ × 0.868 = −1.463 − 0.434 = −1.90.

The recipe, and what the prior becomes

Slide 16 writes the density as P(Y|X, θ) = 1/|2πM|1/2 · exp(−½ YTM−1Y), where M = XCXT + σ2I. Take the log and drop the constant to get the score you optimise over θ (the prior’s own parameters) and σ2: it is −½ log det M − ½ YTM−1Y plus a constant. The two terms pull in opposite directions. The first punishes a large M, meaning a vague model. The second punishes a poor fit.

The slide also shows what C can be. For ridge, C = (1/θ)I: every weight is independent with the same variance. For smoothing, C = (1/θ)L−1, where L is a matrix that penalises differences between neighbouring weights. Same recipe, different prior. A last note on the slide: there is a dual form that is cheaper to compute when the number of trials N is larger than the number of weights d.

When it fails: this exactness needs Gaussian noise. Spike counts are not Gaussian, so the evidence of a Poisson model has no such formula. That is the problem Chapters 6 to 10 solve.

Why does the covariance of Y | X contain two added terms, XCXT and σ2I?

Chapter 4

Where the Posterior Comes From

Build the posterior from a likelihood, a prior and a normaliser, and name each piece in neural terms

A neuron fires 2 spikes when you show a stimulus of strength 1. Before you saw that, you thought the weight was probably near 1, less likely 0 or 2. After the spikes, what should you believe? You should believe more in weights that would have produced about 2 spikes, and less in the others. The posterior is the arithmetic of that shift.

Slide 17 opens the second part of the lecture, with a section title: posterior distributions. Slide 18 repeats the definition from Chapter 0: the posterior is our belief about the regression weights w given the data and the prior. Slides 19 to 22 then ask the question students always ask: where does it come from?

Bayes’ rule in words

Slide 19 gives the rule in a sentence: posterior equals likelihood times prior, divided by a normalising constant. Each piece has a plain meaning.

The likelihood asks: if the weight were w, how probable would the spikes I saw be? It is the model of the neuron, called the encoding model. The prior asks: before any data, how plausible was w? Their product scores every weight by “fits the data” times “was plausible to begin with”. The normalising constant then rescales the product so that the total probability over all weights is 1.

Adding the conditions

The plain form is p(w | Y) = P(Y | w) P(w) / P(Y). Slides 20 and 21 add what we have been quietly holding fixed. We always know the stimuli X, and the prior has a setting θ (the slides use θ and λ for the same hyperparameter). So everything is conditioned on X and θ. Then two simplifications cross things out, in red on the slides.

p(w | Y, X, θ)
The posterior: belief about the weights after the data. Its area over all w is 1.
P(Y | X, w)
The encoding model (slide 22): the probability of the spikes given the stimuli and the weights.
P(w | θ)
The prior: belief about the weights before data, set by the hyperparameter θ.
P(Y | X, θ)
The evidence, or marginal likelihood (slide 22): the numerator’s area. It is the same number you maximised in Chapter 2.

Do it with three weights

Take one trial: stimulus x = 1, observed y = 2 spikes. Allow only three weights: 0, 1 and 2. The prior (illustrative) gives them 0.25, 0.50 and 0.25. The firing rate is ew, so the weights give rates 1, 2.72 and 7.39 spikes. The Poisson probability of exactly 2 spikes is then 0.184, 0.244 and 0.017.

Multiply each by its prior: 0.25 × 0.184 = 0.046, then 0.50 × 0.244 = 0.122, then 0.25 × 0.017 = 0.004. Add them: 0.172. That sum is the evidence. Divide each product by it: the posterior is 0.267, 0.708 and 0.025. These add to 1. The data moved belief toward weight 1, where the rate best matches 2 spikes, and away from weight 2, where the rate is far too high.

Now do the same on a continuous axis. The device below uses a Poisson neuron with the seeded trials of the hero. It draws the numerator, likelihood times prior, with its true size. Then it divides by the evidence.

Divide by the evidence

Choose what to draw. The numerator is likelihood times prior. The posterior is the numerator divided by its own area. Change the number of trials and the prior strength.

3
0.5

Illustrative seeded neuron (spike count Poisson with mean e^(x · w)). The numerator includes every factor: the Poisson probabilities with their factorials, and the Gaussian prior N(0, 1/strength). The evidence is its area on a 600-point grid from −3 to 5.

With 3 trials the numerator is tiny, a few thousandths at its tallest, because it is the probability of a specific list of spike counts. Switch to the posterior and the same shape rescales so that its area is exactly 1. The shape does not change; only the height does. That is all a normalising constant does.

This also explains why the MAP estimate does not need the evidence. Dividing by a constant moves no peak. To find the tallest point you can ignore the denominator. You need it only when you want actual probabilities, error bars or a score for the prior.

When it goes wrong

The symptom: your numerator underflows to 0 for long recordings. The measurement: with hundreds of trials the product of probabilities falls below the smallest computer number (see our Bayes’ rule lesson). The fix: work with logs, where products become sums. That is why the next chapters talk about the log-posterior.

In the three-weight example the numerator values add to 0.172. What does that number represent?

Chapter 5

The Gaussian Posterior, by Completing the Square

Multiply a Gaussian prior by a Gaussian likelihood and read the mean and covariance off the result

Two experts give you an estimate of a neuron’s weight. The first, the prior, says “0, give or take 1”. The second, the data, says “1.0, give or take 0.5”. A sensible person trusts the sharper expert more and lands closer to 1.0 than to 0. How much closer, and how sure should she be? The linear-Gaussian model has an exact answer.

The setup on slides 23 and 24

Slide 23 writes Bayes’ rule with a proportional sign: the posterior is proportional to the likelihood times the prior. (We drop the evidence for now; it only fixes the height.) It then labels all three as Gaussian. The likelihood, as a function of w, is Gaussian when the noise is Gaussian and the response is linear in w. The prior is Gaussian by choice. Slide 24 writes them out: the likelihood is N(Y | Xw, σ2I) and the prior is N(w | 0, C).

Slides 25 and 26 then make the claim that the posterior is Gaussian too, N(w | ŵmap, Σ), and ask what its mean and covariance are. The trick that answers it is called completing the square.

Completing the square, in plain words

A Gaussian is e raised to a negative quadratic: exp(−½(w − m)2/v). So if you take the logarithm of a Gaussian, you get a quadratic in w. Now multiply two Gaussians. Multiplying becomes adding in the log, and the sum of two quadratics in w is another quadratic in w. Any quadratic can be rewritten as a single square, −½(w − m)2/v, plus a constant. That rewriting is completing the square, and the m and v you find are the posterior mean and variance.

Slide 27 gives the result for many weights, with the mean and the covariance labelled in red.

ŵmap
The posterior mean. For a Gaussian it is also the peak, so it is the MAP estimate. It is the ridge-regression answer from Lecture 11, with the penalty set by σ2C−1.
Σ
The posterior covariance: the error bars. XTX/σ2 is the information the data bring, and C−1 is the information the prior brings. Information adds, then you invert to get uncertainty.

The hat on w means “estimated”, and the subscript says the estimate is the peak of the posterior. Notice that the covariance does not contain Y. How certain you are depends on which stimuli you showed, not on what the neuron did. We use that fact in Chapter 9.

Worked: one weight, one trial

Prior: mean 0 and variance C = 1, so precision (one over variance) 1. One trial with x = 1 and y = 1.0, noise variance 0.25, so the data have precision 4. Information adds: posterior precision 1 + 4 = 5, so variance 1/5 = 0.2 and standard deviation 0.45. The mean is the precision-weighted average: (1 × 0 + 4 × 1.0) / 5 = 0.8. The matrix formula agrees: (1 + 0.25/1)−1 × 1 = 0.8. The posterior sits between the experts, closer to the sharper one, and it is sharper than either.

Multiply two Gaussians

The pink prior and the blue likelihood multiply into the warm posterior. The dashed purple curve is the completing-the-square formula. They should lie on top of each other. Change the trials, the prior width and the noise.

3
0.50
0.60

Illustrative: stimulus strengths are the first n of the seeded trials, responses y = 1.2 x + noise with the seeded noise scaled by your σ. The warm curve is the product of prior and likelihood normalised on a 500-point grid. The purple curve uses the formulas above with X a single column.

With 3 trials and a prior variance of 0.5 the posterior sits between the prior at 0 and the likelihood. Add trials and the likelihood gets sharper, so the posterior slides toward it. Widen the prior and the same thing happens, because the prior becomes a weaker expert. Make the noise large and the likelihood goes wide and the prior wins. The purple dashed line never leaves the warm curve, which is what “exact” means here.

Where the prior fails you

The symptom: the posterior mean stays near 0 although the data clearly say 1.2. The measurement: the prior variance is tiny next to the noise divided by the information, here C = 0.05 with 3 noisy trials. The fix: widen C, or choose it by evidence (Chapter 2) rather than guess.

Slide 28 ends the section with the question that opens the next one: what about approximating the posterior in non-Gaussian models? Spike counts are such a model. The product of a Poisson likelihood and a Gaussian prior is not a Gaussian, and no completing of the square will make it one.

The prior has precision 1 and the data have precision 4. What is the posterior variance?

Chapter 6

The Laplace Idea: A Parabola on the Log Curve

Copy the height, slope and bend of the log-posterior at its peak, and the copy is a Gaussian

You have a neuron with a Poisson spike count and a Gaussian prior on its weight. Chapter 5’s trick does not work, because the posterior is not a Gaussian. Yet it still looks like a hill: one peak, smooth sides. A hill that smooth looks a lot like a bell curve near its top. Can we simply fit a bell to the top of the hill?

Slide 29 opens the third part of the lecture with a title, and slide 30 states the goal: find a tractable Gaussian approximation to the posterior. Tractable means two things on the slide: it is easy to work with, and we can describe our uncertainty with a covariance matrix. The MAP estimate gives the location of the maximum. But we may also care how concentrated the posterior is in different directions: its error bars.

The plan: do it on the log

Slide 31 gives the idea: use a second-order Taylor series to approximate the log-posterior at its maximum. Why the log? Because the log of a Gaussian is a parabola, and a parabola is the simplest curve with a peak. If the log-posterior is nearly a parabola near the top, the posterior is nearly a Gaussian there.

A Taylor series is a way to copy a curve near one point with a polynomial. The second-order copy matches three things at that point: the height f(w0), the slope f′(w0) (the first derivative: how steeply the curve rises) and the bend f″(w0) (the second derivative: how fast the slope itself changes). Here is the slide-32 formula.

f(w)
The log-posterior, as a function of the weight. We want a simple copy of it.
f(w0)
The height at the chosen point w0. Just a constant that shifts the curve up or down.
f′(w0)(w − w0)
The slope term: a straight line tilted by the slope at w0.
½ f″(w0)(w − w0)2
The bend term: a parabola. A negative f″ makes it open downward, like a hill.

Now choose w0 to be the peak, the MAP estimate. At a peak the slope is exactly zero, so the slope term vanishes (slide 32 crosses it out). What remains is a constant plus the bend term. Slide 33 applies exp to bring the log back to the posterior itself, and slide 34 shows the result: the exponential of the parabola is a bell curve that sits on the true posterior.

Reading the variance off the bend

A Gaussian with mean μ and variance σ2 is proportional to exp(−(w − μ)2/(2σ2)). Our approximation is proportional to exp(½ f″(w0)(w − w0)2). Match the two. The centres agree at μ = w0. The coefficients agree when −1/(2σ2) = ½ f″, so σ2 = −1/f″(w0). A sharp bend (large negative f″) gives a small variance. A flat top gives a large one.

Slide 35 collects all of it into three steps:

  1. Find the MAP estimate ŵmap, by any optimiser.
  2. Compute the second derivative of the log-posterior there, f″(ŵmap).
  3. Read off the variance: σ2 = −1/f″(ŵmap). The approximation is N(ŵmap, −1/f″(ŵmap)).

Copy the hill with a parabola

Top: the warm log-posterior and the dashed purple parabola from its Taylor series. Bottom: the exponential of each. First slide the trials. Then move the expansion point off the peak and watch the parabola lose the hill.

4
at the peak

Illustrative seeded neuron, prior strength 0.2. The slope and bend at the chosen point are computed exactly: f′ = Σ x(y − exw) − 0.2w and f″ = −Σ x2exw − 0.2. Offsets are in units of the Laplace standard deviation. Off the peak the parabola has a slope term, so its own peak moves.

At the peak, the dashed parabola and the solid curve touch and share their bend. The lower panel shows the bell almost on top of the posterior, as on slide 34. Slide the expansion point to +2 and the parabola still matches height, slope and bend there, but its own peak has moved away and its width no longer describes the hill. That is why step 1 is to find the MAP.

A worked case by hand

One trial, stimulus 1, two spikes, flat prior. The log-posterior is f(w) = 2w − ew (dropping a constant). Slope: f′ = 2 − ew = 0 at w = ln 2 = 0.693. Bend: f″ = −ew = −2 there. So σ2 = 1/2 and σ = 0.71. The parabola is f(0.693) − (w − 0.693)2 = −0.614 − (w − 0.693)2. Check at w = 0: the true value is −1.000 and the parabola gives −1.094. At w = 1.2: true −0.920, parabola −0.871. Close near the top, slightly off in the tails, and the error is not symmetric: the true curve falls faster on the right.

When it goes wrong: the symptom is a Laplace bell that is symmetric while the true posterior leans to one side. The measurement is the overlap read-out. The fix is more data, because every extra trial makes the log curve more parabolic near its top.

At the MAP estimate the log-posterior has slope 0 and second derivative −50. What are the Laplace mean and variance?

Chapter 7

Worked Exercise: One Poisson Neuron

Run the three Laplace steps by hand on one trial of spikes and get a closed-form error bar

You show a bar of light of strength x = 1 and count y = 2 spikes. The model says the spike count is Poisson with mean exw. What do you believe about w, and how wide is that belief? Slides 36 and 37 pose this as the lecture’s in-class exercise. We will do it slowly, with every step visible.

The model on slide 36

A Poisson distribution gives the probability of counting exactly y events when the average is μ: μy e−μ / y!. Here μ is the output of a nonlinearity f applied to the stimulus times the weight, μ = f(xw). The slide picks f(z) = ez, the exponential nonlinearity. It keeps the rate positive, which a firing rate must be, for any sign of the weight (see our GLM lesson or Lecture 10). The prior is flat (λ = 0): we add no belief of our own. Then the posterior is just the normalised likelihood.

The slide also says: assume someone gave you the MAP estimate, ŵmap. We will find it too, because here it takes one line.

Step 1: the log-likelihood

Take the log of the Poisson probability with μ = exw. The product becomes a sum, and the exponent y comes down as a multiplier:

f(w)
The log-posterior with a flat prior, which equals the log-likelihood plus a constant.
y x w
Rewards weights whose rate is high when many spikes were seen. It is linear in w.
exw
Punishes a rate that is too high, since every spike-free moment is evidence against a high rate. It grows quickly with w.
log y!
A constant that does not depend on w. It shifts the curve and has no effect on the peak or the bend.

Step 2: the derivatives

The slope: f′(w) = yx − x exw. Set it to zero to find the peak: exw = y, so ŵmap = (ln y)/x. In words, the best weight makes the model’s predicted rate equal the count you saw. The bend: f″(w) = −x2 exw. It is negative for every w, so the curve is a hill with no second peak. We will use that in Chapter 9.

Step 3: the variance

Apply σ2 = −1/f″(ŵmap). The result is 1/(x2 ex ŵ), the slide-37 answer: N(ŵmap, 1/(x2 ex ŵmap)). Because ex ŵ equals y at the peak, this is the same as 1/(x2y). More spikes and a stronger stimulus both shrink the variance.

For x = 1 and y = 2: ŵ = ln 2 = 0.693, σ2 = 1/(1 × 2) = 0.5, σ = 0.71. For x = 2 and y = 2: ŵ = 0.347, σ2 = 1/(4 × 2) = 0.125, σ = 0.35. For x = 1 and y = 8: ŵ = 2.08, σ2 = 1/8, σ = 0.35. Doubling the stimulus halves the uncertainty. So does quadrupling the count.

Check the exercise

Choose a stimulus strength and a spike count. The warm curve is the exact posterior for a flat prior. The dashed purple curve is the exercise’s answer. Try 0 spikes.

1.00
2

Exact: f(w) = yxw − exw on a 600-point grid, normalised. Laplace: the closed form of this chapter. With y = 0 the log-posterior −exw keeps rising toward negative w, so no peak exists and the posterior with a flat prior cannot be normalised; the curve is drawn unnormalised.

With x = 1 and y = 2 you can see the purple curve sit on the warm one, but a little narrower on the right and wider on the left: the exact posterior leans left. Raise y to 12 and the lean fades. The more spikes you count, the more parabolic the log curve becomes near its peak.

Now set y = 0. There is no peak at all: the likelihood just keeps rising as the weight heads to minus infinity, because the model can always lower the rate further. This is the answer to quiz question 1 on slide 2: the maximum likelihood estimator might not exist. A prior fixes it, which is one more reason to prefer MAP over maximum likelihood.

When it goes wrong

The symptom is an error bar you cannot compute. The measurement: the formula gives 1/(x2y), which with y = 1 and x = 1 is a standard deviation of 1, wide and honest. At y = 0 the formula would divide by zero, because no peak exists. Never apply it without checking that a peak exists.

A trial with stimulus x = 2 gives y = 8 spikes. With a flat prior, what are the Laplace mean and variance of the weight?

Chapter 8

Many Weights: Gradient, Hessian, Covariance

Replace the slope with a vector and the bend with a matrix, and the same three steps give a covariance matrix

A real neuron responds to many stimulus features at once: a bar’s orientation and its contrast, or ten past time bins of a sound. Each feature gets a weight, so w is now a list of d numbers. Two features often rise and fall together. When they do, the data can tell that one of the two weights is large, but not which. A single standard deviation per weight cannot say that. We need to describe how the doubts are linked.

Slide 38 begins by saying exactly that: in the general case w is a vector. The Poisson GLM is the same, with the dot product xTw in place of xw. The one-dimensional Taylor series must grow up too.

The vector Taylor series

Slide 38 writes the multi-dimensional series. The height f(w0) stays. The slope becomes a gradient, the list of d slopes, one per weight, written ∇f(w0). The bend becomes a Hessian, a d × d table H whose entry in row i and column j says how the slope along weight i changes as you move along weight j. In short: the Hessian is the matrix of second derivatives.

f(w)
The log-posterior of all d weights. It returns one number for a list of d numbers.
∇f(w0)T
The gradient: d slopes. At the MAP it is the zero vector (slide 39 crosses it out), exactly as the slope was zero in one dimension.
H
The Hessian, d × d, symmetric. On the diagonal: the bend along each weight. Off the diagonal: how two weights interact.

From the Hessian to the covariance

At the MAP the gradient vanishes, so f(w) ≈ const + ½ (w − w0)T H (w − w0). Slide 39 sets it next to the log of a Gaussian, which is −½ (w − μ)T C−1 (w − μ). The two have the same shape when μ = w0 and H = −C−1. Invert both sides: C = −H−1. Slide 40 gathers it:

  1. Find the MAP estimate ŵmap (now a list of d numbers).
  2. Compute the Hessian H of the log-posterior at ŵmap.
  3. The posterior covariance is C = −H−1, and the approximation is N(ŵmap, −H−1).

It is the 1-D rule, σ2 = −1/f″, with the division replaced by a matrix inverse.

The data flow

For the Poisson GLM with N trials and d features: the stimulus matrix X has shape N × d. The rates are r = exp(Xw), a list of N numbers. The gradient is XT(y − r) − λw, a list of d numbers. The Hessian is −XT diag(r) X − λI, a d × d matrix. The covariance C is d × d. Each rate ri weights how much trial i contributes to the curvature, so trials with a high predicted rate pin the weights down most.

A worked 2 × 2

Suppose at the MAP the Hessian is H = [[−4, −1], [−1, −2]]. Its determinant is (−4)(−2) − (−1)(−1) = 7, so H−1 = (1/7)[[−2, 1], [1, −4]] and C = −H−1 = [[0.286, −0.143], [−0.143, 0.571]]. The standard deviations are √0.286 = 0.53 and √0.571 = 0.76. The correlation of the two weights is −0.143 / (0.53 × 0.76) = −0.35. They trade off: if w1 is a bit higher than the peak, w2 tends to be lower.

Fit two weights at once

Warm shading is the exact posterior of two weights. The purple ellipses are the Laplace Gaussian at one and two standard deviations. Raise the correlation of the two stimulus features and watch the blob stretch and tilt. Add trials and it shrinks.

30
0.70

Illustrative: a seeded neuron with two features and true weights (0.8, 0.5); features are 0.9 times correlated unit noise (average zero), prior strength 0.1. The peak comes from 2-D Newton steps; the Hessian is −Σ ex·w x xT − 0.1 I, summed over your trials. The heat map is the exact posterior on a 56 by 56 grid.

At correlation 0 the features are unrelated, yet the blob still leans (a correlation of about −0.55 with these 30 trials). The Hessian weights each trial by its predicted rate, and the high-rate trials are those where both features are large, so the two weights share credit even then. At correlation 0.7 the lean is stronger, and at 0.95 the blob becomes a long thin sausage: the data pin down the sum of the weights well and the difference hardly at all. The covariance matrix captures that, and a pair of separate error bars could not.

When it goes wrong

The symptom is a huge variance along one direction, with a Hessian that is nearly singular (one tiny eigenvalue). The measurement: the ratio of the largest to the smallest eigenvalue of H, here growing quickly as correlation rises. The fix: collect stimuli that vary the two features independently, or strengthen the prior, whose −λI adds a floor to every eigenvalue.

In the Laplace approximation for many weights, what is the posterior covariance?

Chapter 9

What the Laplace Approximation Gives You, and When to Trust It

Turn the covariance into credible intervals, see why it is exact for Gaussians, and see why GLMs are its home ground

You have a Laplace Gaussian with mean ŵ and covariance C. A collaborator wants one sentence for the paper: “the weight for the 45 degree feature is…” what? And a second collaborator asks whether you should trust this at all, since you replaced a real posterior with a bell. Slide 41 answers both in three short notes.

Note 1: credible intervals from the diagonal

The diagonal entries Cii are the variances of the individual weights. So √Cii is one standard deviation of the posterior for weight wi. A credible interval is the Bayesian error bar: a range that holds a stated share of the posterior probability. The slide calls these confidence intervals and adds that Bayesians say credible. For a Gaussian, the mean plus or minus 1.96 standard deviations holds 95%.

Take Chapter 8’s example, with a peak at (1.0, 0.5) and C = [[0.286, −0.143], [−0.143, 0.571]]. The standard deviations are 0.53 and 0.76. The 95% credible interval for w1 is 1.0 ± 1.96 × 0.53 = [−0.04, 2.04]. For w2 it is 0.5 ± 1.96 × 0.76 = [−0.98, 1.98] (illustrative numbers). Neither interval excludes zero, so this tiny data set cannot say that either weight is nonzero.

Note 2: it is exact when the posterior is Gaussian

The second note says the Laplace approximation recovers the true covariance if the posterior really is Gaussian. The reason is plain. The log of a Gaussian is exactly a parabola, so its second-order Taylor series is not an approximation at all. Check against Chapter 5: the linear-Gaussian log-posterior has Hessian −(XTX/σ2 + C−1), and −H−1 is the covariance Σ that completing the square gave. Same answer by a different road.

Note 3: GLMs have one hill

The third note says Laplace is well suited to GLMs, because there we have a guarantee that the log-posterior is concave: unimodal, curving downward everywhere. You already derived this in Chapter 7: f″(w) = −x2exw is negative for every w. In many weights the Hessian is negative definite, so the log-posterior is one bowl with one peak. Two good things follow. A simple optimiser finds the one peak from any start. And one Gaussian is a reasonable summary of one hill.

The guarantee holds only for such models. A model with hidden structure, such as a mixture or a neural network, can have many peaks. A single Gaussian cannot cover two separate hills.

Check the 95% interval

Choose a model. The bars under the curve are 95% intervals: the exact one in warm, the Laplace one in purple. The green number is how much of the exact posterior the Laplace interval truly holds. It should be 95%.

3

Poisson GLM: the seeded neuron of the hero, prior strength 0.2. Two-peak model: an illustrative toy posterior, 60% of its probability in a bell centred half the gap to the left of zero and 40% in one the same distance to the right, each of standard deviation 0.35, as if a neuron’s preferred feature could be one of two values. Laplace is taken at the taller peak, with its bend measured numerically.

In the GLM mode, with 3 trials the Laplace interval is a little off: it runs from 0.34 to 1.60 where the exact one runs from 0.18 to 1.49, because the exact posterior leans left. It still holds 94% of the exact mass. With 40 trials the two bars are almost the same. Now switch to the two-peak model and slide the gap up. With a gap of 0 the two bells merge into one and Laplace is fine. At a gap of 2 the posterior has two hills, and the Laplace bell sits on the taller one and does not know the other exists. Its interval holds only about 57% of the true probability, and it is far too confident.

When it goes wrong

The symptom: error bars that look small and tidy while the model changes sharply with the starting point of the optimiser. The measurement: run the optimiser from several random starts. If they land on different peaks, the log-posterior is not concave and one Gaussian is not enough. The fix: describe each peak, or sample the posterior with Monte Carlo methods (see our Monte Carlo and importance sampling lessons).

Why can you trust a single Laplace Gaussian for a Poisson GLM more than for a model with two possible tuning peaks?

Chapter 10

Scoring a Prior with the Laplace Approximation

Use the Gaussian to get the evidence of a non-Gaussian model, and pick the prior strength by climbing it

Chapter 2 said: choose the prior by its evidence. Chapter 3 showed a formula for it, but only when the noise is Gaussian. A spike-count model is Poisson, so the evidence is an integral with no formula. Yet we just built a Gaussian that stands in for the posterior. Can it also stand in for the integral? Slides 42 to 44 show that it can, with one rearrangement of Bayes’ rule.

Rearrange Bayes’ rule

Slide 42 puts two lines on screen. Bayes’ rule says the posterior equals the likelihood times the prior over the evidence. The Laplace approximation says the posterior is about N(w | ŵmap, −H−1). Slide 43 sets them equal and colours the new Gaussian green, as the Laplace posterior. Slide 44 then solves for the evidence, which is the one unknown:

P(Y | X, θ)
The evidence we want, for prior setting θ.
P(Y | X, w)
The likelihood of the spikes at the peak weight. We can compute it directly.
P(w | θ)
The prior density at the peak weight. We can compute it directly.
N(w | ŵmap, −H−1)
The Laplace posterior, evaluated at its own peak. Its height there is 1/√(2πσ2) in one dimension, so dividing by it multiplies by √(2πσ2).

The identity is exact for the true posterior at any w. The approximation is that we replace the true posterior by the Laplace Gaussian. We evaluate at the peak because that is where the Gaussian is most accurate. In log form, for one weight: log evidence ≈ log likelihood + log prior + ½ log(2πσ2), all at ŵmap. The last term is the width: a wider hill holds more probability mass, so more evidence.

A worked check

One trial, x = 1 and y = 2, with a flat prior, whose density we set to 1 (this prior is improper, so the evidence is a relative score). The exact evidence is the area of e2we−ew/2. Substitute u = ew: it becomes ∫ u e−u/2 du = 1/2. The Laplace route: the likelihood at the peak ŵ = ln 2 is e−2 × 22/2! = 0.2707. The width factor is √(2π × 0.5) = 1.7725. The product is 0.480. Exact 0.500, Laplace 0.480: four percent low, from a hill that is slightly lopsided.

Optimising the hyperparameters

Slide 44 ends: use this approach to optimise the hyperparameters θ, although it requires recomputing ŵmap for each setting of θ. That is the price. For every candidate prior strength, you must refit the MAP weights and recompute the Hessian. Then you compare the scores and move θ uphill. It is still much cheaper than cross-validation, since there are no held-out sets and the score is smooth.

Compare exact and Laplace evidence

Each curve scores every prior strength by its log evidence: the exact value (warm) and the Laplace value (dashed purple). Move the teal marker along the strength axis, and change the number of trials.

0.10
8

The seeded neuron of the hero. Exact: log of the area of likelihood times prior, with every constant included, on a 1,500-point grid from −5 to 7. Laplace: for each strength, Newton’s method finds the peak and bend afresh, then log likelihood + log prior + ½ log(2πσ2) at the peak.

With 8 trials the two curves lie almost on top of each other, differing by less than 0.01 at a strength of 0.1, and both peak at the same strength, about 1.3. With 40 trials the peak moves to a weaker prior, about 0.6, because more data need less help from the prior. Even a single trial leaves the curves within a few hundredths of each other. A small error in the height of the evidence curve matters little, because we only want where it peaks. The read-out gives the gap at your chosen strength and the strengths at the two peaks.

When it goes wrong

The symptom: Laplace picks a prior strength noticeably different from the exact optimum. The measurement: the distance between the two peak positions in the read-out. The fix: more data, which makes the posterior more Gaussian, or a check of the winner against cross-validation. Also remember the cost. In d dimensions each evaluation needs a determinant of a d × d matrix, which grows as d3 when done by direct elimination.

Why must you recompute the MAP weights and the Hessian for every candidate prior setting when you score priors by the Laplace evidence?

Chapter 11

Field Guide: Laplace in One Page

Keep the numbers, the checklist and the code, and see where to go next

A point estimate hides how sure you are. The posterior says how plausible each weight is. When the model is Gaussian you can write the posterior exactly. When it is not, as with spike counts, you find the peak, measure the bend of the log-posterior there, and read a Gaussian off it. The bend gives the covariance, the covariance gives error bars, and the same trick turns an unsolvable evidence integral into a formula you can use to choose the prior.

The numbers and terms

TermPlain meaningWhereValue in our toys
MAP estimateThe peak of the posterior: the most plausible weight.Ch 0, 61.04 for the hero neuron after 10 trials
PosteriorBelief about the weights after the data. Area 1.Ch 40.267, 0.708, 0.025 over three weights
EvidenceThe probability of the data, averaged over the prior.Ch 2, 40.172 for the three-weight example
Cross-validationScore each prior strength on held-back trials.Ch 1Best test score at strength 1
Linear-Gaussian evidenceY is Gaussian with covariance XCXT + σ2I.Ch 3log evidence −1.90 for two trials
Gaussian posteriorPrecisions add; the mean is a precision-weighted average.Ch 5Mean 0.8, variance 0.2
Laplace variance (1-D)σ2 = −1/f″ at the peak.Ch 60.5 for one trial, y = 2
Poisson trialVariance is 1/(x2y) with a flat prior.Ch 70.125 for x = 2, y = 2
Laplace covarianceC = −H−1 at the peak.Ch 8Standard deviations 0.53 and 0.76
95% credible intervalMean plus or minus 1.96 standard deviations.Ch 9[−0.04, 2.04] for weight 1
Laplace evidencelog likelihood + log prior + ½ log|2πC| at the peak.Ch 100.480 against an exact 0.500

Checklist before you quote an error bar

  1. Is there a peak? With zero spikes and a flat prior there is none. Add a prior.
  2. Is the log-posterior concave? For a GLM, yes. For anything with hidden structure, run several starts.
  3. Did the optimiser converge? The gradient at the answer should be close to zero.
  4. Is the Hessian negative definite? If not, C = −H−1 is meaningless.
  5. Do you have enough data? The bell is best when the posterior is narrow. Check against a sampler once.
  6. Are you quoting off-diagonal terms? A combination of weights needs the full C.

The core as code

import numpy as np

def laplace_poisson_glm(X, y, lam=0.1, iters=50):
    """Gaussian approximation to the posterior of a Poisson GLM.
    X: (N, d) stimuli, y: (N,) spike counts, lam: prior precision.
    Returns the MAP weights (d,) and the posterior covariance (d, d)."""
    N, d = X.shape
    w = np.zeros(d)
    for _ in range(iters):
        r = np.exp(X @ w)                       # (N,) predicted rates
        grad = X.T @ (y - r) - lam * w          # (d,) gradient of the log-posterior
        H = -(X.T * r) @ X - lam * np.eye(d)    # (d, d) Hessian, negative definite
        step = np.linalg.solve(H, grad)         # Newton step
        w = w - np.clip(step, -1, 1)
        if np.abs(step).max() < 1e-10:
            break
    r = np.exp(X @ w)
    H = -(X.T * r) @ X - lam * np.eye(d)
    C = np.linalg.inv(-H)                       # posterior covariance = minus inverse Hessian
    return w, C

def log_evidence(X, y, w, C, lam):
    """Laplace estimate of log P(y | X, lam)."""
    from math import lgamma, log, pi
    t = X @ w
    loglik = np.sum(y * t - np.exp(t)) - sum(lgamma(k + 1) for k in y)
    d = len(w)
    logprior = 0.5 * d * log(lam / (2 * pi)) - 0.5 * lam * (w @ w)
    logdetC = np.linalg.slogdet(C)[1]
    return loglik + logprior + 0.5 * d * log(2 * pi) + 0.5 * logdetC

Shapes: X is N × d, y is N, r is N, grad is d, H and C are d × d. The function returns what slide 40 asks for, N(ŵmap, −H−1), and log_evidence applies slide 44.

Where it sits in the field

The Laplace approximation is the cheapest Bayesian summary. Its cousins trade cost for accuracy. Sampling (Monte Carlo, importance sampling) is more accurate on hard posteriors and slower. Variational inference fits a Gaussian by a different rule and trains it with gradients, as in the VAE lesson. In neural decoding, the same Gaussian-on-a-peak idea appears wherever a state is estimated with a nonlinear observation model: see the Kalman filter, smoothing and the point-process GLM for BCI. For the mixtures that Laplace cannot handle, see EM for Gaussian mixtures. For the Gaussian machinery used here, see PCA.

Keep going

The takeaway. The MAP gives the pin. The bend of the log-posterior at the pin gives the circle. Find the peak, take minus the inverse Hessian, and you have a Gaussian with error bars, and a way to score any prior.

Credit: this lesson re-teaches Lecture 14 of NEU 560, Statistical Modeling and Analysis of Neural Data, Princeton University, Spring 2024, taught by Jonathan Pillow. The ideas and the exercise follow his slides; every device, number and example here is our own, and toy numbers are labelled illustrative. Course site: pillowlab.princeton.edu/teaching/statneuro2024.

Which three steps give the Laplace approximation of a posterior over d weights?

Now say it out loud: open Teach and explain, on a whiteboard, how a bend becomes an error bar. Or go back to the instrument and drag the trials once more.

NEU 560 Lecture 14: The Laplace Approximation
Course site · Back to Gleams