Algorithm Search⌘K

Algorithmadvanced

Bridge sampling

Also called Meng-Wong bridge sampling.

Estimates a ratio of normalizing constants, such as a marginal likelihood, from draws of two distributions linked by a bridge function. The optimal bridge is found iteratively.

Time
Θ(n T) worst
Space
Θ(n) extra
Where
T = the number of iterations; n = the total number of draws, n1 + n2
Properties
deterministicnot exactofflineiterative
Origin
Xiao Li Meng, Wing Hung Wong, Charles H. Bennett, 1996

Bridge sampling estimates a ratio r=c1/c2r = c_1/c_2 of two normalizing constants from draws of the two distributions. Its main use in Bayesian statistics is the marginal likelihood Z=∫f(x∣θ)π(θ) dθZ = \int f(x \mid \theta)\pi(\theta)\, d\theta: take the posterior as the first distribution, with q1=f(x∣θ)π(θ)q_1 = f(x \mid \theta)\pi(\theta) and c1=Zc_1 = Z, and a normalized proposal density gg as the second, with c2=1c_2 = 1. The method rests on the identity r=E2[q1α]/E1[q2α]r = \mathbb{E}_2[q_1\alpha]/\mathbb{E}_1[q_2\alpha], true for every bridge function α\alpha. Importance sampling is the case α=1/q2\alpha = 1/q_2, and the harmonic mean estimator is the case α=1/q1\alpha = 1/q_1 with the prior as gg. The bridge that minimizes the first-order error is α∝1/(s1q1+s2rq2)\alpha \propto 1/(s_1 q_1 + s_2 r q_2); it depends on rr, so it is found by a fixed-point iteration that converges geometrically from any start.

In plain words

To find the size of a hidden region, you can sample points from the region itself, or from a second region whose size you know, or from both. Importance sampling uses only the known region, and it fails when that region misses part of the hidden one. The harmonic mean trick uses only the hidden region, and it fails because a few rare points dominate the answer. Bridge sampling uses both samples and weighs each point by how well it sits in the overlap of the two regions. The best weights depend on the answer, so the method guesses, reweighs, and repeats. Each round moves the guess closer to one fixed value. With a second region that overlaps the first well, the answer is accurate to a few hundredths of a unit on the log scale from a few thousand points.

The problem

Input. Two unnormalized densities q1,q2≥0q_1, q_2 \ge 0 that can be evaluated, with unknown constants ck=∫qk>0c_k = \int q_k > 0 and normalized densities pk=qk/ckp_k = q_k/c_k. Draws θ1,…,θn1\theta_1, \ldots, \theta_{n_1} from p1p_1 and ϕ1,…,ϕn2\phi_1, \ldots, \phi_{n_2} from p2p_2, for example posterior draws from Metropolis-Hastings and independent draws from a normal proposal.

Output. An estimate of log⁡r=log⁡(c1/c2)\log r = \log(c_1/c_2). For a marginal likelihood, log⁡r=log⁡Z\log r = \log Z; for two models, the difference of two such estimates is the log Bayes factor.

The bridge identity. For every α≥0\alpha \ge 0 with 0<∫αq1q2<∞0 < \int \alpha q_1 q_2 < \infty,

r=c1c2=E2[q1(ϕ)α(ϕ)]E1[q2(θ)α(θ)],r = \frac{c_1}{c_2} = \frac{\mathbb{E}_2[q_1(\phi)\alpha(\phi)]}{\mathbb{E}_1[q_2(\theta)\alpha(\theta)]},

because both expectations are integrals of αq1q2\alpha q_1 q_2, divided by c2c_2 and c1c_1. Replacing the two expectations by sample means gives the estimate r^α\hat r_\alpha.

The algorithm

Write l=q1/q2l = q_1/q_2, l1i=l(θi)l_{1i} = l(\theta_i), l2j=l(ϕj)l_{2j} = l(\phi_j), n=n1+n2n = n_1 + n_2 and sk=nk/ns_k = n_k/n. With the optimal bridge α=1/(s1q1+s2rq2)\alpha = 1/(s_1 q_1 + s_2 r q_2), the factor q2q_2 cancels, and the estimate becomes the fixed point of the map on line L8.

  1. BRIDGE(θ₁..θ_{n₁} ~ p₁, φ₁..φ_{n₂} ~ p₂, q₁, q₂)
  2. 1s₁ ← n₁/(n₁ + n₂); s₂ ← n₂/(n₁ + n₂)
  3. 2l₁ᵢ ← q₁(θᵢ)/q₂(θᵢ) for i = 1..n₁ ▷ kept as logarithms
  4. 3l₂ⱼ ← q₁(φⱼ)/q₂(φⱼ) for j = 1..n₂
  5. 4r ← (1/n₂) Σⱼ l₂ⱼ ▷ start: importance sampling
  6. 5repeat
  7. 6N ← (1/n₂) Σⱼ l₂ⱼ / (s₁ l₂ⱼ + s₂ r)
  8. 7D ← (1/n₁) Σᵢ 1 / (s₁ l₁ᵢ + s₂ r)
  9. 8r_new ← N / D
  10. 9if |log r_new - log r| ≤ tol then return log r_new
  11. 10r ← r_new

Lines L2 and L3 evaluate both densities at both samples, 2n2n density evaluations, which is usually the main cost. The ratios ll can be e−500e^{-500} or e500e^{500}, so the code keeps log⁡l\log l and computes L6 and L7 with log-sum-exp; the formulas above are the same in exact arithmetic. L4 is any positive start; the importance sampling estimate is a good one. L6 and L7 are the two sample means of the bridge identity with α=1/(s1q1+s2rq2)\alpha = 1/(s_1 q_1 + s_2 r q_2), after dividing by q2q_2. L9 stops when the log estimate moves by less than the tolerance.

Choosing p2p_2 for a marginal likelihood. A common choice, following Gronau et al. (2017), is a normal density whose mean and covariance match the posterior draws, in a scale where every parameter is unconstrained, with the Jacobian included in q1q_1. The mode and the inverse Hessian of the Laplace approximation also work. The proposal should be fitted on a different part of the posterior draws from the part used in L2.

Example

Trace. Bernoulli data with 33 successes in 1010 trials and the prior Beta(2, 2), in the logit scale θ=log⁡(p/(1−p))\theta = \log(p/(1-p)): q1(θ)=p5(1−p)9/B(2,2)q_1(\theta) = p^5(1 - p)^9/B(2, 2), with the Jacobian p(1−p)p(1-p) included. The exact value is log⁡Z=log⁡B(5,9)−log⁡B(2,2)=−6.977748\log Z = \log B(5, 9) - \log B(2, 2) = -6.977748. For p2p_2 we take the Laplace normal N(−0.587787,0.5577732)N(-0.587787, 0.557773^2) of the Laplace approximation page. With random.Random(5), n1=n2=8n_1 = n_2 = 8: the θi\theta_i are logits of exact Beta(5, 9) draws, and the ϕj\phi_j are normal draws.

