Algorithm Search⌘K

Algorithmadvanced

Nested sampling

Also called Skilling's nested sampling.

Skilling's estimator of the marginal likelihood that replaces the worst of a set of live points by a new prior draw of higher likelihood and integrates over the shrinking prior mass.

Time
Θ(N (H + K) C) expected
Space
Θ(N (H + K)) extra
Where
C = the cost of one constrained prior draw; H = the information, KL(posterior || prior), in nats; K = log(1/eps) for the stopping tolerance eps; N = the number of live points
Properties
randomizednot exactofflineiterative
Origin
John Skilling, 2006

Nested sampling estimates the marginal likelihood Z=∫L(θ)π(θ) dθZ = \int L(\theta)\pi(\theta)\, d\theta, where L(θ)=f(x∣θ)L(\theta) = f(x \mid \theta) is the likelihood and π\pi the prior. It rewrites ZZ as a one-dimensional integral Z=∫01L(X) dXZ = \int_0^1 L(X)\, dX over the prior mass XX that lies above a given likelihood level. It keeps NN live points drawn from the prior. At each step it removes the live point with the lowest likelihood, which shrinks the prior mass above it by a random factor with known law, Beta(N,1)\mathrm{Beta}(N, 1), and replaces the point by a prior draw constrained to higher likelihood. The removed points, with weights, give ZZ and a weighted posterior sample. The error of log⁡Z\log Z is about H/N\sqrt{H/N}, where HH is the information gained from prior to posterior.

In plain words

Picture the likelihood as a landscape of hills and the prior as a layer of sand over it. To find the total "weight" of the landscape, you can slice it into horizontal layers and add up height times the area of sand above each height. Nested sampling makes these slices from the bottom up. It keeps a fixed number of sample points spread over the sand. At each step it throws away the lowest point, and that point's height becomes the next slice. On average, each step removes the same small fraction of the remaining sand, so the area above each slice is known without measuring it. A new point is then placed at random anywhere higher than the one thrown away. The run stops when the points left can add almost nothing. The cost is to find random points above a given height.

The problem

Input. A proper prior π\pi from which we can draw, a likelihood L(θ)≥0L(\theta) \ge 0 that we can evaluate, a number NN of live points, and a stopping tolerance ε\varepsilon. A routine that draws from π\pi restricted to {θ:L(θ)>L∗}\{\theta : L(\theta) > L^*\} for any level L∗L^*.

Output. An estimate of log⁡Z\log Z, an estimate of its error, and weighted posterior draws.

The prior mass. For a level λ\lambda, let X(λ)=π(L>λ)X(\lambda) = \pi(L > \lambda) be the prior mass above it. XX decreases from 11 to 00 as λ\lambda grows. Its inverse L(X)L(X) is a non-increasing function on (0,1)(0, 1), and the layer-cake identity

Z=∫0∞X(λ) dλ=∫01L(X) dXZ = \int_0^\infty X(\lambda)\, d\lambda = \int_0^1 L(X)\, dX

turns an integral over Θ\Theta, of any dimension, into an integral of a monotone function of one variable. The difficulty is that XX cannot be computed. Nested sampling estimates it from the order of the likelihood values.

The algorithm

  1. NESTED-SAMPLING(π, L, N, ε)
  2. 1draw θ₁..θ_N from π ▷ the live points
  3. 2Z ← 0; X₀ ← 1; i ← 0
  4. 3repeat
  5. 4i ← i + 1; k ← argmin_j L(θ_j); Lᵢ* ← L(θ_k) ▷ the dead point
  6. 5Xᵢ ← exp(-i/N) ▷ estimated prior mass above Lᵢ*
  7. 6wᵢ ← X_{i-1} - Xᵢ; Z ← Z + Lᵢ* wᵢ
  8. 7θ_k ← a draw from π restricted to {θ : L(θ) > Lᵢ*}
  9. 8until max_j L(θ_j) · Xᵢ < ε Z
  10. 9Z ← Z + (Xᵢ/N) Σ_j L(θ_j) ▷ the live points share the rest
  11. 10return Z, the dead points with weights Lᵢ* wᵢ / Z, and the live points with weights L(θ_j) Xᵢ / (N Z)

L1 starts with NN independent prior draws. At every step, the live points are independent draws from the prior above the current level, so their prior masses are independent uniform values below the current mass Xi−1X_{i-1}. L4 picks the lowest likelihood, which is the point with the largest prior mass. Its mass is the largest of NN uniform values on (0,Xi−1)(0, X_{i-1}), so the ratio ti=Xi/Xi−1t_i = X_i/X_{i-1} has the law Beta(N,1)\mathrm{Beta}(N, 1), whatever the model is. Since Elog⁡ti=−1/N\mathbb{E}\log t_i = -1/N, L5 sets log⁡Xi\log X_i to its mean −i/N-i/N. L6 adds the slab between XiX_i and Xi−1X_{i-1} at height Li∗L_i^*. L7 is the only model-specific step: it must give an independent draw from the prior above the new level. L8 stops when even the best live point, times the remaining mass, would change ZZ by less than a fraction ε\varepsilon. L9 adds the remaining mass, shared equally among the live points.

The implementation works with log⁡L\log L, log⁡X\log X and log⁡Z\log Z, and adds terms with log-sum-exp, because LL is often e−1000e^{-1000}. It keeps the live points in a heap keyed by LL. It also computes the information

