Algorithm Search⌘K

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
Properties
deterministicnot exactofflineiterative
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 θ\theta (few, say up to about ten) have a prior π(θ)\pi(\theta); a latent field x∈Rnx \in \mathbb{R}^n is Gaussian given θ\theta, x∼N(0,Q(θ)−1)x \sim N(0, Q(\theta)^{-1}), with a sparse precision matrix QQ; and each observation yjy_j depends on one coordinate xjx_j through a likelihood p(yj∣xj)p(y_j \mid x_j). INLA nests two Laplace approximations. The outer one gives the hyperparameter posterior from the identity

π(θ∣y)∝π(x,θ,y)π(x∣θ,y)∣x=x∗(θ),\pi(\theta \mid y) \propto \frac{\pi(x, \theta, y)}{\pi(x \mid \theta, y)}\bigg|_{x = x^*(\theta)},

with the denominator replaced by a Gaussian at the mode x∗(θ)x^*(\theta). The inner one gives the marginal of each xix_i for fixed θ\theta. A weighted sum over a grid of θ\theta values then integrates θ\theta out. Every step is a sparse Cholesky factorization, so models with 10510^5 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 π(θ)\pi(\theta) on a hyperparameter of low dimension, a sparse positive definite precision Q(θ)Q(\theta), observations y1,…,yny_1, \ldots, y_n with log-likelihood terms gj(xj)=log⁡p(yj∣xj)g_j(x_j) = \log p(y_j \mid x_j) that are concave in xjx_j, a grid θ1,…,θK\theta_1, \ldots, \theta_K with spacing Δ\Delta, an index ii, and points z1,…,zGz_1, \ldots, z_G at which to evaluate the marginal of xix_i.

Output. Weights wk≈π(θk∣y)Δw_k \approx \pi(\theta_k \mid y)\Delta, and the values π~(xi=zg∣y)\tilde\pi(x_i = z_g \mid y) of the posterior marginal density of xix_i.

Write Fθ(x)=−12x⊤Q(θ)x+∑jgj(xj)F_\theta(x) = -\frac12 x^\top Q(\theta)x + \sum_j g_j(x_j), the log of the joint density up to terms in θ\theta only.

