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.
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
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.
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.
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.
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.
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.
Chapter 1
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 λ?
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.
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:
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.
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.
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.
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.
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.
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.
Chapter 2
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.
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.
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”.
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.
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.
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.
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.
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.
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.
Chapter 3
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.
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.
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:
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.
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.
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.
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.
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.
Chapter 4
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?
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.
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.
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.
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.
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.
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.
Chapter 5
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.
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.
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.
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.
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.
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.
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.
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.
Chapter 6
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.
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.
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.
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:
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.
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.
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.
Chapter 7
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.
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.
Take the log of the Poisson probability with μ = exw. The product becomes a sum, and the exponent y comes down as a multiplier:
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.
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.
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.
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.
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.
Chapter 8
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.
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.
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:
It is the 1-D rule, σ2 = −1/f″, with the division replaced by a matrix inverse.
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.
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.
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.
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.
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.
Chapter 9
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.
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.
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.
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.
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%.
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.
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).
Chapter 10
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.
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:
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.
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.
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.
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.
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.
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.
Chapter 11
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.
| Term | Plain meaning | Where | Value in our toys |
|---|---|---|---|
| MAP estimate | The peak of the posterior: the most plausible weight. | Ch 0, 6 | 1.04 for the hero neuron after 10 trials |
| Posterior | Belief about the weights after the data. Area 1. | Ch 4 | 0.267, 0.708, 0.025 over three weights |
| Evidence | The probability of the data, averaged over the prior. | Ch 2, 4 | 0.172 for the three-weight example |
| Cross-validation | Score each prior strength on held-back trials. | Ch 1 | Best test score at strength 1 |
| Linear-Gaussian evidence | Y is Gaussian with covariance XCXT + σ2I. | Ch 3 | log evidence −1.90 for two trials |
| Gaussian posterior | Precisions add; the mean is a precision-weighted average. | Ch 5 | Mean 0.8, variance 0.2 |
| Laplace variance (1-D) | σ2 = −1/f″ at the peak. | Ch 6 | 0.5 for one trial, y = 2 |
| Poisson trial | Variance is 1/(x2y) with a flat prior. | Ch 7 | 0.125 for x = 2, y = 2 |
| Laplace covariance | C = −H−1 at the peak. | Ch 8 | Standard deviations 0.53 and 0.76 |
| 95% credible interval | Mean plus or minus 1.96 standard deviations. | Ch 9 | [−0.04, 2.04] for weight 1 |
| Laplace evidence | log likelihood + log prior + ½ log|2πC| at the peak. | Ch 10 | 0.480 against an exact 0.500 |
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.
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.
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.
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.