Type at least 2 letters. Enter opens the first result, Esc closes.

    Calculus for ML · Lesson 11 · Integrals for ML

    Gaussian integrals and Laplace's method

    Advanced 85 min 5 interactive figures 6 videos Colab notebook

    Before this lesson: lesson 03 (the Hessian and the second-order Taylor model), lesson 10 (Fubini's theorem, polar coordinates dx dy=r dr dθdx\,dy = r\,dr\,d\theta, change of variables with ∣det⁡DT∣|\det DT|), linear algebra lesson 06 (the spectral theorem A=QΛQ⊤A = Q\Lambda Q^\top) and linear algebra lesson 07 (positive definite matrices, Cholesky, log⁡det⁡\log\det). 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.


    Why this matters #

    Almost every closed form in probabilistic ML is one Gaussian integral: the normalizing constant of N(μ,Σ)N(\mu, \Sigma), 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.

    1. Predict first #

    2. The picture #

    One bump: height times width #

    The function e−ax2/2e^{-a x^2/2} with a>0a > 0 has height 1 at x=0x = 0. Its curvature at the peak is aa: the second derivative of the exponent −ax2/2-ax^2/2 is −a-a. A large aa gives a narrow bump. The width is of order 1/a1/\sqrt{a}, and the area is exactly 2π/a\sqrt{2\pi/a} (proved in section 3). Area is height times width: four times the curvature gives half the area.

    Two copies make a round bump #

    Let I=∫Re−x2 dxI = \int_{\R} e^{-x^2}\,dx. No formula built from the usual functions has the derivative e−x2e^{-x^2}, so the fundamental theorem of calculus does not help directly. The trick is to compute I2I^2 instead:

    I2=∫e−x2 dx∫e−y2 dy=∬R2e−(x2+y2) dx dy.\begin{aligned} I^2 &= \int e^{-x^2}\,dx \int e^{-y^2}\,dy \\ &= \iint_{\R^2} e^{-(x^2 + y^2)}\,dx\,dy . \end{aligned}

    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 rr with width Δr\Delta r is almost a long thin rectangle: length 2πr2\pi r, width Δr\Delta r, so its area is about 2πr Δr2\pi r\,\Delta r. Over the ring, the bump has height e−r2e^{-r^2}. So the ring holds the volume

    ΔV≈2πr e−r2 Δr.\Delta V \approx 2\pi r\,e^{-r^2}\,\Delta r .

    The factor rr saves us: 2πr e−r22\pi r\,e^{-r^2} is the derivative of −πe−r2-\pi e^{-r^2}. So the volume of all rings is [−πe−r2]0∞=π\big[-\pi e^{-r^2}\big]_0^\infty = \pi, and I=πI = \sqrt\pi. This factor rr is the factor in dx dy=r dr dθdx\,dy = r\,dr\,d\theta from lesson 10.

    Interactive figure: loading…

    Drag the violet point to choose a ring, then increase the number of rings nn. Top: the bump e−(x2+y2)e^{-(x^2 + y^2)} seen from above (darker = higher) and the selected ring. Bottom: each bar is the volume of one ring, divided by Δr\Delta r; the black curve is 2πr e−r22\pi r\,e^{-r^2}. With more rings the bars fill the area under the curve. The sum tends to π(1−e−9)≈π\pi(1 - e^{-9}) \approx \pi (the figure stops at r=3r = 3), so I≈π=1.7725I \approx \sqrt\pi = 1.7725.

    Quick check

    ∫R2e−(x2+y2)/2 dx dy=2π\int_{\R^2} e^{-(x^2 + y^2)/2}\,dx\,dy = 2\pi. What is ∫R2e−(x2+y2)/(2σ2) dx dy\int_{\R^2} e^{-(x^2 + y^2)/(2\sigma^2)}\,dx\,dy for σ>0\sigma > 0?

    Many dimensions: rotate, then factor #

    No coupling. If the integrand is a product, the integral is a product (Fubini's theorem, lesson 10):

    ∬e−ax2/2 e−cy2/2 dx dy=2πa 2πc=2πac.\iint e^{-a x^2/2}\,e^{-c y^2/2}\,dx\,dy = \sqrt{\frac{2\pi}{a}}\,\sqrt{\frac{2\pi}{c}} = \frac{2\pi}{\sqrt{ac}} .

    Here acac is the determinant of diag⁡(a,c)\operatorname{diag}(a, c).

    Coupling is a rotation. A general quadratic form x⊤Axx^\top A x has tilted elliptical level sets. Rotate the coordinates to the eigenvectors of AA. A rotation does not change volume, and in the new coordinates there is no coupling. So the volume is 2π/λ1λ2=2π/det⁡A2\pi/\sqrt{\lambda_1\lambda_2} = 2\pi/\sqrt{\det A}, where λ1,λ2\lambda_1, \lambda_2 are the eigenvalues of AA. Along the eigenvector viv_i the bump has width of order 1/λi1/\sqrt{\lambda_i}.

    A linear term only moves the bump. Adding b⊤xb^\top x to the exponent moves the peak to m=A−1bm = A^{-1}b and changes its height to e12b⊤A−1be^{\frac12 b^\top A^{-1}b}. The width, and so the determinant factor, stays the same.

    Interactive figure: loading…

    Change λ1\lambda_1, λ2\lambda_2 and the angle, then drag the violet peak. The shading is the bump exp⁡(−12x⊤Ax+b⊤x)\exp(-\tfrac12 x^\top A x + b^\top x), with level sets at 1, 2 and 3 "widths". The arrows are the eigenvectors scaled to the widths: v1/λ1v_1/\sqrt{\lambda_1} and v2/λ2v_2/\sqrt{\lambda_2}. The readout splits ZZ into a width part 2π/det⁡A2\pi/\sqrt{\det A} and a height part e12b⊤A−1be^{\frac12 b^\top A^{-1} b}, and compares ZZ with a grid sum. Notice: the angle does not change ZZ; dragging the peak changes only the height part. Try the preset "λ₂ < 0": then the integral is infinite.

    Quick check

    What is ∫R2exp⁡(−12x⊤Ax) dx\int_{\R^2} \exp\big(-\tfrac12 x^\top A x\big)\,dx for A=(2112)A = \begin{pmatrix} 2 & 1 \\ 1 & 2 \end{pmatrix}?

    Laplace's idea: a sharp peak looks Gaussian #

    Now take an integrand that is not Gaussian: e−nφ(x)e^{-n\varphi(x)} for a function φ\varphi with a single minimum at x∗x^* and a large number nn. At x∗x^* the integrand is largest. Elsewhere it is smaller by the factor e−n(φ(x)−φ(x∗))e^{-n(\varphi(x) - \varphi(x^*))}, which is exponentially small in nn. So only a small region around x∗x^* matters, of width of order 1/n1/\sqrt{n}. In that region, φ\varphi is close to its second-order Taylor model (lesson 03):

    φ(x)≈φ(x∗)+12φ′′(x∗)(x−x∗)2.\varphi(x) \approx \varphi(x^*) + \tfrac12 \varphi''(x^*)(x - x^*)^2 .

    There is no linear term, because φ′(x∗)=0\varphi'(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∗))e^{-n\varphi(x^*)}\sqrt{2\pi/(n\varphi''(x^*))}. This is Laplace's method.

    Interactive figure: loading…

    Increase nn, then switch to the zoomed axis. The black curve is the integrand e−n(φ−φ∗)e^{-n(\varphi - \varphi^*)} (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∗)u = \sqrt n\,(x - x^*) the Gaussian stays fixed and the true curve moves onto it. The lower chart shows the relative error against nn, with the slope −1-1 prediction ∣c∣/n|c|/n. Try the four functions: "x2/2x^2/2" is exact for every nn; "Bernoulli" puts Gaussian mass outside (0,1)(0, 1); "(x2−1)2/4(x^2 - 1)^2/4" has two minima, and the error does not go to 0.

    Quick check

    φ\varphi has two minima of equal depth and equal curvature, at x=−1x = -1 and x=1x = 1. You apply Laplace's method at x∗=1x^* = 1 only. As n→∞n \to \infty, what does the ratio (exact integral)/(Laplace value) tend to?

    3. Definitions and main results #

    3.1 The Gaussian integral in one dimension #

    Theorem (Gaussian integral in 1-D).

    (a)∫Re−x2 dx=π,(b)∫Re−ax2/2 dx=2π/a(a>0).\text{(a)}\quad \int_{\R} e^{-x^2}\,dx = \sqrt{\pi}, \qquad \text{(b)}\quad \int_{\R} e^{-a x^2/2}\,dx = \sqrt{2\pi/a} \quad (a > 0).

    Proof.

    1. Let I=∫e−x2 dxI = \int e^{-x^2}\,dx. It is finite: from (∣x∣−12)2≥0(|x| - \tfrac12)^2 \ge 0 we get x2≥∣x∣−14x^2 \ge |x| - \tfrac14, so e−x2≤e1/4 e−∣x∣e^{-x^2} \le e^{1/4}\,e^{-|x|}, and ∫e−∣x∣dx=2\int e^{-|x|}dx = 2.
    2. I2=∫e−x2 dx∫e−y2 dy=∬e−(x2+y2) dx dyI^2 = \int e^{-x^2}\,dx \int e^{-y^2}\,dy = \iint e^{-(x^2 + y^2)}\,dx\,dy. This is Tonelli's theorem (the integrand is positive) in the product case (lesson 10, section 3.3).
    3. Change to polar coordinates, x=rcos⁡θx = r\cos\theta, y=rsin⁡θy = r\sin\theta, with dx dy=r dr dθdx\,dy = r\,dr\,d\theta. The map from (0,∞)×(0,2π)(0, \infty) \times (0, 2\pi) covers the plane except one ray, a set of area zero.
    4. I2=∫02π ⁣∫0∞e−r2 r dr dθ=2π⋅[−12e−r2]0∞=2π⋅12=πI^2 = \int_0^{2\pi}\!\int_0^\infty e^{-r^2}\,r\,dr\,d\theta = 2\pi \cdot \big[-\tfrac12 e^{-r^2}\big]_0^\infty = 2\pi \cdot \tfrac12 = \pi.
    5. I>0I > 0, so I=πI = \sqrt{\pi}.
    6. For (b), substitute x=2/a tx = \sqrt{2/a}\,t, so dx=2/a dtdx = \sqrt{2/a}\,dt and ax2/2=t2a x^2/2 = t^2: ∫e−ax2/2 dx=2/a π=2π/a\int e^{-a x^2/2}\,dx = \sqrt{2/a}\,\sqrt{\pi} = \sqrt{2\pi/a}. ■\blacksquare

    In step 4 the factor rr from the Jacobian is what makes re−r2r e^{-r^2} have an elementary antiderivative. With a=1a = 1, (b) says ∫e−x2/2 dx=2π\int e^{-x^2/2}\,dx = \sqrt{2\pi}: this is the 2π\sqrt{2\pi} in the standard normal density e−x2/2/2πe^{-x^2/2}/\sqrt{2\pi}.

    3.2 The Gaussian integral in dd dimensions #

    A symmetric matrix AA is positive definite, written A≻0A \succ 0, if x⊤Ax>0x^\top A x > 0 for every x≠0x \ne 0. Equivalently, all its eigenvalues are positive (linear algebra lesson 07).

    Theorem (Gaussian integral). Let AA be a symmetric d×dd \times d matrix with A≻0A \succ 0, and let b∈Rdb \in \R^d. Then

    Z(A,b):=∫Rde−12x⊤Ax+b⊤x dx=(2π)d/2det⁡(A)−1/2 e12b⊤A−1b.Z(A, b) := \int_{\R^d} e^{-\frac12 x^\top A x + b^\top x}\,dx = (2\pi)^{d/2}\det(A)^{-1/2}\, e^{\frac12 b^\top A^{-1} b}.

    Proof.

    1. Complete the square. Let m=A−1bm = A^{-1} b. Then
      −12x⊤Ax+b⊤x=−12(x−m)⊤A(x−m)+12b⊤A−1b.-\tfrac12 x^\top A x + b^\top x = -\tfrac12 (x - m)^\top A (x - m) + \tfrac12 b^\top A^{-1} b .
      To check, expand the right side: −12x⊤Ax+12x⊤Am+12m⊤Ax−12m⊤Am+12b⊤A−1b-\tfrac12 x^\top A x + \tfrac12 x^\top A m + \tfrac12 m^\top A x - \tfrac12 m^\top A m + \tfrac12 b^\top A^{-1} b. The two cross terms add up to x⊤Am=x⊤bx^\top A m = x^\top b (this uses A=A⊤A = A^\top). The constant −12m⊤Am=−12b⊤A−1b-\tfrac12 m^\top A m = -\tfrac12 b^\top A^{-1} b cancels the last term.
    2. Shift. Put y=x−my = x - m. A shift has Jacobian determinant 1, so dx=dydx = dy.
    3. Rotate. By the spectral theorem, A=QΛQ⊤A = Q\Lambda Q^\top with QQ orthogonal and Λ=diag⁡(λ1,…,λd)\Lambda = \operatorname{diag}(\lambda_1, \dots, \lambda_d), all λi>0\lambda_i > 0 because A≻0A \succ 0. Put u=Q⊤yu = Q^\top y. Then ∣det⁡Q∣=1|\det Q| = 1, so dy=dudy = du, and y⊤Ay=u⊤Λu=∑iλiui2y^\top A y = u^\top \Lambda u = \sum_i \lambda_i u_i^2.
    4. Factor (Fubini). The integrand is now a product of dd one-dimensional bumps: ∫e−12∑iλiui2 du=∏i2π/λi=(2π)d/2(∏iλi)−1/2=(2π)d/2det⁡(A)−1/2\int e^{-\frac12 \sum_i \lambda_i u_i^2}\,du = \prod_i \sqrt{2\pi/\lambda_i} = (2\pi)^{d/2} \big(\prod_i \lambda_i\big)^{-1/2} = (2\pi)^{d/2} \det(A)^{-1/2}, because the determinant is the product of the eigenvalues.
    5. Multiply by the constant e12b⊤A−1be^{\frac12 b^\top A^{-1} b} from step 1. ■\blacksquare

    Why det⁡−1/2\det^{-1/2}. Each eigen-direction contributes its width 2π/λi\sqrt{2\pi/\lambda_i}. The product of the widths is a volume, and the product of the λi\lambda_i is det⁡A\det A. So a large curvature (a large det⁡A\det A) means a small volume.

    The condition A≻0A \succ 0 is necessary. If one λi≤0\lambda_i \le 0, the uiu_i-integral in step 4 is ∫e−λiui2/2 dui=∞\int e^{-\lambda_i u_i^2/2}\,du_i = \infty. If AA is not symmetric, note that x⊤Axx^\top A x only sees the symmetric part (A+A⊤)/2(A + A^\top)/2: use that matrix in the formula.

    In code: Cholesky, not eigenvectors. With A=LL⊤A = LL^\top (LL lower triangular, linear algebra lesson 07) and u=L⊤yu = L^\top y, you get y⊤Ay=∥u∥2y^\top A y = \|u\|^2 and dy=du/det⁡Ldy = du/\det L, with det⁡L=det⁡(A)1/2\det L = \det(A)^{1/2}. So log⁡det⁡A=2∑ilog⁡Lii\log\det A = 2\sum_i \log L_{ii}, and m=A−1bm = A^{-1}b comes from two triangular solves.

    The Gaussian normalizer. Take A=Σ−1A = \Sigma^{-1} and b=0b = 0, and shift by the mean μ\mu: ∫e−12(x−μ)⊤Σ−1(x−μ) dx=(2π)d/2det⁡(Σ)1/2\int e^{-\frac12 (x - \mu)^\top \Sigma^{-1}(x - \mu)}\,dx = (2\pi)^{d/2}\det(\Sigma)^{1/2}. Dividing by this number gives the density of N(μ,Σ)N(\mu, \Sigma):

    N(x;μ,Σ)=(2π)−d/2det⁡(Σ)−1/2exp⁡ ⁣(−12(x−μ)⊤Σ−1(x−μ)).N(x; \mu, \Sigma) = (2\pi)^{-d/2}\det(\Sigma)^{-1/2}\exp\!\big(-\tfrac12 (x - \mu)^\top \Sigma^{-1}(x - \mu)\big).

    3.3 Moments and marginal likelihoods from ZZ #

    Fix AA and view Z(b)Z(b) as a function of bb. The normalized density is pb(x)=e−12x⊤Ax+b⊤x/Z(b)p_b(x) = e^{-\frac12 x^\top A x + b^\top x}/Z(b).

    1. Mean. Differentiate under the integral sign. This is allowed here, because the integrand and its bb-derivatives are bounded by integrable Gaussians. ∇bZ=∫x e−12x⊤Ax+b⊤x dx\nabla_b Z = \int x\, e^{-\frac12 x^\top A x + b^\top x}\,dx, so ∇blog⁡Z=∇bZ/Z=Epb[x]\nabla_b \log Z = \nabla_b Z / Z = \mathbb E_{p_b}[x].
    2. Covariance. Differentiate once more: ∇b2log⁡Z=Epb[xx⊤]−Epb[x] Epb[x]⊤=Cov⁡pb[x]\nabla_b^2 \log Z = \mathbb E_{p_b}[x x^\top] - \mathbb E_{p_b}[x]\,\mathbb E_{p_b}[x]^\top = \operatorname{Cov}_{p_b}[x].
    3. Read them off. From the closed form, log⁡Z=const+12b⊤A−1b\log Z = \text{const} + \tfrac12 b^\top A^{-1} b, so ∇blog⁡Z=A−1b\nabla_b \log Z = A^{-1}b and ∇b2log⁡Z=A−1\nabla_b^2 \log Z = A^{-1}. So pb=N(A−1b,A−1)p_b = N(A^{-1}b, A^{-1}).

    So AA is the inverse covariance: the precision matrix. The function log⁡Z(b)\log Z(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: dda∫e−ax2/2dx=−12∫x2e−ax2/2dx\frac{d}{da}\int e^{-a x^2/2}dx = -\frac12\int x^2 e^{-a x^2/2}dx and dda2π a−1/2=−122π a−3/2\frac{d}{da}\sqrt{2\pi}\,a^{-1/2} = -\frac12\sqrt{2\pi}\,a^{-3/2}, so E[X2]=1/a\mathbb E[X^2] = 1/a for X∼N(0,1/a)X \sim N(0, 1/a).

    Marginal likelihood of Bayesian linear regression. Take nn data points with features in a design matrix Φ∈Rn×d\Phi \in \R^{n \times d} and targets y∈Rny \in \R^n. The model has the prior w∼N(0,α−1Id)w \sim N(0, \alpha^{-1} I_d) and the likelihood y∣w∼N(Φw,σ2In)y \mid w \sim N(\Phi w, \sigma^2 I_n). The marginal likelihood or evidence is the probability of the data with the weights integrated out: p(y)=∫p(y∣w) p(w) dwp(y) = \int p(y \mid w)\,p(w)\,dw.

    1. The exponent of p(y∣w) p(w)p(y \mid w)\,p(w) is quadratic in ww: −12w⊤Aw+w⊤b−∥y∥2/(2σ2)-\tfrac12 w^\top A w + w^\top b - \|y\|^2/(2\sigma^2), with A=αI+Φ⊤Φ/σ2A = \alpha I + \Phi^\top\Phi/\sigma^2 and b=Φ⊤y/σ2b = \Phi^\top y/\sigma^2.
    2. The constants in front are (2πσ2)−n/2(2\pi\sigma^2)^{-n/2} from the likelihood and (α/2π)d/2(\alpha/2\pi)^{d/2} from the prior.
    3. The Gaussian integral over ww gives (2π)d/2det⁡(A)−1/2e12b⊤A−1b(2\pi)^{d/2}\det(A)^{-1/2}e^{\frac12 b^\top A^{-1} b}. The two factors (2π)±d/2(2\pi)^{\pm d/2} cancel, so
    log⁡p(y)=−n2log⁡(2πσ2)+d2log⁡α−12log⁡det⁡A−∥y∥22σ2+12b⊤A−1b.\log p(y) = -\tfrac{n}{2}\log(2\pi\sigma^2) + \tfrac{d}{2}\log\alpha - \tfrac12\log\det A - \tfrac{\|y\|^2}{2\sigma^2} + \tfrac12 b^\top A^{-1} b .

    The matrix AA is the posterior precision, and m=A−1bm = A^{-1}b is the posterior mean (section 3.3, step 3). This value equals log⁡N(y;0,σ2I+α−1ΦΦ⊤)\log N(y; 0, \sigma^2 I + \alpha^{-1}\Phi\Phi^\top), the Gaussian-process form; section 5 checks this numerically. The term −12log⁡det⁡A-\tfrac12 \log\det A penalizes a posterior that is much narrower than the prior: we come back to this "Occam factor" in section 3.7.

    3.4 Gauss–Hermite quadrature #

    A quadrature rule replaces an integral by a weighted sum of function values. A KK-node Gauss–Hermite rule is a set of nodes t1,…,tKt_1, \dots, t_K and weights w1,…,wK>0w_1, \dots, w_K > 0 with

    ∫Re−t2g(t) dt≈∑k=1Kwk g(tk),\int_{\R} e^{-t^2} g(t)\,dt \approx \sum_{k=1}^{K} w_k\, g(t_k),

    that is exact for every polynomial gg of degree ≤2K−1\le 2K - 1. The nodes are the roots of the Hermite polynomial HKH_K. The count makes sense: KK nodes and KK weights are 2K2K free numbers, enough to match the 2K2K monomials 1,t,…,t2K−11, t, \dots, t^{2K-1}. NumPy gives them as np.polynomial.hermite.hermgauss(K). This is the "physicists'" weight e−t2e^{-t^2}, not e−t2/2e^{-t^2/2}.

    Gaussian expectations. Let X∼N(μ,σ2)X \sim N(\mu, \sigma^2). Substitute x=μ+2 σtx = \mu + \sqrt{2}\,\sigma t, so that (x−μ)2/(2σ2)=t2(x - \mu)^2/(2\sigma^2) = t^2 and dx=2 σ dtdx = \sqrt{2}\,\sigma\,dt:

    E[f(X)]=12π σ∫e−(x−μ)22σ2f(x) dx=1π∫e−t2f(μ+2 σt) dt≈∑k=1Kw~k f(μ+2 σtk),\mathbb E[f(X)] = \frac{1}{\sqrt{2\pi}\,\sigma}\int e^{-\frac{(x-\mu)^2}{2\sigma^2}} f(x)\,dx = \frac{1}{\sqrt{\pi}}\int e^{-t^2} f(\mu + \sqrt{2}\,\sigma t)\,dt \approx \sum_{k=1}^{K} \tilde w_k\, f(\mu + \sqrt{2}\,\sigma t_k),

    with w~k=wk/π\tilde w_k = w_k/\sqrt\pi. Check: with f=1f = 1 the sum must be 1, and indeed ∑kwk=∫e−t2dt=π\sum_k w_k = \int e^{-t^2}dt = \sqrt{\pi}.

    • For smooth ff, the error falls very fast with KK. For ff with a kink (ReLU, max⁡\max, a threshold) it falls slowly, because no polynomial fits a kink well.
    • In DD dimensions, the tensor-product rule needs KDK^D nodes. That is fine for D≤3D \le 3 or so; beyond that, use Monte Carlo (lesson 10) or sparse grids.
    Interactive figure: loading…

    Increase KK and switch between the functions. Top: ff (black), the shape of the density of XX, and the nodes xk=μ+2 σtkx_k = \mu + \sqrt2\,\sigma t_k; a bigger dot means a bigger weight. Bottom: the Gauss–Hermite error against KK, and the typical Monte Carlo error σf/K\sigma_f/\sqrt K for the same number of evaluations. Notice: for x6x^6 the error is exactly 0 from K=4K = 4 on (2K−1≥62K - 1 \ge 6); for exe^x it reaches rounding level near K=12K = 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\langle p, q\rangle = \int e^{-t^2} p(t)\,q(t)\,dt. The Hermite polynomials H0,H1,…H_0, H_1, \dots are orthogonal for this inner product, and HKH_K has degree KK and KK distinct real roots t1,…,tKt_1, \dots, t_K.

    1. Interpolatory weights. Let ℓk\ell_k be the Lagrange polynomial of degree K−1K - 1 with ℓk(tj)=1\ell_k(t_j) = 1 if j=kj = k and 00 otherwise. Set wk=∫e−t2ℓk(t) dtw_k = \int e^{-t^2}\ell_k(t)\,dt. Every polynomial rr of degree ≤K−1\le K - 1 equals ∑kr(tk)ℓk\sum_k r(t_k)\ell_k, so the rule is exact for it.
    2. Divide by HKH_K. Let pp have degree ≤2K−1\le 2K - 1. Polynomial division gives p=qHK+rp = qH_K + r with deg⁡q≤K−1\deg q \le K - 1 and deg⁡r≤K−1\deg r \le K - 1.
    3. The qHKqH_K part. The exact integral is ⟨q,HK⟩=0\langle q, H_K\rangle = 0, because qq is a combination of H0,…,HK−1H_0, \dots, H_{K-1}. The rule gives ∑kwk q(tk)HK(tk)=0\sum_k w_k\,q(t_k)H_K(t_k) = 0, because the nodes are roots of HKH_K.
    4. The rr part is exact by step 1. So the rule is exact for pp.
    5. Degree 2K2K fails. For p(t)=∏k(t−tk)2p(t) = \prod_k (t - t_k)^2, the integral is positive, but the rule gives 0.
    6. Positive weights. Apply the rule to ℓk2\ell_k^2 (degree 2K−22K - 2): wk=∫e−t2ℓk2 dt>0w_k = \int e^{-t^2}\ell_k^2\,dt > 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)X \sim N(0, 1) uses the nodes 0,±30, \pm\sqrt3 with weights 23,16,16\tfrac23, \tfrac16, \tfrac16. For which of these is it exact?

    3.5 Laplace's method #

    Theorem (Laplace's method). Let φ:Rd→R\varphi: \R^d \to \R have a unique global minimizer x∗x^*. Assume φ\varphi has continuous derivatives up to order 4 near x∗x^*, with H=∇2φ(x∗)≻0H = \nabla^2\varphi(x^*) \succ 0; φ\varphi stays at least some δ>0\delta > 0 above φ(x∗)\varphi(x^*) outside every ball around x∗x^* (with δ\delta depending on the ball); and ∫e−φ<∞\int e^{-\varphi} < \infty. Then, as n→∞n \to \infty,

    ∫Rde−nφ(x) dx=e−nφ(x∗)(2πn)d/2det⁡(H)−1/2 (1+O(1/n)).\int_{\R^d} e^{-n\varphi(x)}\,dx = e^{-n\varphi(x^*)} \Big(\frac{2\pi}{n}\Big)^{d/2} \det(H)^{-1/2}\,\big(1 + O(1/n)\big).

    Why it is true, in three steps. (1) Factor out the peak value e−nφ(x∗)e^{-n\varphi(x^*)}. (2) Near x∗x^*, replace φ\varphi by its Taylor model φ(x∗)+12(x−x∗)⊤H(x−x∗)\varphi(x^*) + \tfrac12 (x - x^*)^\top H (x - x^*); far from x∗x^* the integrand is exponentially small. (3) The Gaussian integral of section 3.2 with A=nHA = nH and b=0b = 0 gives (2π)d/2det⁡(nH)−1/2=(2π/n)d/2det⁡(H)−1/2(2\pi)^{d/2}\det(nH)^{-1/2} = (2\pi/n)^{d/2}\det(H)^{-1/2}.

    Proof
    1. Factor out the peak. ∫e−nφ=e−nφ(x∗)∫e−n[φ(x)−φ(x∗)] dx\int e^{-n\varphi} = e^{-n\varphi(x^*)} \int e^{-n[\varphi(x) - \varphi(x^*)]}\,dx.
    2. Taylor at the minimum. ∇φ(x∗)=0\nabla\varphi(x^*) = 0, so φ(x)−φ(x∗)=12(x−x∗)⊤H(x−x∗)+R(x)\varphi(x) - \varphi(x^*) = \tfrac12 (x - x^*)^\top H (x - x^*) + R(x) with ∣R(x)∣≤C∥x−x∗∥3|R(x)| \le C\|x - x^*\|^3 near x∗x^*.
    3. Zoom in. Put u=n (x−x∗)u = \sqrt{n}\,(x - x^*), so dx=n−d/2 dudx = n^{-d/2}\,du. The integral becomes n−d/2∫exp⁡ ⁣(−12u⊤Hu−nR(x∗+u/n)) dun^{-d/2}\int \exp\!\big(-\tfrac12 u^\top H u - n R(x^* + u/\sqrt{n})\big)\,du.
    4. The remainder vanishes. For fixed uu, nR(x∗+u/n)=O(∥u∥3/n)→0n R(x^* + u/\sqrt{n}) = O(\|u\|^3/\sqrt{n}) \to 0. Choose a ball around x∗x^* so small that ∣R(x)∣≤14λmin⁡(H)∥x−x∗∥2|R(x)| \le \tfrac14\lambda_{\min}(H)\|x - x^*\|^2 in it. Inside the ball, the integrand is at most e−14λmin⁡(H)∥u∥2e^{-\frac14\lambda_{\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∗)]e^{-(n-1)\delta}\,e^{-[\varphi(x) - \varphi(x^*)]}: exponentially small.
    5. Gaussian integral. The limit is ∫e−12u⊤Hu du=(2π)d/2det⁡(H)−1/2\int e^{-\frac12 u^\top H u}\,du = (2\pi)^{d/2}\det(H)^{-1/2}. With the factor n−d/2n^{-d/2} this is (2π/n)d/2det⁡(H)−1/2(2\pi/n)^{d/2}\det(H)^{-1/2}.
    6. Why the error is O(1/n)O(1/n). Expand e−nR≈1−nR+12n2R2e^{-nR} \approx 1 - nR + \tfrac12 n^2 R^2. The cubic part of nRnR is odd in uu and of size n−1/2n^{-1/2}; its integral against the symmetric Gaussian is zero. The next terms, the quartic part of nRnR and the square of the cubic part, are of size 1/n1/n. (Steps 1–5 need only three derivatives; this step uses the fourth.) ■\blacksquare

    The first correction in 1-D. With φk=φ(k)(x∗)\varphi_k = \varphi^{(k)}(x^*), the exact integral is the Laplace value times 1+cn+O(n−2)1 + \frac{c}{n} + O(n^{-2}), where

    c=5φ3224φ23−φ48φ22.c = \frac{5\varphi_3^2}{24\varphi_2^3} - \frac{\varphi_4}{8\varphi_2^2} .

    The Laplace figure of section 2 draws ∣c∣/n|c|/n next to the true error.

    Without an explicit nn. In practice you approximate ∫e−Ψ(θ)dθ\int e^{-\Psi(\theta)}d\theta for a function Ψ\Psi that grows with the amount of data. The same steps give

    log⁡∫e−Ψ(θ) dθ≈−Ψ(θ^)+d2log⁡2π−12log⁡det⁡∇2Ψ(θ^),\log \int e^{-\Psi(\theta)}\,d\theta \approx -\Psi(\hat\theta) + \tfrac{d}{2}\log 2\pi - \tfrac12\log\det\nabla^2\Psi(\hat\theta),

    where θ^\hat\theta is the minimizer of Ψ\Psi. The factor (2π/n)d/2(2\pi/n)^{d/2} of the theorem is this formula with Ψ=nφ\Psi = n\varphi, because det⁡(nH)=nddet⁡H\det(nH) = n^d\det H.

    3.6 Stirling's formula #

    1. Write n!=Γ(n+1)=∫0∞xne−x dx=∫0∞enlog⁡x−x dxn! = \Gamma(n+1) = \int_0^\infty x^n e^{-x}\,dx = \int_0^\infty e^{n\log x - x}\,dx.
    2. The peak is at x=nx = n, so rescale: x=ntx = nt, dx=n dtdx = n\,dt. Then nlog⁡x−x=nlog⁡n−n(t−log⁡t)n\log x - x = n\log n - n(t - \log t), and n!=nn+1∫0∞e−nφ(t) dtn! = n^{n+1}\int_0^\infty e^{-n\varphi(t)}\,dt with φ(t)=t−log⁡t\varphi(t) = t - \log t.
    3. φ′(t)=1−1/t=0\varphi'(t) = 1 - 1/t = 0 at t∗=1t^* = 1; φ(1)=1\varphi(1) = 1; φ′′(t)=1/t2\varphi''(t) = 1/t^2, so φ′′(1)=1\varphi''(1) = 1.
    4. Laplace: ∫0∞e−nφ(t)dt≈e−n2π/n\int_0^\infty e^{-n\varphi(t)}dt \approx e^{-n}\sqrt{2\pi/n}. So
      n!≈nn+1e−n2π/n=2πn (ne)n.n! \approx n^{n+1} e^{-n}\sqrt{2\pi/n} = \sqrt{2\pi n}\,\Big(\frac{n}{e}\Big)^n .
    5. With φ3=φ′′′(1)=−2\varphi_3 = \varphi'''(1) = -2 and φ4=φ′′′′(1)=6\varphi_4 = \varphi''''(1) = 6, the correction formula gives c=5⋅424−68=112c = \frac{5 \cdot 4}{24} - \frac{6}{8} = \frac{1}{12}. So n!=2πn (n/e)n (1+112n+O(n−2))n! = \sqrt{2\pi n}\,(n/e)^n\,\big(1 + \frac{1}{12n} + O(n^{-2})\big).
    nn n!n! Stirling n!/Stirling−1n!/\text{Stirling} - 1 1/(12n)1/(12n)
    1 1 0.9221 0.0844 0.0833
    10 3 628 800 3 598 696 0.0084 0.0083
    100 9.333⋅101579.333 \cdot 10^{157} 9.325⋅101579.325 \cdot 10^{157} 0.00083 0.00083

    3.7 The Laplace approximation of a posterior and of the evidence #

    Let θ∈Rd\theta \in \R^d be the parameters of a model, p(θ)p(\theta) the prior and p(D∣θ)p(D \mid \theta) the likelihood of the data DD. Bayes' rule gives the posterior p(θ∣D)=p(D∣θ) p(θ)/p(D)p(\theta \mid D) = p(D \mid \theta)\,p(\theta)/p(D), where the evidence p(D)=∫p(D∣θ) p(θ) dθp(D) = \int p(D \mid \theta)\,p(\theta)\,d\theta is the normalizing constant. Define the negative log joint

    Ψ(θ)=−log⁡p(D∣θ)−log⁡p(θ).\Psi(\theta) = -\log p(D \mid \theta) - \log p(\theta).

    In deep learning, Ψ\Psi is the training loss with weight decay, up to a constant: if the loss is the summed negative log-likelihood, weight decay γ2∥θ∥2\frac{\gamma}{2}\|\theta\|^2 is a Gaussian prior with precision γ\gamma.

    1. MAP. The maximum a posteriori (MAP) estimate is θ^=arg⁡min⁡θΨ(θ)\hat\theta = \arg\min_\theta \Psi(\theta). You find it with Newton's method, L-BFGS or ordinary training.
    2. Curvature. H=∇2Ψ(θ^)=−∇2log⁡p(D∣θ^)−∇2log⁡p(θ^)H = \nabla^2\Psi(\hat\theta) = -\nabla^2\log p(D \mid \hat\theta) - \nabla^2\log p(\hat\theta). A prior N(0,vI)N(0, v I) adds I/vI/v. For logistic regression with inputs xix_i (the rows of XX) and predicted probabilities pip_i, H=X⊤diag⁡(pi(1−pi))X+I/vH = X^\top \operatorname{diag}\big(p_i(1 - p_i)\big) X + I/v (lesson 06).
    3. Posterior. log⁡p(θ∣D)=−Ψ(θ)+const\log p(\theta \mid D) = -\Psi(\theta) + \text{const}. Its second-order Taylor model at θ^\hat\theta has no linear term, so it is the log of a Gaussian density:
      p(θ∣D)≈N(θ^,H−1).p(\theta \mid D) \approx N(\hat\theta, H^{-1}).
      This is the Laplace approximation. The inverse Hessian H−1H^{-1} is its covariance: directions of high curvature are well determined by the data, flat directions are uncertain.
    4. Evidence. p(D)=∫e−Ψ(θ) dθp(D) = \int e^{-\Psi(\theta)}\,d\theta, so Laplace's method gives
      log⁡p(D)≈log⁡p(D∣θ^)+log⁡p(θ^)+d2log⁡2π−12log⁡det⁡H.\log p(D) \approx \log p(D \mid \hat\theta) + \log p(\hat\theta) + \tfrac{d}{2}\log 2\pi - \tfrac12\log\det H .

    MacKay reads the evidence as best-fit likelihood × Occam factor. The Occam factor p(θ^) (2π)d/2det⁡(H)−1/2p(\hat\theta)\,(2\pi)^{d/2}\det(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 vv (the weight decay), without a validation set.

    The BIC. With nn independent data points, H≈n IˉH \approx n\,\bar{I}, where Iˉ\bar{I} is the average curvature per data point. So log⁡det⁡H=dlog⁡n+log⁡det⁡Iˉ\log\det H = d\log n + \log\det\bar{I}. Keep only the terms that grow with nn: log⁡p(D)≈log⁡p(D∣θ^)−d2log⁡n\log p(D) \approx \log p(D \mid \hat\theta) - \tfrac{d}{2}\log n. The usual form is the Bayesian information criterion BIC=−2log⁡p(D∣θ^)+dlog⁡n\mathrm{BIC} = -2\log p(D \mid \hat\theta) + d\log n; smaller is better.

    If Ψ\Psi 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 θ\theta, such as Bayesian linear regression (section 3.3).

    Quick check

    For Bayesian linear regression (Gaussian prior, Gaussian likelihood with mean Φw\Phi w), how good is the Laplace approximation of the posterior?

    3.8 When the Laplace approximation fails #

    1. 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.
    2. 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)O(1/n) error is large. Remedy: an unconstrained parameter (log⁡λ\log\lambda, logit⁡p\operatorname{logit} p). The density then picks up a Jacobian factor (lesson 10), so the result depends on the parameterization.
    3. Not a smooth interior minimum. A mode on the boundary, an active constraint, an L1L_1 prior or a ReLU kink at θ^\hat\theta breaks the Taylor model. Early stopping leaves ∇Ψ(θ^)≠0\nabla\Psi(\hat\theta) \ne 0.
    4. Singular or indefinite Hessian (flat and negative directions of large networks): H−1H^{-1} is not a covariance. Remedy: the generalized Gauss–Newton matrix or the Fisher matrix (both positive semidefinite, lesson 08) plus the prior precision.
    5. Size. A d×dd \times d Hessian for d=107d = 10^7 cannot be stored. Remedy: diagonal, Kronecker-factored (K-FAC) or low-rank curvature, or Laplace on the last layer only.
    6. High dimension. The O(1/n)O(1/n) rate is for a fixed dd; the correction terms grow with dd.
    Interactive figure: loading…

    Move the total count SS and the number of windows mm; then try "no events". Poisson counts in mm time windows with total SS and the prior p(λ)=e−λp(\lambda) = e^{-\lambda}. The black curve is the exact posterior (a Gamma density). The orange dashed curve is the Laplace approximation in λ\lambda; the blue dashed curve is the Laplace approximation in θ=log⁡λ\theta = \log\lambda, drawn as a density in λ\lambda. Notice: with little data the orange Gaussian is too narrow, is centred at the mode, and puts mass at λ<0\lambda < 0. The evidence ratio depends only on SS. With S=0S = 0 the mode is on the boundary, and only the log⁡λ\log\lambda version works.

    Answers to section 1. (1) π\pi. The yy-direction has curvature 4, so its width halves: 2π⋅2π/4=π\sqrt{2\pi}\cdot\sqrt{2\pi/4} = \pi, or 2π/det⁡diag⁡(1,4)=2π/22\pi/\sqrt{\det\operatorname{diag}(1, 4)} = 2\pi/2. (2) Only about 8%: Stirling gives 2π/e=0.9221\sqrt{2\pi}/e = 0.9221 instead of 1!=11! = 1. The ratio n!/Stirlingn!/\text{Stirling} is about 1+1/(12n)1 + 1/(12n), so the error is 0.83% at n=10n = 10 and 0.083% at n=100n = 100. Laplace's method is often good long before nn 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.

    4. Worked example #

    (a) A 2-D Gaussian integral. Compute ZZ for A=(3112)A = \begin{pmatrix} 3 & 1 \\ 1 & 2 \end{pmatrix} and b=(1,1)b = (1, 1).

    1. A≻0A \succ 0: the trace is 5>05 > 0 and det⁡A=6−1=5>0\det A = 6 - 1 = 5 > 0, so both eigenvalues are positive.
    2. A−1=15(2−1−13)A^{-1} = \tfrac15\begin{pmatrix} 2 & -1 \\ -1 & 3 \end{pmatrix}, m=A−1b=15(2−1,−1+3)=(0.2,0.4)m = A^{-1}b = \tfrac15(2 - 1, -1 + 3) = (0.2, 0.4), and b⊤A−1b=b⊤m=0.2+0.4=0.6b^\top A^{-1} b = b^\top m = 0.2 + 0.4 = 0.6.
    3. Z=(2π)2/2⋅5−1/2⋅e0.3=2.8099×1.3499=3.7930Z = (2\pi)^{2/2}\cdot 5^{-1/2}\cdot e^{0.3} = 2.8099 \times 1.3499 = 3.7930, and log⁡Z=1.8379−0.8047+0.3=1.3332\log Z = 1.8379 - 0.8047 + 0.3 = 1.3332.
    4. The normalized density is N(m,A−1)N(m, A^{-1}): mean (0.2,0.4)(0.2, 0.4) and covariance (0.4−0.2−0.20.6)\begin{pmatrix} 0.4 & -0.2 \\ -0.2 & 0.6 \end{pmatrix}. Both come from log⁡Z(b)=const+12b⊤A−1b\log Z(b) = \text{const} + \tfrac12 b^\top A^{-1} b.

    (The "worked example" button of the second figure shows this bump.)

    (b) Gauss–Hermite by hand. Compute E[eX]\mathbb E[e^X] for X∼N(0,1)X \sim N(0, 1). The exact value is e1/2=1.6487e^{1/2} = 1.6487: it is Z(1,1)/Z(1,0)Z(1, 1)/Z(1, 0) in 1-D, that is e12⋅12e^{\frac12 \cdot 1^2}.

    • K=2K = 2: hermgauss(2) gives t=±1/2t = \pm 1/\sqrt2 and w=π/2w = \sqrt{\pi}/2 each. The mapped nodes are x=2 t=±1x = \sqrt2\,t = \pm 1, with weights w~=w/π=12\tilde w = w/\sqrt\pi = \tfrac12. So E[eX]≈12(e+e−1)=1.5431\mathbb E[e^X] \approx \tfrac12(e + e^{-1}) = 1.5431: 6.4% too low.
    • K=3K = 3: t=0,±3/2t = 0, \pm\sqrt{3/2} with w=2π/3,π/6,π/6w = 2\sqrt\pi/3, \sqrt\pi/6, \sqrt\pi/6. Mapped: x=0,±3x = 0, \pm\sqrt3 with weights 23,16,16\tfrac23, \tfrac16, \tfrac16. So E[eX]≈23+16(5.6522+0.1769)=1.6382\mathbb E[e^X] \approx \tfrac23 + \tfrac16(5.6522 + 0.1769) = 1.6382: 0.64% too low.
    • K=5K = 5 gives 1.6486791.648679 (relative error 2.5⋅10−52.5 \cdot 10^{-5}), and K=10K = 10 agrees with e1/2e^{1/2} to about 12 digits.

    The 2-node rule is the "sigma point" rule μ±σ\mu \pm \sigma. It is exact for polynomials up to degree 3.

    (c) Laplace for a Poisson rate. Three equal time windows show y=(2,1,3)y = (2, 1, 3) events. Model: yi∣λ∼Poisson(λ)y_i \mid \lambda \sim \mathrm{Poisson}(\lambda), so p(yi∣λ)=λyie−λ/yi!p(y_i \mid \lambda) = \lambda^{y_i}e^{-\lambda}/y_i!, and the prior is p(λ)=e−λp(\lambda) = e^{-\lambda} on λ>0\lambda > 0.

    1. Joint. p(y,λ)=∏iλyie−λyi!⋅e−λ=λ6e−4λ12p(y, \lambda) = \prod_i \frac{\lambda^{y_i}e^{-\lambda}}{y_i!}\cdot e^{-\lambda} = \frac{\lambda^6 e^{-4\lambda}}{12}, because ∑iyi=6\sum_i y_i = 6 and 2! 1! 3!=122!\,1!\,3! = 12.
    2. Exact answers. p(y)=112∫0∞λ6e−4λdλ=6!12⋅47=0.0036621p(y) = \frac{1}{12}\int_0^\infty \lambda^6 e^{-4\lambda}d\lambda = \frac{6!}{12 \cdot 4^7} = 0.0036621 (substitute x=4λx = 4\lambda and use ∫0∞x6e−xdx=6!\int_0^\infty x^6 e^{-x}dx = 6!), so log⁡p(y)=−5.6097\log p(y) = -5.6097. The posterior is ∝λ6e−4λ\propto \lambda^6 e^{-4\lambda}: a Gamma distribution with shape 7 and rate 4, with mean 7/4=1.757/4 = 1.75 and standard deviation 7/4=0.661\sqrt7/4 = 0.661.
    3. MAP. Ψ(λ)=4λ−6log⁡λ+log⁡12\Psi(\lambda) = 4\lambda - 6\log\lambda + \log 12. Ψ′(λ)=4−6/λ=0\Psi'(\lambda) = 4 - 6/\lambda = 0 gives λ^=1.5\hat\lambda = 1.5.
    4. Curvature. H=Ψ′′(λ^)=6/λ^2=2.667H = \Psi''(\hat\lambda) = 6/\hat\lambda^2 = 2.667. Laplace posterior: N(1.5, 0.375)N(1.5,\ 0.375), standard deviation 0.375=0.612\sqrt{0.375} = 0.612.
    5. Evidence. log⁡p(y∣λ^)=6log⁡1.5−3⋅1.5−log⁡12=−4.5521\log p(y \mid \hat\lambda) = 6\log 1.5 - 3 \cdot 1.5 - \log 12 = -4.5521, log⁡p(λ^)=−1.5\log p(\hat\lambda) = -1.5, and 12log⁡(2π/H)=0.4285\tfrac12\log(2\pi/H) = 0.4285. Sum: log⁡p(y)≈−5.6236\log p(y) \approx -5.6236, so p(y)≈0.0036116p(y) \approx 0.0036116: 1.38% too low.
    6. Check of the error. The 1-D correction of section 3.5 (with Ψ\Psi in place of nφn\varphi, so n=1n = 1) uses Ψ2=6/λ^2=8/3\Psi_2 = 6/\hat\lambda^2 = 8/3, Ψ3=−12/λ^3=−32/9\Psi_3 = -12/\hat\lambda^3 = -32/9 and Ψ4=36/λ^4=64/9\Psi_4 = 36/\hat\lambda^4 = 64/9. It gives c=5(32/9)224(8/3)3−64/98(8/3)2=536−18=172=1.39%c = \frac{5 (32/9)^2}{24 (8/3)^3} - \frac{64/9}{8 (8/3)^2} = \frac{5}{36} - \frac18 = \frac{1}{72} = 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\lambda < 0. This is the "y=(2,1,3)y = (2, 1, 3)" setting of the last figure.

    5. In code #

    NumPy and SciPy check the numbers above with numerical integration and library densities.

    import math
    import numpy as np
    from scipy import integrate, stats
    
    # (a) sqrt(pi), and the 2-D example against the hand value 2*pi/sqrt(5)*e^0.3
    print(round(integrate.quad(lambda x: np.exp(-x * x), -np.inf, np.inf)[0], 6), round(math.sqrt(math.pi), 6))
    f = lambda y, 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(lambda y, x: x * f(y, x), -15, 15, -15, 15)[0] / Z
    print(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 y
    rng = np.random.default_rng(0)
    Phi, y, alpha, s2 = rng.normal(size=(5, 2)), rng.normal(size=5), 2.0, 0.5
    def joint(w2, w1):
        r = y - Phi @ np.array([w1, w2])
        lik = np.exp(-r @ r / (2 * s2)) / (2 * math.pi * s2) ** 2.5
        return lik * 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 / s2
    formula = (-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)
    for K in (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(lambda x: np.exp(x) * stats.norm.pdf(x), -30, 30)[0]     # = e^0.5
    print(round(math.cosh(1), 4), round(2 / 3 + math.cosh(math.sqrt(3)) / 3, 4), round(exact, 4))
    # 1.5431 1.6382 1.6487
    
    import math
    from scipy import special, stats
    
    # Stirling from Laplace: n!/Stirling - 1 is close to 1/(12n)
    for n in (1, 10, 100):
        log_stirling = 0.5 * math.log(2 * math.pi * n) + n * math.log(n) - n
        print(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 4
    log_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.6236
    print(post.mean(), round(post.std(), 4), round(math.sqrt(1.5**2 / 6), 4))   # 1.75 0.6614 0.6124
    print(round(stats.norm(1.5, math.sqrt(0.375)).cdf(0), 4))            # 0.0072: mass on lambda < 0
    

    For a large dd, never compute det and then log: the determinant overflows or underflows. Use np.linalg.slogdet, or 2∑ilog⁡Lii2\sum_i \log L_{ii} from a Cholesky factor, and solve with AA instead of forming A−1A^{-1}.

    6. Where it shows up #

    • Gaussian log-densities. log⁡N(x;μ,Σ)=−12(x−μ)⊤Σ−1(x−μ)−12log⁡det⁡Σ−d2log⁡2π\log N(x; \mu, \Sigma) = -\tfrac12(x - \mu)^\top\Sigma^{-1}(x - \mu) - \tfrac12\log\det\Sigma - \tfrac{d}{2}\log 2\pi is in every Gaussian likelihood and in the KL term of a variational autoencoder. It is evaluated with a Cholesky factor of Σ\Sigma.
    • Marginal likelihood of Gaussian processes. Gaussian-process regression tunes the kernel hyperparameters by maximizing log⁡p(y)=−12y⊤Ky−1y−12log⁡det⁡Ky−n2log⁡2π\log p(y) = -\tfrac12 y^\top K_y^{-1} y - \tfrac12\log\det K_y - \tfrac{n}{2}\log 2\pi, where KyK_y is the kernel matrix plus the noise variance times II. The −12log⁡det⁡Ky-\tfrac12\log\det K_y term penalizes kernels that are too flexible.
    • Gauss–Hermite in practice. GPflow and GPyTorch compute the 1-D expectations Eq(f)[log⁡p(y∣f)]\mathbb E_{q(f)}[\log p(y \mid f)] of variational Gaussian-process classification by Gauss–Hermite quadrature. For a Bayesian logistic model whose score is X∼N(1,22)X \sim N(1, 2^2), E[σ(X)]=0.6477\mathbb E[\sigma(X)] = 0.6477; the probit approximation σ(μ/1+πσ2/8)\sigma\big(\mu/\sqrt{1 + \pi\sigma^2/8}\big) gives 0.6511, and the plug-in σ(μ)\sigma(\mu) gives 0.7311 (overconfident). In 1-D, the unscented transform of the unscented Kalman filter with κ=2\kappa = 2 is exactly the 3-node rule (nodes μ,μ±3 σ\mu, \mu \pm \sqrt3\,\sigma, weights 23,16,16\tfrac23, \tfrac16, \tfrac16).
    • 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 ylog⁡y−y+12log⁡(2πy)y\log y - y + \tfrac12\log(2\pi y) for log⁡y!\log y!.

    7. Common mistakes #

    • Forgetting the rr in r dr dθr\,dr\,d\theta. Without it, the ring areas are wrong and the integral ∫0∞e−r2dr\int_0^\infty e^{-r^2}dr has no elementary antiderivative.
    • Precision and covariance mixed up. ∫e−12x⊤Axdx\int e^{-\frac12 x^\top A x}dx has det⁡(A)−1/2\det(A)^{-1/2}, and AA is the precision. The Gaussian normalizer has det⁡(Σ)+1/2\det(\Sigma)^{+1/2} in the integral and det⁡(Σ)−1/2\det(\Sigma)^{-1/2} in the density.
    • A non-symmetric AA. x⊤Axx^\top A x only sees (A+A⊤)/2(A + A^\top)/2. Symmetrize before you use det⁡A\det A and A−1bA^{-1}b.
    • Forgetting the square root. Each direction contributes 2π/λi\sqrt{2\pi/\lambda_i}, so the integral has det⁡(A)−1/2\det(A)^{-1/2}, not det⁡(A)−1\det(A)^{-1}.
    • Gauss–Hermite constants. hermgauss uses the weight e−t2e^{-t^2}. You need both the 2\sqrt2 in x=μ+2 σtx = \mu + \sqrt2\,\sigma t and the factor 1/π1/\sqrt\pi. Check that the weights sum to 1 for f=1f = 1.
    • Gauss–Hermite for a kink. ReLU, max⁡\max and thresholds converge slowly; split the integral at the kink or use more nodes.
    • Dropping the prior in HH. The posterior precision is the likelihood Hessian plus the prior precision. Without the prior term, HH 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 λ\lambda to log⁡λ\log\lambda.
    • Evidence and likelihood mixed up. The maximum likelihood p(D∣θ^)p(D \mid \hat\theta) always grows with model size; the evidence p(D)=∫p(D∣θ)p(θ) dθp(D) = \int p(D \mid \theta)p(\theta)\,d\theta includes the Occam factor and does not.

    8. Check yourself #

    1. Compute ∫R3exp⁡(−12(x2+2y2+8z2)) dx dy dz\int_{\R^3}\exp\big(-\tfrac12(x^2 + 2y^2 + 8z^2)\big)\,dx\,dy\,dz.
      AnswerA=diag⁡(1,2,8)A = \operatorname{diag}(1, 2, 8), det⁡A=16\det A = 16, so the value is (2π)3/2/16=15.7496/4=3.9374(2\pi)^{3/2}/\sqrt{16} = 15.7496/4 = 3.9374.
    2. Let p(x)∝exp⁡(−a2x2+bx)p(x) \propto \exp(-\tfrac a2 x^2 + bx) with a>0a > 0. Find its mean and variance from log⁡Z(b)\log Z(b).
      Answerlog⁡Z(b)=12log⁡(2π/a)+b22a\log Z(b) = \tfrac12\log(2\pi/a) + \frac{b^2}{2a}. Its derivative b/ab/a is the mean, and its second derivative 1/a1/a is the variance: p=N(b/a,1/a)p = N(b/a, 1/a).
    3. The 3-node Gauss–Hermite rule uses x=0,±3x = 0, \pm\sqrt3 with weights 23,16,16\tfrac23, \tfrac16, \tfrac16. How many nodes make E[X6]\mathbb E[X^6] exact for X∼N(0,1)X \sim N(0, 1), and why?
      AnswerKK nodes are exact up to degree 2K−12K - 1. You need 2K−1≥62K - 1 \ge 6, so K=4K = 4. The 3-node rule gives 2⋅16⋅27=92 \cdot \tfrac16 \cdot 27 = 9 instead of 15.
    4. Redo the evidence of worked example (c) with Laplace in θ=log⁡λ\theta = \log\lambda. Remember the Jacobian.
      Answerλ=eθ\lambda = e^\theta, dλ=eθdθd\lambda = e^\theta d\theta, so the integrand in θ\theta is e7θ−4eθ/12e^{7\theta - 4e^\theta}/12. The mode is eθ^=7/4e^{\hat\theta} = 7/4; the curvature is 4eθ^=74e^{\hat\theta} = 7. Laplace: 1.757e−7/12⋅2π/7=0.0038197×0.9474=0.00361881.75^7 e^{-7}/12 \cdot \sqrt{2\pi/7} = 0.0038197 \times 0.9474 = 0.0036188, 1.18% too low. This is better than 1.38% in λ\lambda, and it puts no mass on invalid values. Two parameterizations give two answers.
    5. With n=1000n = 1000 data points, model 1 has d=3d = 3 parameters and maximum log-likelihood −520.0-520.0; model 2 has d=5d = 5 and −515.0-515.0. Which one does the BIC prefer?
      Answerlog⁡p(D)≈ℓ^−d2log⁡n\log p(D) \approx \hat\ell - \tfrac{d}{2}\log n with log⁡1000=6.9078\log 1000 = 6.9078. Model 1: −520.0−10.36=−530.36-520.0 - 10.36 = -530.36. Model 2: −515.0−17.27=−532.27-515.0 - 17.27 = -532.27. So model 1: the gain of 5 nats does not pay for two more parameters, which cost log⁡1000=6.9\log 1000 = 6.9 nats.
    6. 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Ψ\nabla^2\Psi 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ℓ JJ^\top\nabla^2\ell\,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.
    1. What is ∫Re−x2 dx\int_{\R} e^{-x^2}\,dx, and what is the key step of the proof?

    2. Give ∫Rdexp⁡(−12x⊤Ax+b⊤x) dx\int_{\R^d}\exp(-\tfrac12 x^\top A x + b^\top x)\,dx for symmetric A≻0A \succ 0.

    3. What are the mean and covariance of the density ∝exp⁡(−12x⊤Ax+b⊤x)\propto \exp(-\tfrac12 x^\top A x + b^\top x)?

    4. Why is det⁡(A)−1/2\det(A)^{-1/2} in the Gaussian integral?

    5. How do you compute E[f(X)]\mathbb E[f(X)], X∼N(μ,σ2)X \sim N(\mu, \sigma^2), with Gauss–Hermite nodes tkt_k and weights wkw_k (weight e−t2e^{-t^2})?

    6. For which functions is a KK-node Gauss–Hermite rule exact?

    7. State Laplace's method for ∫Rde−nφ(x) dx\int_{\R^d} e^{-n\varphi(x)}\,dx.

    8. State Stirling's formula and the size of its relative error.

    9. What is the Laplace approximation of a posterior p(θ∣D)p(\theta \mid D)?

    10. Why does the Laplace approximation fail for a bimodal posterior?

    Open the review →

    9. Interview angle #

    • "Compute ∫e−x2dx\int e^{-x^2}dx." — Square it, use polar coordinates and the factor rr: π\sqrt\pi.
    • "Where does det⁡(Σ)1/2\det(\Sigma)^{1/2} in the Gaussian normalizer come from?" — Rotate to the eigenvectors; the integral factors into dd 1-D integrals with widths 2πλi(Σ)\sqrt{2\pi\lambda_i(\Sigma)}, and their product is (2π)d/2det⁡(Σ)1/2(2\pi)^{d/2}\det(\Sigma)^{1/2}.
    • "Write the log marginal likelihood of a GP and say how you compute it." — Cholesky of KyK_y: log⁡det⁡Ky=2∑ilog⁡Lii\log\det K_y = 2\sum_i\log L_{ii}, and two triangular solves for y⊤Ky−1yy^\top K_y^{-1} y.
    • "What is the Laplace approximation? When is it exact, and when does it fail?" — A Gaussian at the MAP with covariance H−1H^{-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 nn.
    • "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.

    10. Practice #

    The notebook for this lesson runs in Colab. It has five exercises, each with a check cell and a folded solution:

    1. Write log_gaussian_integral(A, b) with a Cholesky factor, and check it against dblquad and in d=200d = 200, where det overflows.
    2. Write gauss_hermite_expectation(f, mu, sigma, K), and compare its error with Monte Carlo for a smooth function and for ReLU.
    3. Write laplace_log_integral with Newton's method, and check it on Stirling's formula and on an exact Gaussian.
    4. 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.
    5. Compute the Laplace evidence of the Poisson-rate example in λ\lambda and in log⁡λ\log\lambda, and show that the error depends only on the total count.

    11. Watch and read #

    The volume under the round 2-D bump, cut into rings, and why this gives √π.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Laplace's method step by step: second-order Taylor expansion at the peak, then the Gaussian integral.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    The Laplace approximation of a distribution and of its normalizing constant, as in Bishop's book.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    When a normal approximation of a posterior works, how the parameterization matters, and how to diagnose it.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Laplace approximations for neural networks: which weights, which curvature (GGN, K-FAC) and the evidence for hyperparameters.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Why choosing the nodes as well as the weights makes Gaussian quadrature so accurate.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play