ii or jj 1 2 3 4 5 6 7 8
θi\theta_i −0.7495-0.7495 0.6122 −0.6716-0.6716 −1.1907-1.1907 1.1076 −0.8125-0.8125 −0.2063-0.2063 −0.1818-0.1818
log⁡l1i\log l_{1i} −6.9970-6.9970 −7.1332-7.1332 −6.9976-6.9976 −6.9586-6.9586 −7.2182-7.2182 −6.9958-6.9958 −7.0050-7.0050 −7.0064-7.0064
ϕj\phi_j −0.4630-0.4630 −0.4255-0.4255 −0.8283-0.8283 0.1314 0.2517 −0.5699-0.5699 −0.8398-0.8398 −0.1788-0.1788
log⁡l2j\log l_{2j} −6.9980-6.9980 −6.9983-6.9983 −6.9954-6.9954 −7.0389-7.0389 −7.0585-7.0585 −6.9977-6.9977 −6.9951-6.9951 −7.0066-7.0066

All ratios are close to e−7e^{-7}, because the Laplace normal is close to the posterior. The iteration, with s1=s2=1/2s_1 = s_2 = 1/2:

step NN (L6) DD (L7) log⁡r\log r (L8)
start (L4) −7.010809-7.010809
1 0.999875 1124.111842 −7.024874-7.024874
2 1.006906 1132.142279 −7.024984-7.024984
3 1.006962 1132.205476 −7.024985-7.024985
4 to 6 1.006962 1132.205977 −7.024985-7.024985

The test of L9 with tolerance 10−1210^{-12} stops at step 6. The estimate −7.024985-7.024985 is off by 0.0470.047 nats from 16 draws. Bisection on the estimating equation of the proof gives the same root, −7.024985-7.024985.

Four estimators of the same log⁡Z\log Z. Same model, 200200 repetitions with random.Random(2024), 20002000 draws per estimate: the bridges use 10001000 posterior and 10001000 proposal draws, importance sampling uses 20002000 proposal draws, and the harmonic mean uses 20002000 posterior draws.

estimator bridge function mean error (nats) standard deviation largest error
importance sampling 1/q21/q_2 −0.0001-0.0001 0.0035 0.018
harmonic mean 1/q11/q_1, prior as p2p_2 0.0542 0.1271 0.518
geometric bridge 1/q1q21/\sqrt{q_1 q_2} 0.0002 0.0026 0.008
optimal bridge L1 to L10 0.0002 0.0026 0.008

Here the proposal is good, so importance sampling also works, and the bridges reduce its spread by a quarter. The harmonic mean has infinite variance in this model: Epost[1/f(x∣p)2]∝∫p−2(1−p)−6dp=∞\mathbb{E}_{\mathrm{post}}[1/f(x \mid p)^2] \propto \int p^{-2}(1 - p)^{-6} dp = \infty.

The harmonic mean does not improve with more draws. Take xi∼N(θ,1)x_i \sim N(\theta, 1) for i=1,…,20i = 1, \ldots, 20 and the prior θ∼N(0,102)\theta \sim N(0, 10^2), with data from random.Random(1); the exact value is log⁡Z=−31.327583\log Z = -31.327583. The bridge uses a proposal N(m,2v)N(m, 2v), where N(m,v)N(m, v) is the exact posterior. Twenty repetitions per row:

draws SS per sample harmonic mean, mean error its standard deviation optimal bridge, mean error its standard deviation
100 2.910 0.290 0.0009 0.0349
1000 2.621 0.326 −0.0007-0.0007 0.0090
10000 2.479 0.484 0.0000 0.0028
100000 2.389 0.258

The bridge error falls like 1/S1/\sqrt S. The harmonic mean overestimates log⁡Z\log Z by more than two nats even with 10510^5 draws. In the normal-normal model with noise variance σ2\sigma^2 and prior variance τ2\tau^2, Epost[1/f(x∣θ)2]\mathbb{E}_{\mathrm{post}}[1/f(x \mid \theta)^2] is finite only when nτ2<σ2n\tau^2 < \sigma^2, that is, when the prior is narrower than the noise of one mean. Here nτ2=2000n\tau^2 = 2000 and σ2=1\sigma^2 = 1. The posterior rarely visits the region where the likelihood is small, and that region carries most of Epost[1/f]\mathbb{E}_{\mathrm{post}}[1/f]. There is no page for the harmonic mean estimator, because it should not be used.

Correctness

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

  1. The identity r=E2[q1α]/E1[q2α]r = \mathbb{E}_2[q_1\alpha]/\mathbb{E}_1[q_2\alpha] for every bridge function with 0<∫αq1q2<∞0 < \int\alpha q_1 q_2 < \infty, and the consistency of r^α\hat r_\alpha for a fixed α\alpha by the law of large numbers.
  2. Special cases. α=1/q2\alpha = 1/q_2 gives importance sampling (support of p1p_1 inside that of p2p_2); α=1/q1\alpha = 1/q_1 gives reciprocal importance sampling, and with the prior as p2p_2 the harmonic mean identity Z=1/Epost[1/f(x∣θ)]Z = 1/\mathbb{E}_{\mathrm{post}}[1/f(x \mid \theta)].
  3. The optimal bridge, under an approximation. If all draws are independent, the first-order delta method gives RE2(r^α)≈1ns1s2(∫p1p2(s1p1+s2p2)α2/(∫p1p2α)2−1)\mathrm{RE}^2(\hat r_\alpha) \approx \frac{1}{n s_1 s_2}\big(\int p_1 p_2 (s_1 p_1 + s_2 p_2)\alpha^2 / (\int p_1 p_2\alpha)^2 - 1\big) (Meng and Wong 1996, equation (3.2)). By the Cauchy-Schwarz inequality this is minimized by α∝1/(s1p1+s2p2)\alpha \propto 1/(s_1 p_1 + s_2 p_2), with minimum 1ns1s2((∫p1p2/(s1p1+s2p2))−1−1)\frac{1}{n s_1 s_2}\big((\int p_1 p_2/(s_1 p_1 + s_2 p_2))^{-1} - 1\big). The minimum is always finite, even when importance sampling and the harmonic mean have infinite variance.
  4. The iteration. The fixed points of L8 are the roots of Ψ(ρ)=1n1∑iρs1l1i+s2ρ−1n2∑jl2js1l2j+s2ρ\Psi(\rho) = \frac{1}{n_1}\sum_i \frac{\rho}{s_1 l_{1i} + s_2\rho} - \frac{1}{n_2}\sum_j \frac{l_{2j}}{s_1 l_{2j} + s_2\rho}, which is strictly increasing from −1/s1-1/s_1 to 1/s21/s_2, so there is exactly one. The map sends (0,∞)(0, \infty) into a compact interval, and in the log scale its derivative lies in (−1,1)(-1, 1), so it is a contraction there and converges geometrically from any start.
  5. Consistency of the root. With independent draws and fixed s1,s2s_1, s_2, the root converges to rr almost surely, because the sample estimating function converges to (ρ/c1−1/c2)(\rho/c_1 - 1/c_2) times a positive integral.

