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 for the log of likelihood times prior, for its maximum (the posterior mode) and for the curvature there. Then the posterior is approximately , and the marginal likelihood is approximately
for parameters. It is exact when is quadratic. For observations from a regular model the relative error is . 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 with a constant that grows with the dimension . In the examples below the error is about nats per parameter at and at .
- Unconstrained parameters. Map a probability to its logit, a variance to its logarithm, and include the Jacobian of the map in . 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 over an open . Assume (A1) has an interior maximum at with for every ; (A2) is four times continuously differentiable near and is positive definite; (A3) is twice continuously differentiable near and ; (A4) for some . Then
If moreover near , the version that expands at its own mode, as the template does, has the same relative error. Both are proved in full in proofs/correctness.md: the proof rescales , shows that the odd third-order terms integrate to zero over a symmetric ball, bounds the rest by with a Gaussian envelope, and bounds the part far from the mode by .
What is proved and what is cited. The theorem covers a log-likelihood with a fixed , which includes Bernoulli data with a fixed share of successes, the setting of the examples. For random data, changes with ; Kass, Tierney and Kadane (1990) give conditions, uniform in , under which the relative error is still . That result is cited, not proved here. The 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 θ₀.
LAPLACE(ℓ, ∇ℓ, ∇²ℓ, θ₀) ▷ ℓ(θ) = log f(x | θ) + log π(θ), up to a constant- 1
θ ← θ₀ - 2
repeat - 3
g ← ∇ℓ(θ); H ← -∇²ℓ(θ) - 4
L ← CHOLESKY(H) ▷ fails if H is not positive definite - 5
solve L Lᵀ s = g ▷ the Newton step - 6
t ← 1; while ℓ(θ + t s) < ℓ(θ) do t ← t/2 - 7
θ ← θ + t s - 8
until the step t s is below the tolerance - 9
H ← -∇²ℓ(θ); L ← CHOLESKY(H) - 10
log Ẑ ← ℓ(θ) + (d/2) log 2π - Σᵢ log Lᵢᵢ - 11
return θ̂ = θ, Σ = H⁻¹, log Ẑ
Lines L1 to L8 are Newton's method for the posterior mode, with step halving so that never falls. Line L4 uses the Cholesky decomposition: it costs 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 (a Levenberg-Marquardt step). Line L10 uses , which never forms the determinant itself, so it cannot overflow. The approximate posterior is , and comes from the same factor.
Trace. Bernoulli data with successes in trials, prior Beta(2, 2), logit scale . With and , the log posterior with the Jacobian is , with and .
| step | |||||
|---|---|---|---|---|---|
| 0 | 0 | 0.5 | 3.5 | ||
| 1 | 0.360907 | 3.229145 | |||
| 2 | 0.357151 | 3.214320 | |||
| 3 | 0.357143 | 3.214286 |
The mode is , , and L10 gives . The exact value is , so the error is nats, a relative error of in . The approximate posterior of is .
Classic examples
Stirling's formula. . Here has its maximum at with , and the theorem gives , which is Stirling's approximation. The error in the logarithm is :
| 1 | 2 | 5 | 10 | 100 | 1000 | |
|---|---|---|---|---|---|---|
| 0.081061 | 0.041341 | 0.016645 | 0.0083306 | 0.00083333 | 0.0000833333 | |
| error | 0.0811 | 0.0827 | 0.0832 | 0.0833 | 0.0833 | 0.0833 |
Beta-binomial evidence, and the parameterization. Take successes in Bernoulli trials and the prior Beta(2, 2). The exact log evidence is . The table gives exact minus Laplace, in the probability scale and in the logit scale (Jacobian included):
| exact | error, scale | error | error, logit scale | error | |
|---|---|---|---|---|---|
| 10 | |||||
| 100 | |||||
| 1000 | |||||
| 10000 |
Both errors fall like , 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 , and the Laplace value is exactly Stirling's formula applied to . So the error is , where is the error of Stirling's formula for . The marginal likelihood page has the same check with the flat prior in the scale.
The normal-normal model. and . Then is quadratic in , Newton stops after one step, and the approximation is exact: equals the density of under . 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 that grow with : and . This gives , which is minus one half of the BIC. The dropped terms are why BIC is a cruder approximation than Laplace: in the beta-binomial example above the BIC error is nats at and at , and it tends to instead of .
Posterior moments by Tierney and Kadane. For a positive function , write 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 . For under the Beta posterior, logit scale, :
| exact mean | Tierney-Kadane | relative error | relative error | plug-in mode, relative error | |
|---|---|---|---|---|---|
| 10 | 0.357143 | 0.357991 | 0.237 | ||
| 100 | 0.307692 | 0.307714 | 0.713 | ||
| 1000 | 0.300797 | 0.300797 | 0.828 |
The last column is the error of the posterior mode used as an estimate of the mean: it is . The ratio form is , 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 .
Variations
- Tierney-Kadane marginal densities. For , the marginal posterior of is approximated by , a Laplace approximation of the inner integral at each . 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 at the maximum likelihood estimate and treating the prior as is the form of the theorem. It has the same order.
- Higher-order terms. The next term of the expansion involves the third and fourth derivatives of and , at the mode (de Bruijn, Section 4.4). It reduces the error to but needs derivatives that are rarely available.
- Laplace as a proposal. Use , or a heavier-tailed Student 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 , or a probability with all successes, has 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 , the density in is . Without the factor , is the integral of a different function.
- Several modes. Newton finds one mode. 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 . For independent copies of the trace example, the log error is exactly times , so is off by a factor , which is for . Hierarchical models with one parameter per group have close to , and the 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 by its absolute value; fix the model or the optimizer.
- Overflow in the determinant. grows like . Compute 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.
# 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
- Show that the Laplace approximation of in the logit scale equals the product of Stirling's approximations of , and deduce that its log error lies between and .
- In the probability scale, the same integral with is expanded at . Compute the limit of times the log error for , , and compare it with the value in the table.
- Prove that Newton's method from any start reaches the mode of a quadratic in one step, and that the Laplace approximation of a Gaussian integral is exact.
- For from Poisson() with prior Gamma(, ), write the Laplace approximation of in the scale and compare it with the exact negative binomial evidence for and .
- Two independent coordinates each have log error . Show that the log error of the joint approximation is , and explain what this says about the error for 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 with a fixed . Theorem 2 shows that the version of the page, which expands at its own mode, has the same relative error. Fact 3 is exactness for a Gaussian. Throughout, is the Euclidean norm, and for a -linear form we write , so .
Theorem 1
Hypotheses. Let be open and measurable.
- (A1) has a maximum at an interior point , and the maximum is well separated: for every , .
- (A2) is four times continuously differentiable on a closed ball , and is positive definite. Let be its smallest eigenvalue.
- (A3) is twice continuously differentiable on and .
- (A4) for some .
Claim. As ,
Proof. Translate so that and subtract a constant so that . Then on by (A1), and the claim is unchanged because both sides scale by the same factor .
Constants. Fix with and , where (if any works). Let , , and . All are finite because the derivatives are continuous on a compact ball.
Step 1: the part outside the ball is exponentially small. Let . For we have , so for
Hence by (A4). The same bound with shows that exists for .
Step 2: rescale the ball. Put . Then
Since and , Taylor's theorem with the Lagrange remainder gives, for :
- at order three, ;
- at order four, with and .
From item 1 and , . Together with :
For : with .
Step 3: expand the integrand. Write with , and for some between and , so . Then, dropping the argument ,
The four terms of are bounded, with item 1 for , by
So for a fixed polynomial that does not depend on .
Step 4: integrate. The odd terms integrate to over the ball , because the ball and are symmetric under . By (1),
The constant term gives the Gaussian integral minus its tail:
and the tail is at most .
Step 5: collect. Steps 1 to 4 give
The exponential terms are . Divide by , which is not zero by (A3).
Theorem 2: the expansion at the mode of the log posterior
The page does not split the integrand into and . It takes with , finds its mode , and uses
Claim. Under (A1) to (A4) and on , for all large the function has exactly one critical point in the ball (for a constant ), it is a local maximum, and .
Proof. Keep , and the constants above. Let and , finite by (A3) and .
Existence and location. For , Taylor at order three gives . Take and . On the sphere ,
(if , use any ; the same steps give a strict inequality). So the maximum of the continuous on the closed ball lies inside, and it is a critical point with . On this ball , and for , so is positive definite for . A strictly concave function has at most one critical point on a convex set, so is unique there.
The value. Since , Taylor at order two around gives with and at an intermediate point, . Hence , and .
The determinant. . The determinant is a polynomial in the entries, so .
Multiply: , which is by Theorem 1.
Application to a posterior. If the log-likelihood is for a fixed and the prior density is , then and , so . This covers successes in Bernoulli trials with fixed: , maximized at with . In the logit scale the same holds with . For data drawn at random, depends on through the data; then the same steps go through on the event that the derivative bounds and the separation hold uniformly in . Kass, Tierney and Kadane (1990) give such conditions and prove under them. We cite that result and do not prove it here.
Fact 3: exactness for a Gaussian
If with positive definite, then , everywhere, and
by the change of variables . So the approximation is exact. Newton's method reaches in one full step from any start, because the quadratic model of is itself.
References
- 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)
- 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)
- 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)
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag M8AVZX Edit this page History Report an error Markdown