The algorithm

  1. INLA(y, Q(·), π(θ), θ₁..θ_K, i, z₁..z_G)
  2. 1for k ← 1 to K
  3. 2x* ← argmax_x F_θk(x); P ← Q(θ_k) + diag(c(x*)) ▷ Newton: solve (Q + diag c) x_new = b
  4. 3factor Q(θ_k) and P by sparse Cholesky
  5. 4ℓ_k ← log π(θ_k) + ½ log det Q(θ_k) + F_θk(x*) - ½ log det P
  6. 5for g ← 1 to G
  7. 6x' ← argmax F_θk with x_i fixed at z_g; f_k(z_g) ← exp(F_θk(x') - ½ log det P₋ᵢ(x'))
  8. 7normalize f_k so that it integrates to 1 over z
  9. 8w_k ← exp(ℓ_k) / Σ_m exp(ℓ_m) for each k
  10. 9π̃(z_g | y) ← Σ_k w_k f_k(z_g) for each g
  11. 10return w, π̃(z | y)

Here cj(v)=−gj′′(v)≥0c_j(v) = -g_j''(v) \ge 0 is the curvature of the jj-th log-likelihood term, and b=diag⁡(c(x)) x+g′(x)b = \operatorname{diag}(c(x))\,x + g'(x). L2 is Newton's method for the mode: its step is a linear system with the matrix Q+diag⁡(c)Q + \operatorname{diag}(c), which has the sparsity of QQ. At the mode, N(x∗,P−1)N(x^*, P^{-1}) is the Gaussian approximation πG(x∣θ,y)\pi_G(x \mid \theta, y). L4 is the outer Laplace step: the identity above with πG\pi_G in the denominator, evaluated at x∗x^*, where πG(x∗∣θ,y)=(2π)−n/2det⁡P1/2\pi_G(x^* \mid \theta, y) = (2\pi)^{-n/2}\det P^{1/2}. L6 is the inner step, the full Laplace strategy: for each value zz it holds xi=zx_i = z, maximizes over the other coordinates, and divides by the Gaussian approximation of their conditional law, whose precision is P−i=Q−i,−i+diag⁡(c−i)P_{-i} = Q_{-i,-i} + \operatorname{diag}(c_{-i}). L9 integrates θ\theta out by the rectangle rule on the grid.

The cheap alternative to L5 to L7 is the Gaussian strategy: use the marginal N(xi∗,(P−1)ii)N(x^*_i, (P^{-1})_{ii}) of πG\pi_G. It needs only the diagonal of P−1P^{-1}, but it cannot show skewness.

The same weights give the marginal likelihood: π(y)≈Δ∑keℓk\pi(y) \approx \Delta\sum_k e^{\ell_k}, when the constants of the prior and the likelihood are kept.

Example

A tiny Poisson model. Two counts y=(3,7)y = (3, 7) with yj∼Poisson(exj)y_j \sim \mathrm{Poisson}(e^{x_j}), a latent pair with precision Q=τ(2−1−12)Q = \tau\begin{pmatrix}2 & -1\\ -1 & 2\end{pmatrix}, θ=log⁡τ\theta = \log\tau, and τ∼\tau \sim Gamma(1, 1), so π(θ)=eθe−eθ\pi(\theta) = e^{\theta}e^{-e^{\theta}}. The grid is θ=−6,−5.9,…,4\theta = -6, -5.9, \ldots, 4 (K=101K = 101, Δ=0.1\Delta = 0.1), and the marginal of x1x_1 is computed at z=−4,−3.95,…,5z = -4, -3.95, \ldots, 5. The reference values come from brute-force two-dimensional integration over (x1,x2)(x_1, x_2) with the trapezoid rule for each θ\theta; halving its spacing changes the reference mean of x1x_1 by less than 10−610^{-6}.

θ\theta τ\tau x1∗x^*_1 x2∗x^*_2 Gaussian sd of x1x_1 π~(θ∣y)\tilde\pi(\theta \mid y) exact π(θ∣y)\pi(\theta \mid y)
−3.0-3.0 0.0498 1.0942 1.9261 0.5692 0.0261 0.0266
−2.0-2.0 0.1353 1.0859 1.8923 0.5564 0.1371 0.1391
−1.0-1.0 0.3679 1.0591 1.8023 0.5271 0.4204 0.4221
−0.5-0.5 0.6065 1.0271 1.7129 0.5031 0.4926 0.4912
0.00.0 1.0000 0.9690 1.5733 0.4720 0.3758 0.3722
1.01.0 2.7183 0.7219 1.0974 0.3887 0.0364 0.0357

For small τ\tau the prior is weak and the modes sit near log⁡3=1.10\log 3 = 1.10 and log⁡7=1.95\log 7 = 1.95; as τ\tau grows, both are pulled towards 00 and towards each other. L4 is within 22 percent of the exact density of θ\theta near its mode. Over the whole grid, the total variation distance between the weights and the exact ones is 0.00410.0041, and the posterior mean of θ\theta is −0.7561-0.7561 against −0.7645-0.7645. The estimate of log⁡π(y)\log\pi(y) is −6.9272-6.9272 against −6.9117-6.9117.

marginal of x1x_1 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 x1x_1 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 0.200.20 standard deviations. The full Laplace step of L6 is a hundred times closer.

More data, smaller error. Multiplying the counts by 1010 and 100100 (with grids that follow the narrower posteriors):

yy total variation of the θ\theta weights Gaussian strategy: error of the mean of x1x_1, in sd full Laplace: error of the mean of x1x_1
(3, 7) 0.0041 0.20 0.0004
(30, 70) 0.00002 0.09 below 10−410^{-4}
(300, 700) below 10−510^{-5} 0.03 below 10−410^{-4}

Binary data. With y=(1,0)y = (1, 0) and yj∼y_j \sim Bernoulli(1/(1+e−xj))(1/(1 + e^{-x_j})), the same model has much less information per latent value. The total variation of the θ\theta weights grows to 0.0120.012. The exact posterior of x1x_1 has mean 0.37880.3788 and sd 1.19611.1961; full Laplace gives 0.36600.3660 and 1.18321.1832, and the Gaussian strategy 0.32640.3264 and 1.10101.1010.

A Gaussian likelihood is exact. If yj∼N(xj,s2)y_j \sim N(x_j, s^2), then π(x∣θ,y)\pi(x \mid \theta, y) is Gaussian, L2 converges in one step, and L4 and L6 are exact. The tests check this for four latent values: the differences of ℓk\ell_k match the exact log marginal likelihood log⁡N(y;0,Q−1+s2I)\log N(y; 0, Q^{-1} + s^2 I) to 10−910^{-9}.

Correctness

The full proof is in proofs/correctness.md. It proves:

  1. The basic identity. π(θ∣y)=π(x,θ,y)/(π(x∣θ,y)π(y))\pi(\theta \mid y) = \pi(x, \theta, y)/(\pi(x \mid \theta, y)\pi(y)) for every xx. L4 is this identity with the Gaussian approximation in place of π(x∣θ,y)\pi(x \mid \theta, y), evaluated at its mode; the factors (2π)−n/2(2\pi)^{-n/2} cancel.
  2. The inner step. With concave log-likelihood terms and QQ positive definite, FθF_\theta 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.
  3. The marginal step. L6 is the same identity applied to the split x=(xi,x−i)x = (x_i, x_{-i}) for fixed θ\theta.
  4. 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 θ\theta in L9.
  5. The quadrature. L8 and L9 are the rectangle rule for ∫π(xi∣θ,y)π(θ∣y) dθ\int \pi(x_i \mid \theta, y)\pi(\theta \mid y)\, d\theta, normalized by the same rule for ∫π(θ∣y) dθ\int \pi(\theta \mid y)\, d\theta.

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 θ\theta:

θ∼π(θ),x∣θ∼N(0,Q(θ)−1),yj∣x,θ∼p(yj∣xj) independently,j=1,…,n.\theta \sim \pi(\theta), \qquad x \mid \theta \sim N(0, Q(\theta)^{-1}), \qquad y_j \mid x, \theta \sim p(y_j \mid x_j) \text{ independently}, \quad j = 1, \ldots, n.

Q(θ)Q(\theta) is symmetric positive definite. Write gj(v)=log⁡p(yj∣xj=v)g_j(v) = \log p(y_j \mid x_j = v), and assume each gjg_j is twice differentiable and concave. All densities are with respect to Lebesgue measure on x∈Rnx \in \mathbb{R}^n (and on θ\theta). Write

Fθ(x)=−12x⊤Q(θ)x+∑jgj(xj),F_\theta(x) = -\tfrac12 x^\top Q(\theta) x + \sum_j g_j(x_j),

so that π(x,θ,y)=π(θ) (2π)−n/2det⁡Q(θ)1/2 eFθ(x)\pi(x, \theta, y) = \pi(\theta)\,(2\pi)^{-n/2}\det Q(\theta)^{1/2}\, e^{F_\theta(x)}.

Claim 1: the basic identity

For every θ\theta and every xx,

π(θ∣y)=π(x,θ,y)π(x∣θ,y) π(y).\pi(\theta \mid y) = \frac{\pi(x, \theta, y)}{\pi(x \mid \theta, y)\, \pi(y)}.

Proof. By the definition of conditional densities, π(x,θ,y)=π(x∣θ,y) π(θ∣y) π(y)\pi(x, \theta, y) = \pi(x \mid \theta, y)\, \pi(\theta \mid y)\, \pi(y). Divide by π(x∣θ,y)π(y)\pi(x \mid \theta, y)\pi(y), which is positive because eFθ(x)>0e^{F_\theta(x)} > 0. □\square

So the right-hand side does not depend on xx. L4 replaces the unknown π(x∣θ,y)\pi(x \mid \theta, y) by the Gaussian approximation πG(x∣θ,y)=N(x∗,P−1)\pi_G(x \mid \theta, y) = N(x^*, P^{-1}) and evaluates at x=x∗x = x^*, where πG(x∗∣θ,y)=(2π)−n/2det⁡P1/2\pi_G(x^* \mid \theta, y) = (2\pi)^{-n/2}\det P^{1/2}. The factors (2π)−n/2(2\pi)^{-n/2} cancel, which gives

log⁡π~(θ∣y)=log⁡π(θ)+12log⁡det⁡Q(θ)+Fθ(x∗)−12log⁡det⁡P+const,\log\tilde\pi(\theta \mid y) = \log\pi(\theta) + \tfrac12\log\det Q(\theta) + F_\theta(x^*) - \tfrac12\log\det P + \text{const},

the formula of L4. It is the Laplace approximation of ∫eFθ(x) dx\int e^{F_\theta(x)}\, dx, times π(θ)det⁡Q(θ)1/2\pi(\theta)\det Q(\theta)^{1/2}.

Claim 2: the inner step is Newton's method, and its fixed point is the mode

FθF_\theta is strictly concave and has a unique maximizer x∗x^*. With cj(v)=−gj′′(v)≥0c_j(v) = -g_j''(v) \ge 0, D(x)=diag⁡(cj(xj))D(x) = \operatorname{diag}(c_j(x_j)) and b(x)=D(x)x+g′(x)b(x) = D(x)x + g'(x), where g′(x)=(gj′(xj))jg'(x) = (g_j'(x_j))_j, the Newton step for FθF_\theta from xx is the solution x+x_+ of

(Q+D(x)) x+=b(x),(Q + D(x))\, x_+ = b(x),

and xx is a fixed point of this map if and only if x=x∗x = x^*.

Proof. The Hessian of FθF_\theta is −(Q+D(x))-(Q + D(x)), which is negative definite because QQ is positive definite and D(x)D(x) is non-negative. So FθF_\theta is strictly concave and has at most one maximizer. It has one: concavity gives gj(v)≤gj(0)+gj′(0)vg_j(v) \le g_j(0) + g_j'(0)v, so Fθ(x)≤C+a⊤x−12λmin⁡∥x∥2→−∞F_\theta(x) \le C + a^\top x - \tfrac12\lambda_{\min}\|x\|^2 \to -\infty as ∥x∥→∞\|x\| \to \infty, and a continuous function that tends to −∞-\infty attains its maximum. The gradient is ∇Fθ(x)=−Qx+g′(x)\nabla F_\theta(x) = -Qx + g'(x), and the Newton step is

x+=x+(Q+D)−1(−Qx+g′)=(Q+D)−1((Q+D)x−Qx+g′)=(Q+D)−1(Dx+g′).x_+ = x + (Q + D)^{-1}(-Qx + g') = (Q + D)^{-1}\big((Q + D)x - Qx + g'\big) = (Q + D)^{-1}(Dx + g').

If x+=xx_+ = x, then (Q+D)x=Dx+g′(Q + D)x = Dx + g', so Qx=g′(x)Qx = g'(x), so ∇Fθ(x)=0\nabla F_\theta(x) = 0, and by strict concavity x=x∗x = x^*. Conversely, ∇Fθ(x∗)=0\nabla F_\theta(x^*) = 0 gives x+=x∗x_+ = x^*. □\square

The direction x+−x=(Q+D)−1∇Fθ(x)x_+ - x = (Q + D)^{-1}\nabla F_\theta(x) is an ascent direction, since ∇Fθ⊤(Q+D)−1∇Fθ>0\nabla F_\theta^\top (Q + D)^{-1}\nabla F_\theta > 0 when ∇Fθ≠0\nabla F_\theta \ne 0. The implementation halves the step until FθF_\theta does not decrease. That damped Newton methods converge for smooth strictly concave functions, and quadratically near x∗x^*, 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 θ\theta, index ii and value zz, let x−ix_{-i} be the other coordinates. For every x−ix_{-i},

π(xi=z∣θ,y)=π((z,x−i),θ,y)π(x−i∣xi=z,θ,y) π(θ,y).\pi(x_i = z \mid \theta, y) = \frac{\pi((z, x_{-i}), \theta, y)}{\pi(x_{-i} \mid x_i = z, \theta, y)\, \pi(\theta, y)}.

Proof. Claim 1 with the pair (x−i,xi)(x_{-i}, x_i) in place of (x,θ)(x, \theta). □\square

L6 replaces π(x−i∣xi=z,θ,y)\pi(x_{-i} \mid x_i = z, \theta, y) by a Gaussian approximation with mode x−i′x'_{-i}, the maximizer of FθF_\theta with xi=zx_i = z held (it exists and is unique by Claim 2 applied to the free coordinates, with the linear term −Q−i,iz-Q_{-i,i}z added), and precision P−i(x′)=Q−i,−i+D−i(x′)P_{-i}(x') = Q_{-i,-i} + D_{-i}(x'). At x−i=x−i′x_{-i} = x'_{-i} the approximation equals (2π)−(n−1)/2det⁡P−i1/2(2\pi)^{-(n-1)/2}\det P_{-i}^{1/2}, which gives

π~(xi=z∣θ,y)∝exp⁡(Fθ(x′)−12log⁡det⁡P−i(x′)),\tilde\pi(x_i = z \mid \theta, y) \propto \exp\big(F_\theta(x') - \tfrac12\log\det P_{-i}(x')\big),

with a constant independent of zz; L7 removes it by normalizing over zz.

Claim 4: with a Gaussian likelihood every step is exact

Let gj(v)=−(yj−v)22sj2+constg_j(v) = -\frac{(y_j - v)^2}{2s_j^2} + \text{const}. Then:

(a) π(x∣θ,y)=N(x∗,P−1)\pi(x \mid \theta, y) = N(x^*, P^{-1}) with P=Q(θ)+diag⁡(1/sj2)P = Q(\theta) + \operatorname{diag}(1/s_j^2) and x∗=P−1(yj/sj2)jx^* = P^{-1}(y_j/s_j^2)_j, and L2 reaches x∗x^* in one Newton step from any start.

(b) π~(θ∣y)\tilde\pi(\theta \mid y) of L4 equals π(θ∣y)\pi(\theta \mid y) up to a constant factor.

(c) The marginal of the Gaussian approximation and the full Laplace marginal of L6 both equal π(xi∣θ,y)\pi(x_i \mid \theta, y).

(d) The output of L9 is ∑kwkπ(xi∣θk,y)\sum_k w_k \pi(x_i \mid \theta_k, y) with wk∝π(θk∣y)w_k \propto \pi(\theta_k \mid y): the only error left is that of the numerical integration over θ\theta.

Proof. (a) Fθ(x)=−12x⊤Px+x⊤(yj/sj2)j+constF_\theta(x) = -\tfrac12 x^\top P x + x^\top (y_j/s_j^2)_j + \text{const} is a quadratic with Hessian −P-P, so eFθe^{F_\theta} is proportional to the N(x∗,P−1)N(x^*, P^{-1}) density. D=diag⁡(1/sj2)D = \operatorname{diag}(1/s_j^2) does not depend on xx, and Newton's method maximizes a concave quadratic in one step. (b) πG\pi_G is the exact conditional, so by Claim 1 the ratio in L4 is π(θ∣y)π(y)\pi(\theta \mid y)\pi(y), and π(y)\pi(y) does not depend on θ\theta. (c) The marginal of N(x∗,P−1)N(x^*, P^{-1}) is N(xi∗,(P−1)ii)N(x^*_i, (P^{-1})_{ii}), which is exact by (a). For L6, the law of x−ix_{-i} given xi=zx_i = z under a Gaussian is Gaussian with precision P−i,−iP_{-i,-i} and mean equal to its mode x−i′x'_{-i}, so the approximation in Claim 3 is exact, and π~(xi∣θ,y)=π(xi∣θ,y)\tilde\pi(x_i \mid \theta, y) = \pi(x_i \mid \theta, y) after normalization. (d) L8 normalizes the exact π(θk∣y)\pi(\theta_k \mid y) over the grid, and L9 mixes the exact conditionals. □\square

The tests confirm (b) to 10−910^{-9} in log⁡π~(θ∣y)\log\tilde\pi(\theta \mid y) and (d) to 10−610^{-6} in the density, for n=4n = 4 and 1717 grid values.

Claim 5: L9 is a quadrature rule for the marginal

π(xi∣y)=∫π(xi∣θ,y) π(θ∣y) dθ\pi(x_i \mid y) = \int \pi(x_i \mid \theta, y)\, \pi(\theta \mid y)\, d\theta, and with equally spaced θk\theta_k and wk=π~(θk∣y)/∑mπ~(θm∣y)w_k = \tilde\pi(\theta_k \mid y)/\sum_m \tilde\pi(\theta_m \mid y), L9 is this integral by the rectangle rule, divided by the same rule applied to ∫π(θ∣y) dθ=1\int \pi(\theta \mid y)\, d\theta = 1.

Proof. ∑kwkfk=Δ∑kπ~(θk∣y)fkΔ∑mπ~(θm∣y)\sum_k w_k f_k = \frac{\Delta\sum_k \tilde\pi(\theta_k \mid y) f_k}{\Delta\sum_m \tilde\pi(\theta_m \mid y)}, which is the ratio of the two rectangle sums with spacing Δ\Delta. □\square

The same sum gives the marginal likelihood: by Claim 1 with all constants kept, π(y)=∫π(x∗,θ,y)/π(x∗∣θ,y) dθ\pi(y) = \int \pi(x^*, \theta, y)/\pi(x^* \mid \theta, y)\, d\theta, which the code estimates by Δ∑keℓk\Delta\sum_k e^{\ell_k}.

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 KK grid values, L2 takes II Newton steps, each one a sparse Cholesky factorization of cost CC and two triangular solves of cost O(F)O(F), where FF is the number of non-zeros of the factor. The cost CC depends on the graph of QQ, after a fill-reducing ordering such as nested dissection: Θ(n)\Theta(n) for a time series (a band matrix), Θ(n3/2)\Theta(n^{3/2}) for a field on a two-dimensional grid, and Θ(n2)\Theta(n^2) in three dimensions. The full Laplace step L5 to L7 repeats the inner optimization for GG values of one coordinate, so one marginal costs Θ(KGIC)\Theta(KGIC) and all nn marginals cost nn times as much. The Gaussian strategy needs the diagonal of P−1P^{-1}, which recursions on the Cholesky factor give at a cost of the order of the factorization, so all its marginals cost Θ(KIC)\Theta(KIC). The implementation here uses dense matrices, so C=Θ(n3)C = \Theta(n^3), which suits only small nn. A grid in mm hyperparameters has KK exponential in mm, which is why INLA is limited to a few hyperparameters. The memory holds one factor and the marginals, Θ(KG+F)\Theta(KG + F).

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 θ\theta 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 zz 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 x−ix_{-i} under πG\pi_G given xi=zx_i = z, and update only the coordinates near ii in the graph.
  • Exploration of the hyperparameter space. Find the mode of π~(θ∣y)\tilde\pi(\theta \mid y) 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 log⁡π~\log\tilde\pi 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 0.200.20 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 10−510^{-5}.
  • 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, cjc_j can be negative, PP 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 Q+diag⁡(c)Q + \operatorname{diag}(c) in L3 as a dense matrix costs Θ(n3)\Theta(n^3) and makes large models infeasible. Use a sparse Cholesky factorization with a fill-reducing ordering; see sparse linear systems.
  • Dropping the log determinants. Omitting 12log⁡det⁡Q\frac12\log\det Q or 12log⁡det⁡P\frac12\log\det P in L4 makes π~(θ∣y)\tilde\pi(\theta \mid y) 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 τ\tau, too little smoothing: in the Poisson example, dropping both terms moves the posterior mean of θ\theta from −0.76-0.76 to −1.75-1.75. 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.

integrated_nested_laplace_approximation.pyI0RawGitHub
# 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

  1. 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)
  2. 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)
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
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
  • a scene preset for the example