What is proved and what is only approximate: items 1, 2, 4 and 5 are exact statements. Item 3 is exact for the first-order formula, which is itself an approximation of the true relative error; for draws from a Markov chain, the formula holds with effective sample sizes in place of n1n_1 and n2n_2 only approximately. The errors in the tables are measured.

Proof: The bridge identity, the optimal bridge, and the convergence of the iterationfull

Setting. For k=1,2k = 1, 2 let pk=qk/ckp_k = q_k/c_k be a probability density on Ωk⊆Rd\Omega_k \subseteq \mathbb{R}^d (with respect to a common measure), where qk≥0q_k \ge 0 can be evaluated and ck=∫qk>0c_k = \int q_k > 0 is unknown. The target is r=c1/c2r = c_1/c_2. A bridge function is a measurable α≥0\alpha \ge 0 with

0<∫Ω1∩Ω2α q1q2<∞.(1)0 < \int_{\Omega_1 \cap \Omega_2} \alpha\, q_1 q_2 < \infty. \tag{1}

Ek\mathbb{E}_k is the expectation under pkp_k. The draws are θ1,…,θn1∼p1\theta_1, \ldots, \theta_{n_1} \sim p_1 and ϕ1,…,ϕn2∼p2\phi_1, \ldots, \phi_{n_2} \sim p_2. Write n=n1+n2n = n_1 + n_2, sk=nk/ns_k = n_k/n, and l=q1/q2l = q_1/q_2, with l1i=l(θi)l_{1i} = l(\theta_i) and l2j=l(ϕj)l_{2j} = l(\phi_j).

Claim 1: the bridge identity

For every bridge function α\alpha,   r=E2[q1α]/E1[q2α]\;r = \mathbb{E}_2[q_1 \alpha]/\mathbb{E}_1[q_2 \alpha].

Proof. E2[q1α]=∫q1α q2/c2\mathbb{E}_2[q_1\alpha] = \int q_1 \alpha\, q_2/c_2 and E1[q2α]=∫q2α q1/c1\mathbb{E}_1[q_2\alpha] = \int q_2 \alpha\, q_1/c_1. Both integrands are αq1q2\alpha q_1 q_2, which vanishes outside Ω1∩Ω2\Omega_1 \cap \Omega_2, so the two integrals are J/c2J/c_2 and J/c1J/c_1 with J=∫αq1q2∈(0,∞)J = \int \alpha q_1 q_2 \in (0, \infty) by (1). Their ratio is c1/c2c_1/c_2. ■\blacksquare

Consistency of a fixed bridge. If the draws within each sample are independent (or form ergodic Markov chains) then, by the law of large numbers, 1n2∑jq1(ϕj)α(ϕj)→E2[q1α]\frac{1}{n_2}\sum_j q_1(\phi_j)\alpha(\phi_j) \to \mathbb{E}_2[q_1\alpha] and 1n1∑iq2(θi)α(θi)→E1[q2α]>0\frac{1}{n_1}\sum_i q_2(\theta_i)\alpha(\theta_i) \to \mathbb{E}_1[q_2\alpha] > 0 almost surely, because both expectations are finite by (1). So r^α→r\hat r_\alpha \to r almost surely.

Claim 2: importance sampling and the harmonic mean are bridges

(a) If Ω1⊆Ω2\Omega_1 \subseteq \Omega_2 and α=1/q2\alpha = 1/q_2 on Ω2\Omega_2, then E1[q2α]=1\mathbb{E}_1[q_2\alpha] = 1 and the identity reads r=E2[q1/q2]r = \mathbb{E}_2[q_1/q_2]: importance sampling of q1q_1 with proposal p2p_2. Condition (1) holds: ∫αq1q2=c1\int \alpha q_1 q_2 = c_1.

(b) If Ω2⊆Ω1\Omega_2 \subseteq \Omega_1 and α=1/q1\alpha = 1/q_1 on Ω1\Omega_1, then E2[q1α]=1\mathbb{E}_2[q_1\alpha] = 1 and E1[q2α]=E1[q2/q1]\mathbb{E}_1[q_2\alpha] = \mathbb{E}_1[q_2/q_1], so r=1/E1[q2/q1]r = 1/\mathbb{E}_1[q_2/q_1]: reciprocal importance sampling, the estimator of Gelfand and Dey when q2q_2 is a normalized density. Condition (1) holds: ∫αq1q2=∫Ω2q2=c2\int \alpha q_1 q_2 = \int_{\Omega_2} q_2 = c_2. With q1=f(x∣θ)π(θ)q_1 = f(x \mid \theta)\pi(\theta) and q2=πq_2 = \pi, a normalized prior (c2=1c_2 = 1), this is Z=1/Epost[1/f(x∣θ)]Z = 1/\mathbb{E}_{\mathrm{post}}[1/f(x \mid \theta)], the harmonic mean identity. The identity is exact, but the variance of the estimate is finite only if E1[(q2/q1)2]<∞\mathbb{E}_1[(q_2/q_1)^2] < \infty, which needs q2q_2 to have lighter tails than p1p_1; the prior usually has heavier tails than the posterior. ■\blacksquare

Claim 3: the optimal bridge under the first-order approximation

The approximation. Assume that all nn draws are independent, that ∫p1p2α2(p1+p2)<∞\int p_1 p_2 \alpha^2 (p_1 + p_2) < \infty, and measure the error by the relative mean squared error RE2(r^α)=E(r^α−r)2/r2\mathrm{RE}^2(\hat r_\alpha) = \mathbb{E}(\hat r_\alpha - r)^2/r^2. Write r^α=A/B\hat r_\alpha = A/B with A=1n2∑jq1(ϕj)α(ϕj)A = \frac{1}{n_2}\sum_j q_1(\phi_j)\alpha(\phi_j) and B=1n1∑iq2(θi)α(θi)B = \frac{1}{n_1}\sum_i q_2(\theta_i)\alpha(\theta_i), and μ=∫p1p2α\mu = \int p_1 p_2 \alpha. Then EA=c1μ\mathbb{E}A = c_1\mu, EB=c2μ\mathbb{E}B = c_2\mu, and AA and BB are independent with

Var(A)(EA)2=1n2(∫p12p2α2μ2−1),Var(B)(EB)2=1n1(∫p1p22α2μ2−1).\frac{\mathrm{Var}(A)}{(\mathbb{E}A)^2} = \frac{1}{n_2}\Big(\frac{\int p_1^2 p_2 \alpha^2}{\mu^2} - 1\Big), \qquad \frac{\mathrm{Var}(B)}{(\mathbb{E}B)^2} = \frac{1}{n_1}\Big(\frac{\int p_1 p_2^2 \alpha^2}{\mu^2} - 1\Big).

