Algorithmresearch
Integrated nested Laplace approximation
Also called INLA.
Rue, Martino and Chopin's deterministic approximation of posterior marginals of latent Gaussian models by nested Laplace approximations and numerical integration.
- Time
- Θ(K G I C) worst
- Space
- Θ(K G + F) extra
- Where
- C = the cost of one sparse Cholesky factorization of Q + D; F = the number of non-zeros of the Cholesky factor; G = the number of points of each marginal; I = the number of Newton steps; K = the number of grid values of the hyperparameters
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Håvard Rue, Sara Martino, Nicolas Chopin, 2009
The integrated nested Laplace approximation (INLA) computes posterior marginals of a latent Gaussian model without sampling. In such a model, hyperparameters (few, say up to about ten) have a prior ; a latent field is Gaussian given , , with a sparse precision matrix ; and each observation depends on one coordinate through a likelihood . INLA nests two Laplace approximations. The outer one gives the hyperparameter posterior from the identity
with the denominator replaced by a Gaussian at the mode . The inner one gives the marginal of each for fixed . A weighted sum over a grid of values then integrates out. Every step is a sparse Cholesky factorization, so models with latent values run in seconds or minutes.
In plain words
Many statistical models have two layers: a large set of hidden values, such as a disease risk for each district, that vary smoothly and follow a bell-curve law, and a few settings that control how smooth they are. Sampling methods explore such models by a long random walk. INLA instead computes the answer directly. For each candidate setting it finds the most likely hidden values and replaces the true shape around them by a bell curve. How well the bell curve fits tells how plausible that setting is. It then repeats the trick one hidden value at a time to get each answer's full shape, and averages over the settings. Because each hidden value interacts with only a few neighbours, every step uses fast methods for sparse systems. The result is close to exact when the data are informative.
The problem
Input. A latent Gaussian model: a prior on a hyperparameter of low dimension, a sparse positive definite precision , observations with log-likelihood terms that are concave in , a grid with spacing , an index , and points at which to evaluate the marginal of .
Output. Weights , and the values of the posterior marginal density of .
Write , the log of the joint density up to terms in only.
The algorithm
INLA(y, Q(·), π(θ), θ₁..θ_K, i, z₁..z_G)- 1
for k ← 1 to K - 2
x* ← argmax_x F_θk(x); P ← Q(θ_k) + diag(c(x*)) ▷ Newton: solve (Q + diag c) x_new = b - 3
factor Q(θ_k) and P by sparse Cholesky - 4
ℓ_k ← log π(θ_k) + ½ log det Q(θ_k) + F_θk(x*) - ½ log det P - 5
for g ← 1 to G - 6
x' ← argmax F_θk with x_i fixed at z_g; f_k(z_g) ← exp(F_θk(x') - ½ log det P₋ᵢ(x')) - 7
normalize f_k so that it integrates to 1 over z - 8
w_k ← exp(ℓ_k) / Σ_m exp(ℓ_m) for each k - 9
π̃(z_g | y) ← Σ_k w_k f_k(z_g) for each g - 10
return w, π̃(z | y)
Here is the curvature of the -th log-likelihood term, and . L2 is Newton's method for the mode: its step is a linear system with the matrix , which has the sparsity of . At the mode, is the Gaussian approximation . L4 is the outer Laplace step: the identity above with in the denominator, evaluated at , where . L6 is the inner step, the full Laplace strategy: for each value it holds , maximizes over the other coordinates, and divides by the Gaussian approximation of their conditional law, whose precision is . L9 integrates out by the rectangle rule on the grid.
The cheap alternative to L5 to L7 is the Gaussian strategy: use the marginal of . It needs only the diagonal of , but it cannot show skewness.
The same weights give the marginal likelihood: , when the constants of the prior and the likelihood are kept.
Example
A tiny Poisson model. Two counts with , a latent pair with precision , , and Gamma(1, 1), so . The grid is (, ), and the marginal of is computed at . The reference values come from brute-force two-dimensional integration over with the trapezoid rule for each ; halving its spacing changes the reference mean of by less than .
| Gaussian sd of | exact | |||||
|---|---|---|---|---|---|---|
| 0.0498 | 1.0942 | 1.9261 | 0.5692 | 0.0261 | 0.0266 | |
| 0.1353 | 1.0859 | 1.8923 | 0.5564 | 0.1371 | 0.1391 | |
| 0.3679 | 1.0591 | 1.8023 | 0.5271 | 0.4204 | 0.4221 | |
| 0.6065 | 1.0271 | 1.7129 | 0.5031 | 0.4926 | 0.4912 | |
| 1.0000 | 0.9690 | 1.5733 | 0.4720 | 0.3758 | 0.3722 | |
| 2.7183 | 0.7219 | 1.0974 | 0.3887 | 0.0364 | 0.0357 |
For small the prior is weak and the modes sit near and ; as grows, both are pulled towards and towards each other. L4 is within percent of the exact density of near its mode. Over the whole grid, the total variation distance between the weights and the exact ones is , and the posterior mean of is against . The estimate of is against .
| marginal of | mean | sd | total variation from exact |
|---|---|---|---|
| exact (brute force) | 0.9132 | 0.5270 | 0 |
| Gaussian strategy | 1.0176 | 0.5139 | 0.056 |
| full Laplace (L6) | 0.9128 | 0.5266 | 0.0006 |
The posterior of is skewed to the left, because a Poisson likelihood on the log scale is. The Gaussian strategy puts its centre at the mode and misses the mean by standard deviations. The full Laplace step of L6 is a hundred times closer.
More data, smaller error. Multiplying the counts by and (with grids that follow the narrower posteriors):
| total variation of the weights | Gaussian strategy: error of the mean of , in sd | full Laplace: error of the mean of | |
|---|---|---|---|
| (3, 7) | 0.0041 | 0.20 | 0.0004 |
| (30, 70) | 0.00002 | 0.09 | below |
| (300, 700) | below | 0.03 | below |
Binary data. With and Bernoulli, the same model has much less information per latent value. The total variation of the weights grows to . The exact posterior of has mean and sd ; full Laplace gives and , and the Gaussian strategy and .
A Gaussian likelihood is exact. If , then is Gaussian, L2 converges in one step, and L4 and L6 are exact. The tests check this for four latent values: the differences of match the exact log marginal likelihood to .
Correctness
The full proof is in proofs/correctness.md. It proves:
- The basic identity. for every . L4 is this identity with the Gaussian approximation in place of , evaluated at its mode; the factors cancel.
- The inner step. With concave log-likelihood terms and positive definite, is strictly concave and has a unique maximizer. The linear system of L2 is exactly the Newton step, and its only fixed point is the mode.
- The marginal step. L6 is the same identity applied to the split for fixed .
- Exactness for a Gaussian likelihood. Then the Gaussian approximation is the exact conditional, so L4 is exact up to a constant, both the Gaussian and the full Laplace marginals are exact, and the only error left is the quadrature over in L9.
- The quadrature. L8 and L9 are the rectangle rule for , normalized by the same rule for .
What is proved and what is cited: claims 1 to 5 are exact. For a non-Gaussian likelihood, the size of the error of L4 and L6 is not proved here. Tierney and Kadane (1986) show that ratios of Laplace approximations have small relative errors when the dimension is fixed and the data grow. Rue, Martino and Chopin (2009) discuss the error when the dimension grows with the data, as it does in latent Gaussian models, and Fong, Rue and Wakefield (2010) report poor accuracy for binary data with few observations per latent value. All error sizes in the example are measured against brute-force integration only.
Proof: The identities behind INLA, and its exactness for a Gaussian likelihoodfull
Setting. A latent Gaussian model with hyperparameter :
is symmetric positive definite. Write , and assume each is twice differentiable and concave. All densities are with respect to Lebesgue measure on (and on ). Write
so that .
Claim 1: the basic identity
For every and every ,
Proof. By the definition of conditional densities, . Divide by , which is positive because .
So the right-hand side does not depend on . L4 replaces the unknown by the Gaussian approximation and evaluates at , where . The factors cancel, which gives
the formula of L4. It is the Laplace approximation of , times .
Claim 2: the inner step is Newton's method, and its fixed point is the mode
is strictly concave and has a unique maximizer . With , and , where , the Newton step for from is the solution of
and is a fixed point of this map if and only if .
Proof. The Hessian of is , which is negative definite because is positive definite and is non-negative. So is strictly concave and has at most one maximizer. It has one: concavity gives , so as , and a continuous function that tends to attains its maximum. The gradient is , and the Newton step is
If , then , so , so , and by strict concavity . Conversely, gives .
The direction is an ascent direction, since when . The implementation halves the step until does not decrease. That damped Newton methods converge for smooth strictly concave functions, and quadratically near , is a standard result of numerical optimization; it is used here, not proved, and the tests check that the gradient vanishes at the returned point.
Claim 3: the same identity gives the marginals of L5 and L6
For fixed , index and value , let be the other coordinates. For every ,
Proof. Claim 1 with the pair in place of .
L6 replaces by a Gaussian approximation with mode , the maximizer of with held (it exists and is unique by Claim 2 applied to the free coordinates, with the linear term added), and precision . At the approximation equals , which gives
with a constant independent of ; L7 removes it by normalizing over .
Claim 4: with a Gaussian likelihood every step is exact
Let . Then:
(a) with and , and L2 reaches in one Newton step from any start.
(b) of L4 equals up to a constant factor.
(c) The marginal of the Gaussian approximation and the full Laplace marginal of L6 both equal .
(d) The output of L9 is with : the only error left is that of the numerical integration over .
Proof. (a) is a quadratic with Hessian , so is proportional to the density. does not depend on , and Newton's method maximizes a concave quadratic in one step. (b) is the exact conditional, so by Claim 1 the ratio in L4 is , and does not depend on . (c) The marginal of is , which is exact by (a). For L6, the law of given under a Gaussian is Gaussian with precision and mean equal to its mode , so the approximation in Claim 3 is exact, and after normalization. (d) L8 normalizes the exact over the grid, and L9 mixes the exact conditionals.
The tests confirm (b) to in and (d) to in the density, for and grid values.
Claim 5: L9 is a quadrature rule for the marginal
, and with equally spaced and , L9 is this integral by the rectangle rule, divided by the same rule applied to .
Proof. , which is the ratio of the two rectangle sums with spacing .
The same sum gives the marginal likelihood: by Claim 1 with all constants kept, , which the code estimates by .
What is proved and what is cited
Claims 1 to 5 are exact identities. When the likelihood is not Gaussian, the error of INLA comes from the Gaussian approximations in L4 and L6. For a fixed number of latent variables and growing data, a Laplace approximation of a ratio of integrals, as in L4 after normalization, has a small relative error that shrinks with the amount of data (Tierney and Kadane 1986; Kass, Tierney and Kadane 1990). In latent Gaussian models the dimension usually grows with the data, and Rue, Martino and Chopin (2009) discuss when the approximations stay accurate. Fong, Rue and Wakefield (2010) report that the approximation can be poor for binary data with few observations per latent variable. These error results are cited, not proved. The errors in the examples of the page are measured against brute-force numerical integration only.
Complexity
For each of the grid values, L2 takes Newton steps, each one a sparse Cholesky factorization of cost and two triangular solves of cost , where is the number of non-zeros of the factor. The cost depends on the graph of , after a fill-reducing ordering such as nested dissection: for a time series (a band matrix), for a field on a two-dimensional grid, and in three dimensions. The full Laplace step L5 to L7 repeats the inner optimization for values of one coordinate, so one marginal costs and all marginals cost times as much. The Gaussian strategy needs the diagonal of , which recursions on the Cholesky factor give at a cost of the order of the factorization, so all its marginals cost . The implementation here uses dense matrices, so , which suits only small . A grid in hyperparameters has exponential in , which is why INLA is limited to a few hyperparameters. The memory holds one factor and the marginals, .
Properties
- Deterministic. The same input always gives the same output, with no Monte Carlo error and no convergence diagnostics.
- Not exact, except for a Gaussian likelihood, where only the quadrature over is approximate.
- Marginals, not the joint law. INLA returns the marginal densities of single coordinates and of the hyperparameters. Joint quantities need extra work, such as sampling from the Gaussian approximations.
- Byproducts. The weights of L4 give the marginal likelihood for Bayes factors, and the Gaussian approximations give predictive quantities for model checking.
- Requires a latent Gaussian structure: each observation depends on the latent field through few coordinates, and the hyperparameters are few.
Variants and improvements
- Simplified Laplace. Rue, Martino and Chopin expand the full Laplace density of L6 in to third order around the mode, which adds a skewness correction to the Gaussian strategy at a much smaller cost. It is the default in the R-INLA software.
- Cheaper full Laplace. Instead of a new Newton run in L6, use the conditional mean of under given , and update only the coordinates near in the graph.
- Exploration of the hyperparameter space. Find the mode of by optimization, use its curvature to rotate and scale the coordinates, and lay out the grid in the new coordinates, stopping in each direction when has fallen by a fixed amount. For many hyperparameters, a central composite design replaces the full grid; with only the mode, INLA becomes an empirical Bayes method.
- The stochastic partial differential equation approach. Lindgren, Rue and Lindström (2011) represent Matérn Gaussian processes by sparse Gaussian Markov random fields on a triangulation, which brings spatial kriging models into the scope of INLA.
- Other deterministic methods. Expectation propagation and variational inference also approximate the posterior of latent Gaussian models without sampling, by different criteria.
When to use it
Use INLA for latent Gaussian models with a few hyperparameters and a large latent field: generalized linear models with random effects, linear mixed models with non-Gaussian responses, disease mapping, spatial and spatio-temporal models, smoothing splines, and survival models. In these models it is often orders of magnitude faster than Gibbs sampling or Hamiltonian Monte Carlo at similar accuracy. Prefer a Monte Carlo method when there are many hyperparameters, when the latent field is not Gaussian, when the likelihood terms depend on many latent values at once, or when the data carry little information per latent value, as with binary data.
Pitfalls
- Gaussian marginals of skewed posteriors. Taking the Gaussian strategy in place of L6 puts the marginal at the mode; in the Poisson example its mean is off by standard deviations. Use the full or simplified Laplace step for marginals that matter.
- A grid that misses mass. If the grid of L1 is too narrow, the normalization of L8 renormalizes the part it covers and the marginals lose their tails. Check that the weights at both ends of the grid are negligible; here they are below .
- Little information per latent value. For binary data with one observation per random effect, the Gaussian approximation of L2 is poor, and L4 inherits its error; the weights in the example are three times further from the truth than with counts. Compare with a Monte Carlo method on such data (Fong, Rue and Wakefield 2010).
- Non-concave log-likelihood terms. With a Student t likelihood, for example, can be negative, in L2 need not be positive definite, and Newton's method can fail or find a local mode. Check the factorization, and use a robust optimizer for L2.
- Dense algebra. Factoring in L3 as a dense matrix costs and makes large models infeasible. Use a sparse Cholesky factorization with a fill-reducing ordering; see sparse linear systems.
- Dropping the log determinants. Omitting or in L4 makes the profile of the joint density at its mode. A weaker prior always lets the mode fit the data better, so the profile favours small , too little smoothing: in the Poisson example, dropping both terms moves the posterior mean of from to . Keep both terms.
Implementations
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/integrated-nested-laplace-approximation/. The authors are listed in prov/VKP2D8.jsonl.
"""Integrated nested Laplace approximation (Rue, Martino and Chopin 2009) for a latent
Gaussian model
theta ~ pi(theta), x | theta ~ N(0, Q(theta)^-1), y_j | x ~ p(y_j | x_j),
with one hyperparameter theta on a given grid. Dense matrices, so it suits small n; the
real method uses a sparse Cholesky factor of Q + D, which is the only change needed.
lik(j, v) returns (log p(y_j | x_j = v), first derivative, second derivative) in v.
The second derivative must be negative (log-concave likelihood terms).
"""
import math
from typing import Callable, Sequence
Matrix = list[list[float]]
def cholesky(a: Matrix) -> Matrix:
"""Lower triangular L with a = L L^T. Raises ValueError if a is not positive definite."""
n = len(a)
low = [[0.0] * n for _ in range(n)]
for i in range(n):
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:
raise ValueError("matrix is not positive definite")
low[i][i] = math.sqrt(s)
else:
low[i][j] = s / low[j][j]
return low
def chol_solve(low: Matrix, b: Sequence[float]) -> list[float]:
n = len(low)
z = [0.0] * n
for i in range(n):
z[i] = (b[i] - math.fsum(low[i][k] * z[k] for k in range(i))) / low[i][i]
x = [0.0] * n
for i in reversed(range(n)):
x[i] = (z[i] - math.fsum(low[k][i] * x[k] for k in range(i + 1, n))) / low[i][i]
return x
def log_det(low: Matrix) -> float:
return 2.0 * math.fsum(math.log(low[i][i]) for i in range(len(low)))
def quad_form(q: Matrix, x: Sequence[float]) -> float:
return math.fsum(x[i] * q[i][j] * x[j] for i in range(len(x)) for j in range(len(x)))
def log_joint(q: Matrix, lik: Callable, x: Sequence[float]) -> float:
"""-1/2 x^T Q x + sum_j log p(y_j | x_j): log pi(x, y | theta) up to terms in theta only."""
return -0.5 * quad_form(q, x) + math.fsum(lik(j, v)[0] for j, v in enumerate(x))
def inner_mode(q: Matrix, lik: Callable, x0: Sequence[float], fixed: dict | None = None,
tol: float = 1e-12, max_iter: int = 100) -> tuple[list[float], Matrix]:
"""Newton's method for the mode of log_joint over the free coordinates.
Coordinates in `fixed` (index -> value) are held. Each step solves (Q + D) x = b on
the free coordinates, with D = diag(-second derivatives) and b = D x + gradient terms,
and halves the step while the objective does not increase. Returns the mode and the
Cholesky factor of the precision Q + D of the free coordinates at the mode.
"""
fixed = fixed or {}
n = len(q)
free = [i for i in range(n) if i not in fixed]
x = [fixed.get(i, x0[i]) for i in range(n)]
f = log_joint(q, lik, x)
for _ in range(max_iter):
terms = [lik(j, x[j]) for j in range(n)]
p = [[q[a][b] for b in free] for a in free]
for r, a in enumerate(free):
p[r][r] -= terms[a][2]
rhs = [-terms[a][2] * x[a] + terms[a][1] - math.fsum(q[a][b] * fixed[b] for b in fixed) for a in free]
low = cholesky(p)
target = chol_solve(low, rhs)
step = 1.0
while True:
y = list(x)
for r, a in enumerate(free):
y[a] = x[a] + step * (target[r] - x[a])
fy = log_joint(q, lik, y)
if fy >= f - 1e-14 or step < 1e-10:
break
step /= 2
done = max((abs(y[a] - x[a]) for a in free), default=0.0) < tol
x, f = y, fy
if done:
break
terms = [lik(j, x[j]) for j in range(n)]
p = [[q[a][b] for b in free] for a in free]
for r, a in enumerate(free):
p[r][r] -= terms[a][2]
return x, cholesky(p)
def _trapezoid(z: Sequence[float], f: Sequence[float]) -> float:
return math.fsum((z[g + 1] - z[g]) * (f[g] + f[g + 1]) / 2 for g in range(len(z) - 1))
def inla(
q_of: Callable[[float], Matrix],
log_prior: Callable[[float], float],
lik: Callable,
thetas: Sequence[float],
index: int,
zs: Sequence[float],
strategy: str = "laplace",
) -> dict:
"""INLA on a grid of equally spaced hyperparameter values.
Returns a dict with
'weights' : normalized weights of the grid values thetas (they approximate pi(theta | y) * spacing),
'log_post' : unnormalized log pi~(theta_k | y),
'modes' : the inner modes x*(theta_k),
'density' : pi~(x_index = z | y) on the points zs,
'mean', 'sd': the mean and standard deviation of x_index under that density.
strategy 'gaussian' uses the marginal of the Gaussian approximation in L6;
'laplace' re-optimizes the other coordinates for every z (the full Laplace strategy).
"""
n = len(q_of(thetas[0]))
x0 = [0.0] * n
log_post, modes, dens = [], [], []
for th in thetas: # @line L1
q = q_of(th)
x_star, low_p = inner_mode(q, lik, x0) # @line L2
x0 = x_star # warm start for the next grid value
low_q = cholesky(q) # @line L3
lp = log_prior(th) + 0.5 * log_det(low_q) + log_joint(q, lik, x_star) - 0.5 * log_det(low_p) # @line L4
log_post.append(lp)
modes.append(x_star)
if strategy == "gaussian":
e = [0.0] * n
e[index] = 1.0
var = chol_solve(low_p, e)[index]
f = [math.exp(-0.5 * (z - x_star[index]) ** 2 / var) for z in zs]
else:
logs = []
start = x_star
for z in zs: # @line L5
y, low_c = inner_mode(q, lik, start, fixed={index: z})
start = y
logs.append(log_joint(q, lik, y) - 0.5 * log_det(low_c)) # @line L6
top = max(logs)
f = [math.exp(v - top) for v in logs]
tot = _trapezoid(zs, f)
dens.append([v / tot for v in f]) # @line L7
top = max(log_post)
w = [math.exp(v - top) for v in log_post]
tot = math.fsum(w)
w = [v / tot for v in w] # @line L8
mix = [math.fsum(w[k] * dens[k][g] for k in range(len(thetas))) for g in range(len(zs))] # @line L9
mean = _trapezoid(zs, [z * f for z, f in zip(zs, mix)])
var = _trapezoid(zs, [(z - mean) ** 2 * f for z, f in zip(zs, mix)])
return {"weights": w, "log_post": log_post, "modes": modes, "density": mix, # @line L10
"mean": mean, "sd": math.sqrt(var)}
# Likelihood terms: (log p, d/dx, d2/dx2) for one observation given its latent value v.
def poisson_log_link(ys: Sequence[int]) -> Callable:
def lik(j: int, v: float) -> tuple[float, float, float]:
mu = math.exp(v)
return ys[j] * v - mu - math.lgamma(ys[j] + 1), ys[j] - mu, -mu
return lik
def bernoulli_logit(ys: Sequence[int]) -> Callable:
def lik(j: int, v: float) -> tuple[float, float, float]:
p = 1 / (1 + math.exp(-v))
lp = -math.log1p(math.exp(-v)) if v > 0 else v - math.log1p(math.exp(v))
return ys[j] * v - (v - lp), ys[j] - p, -p * (1 - p)
return lik
def gaussian(ys: Sequence[float], s2: float) -> Callable:
def lik(j: int, v: float) -> tuple[float, float, float]:
return -0.5 * (ys[j] - v) ** 2 / s2 - 0.5 * math.log(2 * math.pi * s2), (ys[j] - v) / s2, -1 / s2
return lik
def rw_precision(n: int, tau: float, kappa: float = 1.0) -> Matrix:
"""tau times the tridiagonal matrix with kappa + 2 (kappa + 1 at the ends) and -1 off the diagonal."""
q = [[0.0] * n for _ in range(n)]
for i in range(n):
q[i][i] = tau * (kappa + (2.0 if 0 < i < n - 1 else 1.0))
if i + 1 < n:
q[i][i + 1] = q[i + 1][i] = -tau
return q
test_integrated_nested_laplace_approximation.py 146 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/integrated-nested-laplace-approximation/. The authors are listed in prov/VKP2D8.jsonl.
"""Tests for INLA: exactness for a Gaussian likelihood, the inner Newton mode, and a
comparison with brute-force numerical integration on a tiny Poisson model with one
hyperparameter on a grid."""
import math
import random
import unittest
from integrated_nested_laplace_approximation import (
chol_solve,
cholesky,
inla,
inner_mode,
log_det,
poisson_log_link,
gaussian,
rw_precision,
)
def log_prior(th):
# tau = exp(th) ~ Gamma(1, 1), so pi(th) = exp(th) exp(-exp(th)).
return th - math.exp(th)
def brute_force(q_of, lik, thetas, grid1, grid2):
"""pi(theta | y) on the grid, pi(x_1 | y) on grid1, and log p(y), by the trapezoid rule
over a box in (x_1, x_2) for each theta (two latent values only)."""
l1 = [lik(0, v)[0] for v in grid1]
l2 = [lik(1, v)[0] for v in grid2]
h1, h2 = grid1[1] - grid1[0], grid2[1] - grid2[0]
logs, margs = [], []
for th in thetas:
q = q_of(th)
base = log_prior(th) + 0.5 * log_det(cholesky(q)) - math.log(2 * math.pi)
cells = [[base + l1[a] + l2[b] - 0.5 * (q[0][0] * u * u + 2 * q[0][1] * u * v + q[1][1] * v * v)
for b, v in enumerate(grid2)] for a, u in enumerate(grid1)]
top = max(max(r) for r in cells)
rows = [math.fsum(math.exp(c - top) for c in r) * h2 for r in cells]
tot = math.fsum(rows) * h1
logs.append(math.log(tot) + top)
margs.append([r / tot for r in rows])
top = max(logs)
w = [math.exp(v - top) for v in logs]
s = math.fsum(w)
w = [v / s for v in w]
mix = [math.fsum(w[k] * margs[k][g] for k in range(len(thetas))) for g in range(len(grid1))]
mean = math.fsum(z * f for z, f in zip(grid1, mix)) * h1
sd = math.sqrt(math.fsum((z - mean) ** 2 * f for z, f in zip(grid1, mix)) * h1)
log_evidence = top + math.log(s * (thetas[1] - thetas[0]))
return w, mix, mean, sd, log_evidence
class TestGaussianLikelihoodIsExact(unittest.TestCase):
def test_hyperparameter_posterior_and_marginals_are_exact(self):
rng = random.Random(5)
n, s2 = 4, 0.5
ys = [rng.gauss(1.0, 1.0) for _ in range(n)]
lik = gaussian(ys, s2)
thetas = [-2 + 0.25 * k for k in range(17)]
zs = [-4 + 0.02 * a for a in range(451)]
def q_of(th):
return rw_precision(n, math.exp(th), 0.5)
def exact_log_marginal(th):
# y ~ N(0, Q^-1 + s2 I)
q = q_of(th)
low = cholesky(q)
cov = [chol_solve(low, [1.0 if i == j else 0.0 for i in range(n)]) for j in range(n)]
for i in range(n):
cov[i][i] += s2
lc = cholesky(cov)
return -0.5 * log_det(lc) - 0.5 * math.fsum(a * b for a, b in zip(ys, chol_solve(lc, ys))) - 0.5 * n * math.log(2 * math.pi)
exact = [log_prior(t) + exact_log_marginal(t) for t in thetas]
for strategy in ("gaussian", "laplace"):
r = inla(q_of, log_prior, lik, thetas, 1, zs, strategy=strategy)
for k in range(len(thetas)):
self.assertAlmostEqual(r["log_post"][k] - r["log_post"][0], exact[k] - exact[0], places=9)
# the marginal of x_1 is the exact mixture of normals
top = max(exact)
w = [math.exp(v - top) for v in exact]
w = [v / math.fsum(w) for v in w]
for g in range(0, len(zs), 25):
z = zs[g]
d = 0.0
for k, t in enumerate(thetas):
q = q_of(t)
p = [[q[i][j] + (1 / s2 if i == j else 0.0) for j in range(n)] for i in range(n)]
lp = cholesky(p)
m = chol_solve(lp, [v / s2 for v in ys])[1]
v = chol_solve(lp, [0.0, 1.0, 0.0, 0.0])[1]
d += w[k] * math.exp(-0.5 * (z - m) ** 2 / v) / math.sqrt(2 * math.pi * v)
self.assertAlmostEqual(r["density"][g], d, delta=1e-6)
class TestInnerMode(unittest.TestCase):
def test_gradient_vanishes_at_the_mode(self):
rng = random.Random(6)
for _ in range(100):
n = rng.randint(1, 6)
ys = [rng.randint(0, 12) for _ in range(n)]
lik = poisson_log_link(ys)
q = rw_precision(n, math.exp(rng.uniform(-3, 3)), rng.uniform(0.1, 2))
fixed = {rng.randrange(n): rng.uniform(-2, 3)} if n > 1 and rng.random() < 0.5 else None
x, _ = inner_mode(q, lik, [0.0] * n, fixed=fixed)
for i in range(n):
if fixed and i in fixed:
self.assertEqual(x[i], fixed[i])
continue
grad = lik(i, x[i])[1] - math.fsum(q[i][j] * x[j] for j in range(n))
self.assertLess(abs(grad), 1e-8)
class TestAgainstBruteForce(unittest.TestCase):
def test_tiny_poisson_model(self):
# y = (3, 7), y_j ~ Poisson(exp(x_j)), Q = tau [[2, -1], [-1, 2]], tau ~ Gamma(1, 1).
lik = poisson_log_link((3, 7))
def q_of(th):
return rw_precision(2, math.exp(th))
thetas = [-6 + 0.1 * k for k in range(101)]
grid = [-4 + 0.05 * a for a in range(181)]
wb, mb, mean_b, sd_b, log_ev = brute_force(q_of, lik, thetas, grid, grid)
lap = inla(q_of, log_prior, lik, thetas, 0, grid, strategy="laplace")
gau = inla(q_of, log_prior, lik, thetas, 0, grid, strategy="gaussian")
h = grid[1] - grid[0]
self.assertLess(0.5 * sum(abs(a - b) for a, b in zip(wb, lap["weights"])), 0.01)
# the log evidence from the weights of L4
top = max(lap["log_post"])
log_ev_inla = top + math.log(math.fsum(math.exp(v - top) for v in lap["log_post"]) * 0.1)
self.assertLess(abs(log_ev_inla - log_ev), 0.03)
# full Laplace marginal of x_1 is close; the Gaussian one misses the skewness
self.assertLess(abs(lap["mean"] - mean_b), 0.002)
self.assertLess(abs(lap["sd"] - sd_b), 0.002)
self.assertLess(0.5 * h * sum(abs(a - b) for a, b in zip(mb, lap["density"])), 0.002)
self.assertGreater(gau["mean"] - mean_b, 0.05)
self.assertGreater(0.5 * h * sum(abs(a - b) for a, b in zip(mb, gau["density"])), 0.03)
if __name__ == "__main__":
unittest.main()
History
Laplace approximations of posterior marginals as ratios of integrals go back to Tierney and Kadane (1986). Rue and Held developed fast computations for Gaussian Markov random fields with sparse Cholesky factors in the early 2000s. Rue, Martino and Chopin combined the two in the integrated nested Laplace approximation, read to the Royal Statistical Society in 2008 and published with discussion in 2009. Fong, Rue and Wakefield (2010) studied it for generalized linear mixed models, and Lindgren, Rue and Lindström (2011) extended its reach to continuous spatial fields. The R-INLA package made the method a standard tool in epidemiology, ecology and spatial statistics.
References
- Håvard Rue, Sara Martino and Nicolas Chopin, Approximate Bayesian inference for latent Gaussian models by using integrated nested Laplace approximations, Journal of the Royal Statistical Society Series B 71(2), 2009, pages 319 to 392, with the discussion: latent Gaussian models, the approximation of the hyperparameter posterior by the ratio in L4, its exploration from the mode, the Gaussian, Laplace and simplified Laplace approximations of the latent marginals, and the discussion of the approximation error (general locator)
- Youyi Fong, Håvard Rue and Jon Wakefield, Bayesian inference for generalized linear mixed models, Biostatistics 11(3), 2010, pages 397 to 412: INLA for generalized linear mixed models, and its loss of accuracy for binary data with few observations per random effect (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 approximation of a marginal posterior density by a ratio of Laplace approximations, which L4 and L6 apply
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 | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag VKP2D8 Edit this page History Report an error Markdown