Algorithm Search⌘K

Techniquecore

Laplace approximation

Also called Laplace's method for posteriors.

Approximates a posterior by a normal law centred at its mode with covariance the inverse Hessian of minus the log posterior. It also approximates the marginal likelihood.

The Laplace approximation replaces a posterior by a normal law. Write ℓ(θ)=log⁡f(x∣θ)+log⁡π(θ)\ell(\theta) = \log f(x \mid \theta) + \log \pi(\theta) for the log of likelihood times prior, θ^\hat\theta for its maximum (the posterior mode) and H=−∇2ℓ(θ^)H = -\nabla^2 \ell(\hat\theta) for the curvature there. Then the posterior is approximately N(θ^,H−1)N(\hat\theta, H^{-1}), and the marginal likelihood Z=m(x)=∫f(x∣θ)π(θ) dθZ = m(x) = \int f(x \mid \theta)\pi(\theta)\, d\theta is approximately

Z^=eℓ(θ^) (2π)d/2det⁡(H)−1/2,log⁡Z^=ℓ(θ^)+d2log⁡2π−12log⁡det⁡H,\hat Z = e^{\ell(\hat\theta)}\, (2\pi)^{d/2} \det(H)^{-1/2}, \qquad \log \hat Z = \ell(\hat\theta) + \frac d2 \log 2\pi - \frac12 \log\det H,

for dd parameters. It is exact when ℓ\ell is quadratic. For nn observations from a regular model the relative error Z^/Z−1\hat Z/Z - 1 is O(1/n)O(1/n). The cost is one optimization and one Hessian, so it is often thousands of times cheaper than sampling.

In plain words

Near its highest point, most smooth hills look like a bell. The Laplace approximation finds the top of the hill of the posterior, measures how sharply the hill curves there, and replaces the hill by the bell with the same top and the same curvature. The volume under a bell has a formula, so you also get the total volume under the hill, which is the evidence for the model. With much data the hill is narrow and very close to a bell, so the answer is good. With little data, a lopsided hill, a hill cut off by a wall, or two hills, the bell is a poor copy, and the answer can be far off.

When it applies

  • The log posterior is smooth, with one dominant interior mode. The theorem below needs four derivatives near the mode and a mode that is clearly higher than everything far from it.
  • Many observations per parameter. The error is O(1/n)O(1/n) with a constant that grows with the dimension dd. In the examples below the error is about 0.030.03 nats per parameter at n=10n = 10 and 0.00030.0003 at n=1000n = 1000.
  • Unconstrained parameters. Map a probability to its logit, a variance to its logarithm, and include the Jacobian of the map in ℓ\ell. A mode on the boundary breaks the method.
  • Not for discrete parameters, and not for multimodal posteriors. Use importance sampling, bridge sampling or nested sampling instead.