The first-order delta method for the ratio A/BA/B of independent averages gives RE2≈Var(A)/(EA)2+Var(B)/(EB)2\mathrm{RE}^2 \approx \mathrm{Var}(A)/(\mathbb{E}A)^2 + \mathrm{Var}(B)/(\mathbb{E}B)^2. With p1n2+p2n1=s1p1+s2p2ns1s2\frac{p_1}{n_2} + \frac{p_2}{n_1} = \frac{s_1 p_1 + s_2 p_2}{n s_1 s_2} and 1n1+1n2=1ns1s2\frac1{n_1} + \frac1{n_2} = \frac{1}{n s_1 s_2} this is

RE2(r^α)≈1ns1s2(∫p1p2(s1p1+s2p2) α2(∫p1p2α)2−1).(2)\mathrm{RE}^2(\hat r_\alpha) \approx \frac{1}{n s_1 s_2}\left(\frac{\int p_1 p_2 (s_1 p_1 + s_2 p_2)\, \alpha^2}{\big(\int p_1 p_2 \alpha\big)^2} - 1\right). \tag{2}

This is equation (3.2) of Meng and Wong (1996). It is an approximation, exact only to the first order in 1/n1/n. The claim below is about the right side of (2).

Claim. Over all bridge functions, the right side of (2) is minimized by αopt∝1/(s1p1+s2p2)\alpha_{\mathrm{opt}} \propto 1/(s_1 p_1 + s_2 p_2) on {p1p2>0}\{p_1 p_2 > 0\}, and the minimum is

1ns1s2((∫p1p2s1p1+s2p2)−1−1).\frac{1}{n s_1 s_2}\left(\Big(\int \frac{p_1 p_2}{s_1 p_1 + s_2 p_2}\Big)^{-1} - 1\right).

Proof. Let w=s1p1+s2p2>0w = s_1 p_1 + s_2 p_2 > 0 on {p1p2>0}\{p_1 p_2 > 0\}. By the Cauchy-Schwarz inequality,

(∫p1p2α)2=(∫(αp1p2w)(p1p2/w))2≤∫p1p2w α2⋅∫p1p2w.\Big(\int p_1 p_2 \alpha\Big)^2 = \Big(\int \big(\alpha\sqrt{p_1 p_2 w}\big)\Big(\sqrt{p_1 p_2/w}\Big)\Big)^2 \le \int p_1 p_2 w\, \alpha^2 \cdot \int \frac{p_1 p_2}{w}.

So the ratio in (2) is at least (∫p1p2/w)−1\big(\int p_1 p_2/w\big)^{-1}. Equality in Cauchy-Schwarz holds exactly when the two factors are proportional, that is αp1p2w=κp1p2/w\alpha\sqrt{p_1 p_2 w} = \kappa \sqrt{p_1 p_2/w}, or α=κ/w\alpha = \kappa/w where p1p2>0p_1 p_2 > 0. The value of α\alpha where p1p2=0p_1 p_2 = 0 does not enter (2). ■\blacksquare

Two consequences. First, ∫p1p2/w≤∫p2/s1=1/s1\int p_1 p_2/w \le \int p_2/s_1 = 1/s_1 is always finite, and it is positive when the supports overlap, so the optimal bridge has a finite first-order error even when the importance sampling and harmonic mean bridges have infinite variance. Second, αopt∝1/(s1q1/c1+s2q2/c2)∝1/(s1q1+s2rq2)\alpha_{\mathrm{opt}} \propto 1/(s_1 q_1/c_1 + s_2 q_2/c_2) \propto 1/(s_1 q_1 + s_2 r q_2) depends on the unknown rr.

Claim 4: the iteration has one fixed point, and it converges to it

Plug α=1/(s1q1+s2ρq2)\alpha = 1/(s_1 q_1 + s_2 \rho q_2), with a trial value ρ\rho in place of rr, into r^=A/B\hat r = A/B. Divide the numerator and the denominator inside each sum by q2q_2:

T(ρ)=1n2∑jl2js1l2j+s2ρ1n1∑i1s1l1i+s2ρ=N(ρ)D(ρ).T(\rho) = \frac{\frac{1}{n_2}\sum_j \frac{l_{2j}}{s_1 l_{2j} + s_2 \rho}}{\frac{1}{n_1}\sum_i \frac{1}{s_1 l_{1i} + s_2 \rho}} = \frac{N(\rho)}{D(\rho)}.

The algorithm iterates ρt+1=T(ρt)\rho_{t+1} = T(\rho_t) (lines L5 to L9). Assume all l1i,l2jl_{1i}, l_{2j} are positive and finite, and let $l_- $ and l+l_+ be the smallest and the largest of them.

(a) The fixed points are the roots of one increasing function. Since D(ρ)>0D(\rho) > 0, T(ρ)=ρT(\rho) = \rho if and only if Ψ(ρ)=0\Psi(\rho) = 0, where

Ψ(ρ)=ρD(ρ)−N(ρ)=1n1∑iρs1l1i+s2ρ−1n2∑jl2js1l2j+s2ρ.\Psi(\rho) = \rho D(\rho) - N(\rho) = \frac{1}{n_1}\sum_i \frac{\rho}{s_1 l_{1i} + s_2\rho} - \frac{1}{n_2}\sum_j \frac{l_{2j}}{s_1 l_{2j} + s_2\rho}.

Each term ρ/(s1l+s2ρ)\rho/(s_1 l + s_2\rho) has derivative s1l/(s1l+s2ρ)2>0s_1 l/(s_1 l + s_2\rho)^2 > 0, and each term l/(s1l+s2ρ)l/(s_1 l + s_2\rho) has derivative −s2l/(s1l+s2ρ)2<0-s_2 l/(s_1 l + s_2 \rho)^2 < 0. So Ψ\Psi is strictly increasing on (0,∞)(0, \infty), with limit −1/s1-1/s_1 as ρ→0\rho \to 0 and 1/s21/s_2 as ρ→∞\rho \to \infty. By the intermediate value theorem it has exactly one root r^\hat r, and TT has exactly one fixed point.

(b) TT maps (0,∞)(0, \infty) into a compact interval. For a≤ba \le b and ρ>0\rho > 0, (s1a+s2ρ)/(s1b+s2ρ)≥a/b(s_1 a + s_2\rho)/(s_1 b + s_2\rho) \ge a/b. Every denominator s1l+s2ρs_1 l + s_2\rho lies between s1l−+s2ρs_1 l_- + s_2\rho and s1l++s2ρs_1 l_+ + s_2\rho, so

T(ρ)≥l−/(s1l++s2ρ)1/(s1l−+s2ρ)≥l−l−l+,T(ρ)≤l+l+l−.T(\rho) \ge \frac{l_-/(s_1 l_+ + s_2\rho)}{1/(s_1 l_- + s_2\rho)} \ge l_-\frac{l_-}{l_+}, \qquad T(\rho) \le l_+ \frac{l_+}{l_-}.