H=∫p(θ∣x)log⁡p(θ∣x)π(θ) dθ≈∑iLi∗wiZlog⁡Li∗−log⁡Z,H = \int p(\theta \mid x)\log\frac{p(\theta \mid x)}{\pi(\theta)}\, d\theta \approx \sum_i \frac{L_i^* w_i}{Z}\log L_i^* - \log Z,

the Kullback-Leibler divergence from the prior to the posterior, and reports H/N\sqrt{H/N} as the error of log⁡Z\log Z.

Constrained draws. In the tests, {L>L∗}\{L > L^*\} is an interval, so L7 draws from the prior restricted to it exactly by the inverse distribution function. In real problems, L7 is approximate: a short Markov chain started from a random live point (slice sampling or random walk Metropolis-Hastings that rejects moves below L∗L^*), or a draw from ellipsoids that bound the live points.

Example

Trace. 33 successes in 1010 Bernoulli trials, L(p)=(103)p3(1−p)7L(p) = \binom{10}{3}p^3(1-p)^7, uniform prior on pp. The exact value is Z=1/11Z = 1/11, log⁡Z=−2.397895\log Z = -2.397895; the posterior is Beta(4, 8) and H=0.6366H = 0.6366. Run with N=4N = 4, ε=10−3\varepsilon = 10^{-3} and random.Random(4). The column "true XiX_i" is the length of the interval {L>Li∗}\{L > L_i^*\}, which the method does not know.

ii dead point pp Li∗L_i^* X^i=e−i/4\hat X_i = e^{-i/4} true XiX_i wiw_i ZZ so far
1 0.1032 0.06149 0.7788 0.4652 0.2212 0.01360
2 0.1341 0.10563 0.6065 0.3785 0.1723 0.03180
3 0.1550 0.13742 0.4724 0.3240 0.1342 0.05023
4 0.4524 0.16404 0.3679 0.2797 0.1045 0.06737
5 0.3966 0.21800 0.2865 0.1826 0.0814 0.08511
6 0.3961 0.21849 0.2231 0.1816 0.0634 0.09896
7 0.2360 0.23969 0.1738 0.1336 0.0494 0.11079
8 0.3537 0.25009 0.1353 0.1040 0.0384 0.12040

The dead points move in from both sides towards the mode 0.30.3, and their likelihoods increase. In this run the first dead point was low by chance: the true mass 0.46520.4652 is far below the estimate 0.77880.7788, because the largest of 44 uniform values happened to be small. That error stays in every later X^i\hat X_i. The test of L8 stops after 3232 dead points, and L9 adds the 44 live points. The result is log⁡Z^=−1.8590\log\hat Z = -1.8590, an error of 0.540.54, with the reported error bar 0.170.17. With N=4N = 4 the error bar is unreliable too, since it uses the estimated H=0.11H = 0.11 in place of 0.640.64.

The error is about H/N\sqrt{H/N}. Same model, ε=10−6\varepsilon = 10^{-6}: over 400400 runs with N=4N = 4 the standard deviation of log⁡Z^\log\hat Z is 0.4220.422, against H/N=0.399\sqrt{H/N} = 0.399. Over 100100 runs with N=50N = 50 it is 0.1140.114, against 0.1130.113.

Normal-normal. x1,…,x20∼N(θ,1)x_1, \ldots, x_{20} \sim N(\theta, 1), prior θ∼N(0,102)\theta \sim N(0, 10^2), data from random.Random(1), exact log⁡Z=−31.327583\log Z = -31.327583 and H=3.3061H = 3.3061 from the closed form in the proof. With ε=10−6\varepsilon = 10^{-6} and exact constrained draws:

NN runs mean error standard deviation H/N\sqrt{H/N} iterations
25 200 0.054 0.391 0.364 451
100 200 −0.007-0.007 0.184 0.182 1802
400 50 −0.023-0.023 0.094 0.091 7200

The standard deviation halves when NN is multiplied by 44, and stays within 88 percent of H/N\sqrt{H/N}. The number of iterations is about N(H+log⁡(1/ε))=N⋅17.1N(H + \log(1/\varepsilon)) = N \cdot 17.1, a little more because the test of L8 uses the estimated ZZ.

Correctness

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

  1. The layer-cake identity Z=∫01L(X) dXZ = \int_0^1 L(X)\, dX with L(X)L(X) non-increasing, for every prior and likelihood.
  2. Uniform prior masses. If the law of L(θ)L(\theta) under the prior has no atoms, the prior mass X(L(θ))X(L(\theta)) of a prior draw is uniform on (0,1)(0, 1), and that of a draw constrained to L>λL > \lambda is uniform on (0,X(λ))(0, X(\lambda)).
  3. The shrinkage law. With exact, independent constrained draws, the ratios ti=Xi/Xi−1t_i = X_i/X_{i-1} of the true masses are independent Beta(N,1)\mathrm{Beta}(N, 1). So −log⁡ti-\log t_i is exponential with rate NN, Elog⁡Xi=−i/N\mathbb{E}\log X_i = -i/N and Varlog⁡Xi=i/N2\mathrm{Var}\log X_i = i/N^2. The key invariant is: after each step, the live points are independent prior draws above the current level.
  4. The estimate. With the true masses, the sum of L6 is an upper Riemann sum of ∫Xm1L(X) dX\int_{X_m}^1 L(X)\, dX for a monotone function, and the live-point term estimates the rest. L5 uses the geometric mean of XiX_i.
  5. The information of the normal-normal model in closed form.