Theorem (Laplace's method). Let In=∫g(θ) enh(θ) dθI_n = \int g(\theta)\, e^{n h(\theta)}\, d\theta over an open Θ⊆Rd\Theta \subseteq \mathbb{R}^d. Assume (A1) hh has an interior maximum at θ^\hat\theta with sup⁡∣θ−θ^∣≥δh(θ)<h(θ^)\sup_{\lvert \theta - \hat\theta \rvert \ge \delta} h(\theta) < h(\hat\theta) for every δ>0\delta > 0; (A2) hh is four times continuously differentiable near θ^\hat\theta and H=−∇2h(θ^)H = -\nabla^2 h(\hat\theta) is positive definite; (A3) gg is twice continuously differentiable near θ^\hat\theta and g(θ^)≠0g(\hat\theta) \ne 0; (A4) ∫∣g∣en0h<∞\int \lvert g \rvert e^{n_0 h} < \infty for some n0n_0. Then

In=enh(θ^)(2πn)d/2det⁡(H)−1/2 g(θ^) (1+O(1/n)).I_n = e^{n h(\hat\theta)} \Big(\frac{2\pi}{n}\Big)^{d/2} \det(H)^{-1/2}\, g(\hat\theta)\, \big(1 + O(1/n)\big).

If moreover g>0g > 0 near θ^\hat\theta, the version that expands ℓn=nh+log⁡g\ell_n = n h + \log g at its own mode, as the template does, has the same O(1/n)O(1/n) relative error. Both are proved in full in proofs/correctness.md: the proof rescales θ−θ^=u/n\theta - \hat\theta = u/\sqrt n, shows that the odd third-order terms integrate to zero over a symmetric ball, bounds the rest by C/nC/n with a Gaussian envelope, and bounds the part far from the mode by e−nηe^{-n\eta}.

What is proved and what is cited. The theorem covers a log-likelihood nh(θ)n h(\theta) with a fixed hh, which includes Bernoulli data with a fixed share of successes, the setting of the examples. For random data, hh changes with nn; Kass, Tierney and Kadane (1990) give conditions, uniform in nn, under which the relative error is still O(1/n)O(1/n). That result is cited, not proved here. The O(n−2)O(n^{-2}) error of the Tierney and Kadane ratio below is also cited, and it is measured in the table.

The template

The holes are the log posterior ℓ (the model, in the chosen parameterization, Jacobian included) and the start θ₀.

  1. LAPLACE(ℓ, ∇ℓ, ∇²ℓ, θ₀) ▷ ℓ(θ) = log f(x | θ) + log π(θ), up to a constant
  2. 1θ ← θ₀
  3. 2repeat
  4. 3g ← ∇ℓ(θ); H ← -∇²ℓ(θ)
  5. 4L ← CHOLESKY(H) ▷ fails if H is not positive definite
  6. 5solve L Lᵀ s = g ▷ the Newton step
  7. 6t ← 1; while ℓ(θ + t s) < ℓ(θ) do t ← t/2
  8. 7θ ← θ + t s
  9. 8until the step t s is below the tolerance
  10. 9H ← -∇²ℓ(θ); L ← CHOLESKY(H)
  11. 10log Ẑ ← ℓ(θ) + (d/2) log 2π - Σᵢ log Lᵢᵢ
  12. 11return θ̂ = θ, Σ = H⁻¹, log Ẑ

Lines L1 to L8 are Newton's method for the posterior mode, with step halving so that ℓ\ell never falls. Line L4 uses the Cholesky decomposition: it costs Θ(d3)\Theta(d^3) and doubles as the test that the current point is in a concave region. If it fails far from the mode, a common fix is to add a multiple of the identity to HH (a Levenberg-Marquardt step). Line L10 uses log⁡det⁡H=2∑ilog⁡Lii\log\det H = 2\sum_i \log L_{ii}, which never forms the determinant itself, so it cannot overflow. The approximate posterior is N(θ^,H−1)N(\hat\theta, H^{-1}), and H−1H^{-1} comes from the same factor.

Trace. Bernoulli data with x=3x = 3 successes in n=10n = 10 trials, prior Beta(2, 2), logit scale θ=log⁡(p/(1−p))\theta = \log(p/(1-p)). With α=2+3=5\alpha = 2 + 3 = 5 and β=2+7=9\beta = 2 + 7 = 9, the log posterior with the Jacobian p(1−p)p(1 - p) is ℓ(θ)=αlog⁡p+βlog⁡(1−p)−log⁡B(2,2)\ell(\theta) = \alpha \log p + \beta \log(1 - p) - \log B(2, 2), with ℓ′=α−(α+β)p\ell' = \alpha - (\alpha + \beta)p and −ℓ′′=(α+β)p(1−p)-\ell'' = (\alpha + \beta)p(1 - p).

step θ\theta pp ℓ′(θ)\ell'(\theta) −ℓ′′(θ)-\ell''(\theta) ℓ(θ)\ell(\theta)
0 0 0.5 −2-2 3.5 −7.912301-7.912301
1 −0.571429-0.571429 0.360907 −0.052702-0.052702 3.229145 −7.333263-7.333263
2 −0.587749-0.587749 0.357151 −0.000121-0.000121 3.214320 −7.332832-7.332832
3 −0.587787-0.587787 0.357143 0.0000000.000000 3.214286 −7.332832-7.332832

The mode is p^=5/14\hat p = 5/14, H=45/14H = 45/14, and L10 gives log⁡Z^=−7.332832+12log⁡2π−12log⁡(45/14)=−6.997696\log \hat Z = -7.332832 + \frac12\log 2\pi - \frac12 \log(45/14) = -6.997696. The exact value is log⁡B(5,9)−log⁡B(2,2)=−6.977748\log B(5, 9) - \log B(2, 2) = -6.977748, so the error is 0.01990.0199 nats, a relative error of 2%2\% in ZZ. The approximate posterior of θ\theta is N(−0.5878,0.55782)N(-0.5878, 0.5578^2).

Classic examples

Stirling's formula. Γ(n+1)=∫0∞tne−tdt=nn+1∫0∞en(log⁡s−s)ds\Gamma(n + 1) = \int_0^\infty t^n e^{-t} dt = n^{n+1}\int_0^\infty e^{n(\log s - s)} ds. Here h(s)=log⁡s−sh(s) = \log s - s has its maximum at s=1s = 1 with −h′′(1)=1-h''(1) = 1, and the theorem gives 2πn nne−n\sqrt{2\pi n}\, n^n e^{-n}, which is Stirling's approximation. The error in the logarithm is 1/(12n)+O(n−3)1/(12n) + O(n^{-3}):

nn 1 2 5 10 100 1000
log⁡Γ(n+1)−log⁡(Laplace)\log \Gamma(n+1) - \log(\text{Laplace}) 0.081061 0.041341 0.016645 0.0083306 0.00083333 0.0000833333
n×n \times error 0.0811 0.0827 0.0832 0.0833 0.0833 0.0833

Beta-binomial evidence, and the parameterization. Take x=0.3nx = 0.3n successes in nn Bernoulli trials and the prior Beta(2, 2). The exact log evidence is log⁡B(2+x,2+n−x)−log⁡B(2,2)\log B(2 + x, 2 + n - x) - \log B(2, 2). The table gives exact minus Laplace, in the probability scale pp and in the logit scale (Jacobian included):

nn exact log⁡Z\log Z error, pp scale n×n \times error error, logit scale n×n \times error
10 −6.977748-6.977748 −0.055784-0.055784 −0.558-0.558 0.0199490.019949 0.1990.199
100 −63.028491-63.028491 −0.006711-0.006711 −0.671-0.671 0.0029600.002960 0.2960.296
1000 −613.949377-613.949377 −0.000685-0.000685 −0.685-0.685 0.0003120.000312 0.3120.312
10000 −6112.878557-6112.878557 −0.0000686-0.0000686 −0.686-0.686 0.00003130.0000313 0.3130.313

Both errors fall like 1/n1/n, as the theorem says, but the logit scale is better by a factor of more than two and has the opposite sign. In the logit scale the integral is ∫pα(1−p)βdθ=B(α,β)\int p^\alpha (1-p)^\beta d\theta = B(\alpha, \beta), and the Laplace value is exactly Stirling's formula applied to Γ(α)Γ(β)/Γ(α+β)\Gamma(\alpha)\Gamma(\beta)/\Gamma(\alpha + \beta). So the error is μ(α)+μ(β)−μ(α+β)\mu(\alpha) + \mu(\beta) - \mu(\alpha + \beta), where 0<μ(z)<1/(12z)0 < \mu(z) < 1/(12z) is the error of Stirling's formula for Γ(z)\Gamma(z). The marginal likelihood page has the same check with the flat prior in the pp scale.

The normal-normal model. xi∼N(θ,σ2)x_i \sim N(\theta, \sigma^2) and θ∼N(μ0,τ2)\theta \sim N(\mu_0, \tau^2). Then ℓ\ell is quadratic in θ\theta, Newton stops after one step, and the approximation is exact: Z^\hat Z equals the density of xx under N(μ01,σ2I+τ211⊤)N(\mu_0 \mathbf{1}, \sigma^2 I + \tau^2 \mathbf{1}\mathbf{1}^\top). The same holds for every linear-Gaussian model, such as Bayesian linear regression with known noise.

The Bayesian information criterion. Keep only the terms of log⁡Z^\log \hat Z that grow with nn: ℓ(θ^)≈log⁡f(x∣θ^ML)\ell(\hat\theta) \approx \log f(x \mid \hat\theta_{\mathrm{ML}}) and log⁡det⁡H≈dlog⁡n+O(1)\log\det H \approx d\log n + O(1). This gives log⁡Z=log⁡f(x∣θ^ML)−d2log⁡n+O(1)\log Z = \log f(x \mid \hat\theta_{\mathrm{ML}}) - \frac d2 \log n + O(1), which is minus one half of the BIC. The dropped O(1)O(1) terms are why BIC is a cruder approximation than Laplace: in the beta-binomial example above the BIC error is 0.3610.361 nats at n=100n = 100 and 0.3690.369 at n=1000n = 1000, and it tends to 12log⁡(2π⋅0.21)+log⁡π(0.3)=0.370\frac12\log(2\pi \cdot 0.21) + \log \pi(0.3) = 0.370 instead of 00.

Posterior moments by Tierney and Kadane. For a positive function qq, write E[q(θ)∣x]=∫eℓ+log⁡q/∫eℓ\mathbb{E}[q(\theta) \mid x] = \int e^{\ell + \log q} / \int e^{\ell} and apply Laplace to the numerator and the denominator separately, each at its own mode (the fully exponential form). Leading error terms cancel in the ratio, and Tierney and Kadane (1986) show a relative error of O(n−2)O(n^{-2}). For q(p)=pq(p) = p under the Beta(2+x,2+n−x)(2 + x, 2 + n - x) posterior, logit scale, x=0.3nx = 0.3n:

nn exact mean Tierney-Kadane relative error n2×n^2 \times relative error plug-in mode, n×n \times relative error
10 0.357143 0.357991 2.37×10−32.37 \times 10^{-3} 0.237 −0.667-0.667
100 0.307692 0.307714 7.13×10−57.13 \times 10^{-5} 0.713 −1.225-1.225
1000 0.300797 0.300797 8.28×10−78.28 \times 10^{-7} 0.828 −1.322-1.322

The last column is the error of the posterior mode used as an estimate of the mean: it is O(1/n)O(1/n). The ratio form is O(n−2)O(n^{-2}), as measured in the fifth column.

Larger models. The same template gives the posterior of Gaussian process classification and of Bayesian logistic regression, and it is the inner step of INLA, which applies it to latent Gaussian models with a sparse precision matrix. The Bernstein-von Mises theorem says that the normal law of this page is the limit of the posterior itself, with the Fisher information in place of H/nH/n.

Variations

  • Tierney-Kadane marginal densities. For θ=(ψ,λ)\theta = (\psi, \lambda), the marginal posterior of ψ\psi is approximated by π(ψ∣x)∝eℓ(ψ,λ^ψ)det⁡(Hλλ(ψ))−1/2\pi(\psi \mid x) \propto e^{\ell(\psi, \hat\lambda_\psi)} \det(H_{\lambda\lambda}(\psi))^{-1/2}, a Laplace approximation of the inner integral at each ψ\psi. INLA uses this form.
  • Choice of scale. The approximation depends on the parameterization, as the beta-binomial table shows. Scales that make the posterior more symmetric, such as logits and logarithms of variances, usually give smaller errors.
  • The likelihood mode instead of the posterior mode. Expanding log⁡f\log f at the maximum likelihood estimate and treating the prior as gg is the form of the theorem. It has the same O(1/n)O(1/n) order.
  • Higher-order terms. The next term of the expansion involves the third and fourth derivatives of ℓ\ell and ∇g\nabla g, ∇2g\nabla^2 g at the mode (de Bruijn, Section 4.4). It reduces the error to O(n−2)O(n^{-2}) but needs derivatives that are rarely available.
  • Laplace as a proposal. Use N(θ^,H−1)N(\hat\theta, H^{-1}), or a heavier-tailed Student tt with the same centre and scale, as the proposal of importance sampling or as the second density of bridge sampling. The Monte Carlo step then removes the bias.
  • Other deterministic approximations. Variational inference chooses the normal law that minimizes a Kullback-Leibler divergence, and expectation propagation matches moments factor by factor. Both look at the whole posterior and not only at the mode.

Pitfalls

  • A mode on the boundary. A variance with a mode at 00, or a probability with all successes, has ∇ℓ(θ^)≠0\nabla \ell(\hat\theta) \ne 0 and the theorem fails. Work in the logarithm or logit scale with the Jacobian, where the mode moves into the interior.
  • Forgetting the Jacobian. After the change p=1/(1+e−θ)p = 1/(1 + e^{-\theta}), the density in θ\theta is f(x∣p)π(p) p(1−p)f(x \mid p)\pi(p)\, p(1 - p). Without the factor p(1−p)p(1 - p), Z^\hat Z is the integral of a different function.
  • Several modes. Newton finds one mode. Z^\hat Z then counts only the mass near it, and for two equal and well separated modes it is off by a factor of two. Run the optimizer from several starts, and use a sampling method if the modes do not merge.
  • Large dimension. The error constant grows with dd. For dd independent copies of the trace example, the log error is exactly dd times 0.01990.0199, so Z^\hat Z is off by a factor e0.0199de^{0.0199 d}, which is 7.37.3 for d=100d = 100. Hierarchical models with one parameter per group have dd close to nn, and the O(1/n)O(1/n) guarantee does not apply.
  • A Hessian that is not positive definite. If the Cholesky factorization fails at the final point, the point is a saddle or the posterior is flat in some direction (an unidentified parameter). Do not replace det⁡H\det H by its absolute value; fix the model or the optimizer.
  • Overflow in the determinant. det⁡H\det H grows like ndn^d. Compute log⁡det⁡H\log\det H from the Cholesky factor, as in L10.

Code

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

laplace_approximation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/laplace-approximation/. The authors are listed in prov/M8AVZX.jsonl.
"""The Laplace approximation of a posterior and of its normalizing constant.

The input is the unnormalized log posterior l(theta) = log f(x | theta) + log pi(theta)
with its gradient and Hessian. laplace() finds the mode by Newton's method with a
Cholesky solve and step halving, then returns the mode, the covariance H^-1 with
H = -Hessian at the mode, and

    log Z_hat = l(theta_hat) + (d/2) log(2 pi) - (1/2) log det H,

the Laplace approximation of log Z = log of the integral of exp(l). The relative error
of Z_hat is O(1/n) for n observations under the conditions on the page.

The other functions are the worked examples of the page: the beta-binomial model in
the probability scale and in the logit scale, Stirling's formula as the Laplace
approximation of Gamma(n + 1), and the Tierney-Kadane approximation of a posterior mean.

Cost: each Newton step costs one gradient, one Hessian and a Cholesky factorization,
Theta(d^3) arithmetic for d parameters. Newton converges quadratically near the mode.
"""

import math
from typing import Callable, Sequence

Vector = list[float]
Matrix = list[list[float]]

LOG_2PI = math.log(2.0 * math.pi)


def cholesky(a: Sequence[Sequence[float]]) -> Matrix:
    """Lower triangular L with L L^T = a. Raises ValueError if a is not positive definite.

    Cost: Theta(d^3) for a d by d matrix.
    """
    d = len(a)
    low = [[0.0] * d for _ in range(d)]
    for i in range(d):
        for j in range(i + 1):
            s = a[i][j] - math.fsum(low[i][k] * low[j][k] for k in range(j))
            if i == j:
                if s <= 0.0:
                    raise ValueError("matrix is not positive definite")
                low[i][i] = math.sqrt(s)
            else:
                low[i][j] = s / low[j][j]
    return low


def cholesky_solve(low: Matrix, b: Sequence[float]) -> Vector:
    """Solve L L^T y = b by forward and back substitution. Cost: Theta(d^2)."""
    d = len(b)
    z = [0.0] * d
    for i in range(d):
        z[i] = (b[i] - math.fsum(low[i][k] * z[k] for k in range(i))) / low[i][i]
    y = [0.0] * d
    for i in reversed(range(d)):
        y[i] = (z[i] - math.fsum(low[k][i] * y[k] for k in range(i + 1, d))) / low[i][i]
    return y


def inverse_from_cholesky(low: Matrix) -> Matrix:
    """(L L^T)^-1, column by column. Cost: Theta(d^3)."""
    d = len(low)
    cols = [cholesky_solve(low, [1.0 if r == c else 0.0 for r in range(d)]) for c in range(d)]
    return [[cols[c][r] for c in range(d)] for r in range(d)]


def laplace(
    logpost: Callable[[Vector], float],
    grad: Callable[[Vector], Vector],
    hess: Callable[[Vector], Matrix],
    theta0: Sequence[float],
    tol: float = 1e-12,
    max_iter: int = 200,
) -> tuple[Vector, Matrix, float]:
    """Return (theta_hat, covariance, log_z_hat) for the unnormalized log posterior logpost.

    Precondition: logpost has a unique interior maximum, and -hess is positive definite
    at every point where Newton steps are taken (the code raises ValueError otherwise).
    """
    theta = [float(t) for t in theta0]  # @line L1
    d = len(theta)
    for _ in range(max_iter):  # @line L2
        g = grad(theta)  # @line L3
        h = [[-v for v in row] for row in hess(theta)]
        low = cholesky(h)  # @line L4
        step = cholesky_solve(low, g)  # @line L5
        t, base = 1.0, logpost(theta)  # @line L6
        while True:
            trial = [theta[i] + t * step[i] for i in range(d)]
            val = logpost(trial)
            if val >= base or t < 1e-12:
                break
            t *= 0.5
        theta = trial  # @line L7
        if max(abs(t * s) for s in step) <= tol * (1.0 + max(abs(v) for v in theta)):  # @line L8
            break
    h = [[-v for v in row] for row in hess(theta)]  # @line L9
    low = cholesky(h)
    log_det_h = 2.0 * math.fsum(math.log(low[i][i]) for i in range(d))
    log_z = logpost(theta) + 0.5 * d * LOG_2PI - 0.5 * log_det_h  # @line L10
    return theta, inverse_from_cholesky(low), log_z  # @line L11


def log_beta(a: float, b: float) -> float:
    """log B(a, b) = log Gamma(a) + log Gamma(b) - log Gamma(a + b)."""
    return math.lgamma(a) + math.lgamma(b) - math.lgamma(a + b)


def beta_binomial_log_z(x: int, n: int, a: float, b: float) -> float:
    """Exact log Z for x successes in n Bernoulli trials with prior Beta(a, b).

    Z = integral of p^x (1 - p)^(n - x) Beta(p; a, b) dp = B(a + x, b + n - x) / B(a, b).
    """
    return log_beta(a + x, b + n - x) - log_beta(a, b)


def beta_binomial_laplace_p(x: int, n: int, a: float, b: float) -> float:
    """Laplace log Z in the probability scale p. Needs a + x > 1 and b + n - x > 1."""
    al, be = a + x - 1.0, b + n - x - 1.0
    lb = log_beta(a, b)

    def lp(v: Vector) -> float:
        p = v[0]
        if not 0.0 < p < 1.0:
            return -math.inf
        return al * math.log(p) + be * math.log1p(-p) - lb

    def gr(v: Vector) -> Vector:
        p = v[0]
        return [al / p - be / (1.0 - p)]

    def he(v: Vector) -> Matrix:
        p = v[0]
        return [[-al / p**2 - be / (1.0 - p) ** 2]]

    return laplace(lp, gr, he, [(al + 0.5) / (al + be + 1.0)])[2]


def beta_binomial_laplace_logit(x: int, n: int, a: float, b: float) -> float:
    """Laplace log Z in the logit scale theta = log(p / (1 - p)), Jacobian p (1 - p) included."""
    al, be = a + x, b + n - x
    lb = log_beta(a, b)

    def lp(v: Vector) -> float:
        t = v[0]
        # log sigma(t) = -log(1 + e^-t), log(1 - sigma(t)) = -log(1 + e^t)
        return -al * _log1pexp(-t) - be * _log1pexp(t) - lb

    def gr(v: Vector) -> Vector:
        p = _sigmoid(v[0])
        return [al - (al + be) * p]

    def he(v: Vector) -> Matrix:
        p = _sigmoid(v[0])
        return [[-(al + be) * p * (1.0 - p)]]

    return laplace(lp, gr, he, [0.0])[2]


def _sigmoid(t: float) -> float:
    if t >= 0:
        return 1.0 / (1.0 + math.exp(-t))
    e = math.exp(t)
    return e / (1.0 + e)


def _log1pexp(t: float) -> float:
    """log(1 + e^t) without overflow."""
    if t > 0:
        return t + math.log1p(math.exp(-t))
    return math.log1p(math.exp(t))


def stirling_log(n: float) -> float:
    """Laplace approximation of log Gamma(n + 1) = log of the integral of t^n e^-t dt.

    With t = n s the integrand is n^(n+1) exp(n (log s - s)); the maximum is at s = 1
    with -h''(1) = 1, which gives n^(n+1) e^-n sqrt(2 pi / n) = sqrt(2 pi n) n^n e^-n.
    """
    return 0.5 * math.log(2.0 * math.pi * n) + n * math.log(n) - n


def tierney_kadane_beta_mean(al: float, be: float) -> float:
    """Tierney-Kadane approximation of E[p] for p ~ Beta(al, be), in the logit scale.

    E[p] = (integral of p * p^al (1 - p)^be dtheta) / (integral of p^al (1 - p)^be dtheta)
    in the logit scale theta. Each integral gets its own Laplace approximation (the fully
    exponential form), so the mode moves for the numerator. The exact answer is
    al / (al + be). The relative error is O(1/n^2) when al and be grow like n.
    """

    def log_z(a1: float, b1: float) -> float:
        # Laplace for the integral of sigma^a1 (1 - sigma)^b1 dtheta: mode p = a1/(a1 + b1),
        # curvature (a1 + b1) p (1 - p).
        p = a1 / (a1 + b1)
        return a1 * math.log(p) + b1 * math.log1p(-p) + 0.5 * LOG_2PI - 0.5 * math.log((a1 + b1) * p * (1 - p))

    return math.exp(log_z(al + 1.0, be) - log_z(al, be))


def gaussian_log_z(mu: Sequence[float], prec: Sequence[Sequence[float]], c: float) -> float:
    """Exact log of the integral of exp(c - (theta - mu)^T Q (theta - mu) / 2)."""
    low = cholesky(prec)
    d = len(mu)
    return c + 0.5 * d * LOG_2PI - math.fsum(math.log(low[i][i]) for i in range(d))
test_laplace_approximation.py 183 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/laplace-approximation/. The authors are listed in prov/M8AVZX.jsonl.
"""Tests for the Laplace approximation: exact Gaussian cases, the O(1/n) error, Stirling, Tierney-Kadane."""

import math
import random
import unittest

from laplace_approximation import (
    beta_binomial_laplace_logit,
    beta_binomial_laplace_p,
    beta_binomial_log_z,
    cholesky,
    cholesky_solve,
    gaussian_log_z,
    laplace,
    log_beta,
    stirling_log,
    tierney_kadane_beta_mean,
)


def simpson_log_z(logf, lo, hi, m=20000):
    """log of the integral of exp(logf) on [lo, hi] by Simpson's rule, scaled by the maximum."""
    h = (hi - lo) / m
    vals = [logf(lo + i * h) for i in range(m + 1)]
    top = max(vals)
    s = 0.0
    for i, v in enumerate(vals):
        w = 1 if i in (0, m) else (4 if i % 2 else 2)
        s += w * math.exp(v - top)
    return top + math.log(s * h / 3.0)


class TestLinearAlgebra(unittest.TestCase):
    def test_cholesky_random(self):
        rng = random.Random(1)
        for _ in range(500):
            d = rng.randint(1, 4)
            b = [[rng.uniform(-1, 1) for _ in range(d)] for _ in range(d)]
            a = [[sum(b[i][k] * b[j][k] for k in range(d)) + (1.0 if i == j else 0.0) for j in range(d)] for i in range(d)]
            low = cholesky(a)
            for i in range(d):
                for j in range(d):
                    self.assertAlmostEqual(sum(low[i][k] * low[j][k] for k in range(d)), a[i][j], places=10)
            y = [rng.uniform(-1, 1) for _ in range(d)]
            x = cholesky_solve(low, y)
            for i in range(d):
                self.assertAlmostEqual(sum(a[i][j] * x[j] for j in range(d)), y[i], places=9)

    def test_not_positive_definite(self):
        with self.assertRaises(ValueError):
            cholesky([[1.0, 2.0], [2.0, 1.0]])


class TestExactGaussian(unittest.TestCase):
    def test_normal_normal_is_exact(self):
        # y_i ~ N(theta, s2), theta ~ N(m0, t2). The log posterior is quadratic, so Laplace is exact.
        rng = random.Random(2)
        for _ in range(500):
            n = rng.randint(1, 8)
            s2, t2, m0 = rng.uniform(0.2, 3), rng.uniform(0.2, 3), rng.uniform(-2, 2)
            ys = [rng.gauss(0, 2) for _ in range(n)]

            def lp(v, ys=ys, s2=s2, t2=t2, m0=m0):
                th = v[0]
                return (-0.5 * sum((y - th) ** 2 for y in ys) / s2 - 0.5 * n * math.log(2 * math.pi * s2)
                        - 0.5 * (th - m0) ** 2 / t2 - 0.5 * math.log(2 * math.pi * t2))

            def gr(v, ys=ys, s2=s2, t2=t2, m0=m0):
                return [sum(y - v[0] for y in ys) / s2 - (v[0] - m0) / t2]

            def he(v, s2=s2, t2=t2):
                return [[-n / s2 - 1 / t2]]

            mode, cov, log_z = laplace(lp, gr, he, [0.0])
            # Oracle: y ~ N(m0 1, s2 I + t2 1 1^T); determinant lemma and Sherman-Morrison.
            r = [y - m0 for y in ys]
            sr = sum(r)
            quad = (sum(v * v for v in r) - t2 * sr * sr / (s2 + n * t2)) / s2
            logdet = n * math.log(s2) + math.log(1 + n * t2 / s2)
            exact = -0.5 * (n * math.log(2 * math.pi) + logdet + quad)
            self.assertAlmostEqual(log_z, exact, places=9)
            post_prec = n / s2 + 1 / t2
            self.assertAlmostEqual(cov[0][0], 1 / post_prec, places=12)
            self.assertAlmostEqual(mode[0], (sum(ys) / s2 + m0 / t2) / post_prec, places=9)

    def test_correlated_two_dim_gaussian(self):
        q = [[2.0, 0.7], [0.7, 1.0]]
        mu = [0.3, -1.2]

        def lp(v):
            a, b = v[0] - mu[0], v[1] - mu[1]
            return 1.5 - 0.5 * (q[0][0] * a * a + 2 * q[0][1] * a * b + q[1][1] * b * b)

        def gr(v):
            a, b = v[0] - mu[0], v[1] - mu[1]
            return [-(q[0][0] * a + q[0][1] * b), -(q[0][1] * a + q[1][1] * b)]

        mode, cov, log_z = laplace(lp, gr, lambda v: [[-q[0][0], -q[0][1]], [-q[0][1], -q[1][1]]], [5.0, 5.0])
        self.assertAlmostEqual(log_z, gaussian_log_z(mu, q, 1.5), places=12)
        self.assertAlmostEqual(mode[0], mu[0], places=12)
        det = q[0][0] * q[1][1] - q[0][1] ** 2
        self.assertAlmostEqual(cov[0][1], -q[0][1] / det, places=12)


class TestErrorRate(unittest.TestCase):
    def test_beta_binomial_values_of_the_page(self):
        self.assertAlmostEqual(beta_binomial_log_z(30, 100, 2, 2), -63.028491, places=5)
        self.assertAlmostEqual(beta_binomial_log_z(30, 100, 2, 2) - beta_binomial_laplace_p(30, 100, 2, 2), -0.006711, places=5)
        self.assertAlmostEqual(beta_binomial_log_z(30, 100, 2, 2) - beta_binomial_laplace_logit(30, 100, 2, 2), 0.002960, places=5)

    def test_relative_error_falls_like_one_over_n(self):
        # x = 0.3 n, prior Beta(2, 2). n times the log error must settle to a constant.
        for fn, limit in ((beta_binomial_laplace_p, -0.6865), (beta_binomial_laplace_logit, 0.3133)):
            scaled = []
            for n in (10, 100, 1000, 10000):
                x = 3 * n // 10
                scaled.append(n * (beta_binomial_log_z(x, n, 2, 2) - fn(x, n, 2, 2)))
            self.assertAlmostEqual(scaled[-1], limit, delta=0.002)
            gaps = [abs(s - limit) for s in scaled]
            self.assertTrue(all(gaps[i + 1] < gaps[i] for i in range(len(gaps) - 1)))

    def test_independent_oracle_by_quadrature(self):
        # Simpson's rule in the p scale gives the exact value to 1e-8, independent of lgamma.
        rng = random.Random(3)
        for _ in range(30):
            n = rng.randint(5, 60)
            x = rng.randint(1, n - 1)
            a, b = rng.uniform(1, 4), rng.uniform(1, 4)
            lb = log_beta(a, b)
            exact = simpson_log_z(lambda p: (a + x - 1) * math.log(p) + (b + n - x - 1) * math.log1p(-p) - lb if 0 < p < 1 else -1e300, 0.0, 1.0)
            self.assertAlmostEqual(exact, beta_binomial_log_z(x, n, a, b), places=6)
            err = abs(exact - beta_binomial_laplace_logit(x, n, a, b))
            # In the logit scale the error is mu(al) + mu(be) - mu(al + be) with
            # 0 < mu(z) < 1/(12 z), the error of Stirling's formula for Gamma(z).
            al, be = a + x, b + n - x
            self.assertLess(err, 1.0 / (12 * al) + 1.0 / (12 * be))

    def test_error_adds_over_independent_blocks(self):
        # d independent copies: the log error is d times the error of one copy.
        x, n, a, b = 3, 10, 2.0, 2.0
        one = beta_binomial_log_z(x, n, a, b) - beta_binomial_laplace_logit(x, n, a, b)
        for d in (1, 2, 3, 5):
            al, be = a + x, b + n - x

            def lp(v):
                return sum(-al * math.log1p(math.exp(-t)) - be * math.log1p(math.exp(t)) - log_beta(a, b) for t in v)

            def gr(v):
                return [al - (al + be) / (1 + math.exp(-t)) for t in v]

            def he(v):
                out = [[0.0] * d for _ in range(d)]
                for i, t in enumerate(v):
                    p = 1 / (1 + math.exp(-t))
                    out[i][i] = -(al + be) * p * (1 - p)
                return out

            log_z = laplace(lp, gr, he, [0.1 * i for i in range(d)])[2]
            self.assertAlmostEqual(d * beta_binomial_log_z(x, n, a, b) - log_z, d * one, places=9)


class TestStirlingAndTierneyKadane(unittest.TestCase):
    def test_stirling(self):
        for n, val in ((1, 0.081061), (10, 0.0083306), (1000, 8.33333e-5)):
            self.assertAlmostEqual(math.lgamma(n + 1) - stirling_log(n), val, delta=val * 1e-4)
        self.assertAlmostEqual(1000 * (math.lgamma(1001) - stirling_log(1000)), 1 / 12, places=6)

    def test_tierney_kadane_error_is_order_n_minus_two(self):
        scaled = []
        for n in (10, 100, 1000):
            x = 3 * n // 10
            al, be = 2 + x, 2 + n - x
            exact = al / (al + be)
            scaled.append(n * n * (tierney_kadane_beta_mean(al, be) - exact) / exact)
        self.assertAlmostEqual(scaled[0], 0.2375, places=3)
        self.assertAlmostEqual(scaled[2], 0.8281, places=3)
        self.assertTrue(all(0 < s < 1 for s in scaled))


if __name__ == "__main__":
    unittest.main()

Exercises

  1. Show that the Laplace approximation of ∫01pa−1(1−p)b−1dp\int_0^1 p^{a-1}(1-p)^{b-1} dp in the logit scale equals the product of Stirling's approximations of Γ(a)Γ(b)/Γ(a+b)\Gamma(a)\Gamma(b)/\Gamma(a + b), and deduce that its log error lies between −1/(12(a+b))-1/(12(a + b)) and 1/(12a)+1/(12b)1/(12a) + 1/(12b).
  2. In the probability scale, the same integral with a,b>1a, b > 1 is expanded at p=(a−1)/(a+b−2)p = (a - 1)/(a + b - 2). Compute the limit of nn times the log error for a=2+0.3na = 2 + 0.3n, b=2+0.7nb = 2 + 0.7n, and compare it with the value −0.686-0.686 in the table.
  3. Prove that Newton's method from any start reaches the mode of a quadratic ℓ\ell in one step, and that the Laplace approximation of a Gaussian integral is exact.
  4. For x1,…,xnx_1, \ldots, x_n from Poisson(λ\lambda) with prior Gamma(aa, bb), write the Laplace approximation of log⁡Z\log Z in the scale log⁡λ\log\lambda and compare it with the exact negative binomial evidence for n=5n = 5 and n=50n = 50.
  5. Two independent coordinates each have log error ε\varepsilon. Show that the log error of the joint approximation is 2ε2\varepsilon, and explain what this says about the error for dd parameters.
Proof: The relative error of Laplace's method is O(1/n)full

We prove three facts. Theorem 1 is Laplace's method for an integral ∫g enh\int g\, e^{n h} with a fixed hh. Theorem 2 shows that the version of the page, which expands ℓn=nh+log⁡g\ell_n = n h + \log g at its own mode, has the same O(1/n)O(1/n) relative error. Fact 3 is exactness for a Gaussian. Throughout, ∣⋅∣\lvert \cdot \rvert is the Euclidean norm, and for a kk-linear form AA we write ∥A∥=sup⁡∣u∣=1∣A[u,…,u]∣\lVert A \rVert = \sup_{\lvert u \rvert = 1} \lvert A[u, \ldots, u] \rvert, so ∣A[u,…,u]∣≤∥A∥ ∣u∣k\lvert A[u, \ldots, u] \rvert \le \lVert A \rVert\, \lvert u \rvert^k.

Theorem 1

Hypotheses. Let Θ⊆Rd\Theta \subseteq \mathbb{R}^d be open and h,g:Θ→Rh, g : \Theta \to \mathbb{R} measurable.

  • (A1) hh has a maximum at an interior point θ^\hat\theta, and the maximum is well separated: for every δ>0\delta > 0, η(δ)=h(θ^)−sup⁡∣θ−θ^∣≥δh(θ)>0\eta(\delta) = h(\hat\theta) - \sup_{\lvert \theta - \hat\theta \rvert \ge \delta} h(\theta) > 0.
  • (A2) hh is four times continuously differentiable on a closed ball Bˉ(θ^,r0)⊂Θ\bar B(\hat\theta, r_0) \subset \Theta, and H=−∇2h(θ^)H = -\nabla^2 h(\hat\theta) is positive definite. Let λ>0\lambda > 0 be its smallest eigenvalue.
  • (A3) gg is twice continuously differentiable on Bˉ(θ^,r0)\bar B(\hat\theta, r_0) and g(θ^)≠0g(\hat\theta) \ne 0.
  • (A4) ∫Θ∣g∣ en0h dθ<∞\int_\Theta \lvert g \rvert\, e^{n_0 h}\, d\theta < \infty for some n0n_0.

Claim. As n→∞n \to \infty,

In=∫Θg(θ) enh(θ) dθ=enh(θ^)(2πn)d/2det⁡(H)−1/2 g(θ^) (1+O(1/n)).I_n = \int_\Theta g(\theta)\, e^{n h(\theta)}\, d\theta = e^{n h(\hat\theta)} \Big(\frac{2\pi}{n}\Big)^{d/2} \det(H)^{-1/2}\, g(\hat\theta)\, \big(1 + O(1/n)\big).

Proof. Translate so that θ^=0\hat\theta = 0 and subtract a constant so that h(0)=0h(0) = 0. Then h≤0h \le 0 on Θ\Theta by (A1), and the claim is unchanged because both sides scale by the same factor enh(θ^)e^{n h(\hat\theta)}.

Constants. Fix δ\delta with 0<δ≤r00 < \delta \le r_0 and δ≤3λ/(2M3)\delta \le 3\lambda/(2 M_3), where M3=sup⁡∣θ∣≤r0∥∇3h(θ)∥M_3 = \sup_{\lvert \theta \rvert \le r_0} \lVert \nabla^3 h(\theta) \rVert (if M3=0M_3 = 0 any δ≤r0\delta \le r_0 works). Let M4=sup⁡∣θ∣≤r0∥∇4h(θ)∥M_4 = \sup_{\lvert \theta \rvert \le r_0} \lVert \nabla^4 h(\theta) \rVert, g0=g(0)g_0 = g(0), g1=∇g(0)g_1 = \nabla g(0) and G2=sup⁡∣θ∣≤r0∥∇2g(θ)∥G_2 = \sup_{\lvert \theta \rvert \le r_0} \lVert \nabla^2 g(\theta) \rVert. All are finite because the derivatives are continuous on a compact ball.

Step 1: the part outside the ball is exponentially small. Let η=η(δ)>0\eta = \eta(\delta) > 0. For ∣θ∣≥δ\lvert \theta \rvert \ge \delta we have h(θ)≤−ηh(\theta) \le -\eta, so for n≥n0n \ge n_0

enh(θ)=en0h(θ) e(n−n0)h(θ)≤en0h(θ) e−(n−n0)η.e^{n h(\theta)} = e^{n_0 h(\theta)}\, e^{(n - n_0) h(\theta)} \le e^{n_0 h(\theta)}\, e^{-(n - n_0)\eta}.

Hence ∣∫∣θ∣≥δg enh∣≤e−(n−n0)η∫∣g∣en0h=O(e−nη)\big\lvert \int_{\lvert \theta \rvert \ge \delta} g\, e^{n h} \big\rvert \le e^{-(n - n_0)\eta} \int \lvert g \rvert e^{n_0 h} = O(e^{-n\eta}) by (A4). The same bound with h≤0h \le 0 shows that InI_n exists for n≥n0n \ge n_0.

Step 2: rescale the ball. Put θ=u/n\theta = u/\sqrt n. Then

∫∣θ∣<δg enh dθ=n−d/2∫∣u∣<δng(u/n) e−12u⊤Hu eφn(u) du,φn(u)=n h(u/n)+12u⊤Hu.\int_{\lvert \theta \rvert < \delta} g\, e^{n h}\, d\theta = n^{-d/2} \int_{\lvert u \rvert < \delta \sqrt n} g(u/\sqrt n)\, e^{-\frac12 u^\top H u}\, e^{\varphi_n(u)}\, du, \qquad \varphi_n(u) = n\, h(u/\sqrt n) + \tfrac12 u^\top H u.

Since ∇h(0)=0\nabla h(0) = 0 and ∇2h(0)=−H\nabla^2 h(0) = -H, Taylor's theorem with the Lagrange remainder gives, for ∣u∣<δn\lvert u \rvert < \delta\sqrt n:

  1. at order three, ∣φn(u)∣≤n⋅M3∣u/n∣3/6=M3∣u∣3/(6n)\lvert \varphi_n(u) \rvert \le n \cdot M_3 \lvert u/\sqrt n \rvert^3/6 = M_3 \lvert u \rvert^3/(6\sqrt n);
  2. at order four, φn(u)=T(u)/(6n)+Rn(u)\varphi_n(u) = T(u)/(6\sqrt n) + R_n(u) with T(u)=∇3h(0)[u,u,u]T(u) = \nabla^3 h(0)[u, u, u] and ∣Rn(u)∣≤M4∣u∣4/(24n)\lvert R_n(u) \rvert \le M_4 \lvert u \rvert^4/(24 n).

From item 1 and ∣u∣/n<δ\lvert u \rvert/\sqrt n < \delta, ∣φn(u)∣≤M3δ∣u∣2/6≤λ∣u∣2/4\lvert \varphi_n(u) \rvert \le M_3 \delta \lvert u \rvert^2/6 \le \lambda \lvert u \rvert^2/4. Together with u⊤Hu≥λ∣u∣2u^\top H u \ge \lambda \lvert u \rvert^2:

e−12u⊤Hu e∣φn(u)∣≤e−λ∣u∣2/4.(1)e^{-\frac12 u^\top H u}\, e^{\lvert \varphi_n(u) \rvert} \le e^{-\lambda \lvert u \rvert^2/4}. \tag{1}

For gg: g(u/n)=g0+g1⋅u/n+ρn(u)g(u/\sqrt n) = g_0 + g_1 \cdot u/\sqrt n + \rho_n(u) with ∣ρn(u)∣≤G2∣u∣2/(2n)\lvert \rho_n(u) \rvert \le G_2 \lvert u \rvert^2/(2n).

Step 3: expand the integrand. Write eφ=1+φ+re^{\varphi} = 1 + \varphi + r with ∣r∣≤12φ2e∣φ∣\lvert r \rvert \le \tfrac12 \varphi^2 e^{\lvert \varphi \rvert}, and eφ−1=φ eξe^{\varphi} - 1 = \varphi\, e^{\xi} for some ξ\xi between 00 and φ\varphi, so ∣eφ−1∣≤∣φ∣e∣φ∣\lvert e^\varphi - 1 \rvert \le \lvert \varphi \rvert e^{\lvert \varphi \rvert}. Then, dropping the argument uu,

g(u/n) eφn=g0+(g0T6n+g1⋅un)⏟odd in u+g0Rn+g0r+g1⋅un(eφn−1)+ρneφn⏟En(u).g(u/\sqrt n)\, e^{\varphi_n} = g_0 + \underbrace{\Big(\frac{g_0 T}{6\sqrt n} + \frac{g_1 \cdot u}{\sqrt n}\Big)}_{\text{odd in } u} + \underbrace{g_0 R_n + g_0 r + \frac{g_1 \cdot u}{\sqrt n}\big(e^{\varphi_n} - 1\big) + \rho_n e^{\varphi_n}}_{E_n(u)}.

The four terms of EnE_n are bounded, with item 1 for φn\varphi_n, by

∣g0∣M4∣u∣424n,∣g0∣M32∣u∣672ne∣φn∣,∣g1∣M3∣u∣46ne∣φn∣,G2∣u∣22ne∣φn∣.\lvert g_0 \rvert \frac{M_4 \lvert u \rvert^4}{24 n}, \quad \lvert g_0 \rvert \frac{M_3^2 \lvert u \rvert^6}{72 n} e^{\lvert \varphi_n \rvert}, \quad \lvert g_1 \rvert \frac{M_3 \lvert u \rvert^4}{6 n} e^{\lvert \varphi_n \rvert}, \quad \frac{G_2 \lvert u \rvert^2}{2 n} e^{\lvert \varphi_n \rvert}.

So ∣En(u)∣≤1nP(∣u∣) e∣φn(u)∣\lvert E_n(u) \rvert \le \frac{1}{n} P(\lvert u \rvert)\, e^{\lvert \varphi_n(u) \rvert} for a fixed polynomial PP that does not depend on nn.

Step 4: integrate. The odd terms integrate to 00 over the ball ∣u∣<δn\lvert u \rvert < \delta\sqrt n, because the ball and e−12u⊤Hue^{-\frac12 u^\top H u} are symmetric under u↦−uu \mapsto -u. By (1),

∣∫∣u∣<δnEn(u) e−12u⊤Hu du∣≤1n∫RdP(∣u∣) e−λ∣u∣2/4 du=Cn.\Big\lvert \int_{\lvert u \rvert < \delta\sqrt n} E_n(u)\, e^{-\frac12 u^\top H u}\, du \Big\rvert \le \frac{1}{n} \int_{\mathbb{R}^d} P(\lvert u \rvert)\, e^{-\lambda \lvert u \rvert^2/4}\, du = \frac{C}{n}.

The constant term gives the Gaussian integral minus its tail:

g0∫∣u∣<δne−12u⊤Hu du=g0(2π)d/2det⁡(H)−1/2−g0∫∣u∣≥δne−12u⊤Hu du,g_0 \int_{\lvert u \rvert < \delta\sqrt n} e^{-\frac12 u^\top H u}\, du = g_0 (2\pi)^{d/2} \det(H)^{-1/2} - g_0 \int_{\lvert u \rvert \ge \delta\sqrt n} e^{-\frac12 u^\top H u}\, du,

and the tail is at most ∫∣u∣≥δne−λ∣u∣2/2 du=O(e−λδ2n/4)\int_{\lvert u \rvert \ge \delta\sqrt n} e^{-\lambda \lvert u \rvert^2/2}\, du = O(e^{-\lambda \delta^2 n/4}).

Step 5: collect. Steps 1 to 4 give

In=n−d/2(g0(2π)d/2det⁡(H)−1/2+O(1/n))+O(e−nη).I_n = n^{-d/2}\Big(g_0 (2\pi)^{d/2} \det(H)^{-1/2} + O(1/n)\Big) + O(e^{-n\eta}).

The exponential terms are o(n−d/2−1)o(n^{-d/2 - 1}). Divide by n−d/2g0(2π)d/2det⁡(H)−1/2n^{-d/2} g_0 (2\pi)^{d/2}\det(H)^{-1/2}, which is not zero by (A3). ■\blacksquare

Theorem 2: the expansion at the mode of the log posterior

The page does not split the integrand into gg and enhe^{nh}. It takes ℓn=nh+log⁡g\ell_n = n h + \log g with g>0g > 0, finds its mode θ~n\tilde\theta_n, and uses

An=eℓn(θ~n)(2π)d/2det⁡(−∇2ℓn(θ~n))−1/2.A_n = e^{\ell_n(\tilde\theta_n)} (2\pi)^{d/2} \det\big(-\nabla^2 \ell_n(\tilde\theta_n)\big)^{-1/2}.

Claim. Under (A1) to (A4) and g>0g > 0 on Bˉ(θ^,r0)\bar B(\hat\theta, r_0), for all large nn the function ℓn\ell_n has exactly one critical point θ~n\tilde\theta_n in the ball ∣θ−θ^∣≤K/n\lvert \theta - \hat\theta \rvert \le K/n (for a constant KK), it is a local maximum, and An=In(1+O(1/n))A_n = I_n (1 + O(1/n)).

Proof. Keep θ^=0\hat\theta = 0, h(0)=0h(0) = 0 and the constants above. Let G=sup⁡∣θ∣≤r0∣∇log⁡g∣G = \sup_{\lvert \theta \rvert \le r_0} \lvert \nabla \log g \rvert and G′=sup⁡∣θ∣≤r0∥∇2log⁡g∥G' = \sup_{\lvert \theta \rvert \le r_0} \lVert \nabla^2 \log g \rVert, finite by (A3) and g>0g > 0.

Existence and location. For ∣θ∣≤δ\lvert \theta \rvert \le \delta, Taylor at order three gives h(θ)≤−12θ⊤Hθ+M3∣θ∣3/6≤−λ∣θ∣2/4h(\theta) \le -\frac12\theta^\top H \theta + M_3 \lvert \theta \rvert^3/6 \le -\lambda \lvert \theta \rvert^2/4. Take K=8G/λK = 8G/\lambda and ρ=K/n\rho = K/n. On the sphere ∣θ∣=ρ\lvert \theta \rvert = \rho,

ℓn(θ)−ℓn(0)≤−nλρ24+Gρ=Kn(G−λK4)=−GKn<0\ell_n(\theta) - \ell_n(0) \le -\frac{n\lambda\rho^2}{4} + G\rho = \frac{K}{n}\Big(G - \frac{\lambda K}{4}\Big) = -\frac{GK}{n} < 0

(if G=0G = 0, use any K>0K > 0; the same steps give a strict inequality). So the maximum of the continuous ℓn\ell_n on the closed ball ∣θ∣≤ρ\lvert \theta \rvert \le \rho lies inside, and it is a critical point θ~n\tilde\theta_n with ∣θ~n∣<K/n\lvert \tilde\theta_n \rvert < K/n. On this ball −∇2ℓn=n(−∇2h)−∇2log⁡g-\nabla^2 \ell_n = n(-\nabla^2 h) - \nabla^2 \log g, and −∇2h(θ)⪰(λ−M3∣θ∣)I⪰λ2I-\nabla^2 h(\theta) \succeq (\lambda - M_3 \lvert \theta \rvert) I \succeq \frac{\lambda}{2} I for ∣θ∣≤λ/(2M3)\lvert \theta \rvert \le \lambda/(2 M_3), so −∇2ℓn⪰(nλ/2−G′)I-\nabla^2 \ell_n \succeq (n\lambda/2 - G') I is positive definite for n>2G′/λn > 2G'/\lambda. A strictly concave function has at most one critical point on a convex set, so θ~n\tilde\theta_n is unique there.

The value. Since ∇ℓn(θ~n)=0\nabla \ell_n(\tilde\theta_n) = 0, Taylor at order two around θ~n\tilde\theta_n gives ℓn(0)=ℓn(θ~n)−12v⊤Sv\ell_n(0) = \ell_n(\tilde\theta_n) - \frac12 v^\top S v with v=−θ~nv = -\tilde\theta_n and S=−∇2ℓnS = -\nabla^2 \ell_n at an intermediate point, ∥S∥≤nsup⁡∥∇2h∥+G′=O(n)\lVert S \rVert \le n \sup \lVert \nabla^2 h \rVert + G' = O(n). Hence ℓn(θ~n)−ℓn(0)=O(n⋅K2/n2)=O(1/n)\ell_n(\tilde\theta_n) - \ell_n(0) = O(n \cdot K^2/n^2) = O(1/n), and eℓn(θ~n)=enh(0)g(0)(1+O(1/n))e^{\ell_n(\tilde\theta_n)} = e^{n h(0)} g(0) (1 + O(1/n)).

The determinant. −∇2ℓn(θ~n)/n=H+(∇2h(0)−∇2h(θ~n))−∇2log⁡g(θ~n)/n=H+O(M3K/n)+O(G′/n)-\nabla^2 \ell_n(\tilde\theta_n)/n = H + \big(\nabla^2 h(0) - \nabla^2 h(\tilde\theta_n)\big) - \nabla^2 \log g(\tilde\theta_n)/n = H + O(M_3 K/n) + O(G'/n). The determinant is a polynomial in the entries, so det⁡(−∇2ℓn(θ~n))=nddet⁡(H) (1+O(1/n))\det\big(-\nabla^2 \ell_n(\tilde\theta_n)\big) = n^d \det(H)\, (1 + O(1/n)).

Multiply: An=enh(0)g(0)(2π/n)d/2det⁡(H)−1/2(1+O(1/n))A_n = e^{n h(0)} g(0) (2\pi/n)^{d/2} \det(H)^{-1/2} (1 + O(1/n)), which is In(1+O(1/n))I_n(1 + O(1/n)) by Theorem 1. ■\blacksquare

Application to a posterior. If the log-likelihood is nh(θ)n h(\theta) for a fixed hh and the prior density is g=πg = \pi, then Zn=∫π enh=InZ_n = \int \pi\, e^{n h} = I_n and Z^n=An\hat Z_n = A_n, so Z^n/Zn=1+O(1/n)\hat Z_n/Z_n = 1 + O(1/n). This covers x=cnx = cn successes in nn Bernoulli trials with c∈(0,1)c \in (0, 1) fixed: h(p)=clog⁡p+(1−c)log⁡(1−p)h(p) = c\log p + (1 - c)\log(1 - p), maximized at p=cp = c with H=1/(c(1−c))H = 1/(c(1 - c)). In the logit scale θ=log⁡(p/(1−p))\theta = \log(p/(1 - p)) the same holds with g(θ)=π(p) p(1−p)g(\theta) = \pi(p)\, p(1 - p). For data drawn at random, hh depends on nn through the data; then the same steps go through on the event that the derivative bounds and the separation hold uniformly in nn. Kass, Tierney and Kadane (1990) give such conditions and prove Z^n/Zn=1+O(1/n)\hat Z_n/Z_n = 1 + O(1/n) under them. We cite that result and do not prove it here.

Fact 3: exactness for a Gaussian

If ℓ(θ)=c−12(θ−μ)⊤Q(θ−μ)\ell(\theta) = c - \frac12(\theta - \mu)^\top Q (\theta - \mu) with QQ positive definite, then ∇ℓ(μ)=0\nabla \ell(\mu) = 0, −∇2ℓ=Q-\nabla^2 \ell = Q everywhere, and

∫eℓdθ=ec(2π)d/2det⁡(Q)−1/2=eℓ(θ^)(2π)d/2det⁡(−∇2ℓ(θ^))−1/2,\int e^{\ell} d\theta = e^{c} (2\pi)^{d/2} \det(Q)^{-1/2} = e^{\ell(\hat\theta)} (2\pi)^{d/2} \det(-\nabla^2 \ell(\hat\theta))^{-1/2},

by the change of variables θ=μ+Q−1/2z\theta = \mu + Q^{-1/2} z. So the approximation is exact. Newton's method reaches θ^=μ\hat\theta = \mu in one full step from any start, because the quadratic model of ℓ\ell is ℓ\ell itself. ■\blacksquare

References

  1. Stephen M. Stigler, Laplace's 1774 memoir on inverse probability, Statistical Science 1(3), 1986, pages 359 to 378 (Stigler's introduction and the English translation of Laplace's Memoir on the probability of the causes of events, where the beta integral of the binomial posterior is approximated at its maximum; general locator)
  2. Luke Tierney and Joseph B. Kadane, Accurate approximations for posterior moments and marginal densities, Journal of the American Statistical Association 81(393), 1986, pages 82 to 86 (the fully exponential form, the ratio of two Laplace approximations with relative error O(n^-2), and the approximation of marginal posterior densities)
  3. Kass, Tierney and Kadane 1990, pages 473 to 488 (regularity conditions under which the Laplace approximation of a posterior integral has relative error O(1/n); general locator)
  4. Robert E. Kass and Adrian E. Raftery, Bayes factors, Journal of the American Statistical Association 90(430), 1995, pages 773 to 795 (the Laplace approximation of the marginal likelihood, its error, and the Schwarz criterion as a cruder version; general locator)
  5. N. G. de Bruijn, Asymptotic Methods in Analysis, 3rd edition, Dover, 1981, Chapter 4, The Laplace method for integrals (4.2 a general case, 4.4 asymptotic expansions, 4.5 the Gamma function, 4.6 multiple integrals)
  6. Andrew Gelman, John B. Carlin, Hal S. Stern, David B. Dunson, Aki Vehtari and Donald B. Rubin, Bayesian Data Analysis, 3rd edition, CRC Press, 2013, Chapter 4, Section 4.1 (normal approximation to the posterior) and Chapter 13 (modal and distributional approximations); general locator

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH2 full proof
  • correctness: no review record reviews/M8AVZX/proof-correctness.yaml
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • three classic examples