So TT maps (0,∞)(0, \infty) into J=[l−2/l+, l+2/l−]J = [l_-^2/l_+,\ l_+^2/l_-].

(c) TT is a contraction in the log scale on JJ. Let u=log⁡ρu = \log \rho and τ(u)=log⁡T(eu)\tau(u) = \log T(e^u). Then

τ′(u)=dlog⁡Ndu−dlog⁡Ddu=−∑jωjs2ρs1l2j+s2ρ+∑iνis2ρs1l1i+s2ρ,\tau'(u) = \frac{d\log N}{du} - \frac{d\log D}{du} = -\sum_j \omega_j \frac{s_2\rho}{s_1 l_{2j} + s_2\rho} + \sum_i \nu_i \frac{s_2\rho}{s_1 l_{1i} + s_2\rho},

where ωj∝l2j/(s1l2j+s2ρ)\omega_j \propto l_{2j}/(s_1 l_{2j} + s_2\rho) and νi∝1/(s1l1i+s2ρ)\nu_i \propto 1/(s_1 l_{1i} + s_2\rho) are positive weights that sum to 11. Each fraction s2ρ/(s1l+s2ρ)s_2\rho/(s_1 l + s_2\rho) lies in (0,1)(0, 1), so each weighted mean lies in (0,1)(0, 1), and τ′(u)∈(−1,1)\tau'(u) \in (-1, 1). τ′\tau' is continuous, so on the compact interval log⁡J\log J it satisfies ∣τ′∣≤κ\lvert \tau' \rvert \le \kappa for some κ<1\kappa < 1. By the mean value theorem, ∣τ(u)−τ(v)∣≤κ∣u−v∣\lvert \tau(u) - \tau(v) \rvert \le \kappa \lvert u - v \rvert for u,v∈log⁡Ju, v \in \log J.

(d) Convergence. After one step ρ1∈J\rho_1 \in J by (b), and τ\tau maps log⁡J\log J into itself. By the Banach fixed point theorem on the complete set log⁡J\log J, log⁡ρt→log⁡r^\log\rho_t \to \log\hat r with ∣log⁡ρt−log⁡r^∣≤κt−1∣log⁡ρ1−log⁡r^∣\lvert \log\rho_t - \log\hat r \rvert \le \kappa^{t-1}\lvert \log\rho_1 - \log\hat r \rvert. So the iteration converges geometrically from any start ρ0>0\rho_0 > 0, and the stopping test of line L9 is reached after O(log⁡(1/tol))O(\log(1/\mathrm{tol})) steps. ■\blacksquare

Meng and Wong (1996, Theorem 2) state the convergence and uniqueness; the argument above is a self-contained proof of the same fact.

Claim 5: the root is a consistent estimate of rr

Let the two samples be independent and identically distributed within each sample, with n1,n2→∞n_1, n_2 \to \infty and s1,s2s_1, s_2 fixed, and let the supports overlap, ∫p1p2>0\int p_1 p_2 > 0. For fixed ρ\rho, the law of large numbers gives Ψn(ρ)→ψ(ρ)\Psi_n(\rho) \to \psi(\rho) almost surely, where

ψ(ρ)=E1[ρs1l+s2ρ]−E2[ls1l+s2ρ]=(ρc1−1c2)∫q1q2s1q1+s2ρq2.\psi(\rho) = \mathbb{E}_1\Big[\frac{\rho}{s_1 l + s_2\rho}\Big] - \mathbb{E}_2\Big[\frac{l}{s_1 l + s_2\rho}\Big] = \Big(\frac{\rho}{c_1} - \frac{1}{c_2}\Big)\int \frac{q_1 q_2}{s_1 q_1 + s_2\rho q_2}.

Both expectations are finite because each integrand is bounded by 1/s21/s_2 and 1/s11/s_1. The integral is positive, so ψ(ρ)<0\psi(\rho) < 0 for ρ<r\rho < r and ψ(ρ)>0\psi(\rho) > 0 for ρ>r\rho > r. Fix ε∈(0,1)\varepsilon \in (0, 1). Almost surely, for all large nn, Ψn(r(1−ε))<0<Ψn(r(1+ε))\Psi_n(r(1 - \varepsilon)) < 0 < \Psi_n(r(1 + \varepsilon)), and since Ψn\Psi_n is increasing its root r^\hat r lies in (r(1−ε),r(1+ε))(r(1 - \varepsilon), r(1 + \varepsilon)). So r^→r\hat r \to r almost surely. ■\blacksquare

Complexity

Lines L2 and L3 evaluate q1q_1 and q2q_2 at all nn draws: 2n2n density evaluations. Each pass of L6 and L7 costs Θ(n)\Theta(n) arithmetic, so TT iterations cost Θ(nT)\Theta(nT). The proof shows that the error in log⁡r\log r shrinks by a factor κ<1\kappa < 1 per step, so T=O(log⁡(1/tol))T = O(\log(1/\mathrm{tol})); in the examples TT is 55 to 88 for a tolerance of 10−1210^{-12}. The ratios take Θ(n)\Theta(n) extra space. For a marginal likelihood, the posterior draws come from an MCMC run that usually costs far more than the bridge step.

Properties

  • Deterministic given the draws. All randomness is in the two samples.
  • Not exact. It is a Monte Carlo estimate. Like every ratio estimate, r^\hat r has a bias of order 1/n1/n; log⁡r^\log\hat r has a bias of the same order.
  • Symmetric in the two distributions. Swapping p1p_1 and p2p_2 gives 1/r^1/\hat r for the optimal bridge, which is not true of importance sampling.
  • Robust to tails. The optimal bridge never has infinite first-order variance, because αq1q2≤q1q2/(s1q1)\alpha q_1 q_2 \le q_1 q_2/(s_1 q_1) and ≤q1q2/(s2rq2)\le q_1 q_2/(s_2 r q_2).
  • Needs overlap. The relative error is governed by ∫p1p2/(s1p1+s2p2)\int p_1 p_2/(s_1 p_1 + s_2 p_2), a measure of how much the two densities overlap. When they barely overlap, the error is large for every bridge.

Variants and improvements

  • Geometric bridge. α=1/q1q2\alpha = 1/\sqrt{q_1 q_2} needs no iteration. In the table it is as good as the optimal one, because the proposal is good.
  • Warp bridge sampling. Meng and Schilling (2002) transform the draws, by centring, scaling and symmetrizing, so that the two densities overlap more before the bridge is applied.
  • Path sampling. Use a chain of bridges between p1p_1 and p2p_2, or a continuous path of densities; this is the annealed importance sampling and thermodynamic integration family (Gelman and Meng 1998).
  • MCMC draws. Replace n1n_1 in s1s_1 and s2s_2 by the effective sample size of the posterior draws (Gronau et al. 2017). The estimate stays consistent; the weights are closer to optimal.
  • Error estimates. Plug the draws into the first-order formula of the Correctness section to estimate the relative error, or repeat the whole run several times.
  • Bayes factors directly. With q1q_1 and q2q_2 the unnormalized posteriors of two models on the same parameter space, the bridge estimates the Bayes factor without a proposal. For nested models, the Savage-Dickey density ratio is often simpler.

