Before this lesson:lesson 03 (the Hessian and the
second-order Taylor model), lesson 10 (Fubini's
theorem, polar coordinates dxdy=rdrdθ, change of variables with ∣detDT∣),linear algebra lesson 06 (the spectral theorem
A=QΛQ⊤) and linear algebra lesson 07
(positive definite matrices, Cholesky, logdet). It helps to know the Gaussian distribution and
Bayes' rule (prior, likelihood, posterior) from the probability and statistics
track; we repeat what we need.
Time: about 85 minutes, plus the notebook.
Almost every closed form in probabilistic ML is one Gaussian integral: the normalizing constant of
N(μ,Σ), the KL divergence between two Gaussians (in the loss of a variational autoencoder),
the marginal likelihood of Bayesian linear regression and of a Gaussian process. When the integral
is not Gaussian, two tools remain before you fall back to Monte Carlo.
Gauss–Hermite quadrature computes a low-dimensional expectation under a Gaussian with a
handful of function evaluations. Gaussian-process libraries use it for non-Gaussian likelihoods.
Laplace's method replaces a peaked integrand by a Gaussian with the same peak and the same
curvature. It gives Stirling's formula, the Bayesian information criterion (BIC), and the
Laplace approximation, which turns a trained network into a Bayesian one for the price of a
Hessian (Laplace Redux, 2021).
In science, the same idea gives uncertainty for inverse problems. In 4D-Var data assimilation (weather
forecasting) and in seismic inversion, the inverse Hessian of the cost at its minimum is the
covariance of the Laplace (Gaussian) posterior.
The function e−ax2/2 with a>0 has height 1 at x=0. Its curvature at the peak
is a: the second derivative of the exponent −ax2/2 is −a. A large a gives a narrow bump.
The width is of order 1/a, and the area is exactly 2π/a (proved in section 3).
Area is height times width: four times the curvature gives half the area.
Let I=∫Re−x2dx. No formula built from the usual functions has the derivative
e−x2, so the fundamental theorem of calculus does not help directly. The trick is to compute
I2 instead:
I2=∫e−x2dx∫e−y2dy=∬R2e−(x2+y2)dxdy.
This is the volume under a round bump in the plane. A round bump is easy to cut into rings. A
thin ring at radius r with width Δr is almost a long thin rectangle: length 2πr, width
Δr, so its area is about 2πrΔr. Over the ring, the bump has height e−r2. So the
ring holds the volume
ΔV≈2πre−r2Δr.
The factor r saves us: 2πre−r2 is the derivative of −πe−r2. So the volume of all
rings is [−πe−r2]0∞=π, and I=π. This factor r is the factor in
dxdy=rdrdθ from lesson 10.
Interactive figure: loading…
Drag the violet point to choose a ring, then increase the number of rings n. Top: the bump
e−(x2+y2) seen from above (darker = higher) and the
selected ring. Bottom: each bar is the volume of one ring, divided by
Δr; the black curve is 2πre−r2. With more rings the bars fill the area under the
curve. The sum tends to π(1−e−9)≈π (the figure stops at r=3), so I≈π=1.7725.
Quick check
∫R2e−(x2+y2)/2dxdy=2π. What is ∫R2e−(x2+y2)/(2σ2)dxdy for σ>0?
Why.
Substitute x=σu,y=σv. Then dxdy=σ2dudv (the Jacobian determinant of the scaling in 2-D), and the integral becomes σ2⋅2π. Each of the two directions gets σ times wider, so the volume grows by σ2. The answer 2πσ forgets that there are two directions; 2π/σ2 confuses the variance σ2 with the curvature 1/σ2.
No coupling. If the integrand is a product, the integral is a product (Fubini's theorem, lesson 10):
∬e−ax2/2e−cy2/2dxdy=a2πc2π=ac2π.
Here ac is the determinant of diag(a,c).
Coupling is a rotation. A general quadratic form x⊤Ax has tilted elliptical level sets.
Rotate the coordinates to the eigenvectors of A. A rotation does not change volume, and in the
new coordinates there is no coupling. So the volume is 2π/λ1λ2=2π/detA,
where λ1,λ2 are the eigenvalues of A. Along the eigenvector vi the bump has width
of order 1/λi.
A linear term only moves the bump. Adding b⊤x to the exponent moves the peak to
m=A−1b and changes its height to e21b⊤A−1b. The width, and so the determinant
factor, stays the same.
Interactive figure: loading…
Change λ1,λ2 and the angle, then drag the violet peak. The shading is the bump
exp(−21x⊤Ax+b⊤x), with level sets at 1, 2 and 3 "widths".
The arrows are the eigenvectors scaled to the widths: v1/λ1 and
v2/λ2. The readout splits Z into a width part 2π/detA
and a height part e21b⊤A−1b, and compares Z with a grid sum. Notice: the angle
does not change Z; dragging the peak changes only the height part. Try the preset
"λ₂ < 0": then the integral is infinite.
Quick check
What is ∫R2exp(−21x⊤Ax)dx for A=(2112)?
Why.
The integral is 2π/detA with detA=4−1=3 (the eigenvalues are 3 and 1). Using only the diagonal entries ignores the coupling: the off-diagonal entries tilt and stretch the ellipse. 2π/3 forgets the square root: each direction contributes 2π/λi, not 2π/λi.
Now take an integrand that is not Gaussian: e−nφ(x) for a function φ with a single
minimum at x∗ and a large number n. At x∗ the integrand is largest. Elsewhere it is smaller
by the factor e−n(φ(x)−φ(x∗)), which is exponentially small in n. So only a small
region around x∗ matters, of width of order 1/n. In that region, φ is close to its
second-order Taylor model (lesson 03):
φ(x)≈φ(x∗)+21φ′′(x∗)(x−x∗)2.
There is no linear term, because φ′(x∗)=0 at a minimum.
So the integrand is close to a Gaussian bump with the same peak and the same curvature, and we know
its area: e−nφ(x∗)2π/(nφ′′(x∗)). This is Laplace's method.
Interactive figure: loading…
Increase n, then switch to the zoomed axis. The black curve is the integrand
e−n(φ−φ∗) (scaled to peak 1); its shaded area is the exact
integral. The dashed curve is the Laplace Gaussian. In the zoomed axis
u=n(x−x∗) the Gaussian stays fixed and the true curve moves onto it. The lower chart
shows the relative error against n, with the slope −1 prediction ∣c∣/n. Try
the four functions: "x2/2" is exact for every n; "Bernoulli" puts
Gaussian mass outside (0,1); "(x2−1)2/4" has two minima, and the error
does not go to 0.
Quick check
φ has two minima of equal depth and equal curvature, at x=−1 and x=1. You apply Laplace's method at x∗=1 only. As n→∞, what does the ratio (exact integral)/(Laplace value) tend to?
Why.
Each minimum carries the same Gaussian bump, so the exact integral is about twice the bump at x∗=1. The error does not shrink with n, because the second peak does not become small compared with the first one: both have the same height. Laplace's theorem assumes a unique global minimizer. With unequal depths, the lower peak wins, and the other one fades like e−nΔ.
Let I=∫e−x2dx. It is finite: from (∣x∣−21)2≥0 we get x2≥∣x∣−41,
so e−x2≤e1/4e−∣x∣, and ∫e−∣x∣dx=2.
I2=∫e−x2dx∫e−y2dy=∬e−(x2+y2)dxdy. This is Tonelli's theorem
(the integrand is positive) in the product case
(lesson 10, section 3.3).
Change to polar coordinates, x=rcosθ,y=rsinθ, with dxdy=rdrdθ. The map
from (0,∞)×(0,2π) covers the plane except one ray, a set of area zero.
I2=∫02π∫0∞e−r2rdrdθ=2π⋅[−21e−r2]0∞=2π⋅21=π.
I>0, so I=π.
For (b), substitute x=2/at, so dx=2/adt and ax2/2=t2:∫e−ax2/2dx=2/aπ=2π/a.■
In step 4 the factor r from the Jacobian is what makes re−r2 have an elementary
antiderivative. With a=1, (b) says ∫e−x2/2dx=2π: this is the 2π in the
standard normal density e−x2/2/2π.
A symmetric matrix A is positive definite, written A≻0, if x⊤Ax>0 for every
x=0. Equivalently, all its eigenvalues are positive
(linear algebra lesson 07).
Theorem (Gaussian integral). Let A be a symmetric d×d matrix with A≻0, and let
b∈Rd. Then
To check, expand the right side: −21x⊤Ax+21x⊤Am+21m⊤Ax−21m⊤Am+21b⊤A−1b.
The two cross terms add up to x⊤Am=x⊤b (this uses A=A⊤). The constant
−21m⊤Am=−21b⊤A−1b cancels the last term.
Shift. Put y=x−m. A shift has Jacobian determinant 1, so dx=dy.
Rotate. By the spectral theorem, A=QΛQ⊤ with Q orthogonal and
Λ=diag(λ1,…,λd), all λi>0 because A≻0.
Put u=Q⊤y. Then ∣detQ∣=1, so dy=du, and y⊤Ay=u⊤Λu=∑iλiui2.
Factor (Fubini). The integrand is now a product of d one-dimensional bumps:
∫e−21∑iλiui2du=∏i2π/λi=(2π)d/2(∏iλi)−1/2=(2π)d/2det(A)−1/2,
because the determinant is the product of the eigenvalues.
Multiply by the constant e21b⊤A−1b from step 1. ■
Why det−1/2. Each eigen-direction contributes its width 2π/λi. The product of
the widths is a volume, and the product of the λi is detA. So a large curvature (a large
detA) means a small volume.
The condition A≻0 is necessary. If one λi≤0, the ui-integral in step 4 is
∫e−λiui2/2dui=∞. If A is not symmetric, note that x⊤Ax only sees the
symmetric part (A+A⊤)/2: use that matrix in the formula.
In code: Cholesky, not eigenvectors. With A=LL⊤(L lower triangular,
linear algebra lesson 07) and u=L⊤y,
you get y⊤Ay=∥u∥2 and dy=du/detL, with detL=det(A)1/2. So
logdetA=2∑ilogLii, and m=A−1b comes from two triangular solves.
The Gaussian normalizer. Take A=Σ−1 and b=0, and shift by the mean μ:∫e−21(x−μ)⊤Σ−1(x−μ)dx=(2π)d/2det(Σ)1/2. Dividing by
this number gives the density of N(μ,Σ):
Fix A and view Z(b) as a function of b. The normalized density is
pb(x)=e−21x⊤Ax+b⊤x/Z(b).
Mean. Differentiate under the integral sign. This is allowed here, because the integrand and
its b-derivatives are bounded by integrable Gaussians. ∇bZ=∫xe−21x⊤Ax+b⊤xdx,
so ∇blogZ=∇bZ/Z=Epb[x].
Covariance. Differentiate once more:
∇b2logZ=Epb[xx⊤]−Epb[x]Epb[x]⊤=Covpb[x].
Read them off. From the closed form, logZ=const+21b⊤A−1b, so
∇blogZ=A−1b and ∇b2logZ=A−1. So pb=N(A−1b,A−1).
So A is the inverse covariance: the precision matrix. The function logZ(b) is the
log-partition function; "its gradient is the mean and its Hessian is the covariance" holds for
every exponential family. For example, the log-sum-exp in the softmax cross-entropy of
lesson 06 is the log-partition function of the categorical
distribution: its gradient is the vector of softmax probabilities. The same trick in a scale
parameter gives a second moment: dad∫e−ax2/2dx=−21∫x2e−ax2/2dx and
dad2πa−1/2=−212πa−3/2, so E[X2]=1/a for X∼N(0,1/a).
Marginal likelihood of Bayesian linear regression. Take n data points with features in a
design matrixΦ∈Rn×d and targets y∈Rn. The model has the prior
w∼N(0,α−1Id) and the likelihood y∣w∼N(Φw,σ2In). The
marginal likelihood or evidence is the probability of the data with the weights integrated
out: p(y)=∫p(y∣w)p(w)dw.
The exponent of p(y∣w)p(w) is quadratic in w:−21w⊤Aw+w⊤b−∥y∥2/(2σ2), with
A=αI+Φ⊤Φ/σ2 and b=Φ⊤y/σ2.
The constants in front are (2πσ2)−n/2 from the likelihood and (α/2π)d/2 from the prior.
The Gaussian integral over w gives (2π)d/2det(A)−1/2e21b⊤A−1b. The two
factors (2π)±d/2 cancel, so
The matrix A is the posterior precision, and m=A−1b is the posterior mean (section 3.3, step 3).
This value equals logN(y;0,σ2I+α−1ΦΦ⊤), the Gaussian-process form; section 5
checks this numerically. The term −21logdetA penalizes a posterior that is much narrower
than the prior: we come back to this "Occam factor" in section 3.7.
A quadrature rule replaces an integral by a weighted sum of function values. A K-node
Gauss–Hermite rule is a set of nodes t1,…,tK and weights w1,…,wK>0 with
∫Re−t2g(t)dt≈k=1∑Kwkg(tk),
that is exact for every polynomial g of degree ≤2K−1. The nodes are the roots of the
Hermite polynomial HK. The count makes sense: K nodes and K weights are 2K free numbers,
enough to match the 2K monomials 1,t,…,t2K−1. NumPy gives them as
np.polynomial.hermite.hermgauss(K). This is the "physicists'" weight e−t2, not e−t2/2.
Gaussian expectations. Let X∼N(μ,σ2). Substitute x=μ+2σt, so that
(x−μ)2/(2σ2)=t2 and dx=2σdt:
with w~k=wk/π. Check: with f=1 the sum must be 1, and indeed
∑kwk=∫e−t2dt=π.
For smooth f, the error falls very fast with K. For f with a kink (ReLU, max, a threshold)
it falls slowly, because no polynomial fits a kink well.
In D dimensions, the tensor-product rule needs KD nodes. That is fine for D≤3 or so;
beyond that, use Monte Carlo (lesson 10) or sparse grids.
Interactive figure: loading…
Increase K and switch between the functions. Top: f (black), the
shape of the density of X, and the nodesxk=μ+2σtk; a bigger dot means a bigger weight. Bottom: the
Gauss–Hermite error against K, and the typical Monte Carlo
errorσf/K for the same number of evaluations. Notice: for x6 the error is exactly 0
from K=4 on (2K−1≥6); for ex it reaches rounding level near K=12; for ReLU it falls slowly.
Why K nodes are exact up to degree 2K − 1
Write ⟨p,q⟩=∫e−t2p(t)q(t)dt. The Hermite polynomials H0,H1,… are
orthogonal for this inner product, and HK has degree K and K distinct real roots t1,…,tK.
Interpolatory weights. Let ℓk be the Lagrange polynomial of degree K−1 with
ℓk(tj)=1 if j=k and 0 otherwise. Set wk=∫e−t2ℓk(t)dt. Every polynomial r
of degree ≤K−1 equals ∑kr(tk)ℓk, so the rule is exact for it.
Divide by HK. Let p have degree ≤2K−1. Polynomial division gives p=qHK+r with
degq≤K−1 and degr≤K−1.
The qHK part. The exact integral is ⟨q,HK⟩=0, because q is a combination of
H0,…,HK−1. The rule gives ∑kwkq(tk)HK(tk)=0, because the nodes are roots of HK.
The r part is exact by step 1. So the rule is exact for p.
Degree 2K fails. For p(t)=∏k(t−tk)2, the integral is positive, but the rule gives 0.
Positive weights. Apply the rule to ℓk2 (degree 2K−2):wk=∫e−t2ℓk2dt>0.
In practice, the nodes and weights come from the Golub–Welsch method: the nodes are the eigenvalues
of a small symmetric tridiagonal matrix built from the three-term recurrence of the Hermite
polynomials, and the weights come from the first entries of its eigenvectors. The figure above
computes them this way.
Quick check
The 3-node Gauss–Hermite rule for X∼N(0,1) uses the nodes 0,±3 with weights 32,61,61. For which of these is it exact?
Why.
K=3 nodes are exact up to degree 2K−1=5. For X4:2⋅61⋅9=3, exact. For X6:2⋅61⋅27=9=15. "Degree ≤K" would be true for a rule with fixed nodes; Gaussian quadrature also chooses the nodes, which doubles the exact degree. For eX the rule gives 1.6382 instead of e1/2=1.6487: close, but not exact.
Theorem (Laplace's method). Let φ:Rd→R have a unique global minimizer x∗. Assume
φ has continuous derivatives up to order 4 near x∗, with H=∇2φ(x∗)≻0;φ stays at least some δ>0 above φ(x∗) outside every ball around x∗ (with δ
depending on the ball); and ∫e−φ<∞. Then, as n→∞,
Why it is true, in three steps. (1) Factor out the peak value e−nφ(x∗). (2) Near x∗,
replace φ by its Taylor model φ(x∗)+21(x−x∗)⊤H(x−x∗); far from x∗ the
integrand is exponentially small. (3) The Gaussian integral of section 3.2 with A=nH and b=0 gives
(2π)d/2det(nH)−1/2=(2π/n)d/2det(H)−1/2.
Proof
Factor out the peak.∫e−nφ=e−nφ(x∗)∫e−n[φ(x)−φ(x∗)]dx.
Taylor at the minimum.∇φ(x∗)=0, so
φ(x)−φ(x∗)=21(x−x∗)⊤H(x−x∗)+R(x) with ∣R(x)∣≤C∥x−x∗∥3 near x∗.
Zoom in. Put u=n(x−x∗), so dx=n−d/2du. The integral becomes
n−d/2∫exp(−21u⊤Hu−nR(x∗+u/n))du.
The remainder vanishes. For fixed u,nR(x∗+u/n)=O(∥u∥3/n)→0.
Choose a ball around x∗ so small that ∣R(x)∣≤41λmin(H)∥x−x∗∥2 in it. Inside
the ball, the integrand is at most e−41λmin(H)∥u∥2, which is integrable, so the
dominated convergence theorem lets the limit pass inside the integral. Outside the ball, the integrand
of step 1 is at most e−(n−1)δe−[φ(x)−φ(x∗)]: exponentially small.
Gaussian integral. The limit is ∫e−21u⊤Hudu=(2π)d/2det(H)−1/2. With the
factor n−d/2 this is (2π/n)d/2det(H)−1/2.
Why the error is O(1/n). Expand e−nR≈1−nR+21n2R2. The cubic part of nR
is odd in u and of size n−1/2; its integral against the symmetric Gaussian is zero. The next
terms, the quartic part of nR and the square of the cubic part, are of size 1/n. (Steps 1–5 need
only three derivatives; this step uses the fourth.) ■
The first correction in 1-D. With φk=φ(k)(x∗), the exact integral is the Laplace
value times 1+nc+O(n−2), where
c=24φ235φ32−8φ22φ4.
The Laplace figure of section 2 draws ∣c∣/n next to the true error.
Without an explicit n. In practice you approximate ∫e−Ψ(θ)dθ for a function Ψ
that grows with the amount of data. The same steps give
log∫e−Ψ(θ)dθ≈−Ψ(θ^)+2dlog2π−21logdet∇2Ψ(θ^),
where θ^ is the minimizer of Ψ. The factor (2π/n)d/2 of the theorem is this formula with
Ψ=nφ, because det(nH)=nddetH.
The peak is at x=n, so rescale: x=nt,dx=ndt. Then nlogx−x=nlogn−n(t−logt), and
n!=nn+1∫0∞e−nφ(t)dt with φ(t)=t−logt.
φ′(t)=1−1/t=0 at t∗=1;φ(1)=1;φ′′(t)=1/t2, so φ′′(1)=1.
Laplace: ∫0∞e−nφ(t)dt≈e−n2π/n. So
n!≈nn+1e−n2π/n=2πn(en)n.
With φ3=φ′′′(1)=−2 and φ4=φ′′′′(1)=6, the correction formula gives
c=245⋅4−86=121. So n!=2πn(n/e)n(1+12n1+O(n−2)).
n
n!
Stirling
n!/Stirling−1
1/(12n)
1
1
0.9221
0.0844
0.0833
10
3 628 800
3 598 696
0.0084
0.0083
100
9.333⋅10157
9.325⋅10157
0.00083
0.00083
3.7 The Laplace approximation of a posterior and of the evidence #
Let θ∈Rd be the parameters of a model, p(θ) the prior and p(D∣θ) the
likelihood of the data D. Bayes' rule gives the posteriorp(θ∣D)=p(D∣θ)p(θ)/p(D),
where the evidencep(D)=∫p(D∣θ)p(θ)dθ is the normalizing constant. Define the
negative log joint
Ψ(θ)=−logp(D∣θ)−logp(θ).
In deep learning, Ψ is the training loss with weight decay, up to a constant: if the loss is the
summed negative log-likelihood, weight decay 2γ∥θ∥2 is a Gaussian prior with precision γ.
MAP. The maximum a posteriori (MAP) estimate is θ^=argminθΨ(θ). You find it with
Newton's method, L-BFGS or ordinary training.
Curvature.H=∇2Ψ(θ^)=−∇2logp(D∣θ^)−∇2logp(θ^). A prior
N(0,vI) adds I/v. For logistic regression with inputs xi (the rows of X) and predicted
probabilities pi,H=X⊤diag(pi(1−pi))X+I/v
(lesson 06).
Posterior.logp(θ∣D)=−Ψ(θ)+const. Its second-order Taylor model at θ^
has no linear term, so it is the log of a Gaussian density:
p(θ∣D)≈N(θ^,H−1).
This is the Laplace approximation. The inverse Hessian H−1 is its covariance: directions of
high curvature are well determined by the data, flat directions are uncertain.
Evidence.p(D)=∫e−Ψ(θ)dθ, so Laplace's method gives
logp(D)≈logp(D∣θ^)+logp(θ^)+2dlog2π−21logdetH.
MacKay reads the evidence as best-fit likelihood × Occam factor. The Occam factorp(θ^)(2π)d/2det(H)−1/2 is roughly the posterior volume divided by the prior volume. It is
small for a flexible model whose data pin down many parameters. So the evidence prefers the simplest
model that explains the data, and you can use it to choose hyperparameters, such as the prior variance
v (the weight decay), without a validation set.
The BIC. With n independent data points, H≈nIˉ, where Iˉ is the average curvature
per data point. So logdetH=dlogn+logdetIˉ. Keep only the terms that grow with n:logp(D)≈logp(D∣θ^)−2dlogn. The usual form is the
Bayesian information criterionBIC=−2logp(D∣θ^)+dlogn; smaller is better.
If Ψ is exactly quadratic, steps 3 and 4 are exact. This is the case for a Gaussian prior and a
Gaussian likelihood whose mean is linear in θ, such as Bayesian linear regression (section 3.3).
Quick check
For Bayesian linear regression (Gaussian prior, Gaussian likelihood with mean Φw), how good is the Laplace approximation of the posterior?
Why.
Ψ(w)=2σ21∥y−Φw∥2+2α∥w∥2+const is a quadratic function of w. Its second-order Taylor model has no remainder, so the posterior is exactly N(w^,H−1) with H=αI+Φ⊤Φ/σ2, and the Laplace evidence equals the exact marginal likelihood of section 3.3. The O(1/n) error comes from the cubic and quartic Taylor terms, and here they are zero.
Several modes (mixtures; the permutations of hidden units in networks). One Gaussian sees one
mode and underestimates the uncertainty. Remedy: an ensemble of Laplace approximations, or sampling.
Skewed or bounded posteriors (a rate, a variance, a probability near 0 or 1, little data). The
Gaussian is centred at the mode, not the mean, puts mass outside the support, and the O(1/n) error
is large. Remedy: an unconstrained parameter (logλ,logitp). The density then picks
up a Jacobian factor (lesson 10), so the result depends on
the parameterization.
Not a smooth interior minimum. A mode on the boundary, an active constraint, an L1 prior or a
ReLU kink at θ^ breaks the Taylor model. Early stopping leaves ∇Ψ(θ^)=0.
Singular or indefinite Hessian (flat and negative directions of large networks): H−1 is not a
covariance. Remedy: the generalized Gauss–Newton matrix or the Fisher matrix (both positive
semidefinite, lesson 08) plus the prior precision.
Size. A d×d Hessian for d=107 cannot be stored. Remedy: diagonal, Kronecker-factored
(K-FAC) or low-rank curvature, or Laplace on the last layer only.
High dimension. The O(1/n) rate is for a fixed d; the correction terms grow with d.
Interactive figure: loading…
Move the total count S and the number of windows m; then try "no events". Poisson counts
in m time windows with total S and the prior p(λ)=e−λ. The black curve is the exact
posterior (a Gamma density). The orange dashed curve is the Laplace approximation
in λ; the blue dashed curve is the Laplace approximation in θ=logλ,
drawn as a density in λ. Notice: with little data the orange Gaussian is too narrow, is centred at
the mode, and puts mass at λ<0. The evidence ratio depends only on S. With
S=0 the mode is on the boundary, and only the logλ version works.
Answers to section 1.
(1) π. The y-direction has curvature 4, so its width halves: 2π⋅2π/4=π, or
2π/detdiag(1,4)=2π/2.
(2) Only about 8%: Stirling gives 2π/e=0.9221 instead of 1!=1. The ratio n!/Stirling is
about 1+1/(12n), so the error is 0.83% at n=10 and 0.083% at n=100. Laplace's method is often
good long before n is large.
(3) Below. The Gaussian is centred at the mode, and for a distribution skewed to the right, the mode is
below the mean. In worked example (c) the mode is 1.5 and the mean is 1.75.
(a) A 2-D Gaussian integral. Compute Z for A=(3112) and b=(1,1).
A≻0: the trace is 5>0 and detA=6−1=5>0, so both eigenvalues are positive.
A−1=51(2−1−13),m=A−1b=51(2−1,−1+3)=(0.2,0.4),
and b⊤A−1b=b⊤m=0.2+0.4=0.6.
Z=(2π)2/2⋅5−1/2⋅e0.3=2.8099×1.3499=3.7930, and
logZ=1.8379−0.8047+0.3=1.3332.
The normalized density is N(m,A−1): mean (0.2,0.4) and covariance
(0.4−0.2−0.20.6). Both come from logZ(b)=const+21b⊤A−1b.
(The "worked example" button of the second figure shows this bump.)
(b) Gauss–Hermite by hand. Compute E[eX] for X∼N(0,1). The exact value is
e1/2=1.6487: it is Z(1,1)/Z(1,0) in 1-D, that is e21⋅12.
K=2:hermgauss(2) gives t=±1/2 and w=π/2 each. The mapped nodes are
x=2t=±1, with weights w~=w/π=21. So
E[eX]≈21(e+e−1)=1.5431: 6.4% too low.
K=3:t=0,±3/2 with w=2π/3,π/6,π/6. Mapped: x=0,±3 with
weights 32,61,61. So E[eX]≈32+61(5.6522+0.1769)=1.6382: 0.64% too low.
K=5 gives 1.648679 (relative error 2.5⋅10−5), and K=10 agrees with e1/2 to about 12 digits.
The 2-node rule is the "sigma point" rule μ±σ. It is exact for polynomials up to degree 3.
(c) Laplace for a Poisson rate. Three equal time windows show y=(2,1,3) events. Model:
yi∣λ∼Poisson(λ), so p(yi∣λ)=λyie−λ/yi!, and the prior is
p(λ)=e−λ on λ>0.
Joint.p(y,λ)=∏iyi!λyie−λ⋅e−λ=12λ6e−4λ,
because ∑iyi=6 and 2!1!3!=12.
Exact answers.p(y)=121∫0∞λ6e−4λdλ=12⋅476!=0.0036621
(substitute x=4λ and use ∫0∞x6e−xdx=6!), so logp(y)=−5.6097. The posterior is
∝λ6e−4λ: a Gamma distribution with shape 7 and rate 4, with mean 7/4=1.75 and
standard deviation 7/4=0.661.
Curvature.H=Ψ′′(λ^)=6/λ^2=2.667. Laplace posterior: N(1.5,0.375), standard
deviation 0.375=0.612.
Evidence.logp(y∣λ^)=6log1.5−3⋅1.5−log12=−4.5521,logp(λ^)=−1.5,
and 21log(2π/H)=0.4285. Sum: logp(y)≈−5.6236, so p(y)≈0.0036116: 1.38% too low.
Check of the error. The 1-D correction of section 3.5 (with Ψ in place of nφ, so n=1)
uses Ψ2=6/λ^2=8/3,Ψ3=−12/λ^3=−32/9 and Ψ4=36/λ^4=64/9. It gives
c=24(8/3)35(32/9)2−8(8/3)264/9=365−81=721=1.39%, as observed.
The defects of section 3.8 are visible. The Laplace mean is the mode 1.5, not the mean 1.75, because the
posterior is skewed. The Laplace standard deviation (0.612) is too small (0.661). And the Gaussian puts
0.7% of its mass on λ<0. This is the "y=(2,1,3)" setting of the last figure.
NumPy and SciPy check the numbers above with numerical integration and library densities.
importmathimportnumpyasnpfromscipyimportintegrate,stats# (a) sqrt(pi), and the 2-D example against the hand value 2*pi/sqrt(5)*e^0.3print(round(integrate.quad(lambdax:np.exp(-x*x),-np.inf,np.inf)[0],6),round(math.sqrt(math.pi),6))f=lambday,x:np.exp(-0.5*(3*x*x+2*x*y+2*y*y)+x+y)Z=integrate.dblquad(f,-15,15,-15,15)[0]mean_x=integrate.dblquad(lambday,x:x*f(y,x),-15,15,-15,15)[0]/Zprint(round(Z,4),round(2*math.pi/math.sqrt(5)*math.exp(0.3),4),round(mean_x,4))# 1.772454 1.772454# 3.793 3.793 0.2# Bayesian linear regression: the evidence (an integral over w) is the density of yrng=np.random.default_rng(0)Phi,y,alpha,s2=rng.normal(size=(5,2)),rng.normal(size=5),2.0,0.5defjoint(w2,w1):r=y-Phi@np.array([w1,w2])lik=np.exp(-r@r/(2*s2))/(2*math.pi*s2)**2.5returnlik*alpha/(2*math.pi)*np.exp(-alpha*(w1*w1+w2*w2)/2)evidence=integrate.dblquad(joint,-10,10,-10,10,epsabs=1e-14)[0]A,b=alpha*np.eye(2)+Phi.T@Phi/s2,Phi.T@y/s2formula=(-5/2*math.log(2*math.pi*s2)+math.log(alpha)-0.5*np.linalg.slogdet(A)[1]-y@y/(2*s2)+0.5*b@np.linalg.solve(A,b))gp_form=stats.multivariate_normal(np.zeros(5),s2*np.eye(5)+Phi@Phi.T/alpha).logpdf(y)print(round(math.log(evidence),6),round(formula,6),round(gp_form,6))# -10.580234 -10.580234 -10.580234# (b) Gauss-Hermite nodes and weights after x = sqrt(2) t, for N(0, 1)forKin(2,3):t,w=np.polynomial.hermite.hermgauss(K)print(np.round(np.sqrt(2)*t,4),np.round(w/np.sqrt(np.pi),4))# [-1. 1.] [0.5 0.5]# [-1.7321 0. 1.7321] [0.1667 0.6667 0.1667]exact=integrate.quad(lambdax:np.exp(x)*stats.norm.pdf(x),-30,30)[0]# = e^0.5print(round(math.cosh(1),4),round(2/3+math.cosh(math.sqrt(3))/3,4),round(exact,4))# 1.5431 1.6382 1.6487
importmathfromscipyimportspecial,stats# Stirling from Laplace: n!/Stirling - 1 is close to 1/(12n)fornin(1,10,100):log_stirling=0.5*math.log(2*math.pi*n)+n*math.log(n)-nprint(n,round(math.expm1(math.lgamma(n+1)-log_stirling),6),round(1/(12*n),6))# 1 0.084438 0.083333# 10 0.008365 0.008333# 100 0.000834 0.000833# (c) the Poisson rate: exact evidence and posterior against the Laplace numbers of section 4log_ev_exact=special.gammaln(7)-7*math.log(4)-math.log(12)log_ev_laplace=(6*math.log(1.5)-4*1.5-math.log(12))+0.5*math.log(2*math.pi/(6/1.5**2))post=stats.gamma(a=7,scale=1/4)print(round(log_ev_exact,4),round(log_ev_laplace,4))# -5.6097 -5.6236print(post.mean(),round(post.std(),4),round(math.sqrt(1.5**2/6),4))# 1.75 0.6614 0.6124print(round(stats.norm(1.5,math.sqrt(0.375)).cdf(0),4))# 0.0072: mass on lambda < 0
For a large d, never compute det and then log: the determinant overflows or underflows. Use
np.linalg.slogdet, or 2∑ilogLii from a Cholesky factor, and solve with A instead of
forming A−1.
Gaussian log-densities.logN(x;μ,Σ)=−21(x−μ)⊤Σ−1(x−μ)−21logdetΣ−2dlog2π
is in every Gaussian likelihood and in the KL term of a variational autoencoder. It is evaluated with a
Cholesky factor of Σ.
Marginal likelihood of Gaussian processes. Gaussian-process regression tunes the kernel
hyperparameters by maximizing logp(y)=−21y⊤Ky−1y−21logdetKy−2nlog2π,
where Ky is the kernel matrix plus the noise variance times I. The −21logdetKy term penalizes
kernels that are too flexible.
Gauss–Hermite in practice. GPflow and GPyTorch compute the 1-D expectations
Eq(f)[logp(y∣f)] of variational Gaussian-process classification by Gauss–Hermite
quadrature. For a Bayesian logistic model whose score is X∼N(1,22),E[σ(X)]=0.6477; the
probit approximation σ(μ/1+πσ2/8) gives 0.6511, and the plug-in σ(μ) gives
0.7311 (overconfident). In 1-D, the unscented transform of the unscented Kalman filter with κ=2
is exactly the 3-node rule (nodes μ,μ±3σ, weights 32,61,61).
Bayesian deep learning. Laplace on the last layer or with K-FAC curvature, with the generalized
Gauss–Newton matrix in place of the Hessian, the evidence to tune the weight decay, and a probit or
linearized predictive (Laplace Redux and the laplace-torch library). How to compute curvature
products without forming the matrix: lesson 08.
ML for science. In 4D-Var data assimilation and in seismic full-waveform inversion, the minimizer
of the cost is the MAP estimate, and the inverse Gauss–Newton Hessian there is the covariance of the
Laplace posterior (exact for a linear forward model). INLA (integrated nested Laplace approximations)
uses nested Laplace approximations for latent Gaussian fields in spatial statistics.
Model selection and Stirling. The BIC chooses the number of components of a Gaussian mixture
(see the ML fundamentals track, coming later). PyTorch's poisson_nll_loss(..., full=True) adds
the Stirling term ylogy−y+21log(2πy) for logy!.
Forgetting the r in rdrdθ. Without it, the ring areas are wrong and the integral
∫0∞e−r2dr has no elementary antiderivative.
Precision and covariance mixed up.∫e−21x⊤Axdx has det(A)−1/2, and A is the
precision. The Gaussian normalizer has det(Σ)+1/2 in the integral and det(Σ)−1/2 in the density.
A non-symmetric A.x⊤Ax only sees (A+A⊤)/2. Symmetrize before you use detA and A−1b.
Forgetting the square root. Each direction contributes 2π/λi, so the integral has
det(A)−1/2, not det(A)−1.
Gauss–Hermite constants.hermgauss uses the weight e−t2. You need both the 2 in
x=μ+2σt and the factor 1/π. Check that the weights sum to 1 for f=1.
Gauss–Hermite for a kink. ReLU, max and thresholds converge slowly; split the integral at the
kink or use more nodes.
Dropping the prior in H. The posterior precision is the likelihood Hessian plus the prior
precision. Without the prior term, H can be singular and the evidence is wrong.
Treating Laplace as parameterization-free. The mode, the Gaussian and the evidence estimate all
change when you change variables, for example from λ to logλ.
Evidence and likelihood mixed up. The maximum likelihood p(D∣θ^) always grows with model
size; the evidence p(D)=∫p(D∣θ)p(θ)dθ includes the Occam factor and does not.
Compute ∫R3exp(−21(x2+2y2+8z2))dxdydz.AnswerA=diag(1,2,8),detA=16, so the value is (2π)3/2/16=15.7496/4=3.9374.
Let p(x)∝exp(−2ax2+bx) with a>0. Find its mean and variance from logZ(b).AnswerlogZ(b)=21log(2π/a)+2ab2. Its derivative b/a is the mean, and its second derivative 1/a is the variance: p=N(b/a,1/a).
The 3-node Gauss–Hermite rule uses x=0,±3 with weights 32,61,61. How many nodes make E[X6] exact for X∼N(0,1), and why?AnswerK nodes are exact up to degree 2K−1. You need 2K−1≥6, so K=4. The 3-node rule gives 2⋅61⋅27=9 instead of 15.
Redo the evidence of worked example (c) with Laplace in θ=logλ. Remember the Jacobian.Answerλ=eθ,dλ=eθdθ, so the integrand in θ is e7θ−4eθ/12. The mode is eθ^=7/4; the curvature is 4eθ^=7. Laplace: 1.757e−7/12⋅2π/7=0.0038197×0.9474=0.0036188, 1.18% too low. This is better than 1.38% in λ, and it puts no mass on invalid values. Two parameterizations give two answers.
With n=1000 data points, model 1 has d=3 parameters and maximum log-likelihood −520.0; model 2 has d=5 and −515.0. Which one does the BIC prefer?Answerlogp(D)≈ℓ^−2dlogn with log1000=6.9078. Model 1: −520.0−10.36=−530.36. Model 2: −515.0−17.27=−532.27. So model 1: the gain of 5 nats does not pay for two more parameters, which cost log1000=6.9 nats.
Why does a Laplace approximation of a deep network usually use the generalized Gauss–Newton matrix instead of the true Hessian?AnswerAt a trained network, ∇2Ψ is often indefinite (SGD does not stop at an exact minimum, and there are flat and negative directions), so its inverse is not a covariance. The GGN J⊤∇2ℓJ is positive semidefinite for convex losses; adding the prior precision makes it positive definite; and it has cheap matrix-free and Kronecker-factored forms.
Recall cardsAnswer in your head first, then reveal. Add the cards to your review deck to see them again just before you would forget.
What is ∫Re−x2dx, and what is the key step of the proof?
π. Square it, write I2 as a 2-D integral and use polar coordinates: the factor r makes ∫0∞e−r2rdr=21.
Give ∫Rdexp(−21x⊤Ax+b⊤x)dx for symmetric A≻0.
(2π)d/2det(A)−1/2exp(21b⊤A−1b).
What are the mean and covariance of the density ∝exp(−21x⊤Ax+b⊤x)?
Mean A−1b, covariance A−1 (the gradient and the Hessian of logZ(b)).
Why is det(A)−1/2 in the Gaussian integral?
In the eigenbasis the integral factors into 1-D bumps of area 2π/λi, and ∏iλi=detA.
How do you compute E[f(X)],X∼N(μ,σ2), with Gauss–Hermite nodes tk and weights wk (weight e−t2)?
E[f(X)]≈π1∑kwkf(μ+2σtk).
For which functions is a K-node Gauss–Hermite rule exact?
For e−t2 times any polynomial of degree ≤2K−1.
State Laplace's method for ∫Rde−nφ(x)dx.
≈e−nφ(x∗)(2π/n)d/2det(∇2φ(x∗))−1/2, with relative error O(1/n), for a unique minimizer x∗ with a positive definite Hessian.
State Stirling's formula and the size of its relative error.
n!≈2πn(n/e)n; the ratio n!/Stirling is about 1+1/(12n).
What is the Laplace approximation of a posterior p(θ∣D)?
N(θ^,H−1), where θ^ is the MAP estimate and H is the Hessian of −logp(D∣θ)−logp(θ) at θ^.
Why does the Laplace approximation fail for a bimodal posterior?
One Gaussian sits on one mode. It misses the mass of the other mode and underestimates the uncertainty.
"Compute ∫e−x2dx." — Square it, use polar coordinates and the factor r:π.
"Where does det(Σ)1/2 in the Gaussian normalizer come from?" — Rotate to the eigenvectors;
the integral factors into d 1-D integrals with widths 2πλi(Σ), and their product is
(2π)d/2det(Σ)1/2.
"Write the log marginal likelihood of a GP and say how you compute it." — Cholesky of Ky:logdetKy=2∑ilogLii, and two triangular solves for y⊤Ky−1y.
"What is the Laplace approximation? When is it exact, and when does it fail?" — A Gaussian at the MAP
with covariance H−1; exact for linear-Gaussian models; it fails for multimodal, skewed or bounded
posteriors, kinks, and indefinite Hessians.
"Where does the BIC come from?" — From the Laplace evidence, keeping only the terms that grow with n.
"How do you get cheap uncertainty for a trained network?" — Last-layer or K-FAC Laplace with the GGN,
the prior precision tuned on the evidence, and a probit or linearized predictive.
The notebook for this lesson runs in Colab. It has five exercises, each with a check cell and
a folded solution:
Write log_gaussian_integral(A, b) with a Cholesky factor, and check it against dblquad and in
d=200, where det overflows.
Write gauss_hermite_expectation(f, mu, sigma, K), and compare its error with Monte Carlo for a
smooth function and for ReLU.
Write laplace_log_integral with Newton's method, and check it on Stirling's formula and on an
exact Gaussian.
Write laplace_logistic_evidence for Bayesian logistic regression on the breast-cancer data, check
it against importance sampling, and choose the prior variance by the evidence.
Compute the Laplace evidence of the Poisson-rate example in λ and in logλ, and show that
the error depends only on the total count.
Deisenroth, Faisal and Ong, Mathematics for Machine Learning, free PDF:
§6.5 (Gaussian distribution), §8.6 (Bayesian model selection) and §9.3.5 (marginal likelihood of
Bayesian linear regression).
Rasmussen and Williams, Gaussian Processes for Machine Learning, free
PDF: §2.2 (the marginal likelihood as a Gaussian integral) and §3.4 (the Laplace approximation for
Gaussian-process classification).
Gelman et al., Bayesian Data Analysis, 3rd ed., free
PDF: §4.1 (normal approximations to the posterior), §13.1 (finding posterior modes) and §13.3
(normal and related mixture approximations).