What is proved and what is only measured: items 1 to 3 and 5 are exact. The error size H/N\sqrt{H/N} is a heuristic of Skilling (2006): the posterior mass sits near log⁡X=−H\log X = -H, reached after about NHNH steps, where log⁡X\log X has standard deviation NH/N\sqrt{NH}/N. Chopin and Robert (2010) prove consistency and an error of order N−1/2N^{-1/2} with exact constrained draws; this page cites that result and does not prove it. The agreement of the measured standard deviations with H/N\sqrt{H/N} in the tables is measured only. With approximate constrained draws, none of the guarantees hold.

Proof: The layer-cake identity and the shrinkage law of nested samplingfull

Setting. π\pi is a prior probability measure on a parameter space Θ\Theta, and L(θ)=f(x∣θ)≥0L(\theta) = f(x \mid \theta) \ge 0 is the likelihood, with Z=∫L dπ<∞Z = \int L\, d\pi < \infty. For λ≥0\lambda \ge 0 let

X(λ)=π({θ:L(θ)>λ}),X(\lambda) = \pi(\{\theta : L(\theta) > \lambda\}),

the prior mass above the level λ\lambda. XX is non-increasing, X(λ)≤1X(\lambda) \le 1, and XX is right-continuous, because {L>λk}↑{L>λ}\{L > \lambda_k\} \uparrow \{L > \lambda\} when λk↓λ\lambda_k \downarrow \lambda. For x∈(0,1)x \in (0, 1) define the generalized inverse

L(x)=sup⁡{λ≥0:X(λ)>x},sup⁡∅=0.L(x) = \sup\{\lambda \ge 0 : X(\lambda) > x\}, \qquad \sup\emptyset = 0.

Claim 1: the layer-cake identity

Z=∫0∞X(λ) dλ=∫01L(x) dxZ = \int_0^\infty X(\lambda)\, d\lambda = \int_0^1 L(x)\, dx, and x↦L(x)x \mapsto L(x) is non-increasing.

Proof. First, L(θ)=∫0∞1{λ<L(θ)} dλL(\theta) = \int_0^\infty \mathbf{1}\{\lambda < L(\theta)\}\, d\lambda, so Tonelli's theorem gives Z=∫ ⁣∫0∞1{L(θ)>λ} dλ π(dθ)=∫0∞X(λ) dλZ = \int\!\int_0^\infty \mathbf{1}\{L(\theta) > \lambda\}\, d\lambda\, \pi(d\theta) = \int_0^\infty X(\lambda)\, d\lambda.

Second, for λ≥0\lambda \ge 0 and x∈(0,1)x \in (0, 1),

X(λ)>x  ⟺  λ<L(x).(1)X(\lambda) > x \iff \lambda < L(x). \tag{1}