When to use it

Use bridge sampling for the marginal likelihood when you already have posterior draws, the parameter space is continuous and of moderate dimension, and you can fit a proposal that covers the posterior. It is more accurate than importance sampling from the same proposal and never has its failure mode of infinite variance. The Laplace approximation is cheaper but has an O(1/n)O(1/n) bias. Nested sampling needs no posterior draws but needs a sampler under a likelihood constraint. For multimodal posteriors, or when no proposal overlaps the posterior well, use path sampling, parallel tempering or sequential Monte Carlo. Never use the harmonic mean.

Pitfalls

  • The harmonic mean. Replacing L5 to L10 by the bridge α=1/q1\alpha = 1/q_1 with the prior as p2p_2 gives an exact identity, but its variance is infinite in most models, as the second table shows. Keep L5 to L10 and use a proposal fitted to the posterior.
  • Fitting the proposal on the same draws. If the draws in L2 were also used to fit p2p_2, the two are dependent and the estimate is biased. Fit p2p_2 on one half of the posterior draws and use the other half in L2.
  • A missing Jacobian. If p2p_2 is a normal on log⁡σ\log\sigma or on a logit, then q1q_1 in L2 and L3 must be the posterior density in that scale, Jacobian included. Otherwise L8 converges to the integral of a different function.
  • Overflow. ll is often e−1000e^{-1000} or smaller. Computing L6 and L7 in floating point gives 0/00/0. Keep log⁡l\log l and use log-sum-exp, as the implementation does.
  • Correlated draws counted as independent. With MCMC draws, s1=n1/ns_1 = n_1/n in L1 overweights the posterior sample. Use the effective sample size in L1.
  • Poor overlap. A proposal that is too narrow leaves posterior draws with tiny l2jl_{2j} and huge l1il_{1i}; the error grows quickly. Check the overlap, for example with a heavier-tailed Student tt proposal or by warping.

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.

bridge_sampling.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bridge-sampling/. The authors are listed in prov/TC3WDX.jsonl.
"""Bridge sampling of a ratio of normalizing constants (Meng and Wong 1996).

Two densities p_k = q_k / c_k, k = 1, 2, are known only up to the constants c_k.
Given draws theta_1..theta_n1 from p1 and phi_1..phi_n2 from p2, the bridge
identity

    r = c1 / c2 = E_2[q1 alpha] / E_1[q2 alpha]

holds for every bridge function alpha with 0 < integral of alpha q1 q2 < infinity.
All functions here work with logarithms, because q1 and q2 often differ by
hundreds of orders of magnitude.

For a marginal likelihood, p1 is the posterior with q1 = f(x | theta) pi(theta), so
c1 = Z, and p2 is a normalized proposal density g with c2 = 1. Then r = Z.

The inputs are the log ratios log l = log q1 - log q2 at the two samples:
  log_l1[i] = log q1(theta_i) - log q2(theta_i),  theta_i ~ p1,
  log_l2[j] = log q1(phi_j) - log q2(phi_j),      phi_j ~ p2.

Cost: one pass over the n1 + n2 ratios per iteration, Theta((n1 + n2) T) for T
iterations. The iteration is a contraction in log r, so T = O(log(1/tol)).
"""

import math
from typing import Callable, Sequence


def log_sum_exp(xs: Sequence[float]) -> float:
    """log(sum(exp(x))) without overflow."""
    m = max(xs)
    if m == -math.inf:
        return -math.inf
    return m + math.log(math.fsum(math.exp(x - m) for x in xs))


def log_mean_exp(xs: Sequence[float]) -> float:
    return log_sum_exp(xs) - math.log(len(xs))


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


def optimal_bridge(
    log_l1: Sequence[float],
    log_l2: Sequence[float],
    tol: float = 1e-12,
    max_iter: int = 10000,
    log_r0: float | None = None,
) -> tuple[float, int]:
    """Meng-Wong iteration for the optimal bridge. Returns (log r_hat, iterations).

    Precondition: both samples are non-empty and all log ratios are finite.
    """
    n1, n2 = len(log_l1), len(log_l2)
    s1 = n1 / (n1 + n2)  # @line L1
    s2 = n2 / (n1 + n2)
    ls1, ls2 = math.log(s1), math.log(s2)
    # L2 and L3: the caller passes log l1 and log l2.
    log_r = log_mean_exp(log_l2) if log_r0 is None else log_r0  # @line L4
    for it in range(1, max_iter + 1):  # @line L5
        # log of (1/n2) sum_j l2j / (s1 l2j + s2 r)
        num = log_mean_exp([b - _log_add(ls1 + b, ls2 + log_r) for b in log_l2])  # @line L6
        # log of (1/n1) sum_i 1 / (s1 l1i + s2 r)
        den = log_mean_exp([-_log_add(ls1 + a, ls2 + log_r) for a in log_l1])  # @line L7
        new = num - den  # @line L8
        if abs(new - log_r) <= tol:  # @line L9
            return new, it
        log_r = new
    return log_r, max_iter  # @line L10


def bridge_from_densities(
    log_q1: Callable[[float], float],
    log_q2: Callable[[float], float],
    draws1: Sequence,
    draws2: Sequence,
    tol: float = 1e-12,
) -> float:
    """log r_hat from the two samples and the two log densities (lines L2 and L3, then L4 to L10).

    draws1 come from p1 = q1/c1 and draws2 from p2 = q2/c2. Cost: 2 (n1 + n2) density
    evaluations plus the iteration.
    """
    log_l1 = [log_q1(t) - log_q2(t) for t in draws1]  # @line L2
    log_l2 = [log_q1(t) - log_q2(t) for t in draws2]  # @line L3
    return optimal_bridge(log_l1, log_l2, tol)[0]


def estimating_function(log_r: float, log_l1: Sequence[float], log_l2: Sequence[float]) -> float:
    """(1/n1) sum r / (s1 l1i + s2 r) - (1/n2) sum l2j / (s1 l2j + s2 r).

    Strictly increasing in r, from -1/s1 at r = 0 to 1/s2 as r grows; its unique root
    is the fixed point of the iteration. Used by the tests and by bisection_bridge.
    """
    n1, n2 = len(log_l1), len(log_l2)
    s1, s2 = n1 / (n1 + n2), n2 / (n1 + n2)
    left = math.fsum(1.0 / (s1 * math.exp(a - log_r) + s2) for a in log_l1) / n1
    right = math.fsum(1.0 / (s1 + s2 * math.exp(log_r - b)) for b in log_l2) / n2
    return left - right


