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
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Xiao Li Meng, Wing Hung Wong, Charles H. Bennett, 1996
Bridge sampling estimates a ratio of two normalizing constants from draws of the two distributions. Its main use in Bayesian statistics is the marginal likelihood : take the posterior as the first distribution, with and , and a normalized proposal density as the second, with . The method rests on the identity , true for every bridge function . Importance sampling is the case , and the harmonic mean estimator is the case with the prior as . The bridge that minimizes the first-order error is ; it depends on , 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 that can be evaluated, with unknown constants and normalized densities . Draws from and from , for example posterior draws from Metropolis-Hastings and independent draws from a normal proposal.
Output. An estimate of . For a marginal likelihood, ; for two models, the difference of two such estimates is the log Bayes factor.
The bridge identity. For every with ,
because both expectations are integrals of , divided by and . Replacing the two expectations by sample means gives the estimate .
The algorithm
Write , , , and . With the optimal bridge , the factor cancels, and the estimate becomes the fixed point of the map on line L8.
BRIDGE(θ₁..θ_{n₁} ~ p₁, φ₁..φ_{n₂} ~ p₂, q₁, q₂)- 1
s₁ ← n₁/(n₁ + n₂); s₂ ← n₂/(n₁ + n₂) - 2
l₁ᵢ ← q₁(θᵢ)/q₂(θᵢ) for i = 1..n₁ ▷ kept as logarithms - 3
l₂ⱼ ← q₁(φⱼ)/q₂(φⱼ) for j = 1..n₂ - 4
r ← (1/n₂) Σⱼ l₂ⱼ ▷ start: importance sampling - 5
repeat - 6
N ← (1/n₂) Σⱼ l₂ⱼ / (s₁ l₂ⱼ + s₂ r) - 7
D ← (1/n₁) Σᵢ 1 / (s₁ l₁ᵢ + s₂ r) - 8
r_new ← N / D - 9
if |log r_new - log r| ≤ tol then return log r_new - 10
r ← r_new
Lines L2 and L3 evaluate both densities at both samples, density evaluations, which is usually the main cost. The ratios can be or , so the code keeps 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 , after dividing by . L9 stops when the log estimate moves by less than the tolerance.
Choosing 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 . 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 successes in trials and the prior Beta(2, 2), in the logit scale : , with the Jacobian included. The exact value is . For we take the Laplace normal of the Laplace approximation page. With random.Random(5), : the are logits of exact Beta(5, 9) draws, and the are normal draws.
| or | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|
| 0.6122 | 1.1076 | |||||||
| 0.1314 | 0.2517 | |||||||
All ratios are close to , because the Laplace normal is close to the posterior. The iteration, with :
| step | (L6) | (L7) | (L8) |
|---|---|---|---|
| start (L4) | |||
| 1 | 0.999875 | 1124.111842 | |
| 2 | 1.006906 | 1132.142279 | |
| 3 | 1.006962 | 1132.205476 | |
| 4 to 6 | 1.006962 | 1132.205977 |
The test of L9 with tolerance stops at step 6. The estimate is off by nats from 16 draws. Bisection on the estimating equation of the proof gives the same root, .
Four estimators of the same . Same model, repetitions with random.Random(2024), draws per estimate: the bridges use posterior and proposal draws, importance sampling uses proposal draws, and the harmonic mean uses posterior draws.
| estimator | bridge function | mean error (nats) | standard deviation | largest error |
|---|---|---|---|---|
| importance sampling | 0.0035 | 0.018 | ||
| harmonic mean | , prior as | 0.0542 | 0.1271 | 0.518 |
| geometric bridge | 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: .
The harmonic mean does not improve with more draws. Take for and the prior , with data from random.Random(1); the exact value is . The bridge uses a proposal , where is the exact posterior. Twenty repetitions per row:
| draws 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.0090 | |
| 10000 | 2.479 | 0.484 | 0.0000 | 0.0028 |
| 100000 | 2.389 | 0.258 |
The bridge error falls like . The harmonic mean overestimates by more than two nats even with draws. In the normal-normal model with noise variance and prior variance , is finite only when , that is, when the prior is narrower than the noise of one mean. Here and . The posterior rarely visits the region where the likelihood is small, and that region carries most of . 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:
- The identity for every bridge function with , and the consistency of for a fixed by the law of large numbers.
- Special cases. gives importance sampling (support of inside that of ); gives reciprocal importance sampling, and with the prior as the harmonic mean identity .
- The optimal bridge, under an approximation. If all draws are independent, the first-order delta method gives (Meng and Wong 1996, equation (3.2)). By the Cauchy-Schwarz inequality this is minimized by , with minimum . The minimum is always finite, even when importance sampling and the harmonic mean have infinite variance.
- The iteration. The fixed points of L8 are the roots of , which is strictly increasing from to , so there is exactly one. The map sends into a compact interval, and in the log scale its derivative lies in , so it is a contraction there and converges geometrically from any start.
- Consistency of the root. With independent draws and fixed , the root converges to almost surely, because the sample estimating function converges to 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 and only approximately. The errors in the tables are measured.
Proof: The bridge identity, the optimal bridge, and the convergence of the iterationfull
Setting. For let be a probability density on (with respect to a common measure), where can be evaluated and is unknown. The target is . A bridge function is a measurable with
is the expectation under . The draws are and . Write , , and , with and .
Claim 1: the bridge identity
For every bridge function , .
Proof. and . Both integrands are , which vanishes outside , so the two integrals are and with by (1). Their ratio is .
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, and almost surely, because both expectations are finite by (1). So almost surely.
Claim 2: importance sampling and the harmonic mean are bridges
(a) If and on , then and the identity reads : importance sampling of with proposal . Condition (1) holds: .
(b) If and on , then and , so : reciprocal importance sampling, the estimator of Gelfand and Dey when is a normalized density. Condition (1) holds: . With and , a normalized prior (), this is , the harmonic mean identity. The identity is exact, but the variance of the estimate is finite only if , which needs to have lighter tails than ; the prior usually has heavier tails than the posterior.
Claim 3: the optimal bridge under the first-order approximation
The approximation. Assume that all draws are independent, that , and measure the error by the relative mean squared error . Write with and , and . Then , , and and are independent with
The first-order delta method for the ratio of independent averages gives . With and this is
This is equation (3.2) of Meng and Wong (1996). It is an approximation, exact only to the first order in . The claim below is about the right side of (2).
Claim. Over all bridge functions, the right side of (2) is minimized by on , and the minimum is
Proof. Let on . By the Cauchy-Schwarz inequality,
So the ratio in (2) is at least . Equality in Cauchy-Schwarz holds exactly when the two factors are proportional, that is , or where . The value of where does not enter (2).
Two consequences. First, 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, depends on the unknown .
Claim 4: the iteration has one fixed point, and it converges to it
Plug , with a trial value in place of , into . Divide the numerator and the denominator inside each sum by :
The algorithm iterates (lines L5 to L9). Assume all are positive and finite, and let $l_- $ and be the smallest and the largest of them.
(a) The fixed points are the roots of one increasing function. Since , if and only if , where
Each term has derivative , and each term has derivative . So is strictly increasing on , with limit as and as . By the intermediate value theorem it has exactly one root , and has exactly one fixed point.
(b) maps into a compact interval. For and , . Every denominator lies between and , so
So maps into .
(c) is a contraction in the log scale on . Let and . Then
where and are positive weights that sum to . Each fraction lies in , so each weighted mean lies in , and . is continuous, so on the compact interval it satisfies for some . By the mean value theorem, for .
(d) Convergence. After one step by (b), and maps into itself. By the Banach fixed point theorem on the complete set , with . So the iteration converges geometrically from any start , and the stopping test of line L9 is reached after steps.
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
Let the two samples be independent and identically distributed within each sample, with and fixed, and let the supports overlap, . For fixed , the law of large numbers gives almost surely, where
Both expectations are finite because each integrand is bounded by and . The integral is positive, so for and for . Fix . Almost surely, for all large , , and since is increasing its root lies in . So almost surely.
Complexity
Lines L2 and L3 evaluate and at all draws: density evaluations. Each pass of L6 and L7 costs arithmetic, so iterations cost . The proof shows that the error in shrinks by a factor per step, so ; in the examples is to for a tolerance of . The ratios take 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, has a bias of order ; has a bias of the same order.
- Symmetric in the two distributions. Swapping and gives for the optimal bridge, which is not true of importance sampling.
- Robust to tails. The optimal bridge never has infinite first-order variance, because and .
- Needs overlap. The relative error is governed by , 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. 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 and , or a continuous path of densities; this is the annealed importance sampling and thermodynamic integration family (Gelman and Meng 1998).
- MCMC draws. Replace in and 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 and 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 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 with the prior as 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 , the two are dependent and the estimate is biased. Fit on one half of the posterior draws and use the other half in L2.
- A missing Jacobian. If is a normal on or on a logit, then 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. is often or smaller. Computing L6 and L7 in floating point gives . Keep and use log-sum-exp, as the implementation does.
- Correlated draws counted as independent. With MCMC draws, 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 and huge ; the error grows quickly. Check the overlap, for example with a heavier-tailed Student 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.
# 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
- 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)
- 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)
- 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)
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag TC3WDX Edit this page History Report an error Markdown