If λ<L(x)\lambda < L(x), there is λ′>λ\lambda' > \lambda with X(λ′)>xX(\lambda') > x, and X(λ)≥X(λ′)>xX(\lambda) \ge X(\lambda') > x because XX is non-increasing. If X(λ)>xX(\lambda) > x, right-continuity gives δ>0\delta > 0 with X(λ+δ)>xX(\lambda + \delta) > x, so L(x)≥λ+δ>λL(x) \ge \lambda + \delta > \lambda. By (1) and Tonelli's theorem on (0,1)×[0,∞)(0, 1) \times [0, \infty),

∫01L(x) dx=∫01 ⁣ ⁣∫0∞1{λ<L(x)} dλ dx=∫0∞ ⁣ ⁣∫011{x<X(λ)} dx dλ=∫0∞X(λ) dλ,\int_0^1 L(x)\, dx = \int_0^1\!\!\int_0^\infty \mathbf{1}\{\lambda < L(x)\}\, d\lambda\, dx = \int_0^\infty\!\!\int_0^1 \mathbf{1}\{x < X(\lambda)\}\, dx\, d\lambda = \int_0^\infty X(\lambda)\, d\lambda,

where the last step uses 0≤X(λ)≤10 \le X(\lambda) \le 1. Finally, if x<x′x < x' then every λ\lambda with X(λ)>x′X(\lambda) > x' also has X(λ)>xX(\lambda) > x, so L(x)≥L(x′)L(x) \ge L(x'). ■\blacksquare

The identity holds for every prior and likelihood, with or without atoms, in any dimension: the integral over Θ\Theta becomes an integral of a monotone function on (0,1)(0, 1).

Claim 2: the prior mass of a prior draw is uniform

Assume that the law of L(θ)L(\theta) under θ∼π\theta \sim \pi has no atoms. Let θ∼π\theta \sim \pi and U=X(L(θ))U = X(L(\theta)). Then U∼U(0,1)U \sim \mathrm{U}(0, 1). Moreover, for every λ\lambda with X(λ)>0X(\lambda) > 0, if θ\theta is drawn from π\pi restricted to {L>λ}\{L > \lambda\}, then U∼U(0,X(λ))U \sim \mathrm{U}(0, X(\lambda)).

Proof. Let FF be the distribution function of Y=L(θ)Y = L(\theta); it is continuous, and X(λ)=1−F(λ)X(\lambda) = 1 - F(\lambda). For u∈(0,1)u \in (0, 1) the set {y:F(y)=u}\{y : F(y) = u\} is non-empty (intermediate value theorem, as FF goes from 00 to 11), closed and bounded above; let qq be its largest element. If Y≤qY \le q then F(Y)≤uF(Y) \le u. If Y>qY > q then F(Y)≥uF(Y) \ge u and F(Y)≠uF(Y) \ne u, so F(Y)>uF(Y) > u. Hence P(F(Y)≤u)=P(Y≤q)=F(q)=uP(F(Y) \le u) = P(Y \le q) = F(q) = u, so F(Y)F(Y) and U=1−F(Y)U = 1 - F(Y) are uniform on (0,1)(0, 1).

For the second part, {L(θ)>λ}\{L(\theta) > \lambda\} and {U<X(λ)}\{U < X(\lambda)\} differ by a null set. If L(θ)≤λL(\theta) \le \lambda then U=1−F(L(θ))≥1−F(λ)=X(λ)U = 1 - F(L(\theta)) \ge 1 - F(\lambda) = X(\lambda). If L(θ)>λL(\theta) > \lambda then U≤X(λ)U \le X(\lambda), with equality only when F(Y)=F(λ)F(Y) = F(\lambda). Let q′q' be the largest yy with F(y)=F(λ)F(y) = F(\lambda); then {Y>λ, F(Y)=F(λ)}⊆{λ<Y≤q′}\{Y > \lambda,\ F(Y) = F(\lambda)\} \subseteq \{\lambda < Y \le q'\}, which has probability F(q′)−F(λ)=0F(q') - F(\lambda) = 0. So, conditional on L(θ)>λL(\theta) > \lambda, UU is a uniform variable conditioned to lie below X(λ)X(\lambda), which is U(0,X(λ))\mathrm{U}(0, X(\lambda)). ■\blacksquare

Claim 3: the shrinkage law

Under the assumption of Claim 2, and with exact and independent constrained draws on line L7, let Xi=X(Li∗)X_i = X(L_i^*) be the true prior mass above the ii-th dead point. Then ti=Xi/Xi−1t_i = X_i/X_{i-1} (X0=1X_0 = 1) are independent with ti∼Beta(N,1)t_i \sim \mathrm{Beta}(N, 1), that is P(ti≤s)=sNP(t_i \le s) = s^N on [0,1][0, 1]. Consequently

Elog⁡ti=−1N,Varlog⁡ti=1N2,Elog⁡Xi=−iN,Varlog⁡Xi=iN2.\mathbb{E}\log t_i = -\frac{1}{N}, \qquad \mathrm{Var}\log t_i = \frac{1}{N^2}, \qquad \mathbb{E}\log X_i = -\frac{i}{N}, \qquad \mathrm{Var}\log X_i = \frac{i}{N^2}.

Proof. Map each live point to its prior mass U=X(L(θ))U = X(L(\theta)). Because XX is non-increasing and, by Claim 2, the values UU are almost surely distinct, the live point with the lowest likelihood is the one with the largest UU.

Induction hypothesis HiH_{i}: after ii iterations, given X1,…,XiX_1, \ldots, X_i, the NN live values UU are independent and U(0,Xi)\mathrm{U}(0, X_i). H0H_0 holds by Claim 2 with X0=1X_0 = 1.

Assume Hi−1H_{i-1}. The dead point of iteration ii has Xi=max⁡X_i = \max of NN independent U(0,Xi−1)\mathrm{U}(0, X_{i-1}) values, so P(Xi≤sXi−1)=sNP(X_i \le s X_{i-1}) = s^N, and ti∼Beta(N,1)t_i \sim \mathrm{Beta}(N, 1) independently of the past. Given the maximum XiX_i, the joint density of the other N−1N - 1 values is ∏j1{uj<Xi}/XiN−1\prod_j \mathbf{1}\{u_j < X_i\}/X_i^{N-1}, so they are independent U(0,Xi)\mathrm{U}(0, X_i). The new point of line L7 has L>Li∗L > L_i^*, so by Claim 2 its value is U(0,Xi)\mathrm{U}(0, X_i), independent of the others because the draw is independent. This is HiH_i.

For the moments, P(−log⁡t>y)=P(t<e−y)=e−NyP(-\log t > y) = P(t < e^{-y}) = e^{-Ny}, so −log⁡t-\log t is exponential with rate NN: mean 1/N1/N and variance 1/N21/N^2. Sums of independent terms give the last two formulas. ■\blacksquare

Claim 4: what the estimate computes

Let mm be the number of dead points. The estimate is

Z^=∑i=1mLi∗ (X^i−1−X^i)+X^mN∑k=1NL(θklive),X^i=e−i/N.\hat Z = \sum_{i=1}^m L_i^*\,(\hat X_{i-1} - \hat X_i) + \frac{\hat X_m}{N}\sum_{k=1}^N L(\theta_k^{\mathrm{live}}), \qquad \hat X_i = e^{-i/N}.

(a) With the true masses XiX_i in place of X^i\hat X_i, the sum is an upper Riemann sum of ∫Xm1L(x) dx\int_{X_m}^1 L(x)\, dx. Indeed Li∗=L(Xi)L_i^* = L(X_i) almost surely, and L(x)≤L(Xi)L(x) \le L(X_i) for x∈[Xi,Xi−1]x \in [X_i, X_{i-1}] by Claim 1. Since LL is monotone, the gap between the upper sum and the integral is at most (L(Xm)−L(1))max⁡i(Xi−1−Xi)(L(X_m) - L(1))\max_i (X_{i-1} - X_i). The rest, ∫0XmL(x) dx\int_0^{X_m} L(x)\, dx, lies between 00 and XmLmax⁡X_m L_{\max}; the stopping rule of line L8 asks that Lmax⁡liveX^m<εZ^L_{\max}^{\mathrm{live}} \hat X_m < \varepsilon \hat Z, and the live-point term of line L9 is a Monte Carlo estimate of that rest, since the live values UU are uniform on (0,Xm)(0, X_m) by Claim 3.

(b) The plug-in. By Claim 3, X^i=e−i/N=exp⁡(Elog⁡Xi)\hat X_i = e^{-i/N} = \exp(\mathbb{E}\log X_i), the geometric mean of XiX_i. The error log⁡Xi−log⁡X^i\log X_i - \log\hat X_i has mean 00 and standard deviation i/N\sqrt{i}/N.

(c) The information. Let H=∫log⁡p(θ∣x)π(θ) p(θ∣x) dθH = \int \log\frac{p(\theta \mid x)}{\pi(\theta)}\, p(\theta \mid x)\, d\theta be the Kullback-Leibler divergence from the prior to the posterior. The posterior mass sits where log⁡X≈−H\log X \approx -H, so it is reached after about NHNH iterations. There, by (b), the error of log⁡X\log X is about NH/N=H/N\sqrt{NH}/N = \sqrt{H/N}, which is the error estimate H/N\sqrt{H/N} of log⁡Z^\log\hat Z (Skilling 2006).

Part (a) and the moments in (b) are exact. The step from (b) to the size of the error of log⁡Z^\log\hat Z in (c) is a heuristic: it treats the posterior mass as sitting at one value of log⁡X\log X. Chopin and Robert (2010) prove that, with exact constrained draws, the estimate is consistent and its error is of order N−1/2N^{-1/2}. On the page, the ratio of the measured standard deviation to H/N\sqrt{H/N} is measured, not proved. ■\blacksquare

Claim 5: the exact information of the normal-normal model

For x1,…,xn∼N(θ,σ2)x_1, \ldots, x_n \sim N(\theta, \sigma^2) and θ∼N(0,τ2)\theta \sim N(0, \tau^2) the posterior is N(m,v)N(m, v) with v=(n/σ2+1/τ2)−1v = (n/\sigma^2 + 1/\tau^2)^{-1} and m=vnxˉ/σ2m = v n\bar x/\sigma^2, and

H=12log⁡τ2v−12+v+m22τ2.H = \tfrac12\log\frac{\tau^2}{v} - \tfrac12 + \frac{v + m^2}{2\tau^2}.

Proof. H=EN(m,v)[log⁡N(θ;m,v)−log⁡N(θ;0,τ2)]=(−12log⁡(2πv)−12)−(−12log⁡(2πτ2)−v+m22τ2)H = \mathbb{E}_{N(m, v)}\big[\log N(\theta; m, v) - \log N(\theta; 0, \tau^2)\big] = \big(-\frac12\log(2\pi v) - \frac12\big) - \big(-\frac12\log(2\pi\tau^2) - \frac{v + m^2}{2\tau^2}\big), using E(θ−m)2=v\mathbb{E}(\theta - m)^2 = v and Eθ2=v+m2\mathbb{E}\theta^2 = v + m^2. ■\blacksquare

Complexity

The run ends when log⁡Xi\log X_i is near −H−log⁡(1/ε)-H - \log(1/\varepsilon), after about N(H+K)N(H + K) iterations with K=log⁡(1/ε)K = \log(1/\varepsilon). Each iteration makes one constrained draw of cost CC and one heap update of cost O(log⁡N)O(\log N); the test of L8 costs O(N)O(N), and the code runs it once every NN iterations. The expected time is Θ(N(H+K)C)\Theta(N(H + K)C). Since the error is about H/N\sqrt{H/N}, halving the error costs four times the work. HH grows with the dimension dd, roughly like d2log⁡(n)\frac{d}{2}\log(n) for nn data points in a regular model, and the cost CC of a constrained draw also grows with dd. The dead points take Θ(N(H+K))\Theta(N(H + K)) space.

Properties

  • Randomized and not exact. log⁡Z^\log\hat Z has a random error of size about H/N\sqrt{H/N}, and Z^\hat Z has a small bias in finite runs.
  • One run gives three results: log⁡Z\log Z, an error estimate, and a weighted posterior sample.
  • No tuning of a temperature schedule. The level of L4 sets its own schedule, which adapts to the likelihood.
  • Handles phase transitions. Methods that follow a path of tempered posteriors πLβ\pi L^\beta can jump across a region where the energy changes suddenly; nested sampling moves in prior mass and does not.
  • Needs a proper prior from which one can draw, and works best when the posterior is not far smaller than the prior, since the work grows with HH.

Variants and improvements

  • Ellipsoidal and multi-ellipsoidal sampling. Mukherjee, Parkinson and Liddle (2006) draw L7 from an ellipsoid around the live points; MultiNest (Feroz, Hobson and Bridges, 2009) uses several ellipsoids for multimodal posteriors.
  • Slice sampling in L7. PolyChord (Handley, Hobson and Lasenby, 2015) replaces L7 by a short slice sampling chain, which scales to more dimensions than ellipsoids.
  • Dynamic nested sampling. Higson and coauthors (2019) change NN during the run, with more live points where the posterior mass is.
  • Several dead points per step. Removing the rr worst points at once lets rr constrained draws run in parallel; log⁡X\log X then shrinks by order statistics of uniform values.
  • Random XiX_i. Replace the plug-in of L5 by draws of ti∼Beta(N,1)t_i \sim \mathrm{Beta}(N, 1), repeat the sum many times, and read the error bar from the spread of log⁡Z^\log\hat Z.

When to use it

Use nested sampling when you need the marginal likelihood and also posterior draws, the posterior may be multimodal, and the dimension is small or moderate. It is a standard choice for Bayes factors in cosmology and astrophysics. If you already have posterior draws and a proposal that covers them, bridge sampling is more accurate for the same work. The Laplace approximation is far cheaper when the posterior is close to normal. Annealed importance sampling and sequential Monte Carlo are alternatives that follow a path of tempered densities.

Pitfalls

  • Correlated constrained draws. If L7 runs a Markov chain from a live point for only a few steps, the new point is not an independent draw above Li∗L_i^*, the law Beta(N,1)\mathrm{Beta}(N, 1) fails, and log⁡Z\log Z is biased. Run the chain in L7 long enough to forget its start, and check the result by repeated runs or by comparing with a smaller ε\varepsilon and a larger NN.
  • Likelihood plateaus. If LL is constant on a region of positive prior mass, the uniform law of Claim 2 fails, and L4 has ties. L5 then assigns wrong masses. Break the ties in L4 by a tiny random extra coordinate, or treat the plateau mass separately.
  • Linear-scale arithmetic. Computing L6 as written underflows when Li∗≈e−1000L_i^* \approx e^{-1000}, and the sum is 00. Keep log⁡L\log L, log⁡X\log X and log⁡Z\log Z, and add with log-sum-exp.
  • Dropping the live points. Stopping at L8 and returning without L9 loses the part of ZZ under the live points. At the stop of L8 it is below εZ\varepsilon Z, but with a loose ε\varepsilon or a run cut short by an iteration limit it can be most of ZZ. Keep L9.
  • Dead points as an equal-weight sample. The dead points are spread over the prior, not the posterior. Weighting them equally in L10 gives a sample from the wrong law. Use the weights Li∗wi/ZL_i^* w_i/Z, or resample with them.
  • Too few live points for many modes. With small NN, a mode of small prior mass can lose all its live points early and is never found again. Increase NN until the estimate is stable.

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.

nested_sampling.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/nested-sampling/. The authors are listed in prov/G4YCZZ.jsonl.
"""Nested sampling (Skilling 2006) for the marginal likelihood Z = integral of L(theta) pi(d theta).

The caller gives:
  log_lik(theta)                     the log-likelihood log L(theta);
  prior_draw(rng)                    one draw from the prior pi;
  constrained_draw(rng, log_l_star)  one draw from pi restricted to {log L > log_l_star}.

The prior mass above the i-th dead likelihood is estimated by X_i = exp(-i/N), because
log X_i is a sum of i independent terms log t with t ~ Beta(N, 1) and E log t = -1/N.

Cost: about N (H + log(1/eps)) iterations for N live points, information H (nats) and
stopping tolerance eps. Each iteration makes one constrained draw and one O(log N)
heap update; the stopping test costs O(N) once every N iterations.
"""

import heapq
import math
import random
from fractions import Fraction
from typing import Callable, Sequence


def _log_add(a: float, b: float) -> float:
    """log(e^a + e^b)."""
    if a == -math.inf:
        return b
    if b == -math.inf:
        return a
    if a < b:
        a, b = b, a
    return a + math.log1p(math.exp(b - a))


def _update_h(h_acc: float, log_z_old: float, log_z_new: float, log_term: float, log_l: float) -> float:
    """Running value of (1/Z) sum_i w_i L_i log L_i, rescaled each time Z grows."""
    if log_z_old == -math.inf:
        return log_l
    return math.exp(log_z_old - log_z_new) * h_acc + math.exp(log_term - log_z_new) * log_l


def nested_sampling(
    log_lik: Callable,
    prior_draw: Callable,
    constrained_draw: Callable,
    n_live: int,
    rng: random.Random,
    eps: float = 1e-8,
    max_iter: int = 10**7,
) -> dict:
    """Run nested sampling. Returns a dict with
      log_z       the estimate of log Z,
      h           the estimated information H = KL(posterior || prior) in nats,
      error       Skilling's error estimate sqrt(h / n_live) for log_z,
      iterations  the number of dead points before the live points are added,
      dead        a list of (theta, log L, log w) for posterior summaries.

    Precondition: n_live >= 1; the law of L(theta) under the prior has no atoms;
    constrained_draw returns exact, independent draws from the constrained prior.
    """
    live = []
    for k in range(n_live):  # @line L1
        th = prior_draw(rng)
        live.append((log_lik(th), k, th))
    heapq.heapify(live)  # live[0] is the live point with the lowest likelihood
    counter = n_live
    log_z, log_x_prev, i = -math.inf, 0.0, 0  # @line L2
    h_acc = 0.0
    dead = []
    while i < max_iter:  # @line L3
        i += 1
        log_l_star, _, th_star = live[0]  # @line L4
        log_x = -i / n_live  # @line L5
        log_w = log_x_prev + math.log(-math.expm1(log_x - log_x_prev))  # log(X_{i-1} - X_i)
        log_z_new = _log_add(log_z, log_l_star + log_w)  # @line L6
        h_acc = _update_h(h_acc, log_z, log_z_new, log_l_star + log_w, log_l_star)
        log_z = log_z_new
        dead.append((th_star, log_l_star, log_w))
        th_new = constrained_draw(rng, log_l_star)  # @line L7
        heapq.heapreplace(live, (log_lik(th_new), counter, th_new))
        counter += 1
        log_x_prev = log_x
        if i % n_live == 0:
            log_l_max = max(p[0] for p in live)
            if log_l_max + log_x < math.log(eps) + log_z:  # @line L8
                break
    log_w = log_x_prev - math.log(n_live)
    for log_l, _, th in live:
        log_z_new = _log_add(log_z, log_l + log_w)  # @line L9
        h_acc = _update_h(h_acc, log_z, log_z_new, log_l + log_w, log_l)
        log_z = log_z_new
        dead.append((th, log_l, log_w))
    h = h_acc - log_z
    return {  # @line L10
        "log_z": log_z,
        "h": h,
        "error": math.sqrt(max(h, 0.0) / n_live),
        "iterations": i,
        "dead": dead,
    }


def posterior_mean(result: dict, f: Callable) -> float:
    """Posterior mean of f(theta) from the dead points, with weights w_i L_i / Z."""
    log_z = result["log_z"]
    return math.fsum(math.exp(lw + ll - log_z) * f(th) for th, ll, lw in result["dead"])


def layer_cake(values: Sequence, probs: Sequence) -> Fraction:
    """Z = integral_0^1 L(X) dX for a discrete prior, as an exact sum over the levels of L.

    X(lam) = P(L > lam) is a step function; sorting the distinct values of L in
    decreasing order and adding L_k (X(L_k-) - X(L_k)) gives sum_k p_k L_k exactly.
    Inputs are Fractions (or ints); ties in L are allowed.
    """
    levels = sorted(set(values), reverse=True)
    total = Fraction(0)
    for lam in levels:
        above = sum((p for v, p in zip(values, probs) if v > lam), Fraction(0))  # X(lam)
        at_or_above = sum((p for v, p in zip(values, probs) if v >= lam), Fraction(0))
        total += Fraction(lam) * (at_or_above - above)
    return total
test_nested_sampling.py 144 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/nested-sampling/. The authors are listed in prov/G4YCZZ.jsonl.
"""Tests for nested sampling: the layer-cake identity, the shrinkage law, and log Z of conjugate models.

All constrained draws are exact: the set {L > L*} is an interval in these models, so a
draw from the prior restricted to it comes from the inverse CDF.
"""

import math
import random
import statistics
import unittest
from fractions import Fraction as F

from nested_sampling import layer_cake, nested_sampling, posterior_mean

ND = statistics.NormalDist()


def normal_model(xs, sigma, tau):
    """x_j ~ N(theta, sigma^2), theta ~ N(0, tau^2). Returns the model and exact log Z, H, mean."""
    n = len(xs)
    xb = sum(xs) / n
    s2 = sum((x - xb) ** 2 for x in xs)
    c = -0.5 * n * math.log(2 * math.pi * sigma**2) - 0.5 * s2 / sigma**2

    def log_lik(t):
        return c - 0.5 * n * (t - xb) ** 2 / sigma**2

    def prior_draw(rng):
        return rng.gauss(0.0, tau)

    def constrained_draw(rng, log_l_star):
        r = math.sqrt(max((c - log_l_star) * 2 * sigma**2 / n, 0.0))
        lo, hi = ND.cdf((xb - r) / tau), ND.cdf((xb + r) / tau)
        u = lo + (hi - lo) * rng.random()
        return tau * ND.inv_cdf(min(max(u, 1e-300), 1 - 1e-16))

    v = 1 / (n / sigma**2 + 1 / tau**2)
    m = v * n * xb / sigma**2
    log_z = c + 0.5 * math.log(v / tau**2) - 0.5 * xb**2 / (tau**2 + sigma**2 / n)
    h = 0.5 * math.log(tau**2 / v) - 0.5 + 0.5 * (v + m * m) / tau**2
    return log_lik, prior_draw, constrained_draw, log_z, h, m


def binomial_model(n, x):
    """x successes in n trials, uniform prior on p. Exact Z = 1/(n+1)."""
    log_c = math.lgamma(n + 1) - math.lgamma(x + 1) - math.lgamma(n - x + 1)
    mode = x / n

    def log_lik(p):
        if p <= 0.0 or p >= 1.0:
            return -math.inf
        return log_c + x * math.log(p) + (n - x) * math.log1p(-p)

    def prior_draw(rng):
        return rng.random()

    def edge(lo, hi, log_l_star, rising):
        for _ in range(60):
            mid = 0.5 * (lo + hi)
            if (log_lik(mid) > log_l_star) == rising:
                hi = mid
            else:
                lo = mid
        return 0.5 * (lo + hi)

    def constrained_draw(rng, log_l_star):
        a = edge(0.0, mode, log_l_star, True)
        b = edge(mode, 1.0, log_l_star, False)
        return a + (b - a) * rng.random()

    return log_lik, prior_draw, constrained_draw, -math.log(n + 1)


class TestIdentities(unittest.TestCase):
    def test_layer_cake_is_exact_on_discrete_priors(self):
        rng = random.Random(1)
        for _ in range(500):
            m = rng.randint(1, 8)
            vals = [F(rng.randint(0, 6), rng.randint(1, 4)) for _ in range(m)]  # ties happen
            w = [rng.randint(1, 9) for _ in range(m)]
            probs = [F(k, sum(w)) for k in w]
            self.assertEqual(layer_cake(vals, probs), sum(p * v for p, v in zip(probs, vals)))

    def test_shrinkage_law_beta_n_1(self):
        # L(theta) = theta on a uniform prior, so X(lambda) = 1 - lambda exactly and the
        # true prior mass X_i above the i-th dead point is known. Theory: log X_i is a sum of
        # i iid log t, t ~ Beta(N, 1): mean -i/N, variance i/N^2; E t = N/(N+1).
        rng = random.Random(2)
        n_live, steps, reps = 10, 30, 2000
        logs, ratios = [], []
        for _ in range(reps):
            res = nested_sampling(
                math.log,
                lambda r: 1.0 - r.random(),
                lambda r, ls: 1.0 - (1.0 - math.exp(ls)) * r.random(),
                n_live, rng, max_iter=steps,
            )
            xs = [1.0 - th for th, _, _ in res["dead"][:steps]]
            logs.append(math.log(xs[-1]))
            ratios.append(xs[1] / xs[0])
        se = math.sqrt(steps / n_live**2 / reps)
        self.assertLess(abs(statistics.mean(logs) + steps / n_live), 4 * se)
        self.assertLess(abs(statistics.variance(logs) / (steps / n_live**2) - 1), 0.12)
        self.assertLess(abs(statistics.mean(ratios) - n_live / (n_live + 1)), 4 * math.sqrt(0.0069 / reps))


class TestConjugateModels(unittest.TestCase):
    def test_normal_normal_log_z_and_error_bar(self):
        rng = random.Random(1)
        xs = [round(rng.gauss(1.0, 1.0), 2) for _ in range(20)]
        log_lik, prior_draw, cdraw, exact, h, m = normal_model(xs, 1.0, 10.0)
        self.assertAlmostEqual(exact, -31.327583, places=5)
        self.assertAlmostEqual(h, 3.306072, places=5)
        n_live, reps = 100, 60
        errs, hs, inside = [], [], 0
        for _ in range(reps):
            res = nested_sampling(log_lik, prior_draw, cdraw, n_live, rng, eps=1e-6)
            e = res["log_z"] - exact
            errs.append(e)
            hs.append(res["h"])
            inside += abs(e) <= 2 * res["error"]
            self.assertLess(abs(posterior_mean(res, lambda t: t) - m), 0.05)
        self.assertLess(abs(statistics.mean(hs) - h), 0.1)
        sd = statistics.stdev(errs)
        self.assertLess(abs(statistics.mean(errs)), 4 * sd / math.sqrt(reps))
        self.assertTrue(0.7 < sd / math.sqrt(h / n_live) < 1.4)
        self.assertGreaterEqual(inside, int(0.85 * reps))

    def test_beta_binomial_uniform_prior(self):
        rng = random.Random(3)
        log_lik, prior_draw, cdraw, exact = binomial_model(10, 3)
        errs = []
        for _ in range(20):
            res = nested_sampling(log_lik, prior_draw, cdraw, 50, rng, eps=1e-6)
            errs.append(res["log_z"] - exact)
            self.assertLess(abs(res["log_z"] - exact), 4 * res["error"])
            self.assertLess(abs(posterior_mean(res, lambda p: p) - 4 / 12), 0.03)
        self.assertLess(abs(statistics.mean(errs)), 0.1)


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

History

John Skilling presented nested sampling in 2004 and gave the full account in Bayesian Analysis in 2006. He took the idea of sorting the prior by likelihood from statistical physics, where the density of states plays the same role as XX. Mukherjee, Parkinson and Liddle (2006) applied it to cosmological model selection with ellipsoidal sampling. Chopin and Robert (2010) gave the first formal analysis, with consistency and the rate of the error. MultiNest (2009) and PolyChord (2015) made the method practical for multimodal and higher-dimensional problems, and dynamic nested sampling (2019) changes the number of live points during the run.

References

  1. John Skilling, Nested sampling for general Bayesian computation, Bayesian Analysis 1(4), 2006, pages 833 to 859: the transformation of Z into a one-dimensional integral over the prior mass X, the shrinkage of X by Beta(N, 1) factors, the information H and the error estimate sqrt(H/N), and the termination rule (general locator)
  2. Nicolas Chopin and Christian P. Robert, Properties of nested sampling, Biometrika 97(3), 2010, pages 741 to 755: consistency of the estimate and the order N^(-1/2) of its error under exact constrained draws (general locator)

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.expected
  • 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
  • at least three sources
  • a scene preset for the example