def bisection_bridge(log_l1: Sequence[float], log_l2: Sequence[float], tol: float = 1e-13) -> float:
    """The root of estimating_function by bisection in log r: an independent oracle."""
    lo = min(min(log_l1), min(log_l2)) - 1.0
    hi = max(max(log_l1), max(log_l2)) + 1.0
    while estimating_function(lo, log_l1, log_l2) > 0:
        lo -= 10.0
    while estimating_function(hi, log_l1, log_l2) < 0:
        hi += 10.0
    while hi - lo > tol:
        mid = 0.5 * (lo + hi)
        if estimating_function(mid, log_l1, log_l2) < 0:
            lo = mid
        else:
            hi = mid
    return 0.5 * (lo + hi)


def general_bridge(
    log_q1_at_1: Sequence[float],
    log_q2_at_1: Sequence[float],
    log_q1_at_2: Sequence[float],
    log_q2_at_2: Sequence[float],
    log_alpha: Callable[[float, float], float],
) -> float:
    """log of r_hat = mean_j q1(phi_j) alpha(phi_j) / mean_i q2(theta_i) alpha(theta_i).

    log_alpha(log_q1, log_q2) gives log alpha at a point from the two log densities there.
    alpha = 1/q2 gives importance sampling with proposal p2; alpha = 1/q1 gives reciprocal
    importance sampling (the harmonic mean when p2 is the prior); alpha = 1/sqrt(q1 q2)
    gives the geometric bridge.
    """
    num = log_mean_exp([a + log_alpha(a, b) for a, b in zip(log_q1_at_2, log_q2_at_2)])
    den = log_mean_exp([b + log_alpha(a, b) for a, b in zip(log_q1_at_1, log_q2_at_1)])
    return num - den


def importance_sampling(log_q1_at_2: Sequence[float], log_q2_at_2: Sequence[float]) -> float:
    """log of mean_j q1(phi_j) / q2(phi_j) with phi_j ~ p2: the bridge with alpha = 1/q2."""
    return log_mean_exp([a - b for a, b in zip(log_q1_at_2, log_q2_at_2)])


def harmonic_mean(log_lik_at_post: Sequence[float]) -> float:
    """Harmonic mean estimate of log Z from log f(x | theta_i), theta_i ~ posterior.

    It is the bridge with p2 = prior and alpha = 1/q1: 1/Z = E_post[1/f(x | theta)].
    Its variance is often infinite; see the page.
    """
    return -log_mean_exp([-v for v in log_lik_at_post])
test_bridge_sampling.py 176 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bridge-sampling/. The authors are listed in prov/TC3WDX.jsonl.
"""Tests for bridge sampling: the exact identity, the iteration, and log Z of conjugate models."""

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

from bridge_sampling import (
    bisection_bridge,
    bridge_from_densities,
    estimating_function,
    general_bridge,
    harmonic_mean,
    importance_sampling,
    optimal_bridge,
)


def lbeta(a, b):
    return math.lgamma(a) + math.lgamma(b) - math.lgamma(a + b)


class TestIdentityExact(unittest.TestCase):
    def test_bridge_identity_on_finite_sets(self):
        # p_k = q_k / c_k on a finite set; expectations are exact sums in Fractions.
        rng = random.Random(10)
        for _ in range(500):
            m = rng.randint(1, 6)
            q1 = [F(rng.randint(0, 9)) for _ in range(m)]
            q2 = [F(rng.randint(0, 9)) for _ in range(m)]
            alpha = [F(rng.randint(1, 9), rng.randint(1, 9)) for _ in range(m)]
            if sum(q1) == 0 or sum(q2) == 0:
                continue
            c1, c2 = sum(q1), sum(q2)
            overlap = sum(a * u * v for a, u, v in zip(alpha, q1, q2))
            if overlap == 0:
                continue
            e2 = sum(u * a * v / c2 for u, a, v in zip(q1, alpha, q2))  # E_2[q1 alpha]
            e1 = sum(v * a * u / c1 for u, a, v in zip(q1, alpha, q2))  # E_1[q2 alpha]
            self.assertEqual(e2 / e1, c1 / c2)

    def test_importance_sampling_is_the_bridge_with_alpha_one_over_q2(self):
        rng = random.Random(11)
        for _ in range(200):
            n1, n2 = rng.randint(1, 6), rng.randint(1, 6)
            a1 = [rng.uniform(-5, 5) for _ in range(n1)]
            b1 = [rng.uniform(-5, 5) for _ in range(n1)]
            a2 = [rng.uniform(-5, 5) for _ in range(n2)]
            b2 = [rng.uniform(-5, 5) for _ in range(n2)]
            g = general_bridge(a1, b1, a2, b2, lambda a, b: -b)
            self.assertAlmostEqual(g, importance_sampling(a2, b2), places=12)

    def test_harmonic_mean_is_the_bridge_with_prior_and_alpha_one_over_q1(self):
        rng = random.Random(12)
        for _ in range(200):
            n1, n2 = rng.randint(1, 6), rng.randint(1, 6)
            loglik1 = [rng.uniform(-5, 0) for _ in range(n1)]
            logprior1 = [rng.uniform(-3, 0) for _ in range(n1)]
            loglik2 = [rng.uniform(-5, 0) for _ in range(n2)]
            logprior2 = [rng.uniform(-3, 0) for _ in range(n2)]
            # q1 = lik * prior, q2 = prior. With alpha = 1/q1 the numerator is the mean of 1
            # over the prior draws, so only the posterior draws matter.
            a1 = [u + v for u, v in zip(loglik1, logprior1)]
            a2 = [u + v for u, v in zip(loglik2, logprior2)]
            g = general_bridge(a1, logprior1, a2, logprior2, lambda a, b: -a)
            self.assertAlmostEqual(g, harmonic_mean(loglik1), places=12)


class TestIteration(unittest.TestCase):
    def test_estimating_function_is_increasing_with_the_right_limits(self):
        rng = random.Random(20)
        l1 = [rng.uniform(-3, 3) for _ in range(5)]
        l2 = [rng.uniform(-3, 3) for _ in range(7)]
        s1, s2 = 5 / 12, 7 / 12
        vals = [estimating_function(u / 4, l1, l2) for u in range(-60, 61)]
        self.assertTrue(all(vals[i] < vals[i + 1] for i in range(len(vals) - 1)))
        self.assertAlmostEqual(estimating_function(-60, l1, l2), -1 / s1, places=6)
        self.assertAlmostEqual(estimating_function(60, l1, l2), 1 / s2, places=6)

    def test_iteration_equals_the_bisection_root(self):
        rng = random.Random(21)
        for _ in range(500):
            n1, n2 = rng.randint(1, 8), rng.randint(1, 8)
            shift = rng.uniform(-50, 50)
            l1 = [shift + rng.gauss(0, 2) for _ in range(n1)]
            l2 = [shift + rng.gauss(0, 2) for _ in range(n2)]
            start = rng.uniform(-100, 100)
            got, its = optimal_bridge(l1, l2, log_r0=start)
            self.assertLess(its, 10000)
            self.assertAlmostEqual(got, bisection_bridge(l1, l2), places=8)

    def test_constant_ratio_gives_the_exact_answer(self):
        # If q1 / q2 = c everywhere, every bridge returns c in one step.
        got, _ = optimal_bridge([2.5] * 4, [2.5] * 9)
        self.assertAlmostEqual(got, 2.5, places=12)


class TestConjugateModels(unittest.TestCase):
    def test_beta_binomial_trace_of_the_page(self):
        # 3 successes in 10 trials, prior Beta(2, 2), logit scale; proposal = the Laplace normal.
        m, s = -0.587787, 0.557773
        exact = lbeta(5, 9) - lbeta(2, 2)

        def lq1(t):
            return -5 * math.log1p(math.exp(-t)) - 9 * math.log1p(math.exp(t)) - lbeta(2, 2)

        def lq2(t):
            return -0.5 * math.log(2 * math.pi * s * s) - 0.5 * (t - m) ** 2 / (s * s)

        rng = random.Random(5)
        th = []
        for _ in range(8):
            p = rng.betavariate(5, 9)
            th.append(math.log(p / (1 - p)))
        ph = [rng.gauss(m, s) for _ in range(8)]
        got, its = optimal_bridge([lq1(t) - lq2(t) for t in th], [lq1(t) - lq2(t) for t in ph])
        self.assertAlmostEqual(got, -7.024985, places=5)
        self.assertLessEqual(its, 8)
        self.assertAlmostEqual(bridge_from_densities(lq1, lq2, th, ph), got, places=12)
        self.assertAlmostEqual(exact, -6.977748, places=6)

        # 1000 + 1000 draws, 40 repetitions: every optimal bridge estimate within 0.02 nats.
        errs = []
        for _ in range(40):
            th = []
            for _ in range(1000):
                p = rng.betavariate(5, 9)
                th.append(math.log(p / (1 - p)))
            ph = [rng.gauss(m, s) for _ in range(1000)]
            got, _ = optimal_bridge([lq1(t) - lq2(t) for t in th], [lq1(t) - lq2(t) for t in ph])
            errs.append(got - exact)
        self.assertLess(max(abs(e) for e in errs), 0.02)
        self.assertLess(abs(statistics.mean(errs)), 0.003)

    def test_normal_normal_bridge_beats_harmonic_mean(self):
        # x_i ~ N(theta, 1), theta ~ N(0, 10^2), n = 20: n tau^2 >= sigma^2, so the
        # harmonic mean has infinite variance. Exact log Z is in closed form.
        rng = random.Random(1)
        n, tau = 20, 10.0
        xs = [round(rng.gauss(1.0, 1.0), 2) for _ in range(n)]
        xb = sum(xs) / n
        s2 = sum((x - xb) ** 2 for x in xs)
        v = 1 / (n + 1 / tau**2)
        m = v * sum(xs)
        exact = (-0.5 * n * math.log(2 * math.pi) - 0.5 * s2 - 0.5 * math.log(1 + n * tau**2)
                 - 0.5 * n * xb**2 / (1 + n * tau**2))
        self.assertAlmostEqual(exact, -31.327583, places=5)

        def llik(t):
            return -0.5 * n * math.log(2 * math.pi) - 0.5 * (s2 + n * (t - xb) ** 2)

        def lprior(t):
            return -0.5 * math.log(2 * math.pi * tau**2) - 0.5 * t * t / tau**2

        sd2 = math.sqrt(2 * v)

        def lq2(t):
            return -0.5 * math.log(2 * math.pi * sd2 * sd2) - 0.5 * (t - m) ** 2 / sd2**2

        hm_errs, br_errs = [], []
        for _ in range(20):
            th = [rng.gauss(m, math.sqrt(v)) for _ in range(2000)]
            ph = [rng.gauss(m, sd2) for _ in range(2000)]
            hm_errs.append(harmonic_mean([llik(t) for t in th]) - exact)
            br = optimal_bridge([llik(t) + lprior(t) - lq2(t) for t in th], [llik(t) + lprior(t) - lq2(t) for t in ph])[0]
            br_errs.append(br - exact)
        self.assertLess(max(abs(e) for e in br_errs), 0.03)
        # The harmonic mean overestimates Z by more than one nat in every run.
        self.assertGreater(min(hm_errs), 1.0)


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

History

Bennett (1976) found the acceptance ratio method for the difference of free energies of two physical systems, with the weighting that is optimal to first order. Meng and Wong (1996) brought the idea into statistics as bridge sampling, proved the identity for general bridges, derived the optimal bridge by the Cauchy-Schwarz inequality, and gave the iterative scheme with a convergence theorem. Gelman and Meng (1998) placed it between importance sampling and path sampling. Meng and Schilling (2002) added warping. The harmonic mean estimator of Newton and Raftery (1994) was criticized in the discussion of that paper for its instability, and its infinite variance in common models is a standard warning. Gronau and coauthors (2017) wrote a tutorial and the R package bridgesampling, which made the method a routine tool for Bayes factors.

References

  1. Meng and Wong 1996, pages 831 to 860: Section 2 (identity (2.3) and condition (2.1); importance sampling as alpha = 1/q2 and the generalized harmonic mean as special cases), Section 3 (relative mean squared error (3.1), its first-order form (3.2), Theorem 1 with the optimal bridge and its proof by Cauchy-Schwarz), Section 4 (the iterative scheme (4.1) and Theorem 2 on its convergence)
  2. Charles H. Bennett, Efficient estimation of free energy differences from Monte Carlo data, Journal of Computational Physics 22(2), 1976, pages 245 to 268 (the acceptance ratio method and its optimal weighting function; general locator)
  3. Andrew Gelman and Xiao-Li Meng, Simulating normalizing constants: from importance sampling to bridge sampling to path sampling, Statistical Science 13(2), 1998, pages 163 to 185 (bridge sampling between importance sampling and path sampling; general locator)
  4. Quentin F. Gronau, Alexandra Sarafoglou, Dora Matzke and others, A tutorial on bridge sampling, Journal of Mathematical Psychology 81, 2017, pages 80 to 97 (the beta-binomial running example, the normal proposal, splitting the posterior draws, the effective sample size in place of n1; general locator)
  5. Xiao-Li Meng and Stephen Schilling, Warp bridge sampling, Journal of Computational and Graphical Statistics 11(3), 2002, pages 552 to 586 (transforming the draws so that the two densities overlap more; general locator)
  6. Michael A. Newton and Adrian E. Raftery, Approximate Bayesian inference with the weighted likelihood bootstrap, Journal of the Royal Statistical Society Series B 56(1), 1994, pages 3 to 48 with the discussion (the harmonic mean estimator of the marginal likelihood and its instability; 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.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