Algorithmresearch
Preconditioned Crank-Nicolson MCMC
Also called pCN sampler, pCN, preconditioned Crank-Nicolson.
A Metropolis-Hastings sampler whose proposal keeps a Gaussian prior invariant, so its acceptance rate does not fall as the discretization is refined.
- Time
- Θ(N (n + D + T)) worst · average · best
- Space
- Θ(N n) extra
- Where
- D = the cost of one prior draw; N = the number of steps; T = the cost of one misfit evaluation; n = the dimension of the discretized unknown
- Model
- Real RAM
- Properties
- dimension robustexact invariancenot needs prior densityrandomized
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Simon L. Cotter, Gareth O. Roberts, Andrew M. Stuart, David White, 2013
Preconditioned Crank-Nicolson (pCN) is a Metropolis-Hastings method for posteriors of the form "Gaussian prior times likelihood". From the state it proposes , where is a fresh draw from the centred prior and is a step size, and it accepts with probability , where is the data misfit. The proposal leaves the prior invariant, so the prior cancels from the acceptance ratio and only the likelihood is left. This makes the method well defined on a function space, and its acceptance rate stays the same when the mesh of the discretization is refined. Random-walk Metropolis, in contrast, needs a step size that goes to zero as the dimension grows. Cotter, Roberts, Stuart and White (2013) introduced the name and the function-space view; Hairer, Stuart and Vollmer (2014) proved a dimension-independent spectral gap.
In plain words
You want samples of an unknown function that fit the data, and you started with a Gaussian guess about what such functions look like. A plain random walk adds random noise to the current function. In fine resolution almost every such step makes the function rougher than the prior allows, so almost all steps are rejected. pCN instead shrinks the current function a little toward the prior mean and adds a fresh prior-like function. If there were no data, every such step would be accepted. So the only reason to reject a step is that it fits the data worse, and that does not get harder when you refine the grid.
The problem
Sample the posterior of a Bayesian inverse problem with a Gaussian prior and misfit :
The unknown may be a vector in that comes from discretizing a function. The input is a way to evaluate , a way to draw from , a start , a step size and a number of steps . The output is a Markov chain whose law converges to , and the rate of accepted moves.
The algorithm
PCN(Phi, draw_prior, u_0, beta, N, m_0) ▷ prior N(m_0, C), draw_prior returns xi ~ N(0, C)- 1
u ← u_0, Phi_u ← Phi(u) - 2
for k = 1, ..., N - 3
xi ← draw_prior() - 4
v ← m_0 + sqrt(1 - beta²) (u - m_0) + beta xi - 5
Phi_v ← Phi(v) - 6
draw U uniform on (0, 1]; if log U < Phi_u - Phi_v - 7
u ← v, Phi_u ← Phi_v, count the move as accepted - 8
append u to the chain - 9
return the chain and (number of accepted moves) / N
Line L1 evaluates the misfit at the start and keeps it, so each step needs one new evaluation. Line L3 draws from the prior covariance: with a Karhunen-Loeve basis this is a sum of basis functions with independent Gaussian weights, and with a dense covariance it is with a Cholesky factor and . Line L4 is the proposal. If has the prior law, so does , because . Lines L5 and L6 accept with probability . The prior density is not in this ratio. Line L8 stores the current state, which is the old one after a rejection.
The name comes from the Crank-Nicolson scheme. Discretize the Langevin equation , which has the prior as its invariant law, with the implicit midpoint rule (Crank-Nicolson) and time step . This gives line L4 with and . The covariance in the noise term is the preconditioner. The case is the independence sampler with the prior as proposal.
Example
A scalar problem: with , , prior and . The posterior is ; see the Bayesian inverse problem page. Each run has 20000 steps from with random.Random(1), and the statistics drop the first 1000 states.
| acceptance | sample mean | sample variance | |
|---|---|---|---|
| 0.1 | 0.935 | 0.997 | 0.182 |
| 0.3 | 0.808 | 0.963 | 0.196 |
| 0.5 | 0.689 | 0.967 | 0.195 |
| 0.9 | 0.453 | 0.958 | 0.204 |
| 1.0 | 0.326 | 0.959 | 0.203 |
Small gives a high acceptance rate but small moves, and its estimates are the worst here. A high acceptance rate alone does not mean good mixing.
The effect of the dimension: prior variances for (a Karhunen-Loeve type prior), one observation of with value and noise standard deviation , , 2000 steps, random.Random(2). Random-walk Metropolis uses the proposal with the same .
| pCN acceptance | random-walk acceptance | |
|---|---|---|
| 10 | 0.384 | 0.294 |
| 100 | 0.371 | 0.043 |
| 1000 | 0.376 | 0.000 |
pCN keeps its rate. The random walk loses it, because grows like , and the prior ratio in its acceptance test goes to zero. These are measurements with fixed seeds.
Correctness
The proof is in proofs/correctness.md. The loop has passes, so the method stops. If and is made by line L4, then and have the same Gaussian law, because their cross-covariance is symmetric. So the proposal is reversible for the prior. Then
is symmetric in , which is detailed balance, and the posterior is invariant. In finite dimension with finite the chain is irreducible, and averages converge to posterior expectations. All this is a theorem. That the convergence speed does not depend on is a deeper theorem of Hairer, Stuart and Vollmer (2014), under conditions on , and is cited here; the tables above are measurements.
Proof: The pCN chain stops after the given number of steps and leaves the posterior invariantfull
Setting. is a Gaussian prior on with symmetric positive definite, is measurable, and is finite and positive. The target is the posterior . Fix and put . The proposal kernel is the law of with , which is line L4. The proofs below use only Gaussian measures and densities with respect to , so they hold word for word on a separable Hilbert space with a trace-class .
Claim 1 (termination and output). For steps, the procedure stops after exactly passes of lines L3 to L8, returns a list of states, and an acceptance rate in .
Proof. Line L2 runs a loop of fixed length . Each pass draws one prior sample (L3), forms one proposal (L4), evaluates once (L5), and does a constant amount of other work, so it ends if ends. Line L8 appends one state per pass, and the counter of accepted moves is between and . Line L9 returns.
Claim 2 (the proposal keeps the prior and is reversible for it). If and , then and have the same law. In particular , and .
Proof. Put and , with and independent. The pair is jointly Gaussian with mean zero, and
The last matrix is symmetric, so has the same covariance blocks as . A centred Gaussian law is fixed by its covariance, so the two pairs have the same law. Shifting by gives the claim.
Claim 3 (the acceptance test). Given and , line L6 accepts with probability .
Proof. rng.random() is uniform on , so $U = 1 - $ rng.random() is uniform on and is finite. With , the test is the event , whose probability is .
Claim 4 (detailed balance and invariance). The transition kernel of one pass,
satisfies . So if the state has law before a pass, it has law after it.
Proof. For the moving part,
The scalar factor is symmetric in , and by Claim 2 so is the measure . Hence the moving part is symmetric. The staying part lives on the diagonal and is symmetric too. Integrating the detailed balance relation over gives for every measurable .
By Claim 3, lines L4 to L7 draw from , and line L8 stores the new state, so the stored chain is a Markov chain with kernel and invariant law . The prior density never enters the acceptance ratio. This is why the method is defined on a function space, where has no Lebesgue density.
Claim 5 (averages converge in finite dimension). Let be finite and be finite everywhere. Then for every -integrable and -almost every start , almost surely.
Proof. The proposal has a Gaussian density that is positive everywhere, because and is positive definite, and for all because is finite. So for every set with , which has positive Lebesgue measure, from every . The chain is -irreducible. It has the invariant probability measure by Claim 4. A -irreducible chain with an invariant probability measure satisfies the law of large numbers for -almost every start; this is a standard theorem on Markov chains (Tierney 1994, Meyn and Tweedie).
The theorem says nothing about the speed. The speed is what distinguishes pCN from random-walk Metropolis: Hairer, Stuart and Vollmer (2014) prove a spectral gap for pCN that does not depend on the dimension, under conditions on . That result is cited, not proved here, and the test of the dimension effect in the implementation is a measurement.
Complexity
Each step does one prior draw (line L3), one linear combination of length (line L4) and one misfit evaluation (line L5). With the cost of a draw and that of , steps cost . A draw costs with a diagonal or Karhunen-Loeve prior and with a dense Cholesky factor, which costs once. In inverse problems is usually a forward PDE solve and dominates everything. Storing the chain needs space; running averages need .
Properties
- Exact: the posterior is invariant for every , with no discretization bias from the Crank-Nicolson step.
- Prior-reversible proposal: with every proposal is accepted.
- Robust to mesh refinement: the acceptance rate and, under conditions, the spectral gap do not depend on the dimension of the discretization.
- Needs only and prior draws. No gradient, and no prior density.
- Scale of : acceptance rates of 0.2 to 0.4 are a common target; is tuned in a short pilot run.
Variants and improvements
- Non-centred priors. Line L4 with as written; for a prior the misfit is unchanged.
- Gradient versions. pCN-Langevin (pCNL) adds a drift term with , the analogue of MALA, and stays well defined on function space (Cotter et al. 2013).
- Geometry-aware versions. Replace in the proposal by a covariance adapted to the posterior, such as a Laplace approximation at the MAP point, so that the step is large in directions the data do not inform and small in those they do. Dimension-independent likelihood-informed (DILI) MCMC and infinite-dimensional manifold methods follow this idea.
- Hierarchical priors. If the prior has its own hyperparameters, update them in a Gibbs step, with care, since the prior and the hyperparameter are strongly coupled in high dimension.
- Multilevel and delayed acceptance. Evaluate a cheap coarse model first and the expensive one only if the coarse step passes.
When to use it
Use pCN when the prior is Gaussian, the unknown is a discretized function, and you want a simple sampler that keeps working when the mesh is refined, for example for PDE-constrained inverse problems with a Gaussian random field prior. It needs no gradients. If the data are very informative, the posterior is much narrower than the prior in some directions, must be small, and mixing is slow; then use a geometry-aware variant, Hamiltonian Monte Carlo, or randomize-then-optimize. For non-Gaussian priors, transform them to a Gaussian first, or use another method.
Pitfalls
- Using the prior density in the test of line L6. The ratio must be only. Adding the prior ratio counts the prior twice and samples the wrong law.
- Drawing in line L3 from the wrong covariance, for example when the prior is . Then the proposal is no longer prior-reversible, and the chain samples the wrong law.
- Forgetting the mean in line L4. With the proposal must shrink , not .
- Recomputing in every step instead of keeping it from line L1 or L7. This doubles the cost when is a PDE solve.
- Taking the acceptance rate from line L9 as a measure of quality. Small gives a high rate and slow mixing; use the effective sample size.
- Using
log(random())in line L6 when the generator can return 0. Draw in .
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
# Shared helper of the imaging and inverse problems pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Dense linear algebra on lists of rows (float, complex or Fraction entries).
A matrix is a list of rows. A vector is a list of numbers. The inner product
is <u, v> = sum_i conj(u_i) v_i, linear in the second argument, so that the
adjoint A^H satisfies <A x, y> = <x, A^H y>.
"""
import math
def _flat(x):
"""Flatten a list of rows (an image) into one list; a vector is returned as is."""
if x and isinstance(x[0], (list, tuple)):
return [v for row in x for v in row]
return x
def zeros(m, n):
"""The m x n zero matrix."""
return [[0.0] * n for _ in range(m)]
def eye(n):
"""The n x n identity matrix."""
out = zeros(n, n)
for i in range(n):
out[i][i] = 1.0
return out
def transpose(a):
"""A^T."""
return [list(col) for col in zip(*a)]
def conj_transpose(a):
"""A^H, the conjugate transpose."""
return [[v.conjugate() for v in col] for col in zip(*a)]
def matmul(a, b):
"""The product A B."""
bt = list(zip(*b))
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def matvec(a, x):
"""The product A x."""
return [sum(v * w for v, w in zip(row, x)) for row in a]
def rmatvec(a, y):
"""The product A^H y."""
n = len(a[0]) if a else 0
out = [0.0] * n
for row, yi in zip(a, y):
if yi == 0:
continue
for j, v in enumerate(row):
out[j] += v.conjugate() * yi
return out
def dot(u, v):
"""<u, v> = sum_i conj(u_i) v_i. Images (lists of rows) are flattened."""
return sum(a.conjugate() * b for a, b in zip(_flat(u), _flat(v)))
def norm2(x):
"""The Euclidean norm. Images (lists of rows) are flattened."""
return math.sqrt(sum(abs(v) ** 2 for v in _flat(x)))
def solve(a, b):
"""Solve A x = b by Gaussian elimination with partial pivoting.
b is a vector or a matrix (a list of rows). A must be square and
nonsingular; a zero pivot raises ValueError. Fractions stay exact.
"""
n = len(a)
vec = not (b and isinstance(b[0], (list, tuple)))
rhs = [[bi] for bi in b] if vec else [list(r) for r in b]
m = [list(row) + rhs[i] for i, row in enumerate(a)]
w = len(m[0])
for c in range(n):
p = max(range(c, n), key=lambda r: abs(m[r][c]))
if m[p][c] == 0:
raise ValueError("singular matrix")
m[c], m[p] = m[p], m[c]
piv = m[c][c]
for r in range(c + 1, n):
f = m[r][c] / piv
if f != 0:
mr, mc = m[r], m[c]
for j in range(c, w):
mr[j] -= f * mc[j]
x = [[0.0] * (w - n) for _ in range(n)]
for r in range(n - 1, -1, -1):
for j in range(w - n):
s = m[r][n + j] - sum(m[r][k] * x[k][j] for k in range(r + 1, n))
x[r][j] = s / m[r][r]
return [row[0] for row in x] if vec else x
def cholesky(a):
"""Lower triangular L with A = L L^H for a Hermitian positive definite A."""
n = len(a)
low = zeros(n, n)
for j in range(n):
d = a[j][j] - sum(abs(low[j][k]) ** 2 for k in range(j))
d = d.real if isinstance(d, complex) else d
if not d > 0:
raise ValueError("matrix is not positive definite")
ljj = math.sqrt(d)
low[j][j] = ljj
for i in range(j + 1, n):
s = a[i][j] - sum(low[i][k] * low[j][k].conjugate() for k in range(j))
low[i][j] = s / ljj
return low
def cho_solve(low, b):
"""Solve (L L^H) x = b, with L from cholesky."""
n = len(low)
z = [0.0] * n
for i in range(n):
z[i] = (b[i] - sum(low[i][k] * z[k] for k in range(i))) / low[i][i]
x = [0.0] * n
for i in range(n - 1, -1, -1):
s = z[i] - sum(low[k][i].conjugate() * x[k] for k in range(i + 1, n))
x[i] = s / low[i][i].conjugate()
return x
def _rot_params(app, aqq, apq):
"""c, s of the Jacobi rotation that zeroes the (p, q) entry of [[app, apq], [apq, aqq]]."""
theta = (aqq - app) / (2.0 * apq)
t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
c = 1.0 / math.sqrt(1.0 + t * t)
return c, c * t
def sym_eig(a, tol=1e-15, max_sweeps=100):
"""Eigenvalues (ascending) and eigenvectors (as columns) of a real symmetric matrix.
Cyclic Jacobi method. Returns (w, Q) with A = Q diag(w) Q^T.
"""
n = len(a)
m = [[float(v) for v in row] for row in a]
q = eye(n)
for _ in range(max_sweeps):
off = sum(m[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
scale = sum(m[i][i] ** 2 for i in range(n)) + off
if off <= (tol * tol) * scale or off == 0.0:
break
for p in range(n - 1):
for r in range(p + 1, n):
apq = m[p][r]
if apq == 0.0:
continue
c, s = _rot_params(m[p][p], m[r][r], apq)
for k in range(n):
mkp, mkr = m[k][p], m[k][r]
m[k][p] = c * mkp - s * mkr
m[k][r] = s * mkp + c * mkr
mp, mr = m[p], m[r]
for k in range(n):
mpk, mrk = mp[k], mr[k]
mp[k] = c * mpk - s * mrk
mr[k] = s * mpk + c * mrk
m[p][r] = m[r][p] = 0.0
for k in range(n):
qkp, qkr = q[k][p], q[k][r]
q[k][p] = c * qkp - s * qkr
q[k][r] = s * qkp + c * qkr
order = sorted(range(n), key=lambda i: m[i][i])
w = [m[i][i] for i in order]
qs = [[q[k][i] for i in order] for k in range(n)]
return w, qs
def _complete(cols, m):
"""Replace zero columns of an m-row column list by unit vectors orthogonal to the others."""
for idx, col in enumerate(cols):
if any(v != 0.0 for v in col):
continue
for e in range(m):
cand = [0.0] * m
cand[e] = 1.0
for _ in range(2):
for jdx, other in enumerate(cols):
if jdx == idx or not any(v != 0.0 for v in other):
continue
h = sum(a * b for a, b in zip(other, cand))
cand = [a - h * b for a, b in zip(cand, other)]
nrm = math.sqrt(sum(v * v for v in cand))
if nrm > 0.5:
cols[idx] = [v / nrm for v in cand]
break
return cols
def svd(a, tol=1e-15, max_sweeps=100):
"""Thin SVD of a real m x n matrix by one-sided Jacobi (Hestenes).
Returns (U, S, V) with p = min(m, n): U is m x p, S a list of p values in
descending order, V is n x p, U^T U = I, V^T V = I and A = U diag(S) V^T.
"""
m, n = len(a), len(a[0])
if m < n:
v, s, u = svd(transpose(a), tol, max_sweeps)
return u, s, v
cols = [[float(a[i][j]) for i in range(m)] for j in range(n)]
vcols = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)]
for _ in range(max_sweeps):
rotated = False
for p in range(n - 1):
for r in range(p + 1, n):
cp, cr = cols[p], cols[r]
alpha = sum(x * x for x in cp)
beta = sum(x * x for x in cr)
gamma = sum(x * y for x, y in zip(cp, cr))
if gamma == 0.0 or abs(gamma) <= tol * math.sqrt(alpha * beta):
continue
rotated = True
c, s = _rot_params(alpha, beta, gamma)
cols[p] = [c * x - s * y for x, y in zip(cp, cr)]
cols[r] = [s * x + c * y for x, y in zip(cp, cr)]
vp, vr = vcols[p], vcols[r]
vcols[p] = [c * x - s * y for x, y in zip(vp, vr)]
vcols[r] = [s * x + c * y for x, y in zip(vp, vr)]
if not rotated:
break
sig = [math.sqrt(sum(x * x for x in col)) for col in cols]
# A column below 1e-150 times the largest one is zero to working precision;
# its squares underflow, so its direction carries no information.
floor = max(sig) * 1e-150 if sig else 0.0
sig = [t if t > floor and t > 1e-150 else 0.0 for t in sig]
order = sorted(range(n), key=lambda j: -sig[j])
s_out = [sig[j] for j in order]
ucols = [[x / sig[j] for x in cols[j]] if sig[j] > 0.0 else [0.0] * m for j in order]
ucols = _complete(ucols, m)
u = [[ucols[j][i] for j in range(n)] for i in range(m)]
v = [[vcols[j][i] for j in order] for i in range(n)]
return u, s_out, v
def adjoint_gap(apply_a, apply_ah, x, y):
"""|<A x, y> - <x, A^H y>| / (||A x|| ||y||) for given functions A and A^H.
x and y may be vectors or images (lists of rows). If the denominator is
zero, the absolute gap is returned.
"""
ax = apply_a(x)
gap = abs(dot(ax, y) - dot(x, apply_ah(y)))
den = norm2(ax) * norm2(y)
return gap / den if den > 0.0 else gap
preconditioned_crank_nicolson_mcmc.py 109 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/preconditioned-crank-nicolson-mcmc/. The authors are listed in prov/63HRT4.jsonl.
"""Preconditioned Crank-Nicolson (pCN) MCMC.
Target: the posterior mu^y with d mu^y / d mu_0 (u) proportional to
exp(-Phi(u)), where mu_0 = N(m0, C) is a Gaussian prior and Phi is the
negative log-likelihood (the data misfit). The proposal
v = m0 + sqrt(1 - beta^2) (u - m0) + beta xi, xi ~ N(0, C),
leaves mu_0 invariant and is reversible with respect to it, so the
Metropolis-Hastings acceptance probability is min(1, exp(Phi(u) - Phi(v))).
The prior density never appears.
"""
import math
from imgla import cholesky, matvec
def gaussian_sampler(cov):
"""Return a function rng -> xi with xi ~ N(0, cov), using a Cholesky factor."""
low = cholesky(cov)
n = len(cov)
def draw(rng):
return matvec(low, [rng.gauss(0.0, 1.0) for _ in range(n)])
return draw
def diagonal_sampler(variances):
"""Return a function rng -> xi with independent N(0, variances[k]) entries."""
sd = [math.sqrt(c) for c in variances]
def draw(rng):
return [s * rng.gauss(0.0, 1.0) for s in sd]
return draw
def pcn(phi, draw_prior, u0, beta, steps, rng, m0=None):
"""Run pCN for the given number of steps.
phi: function u -> Phi(u), the negative log-likelihood.
draw_prior: function rng -> xi ~ N(0, C).
Returns (chain, acceptance_rate); chain[k] is the state after step k + 1.
"""
if not 0.0 < beta <= 1.0:
raise ValueError("beta must be in (0, 1]")
n = len(u0)
if m0 is None:
m0 = [0.0] * n
rho = math.sqrt(1.0 - beta * beta)
u = list(u0)
phi_u = phi(u) # @line L1
chain = []
accepted = 0
for _ in range(steps): # @line L2
xi = draw_prior(rng) # @line L3
v = [m + rho * (ui - m) + beta * x for m, ui, x in zip(m0, u, xi)] # @line L4
phi_v = phi(v) # @line L5
if math.log(1.0 - rng.random()) < phi_u - phi_v: # @line L6
u, phi_u = v, phi_v # @line L7
accepted += 1
chain.append(u) # @line L8
return chain, accepted / steps # @line L9
def random_walk_metropolis(phi, prior_precision_diag, u0, beta, steps, rng, draw_prior):
"""Random-walk Metropolis with proposal v = u + beta xi, xi ~ N(0, C), for a
centred Gaussian prior with diagonal covariance (given by its inverse
diagonal). Used only for comparison with pCN."""
u = list(u0)
def log_target(w):
return -phi(w) - 0.5 * sum(p * wi * wi for p, wi in zip(prior_precision_diag, w))
lu = log_target(u)
chain = []
accepted = 0
for _ in range(steps):
xi = draw_prior(rng)
v = [ui + beta * x for ui, x in zip(u, xi)]
lv = log_target(v)
if math.log(1.0 - rng.random()) < lv - lu:
u, lu = v, lv
accepted += 1
chain.append(u)
return chain, accepted / steps
def linear_gaussian_misfit(a, y, sigma):
"""Phi(u) = ||A u - y||^2 / (2 sigma^2)."""
def phi(u):
r = matvec(a, u)
return sum((ri - yi) ** 2 for ri, yi in zip(r, y)) / (2.0 * sigma * sigma)
return phi
def mean_and_covariance(chain):
"""Sample mean and sample covariance (divisor N - 1) of a list of vectors."""
k = len(chain)
n = len(chain[0])
mean = [sum(c[i] for c in chain) / k for i in range(n)]
cov = [[sum((c[i] - mean[i]) * (c[j] - mean[j]) for c in chain) / (k - 1) for j in range(n)] for i in range(n)]
return mean, cov
test_preconditioned_crank_nicolson_mcmc.py 108 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/preconditioned-crank-nicolson-mcmc/. The authors are listed in prov/63HRT4.jsonl.
import math
import random
from imgla import matmul, matvec, solve, transpose
from preconditioned_crank_nicolson_mcmc import (
diagonal_sampler,
gaussian_sampler,
linear_gaussian_misfit,
mean_and_covariance,
pcn,
random_walk_metropolis,
)
def test_zero_misfit_accepts_every_proposal_and_keeps_the_prior():
# Phi = 0: the acceptance probability is min(1, exp(0)) = 1, and the
# chain is an AR(1) process whose stationary law is the prior N(3, 4).
chain, acc = pcn(lambda u: 0.0, diagonal_sampler([4.0]), [3.0], 0.5, 10000, random.Random(5), m0=[3.0])
assert acc == 1.0
assert len(chain) == 10000
mean, cov = mean_and_covariance(chain[500:])
assert abs(mean[0] - 3.0) < 0.15
assert abs(cov[0][0] - 4.0) < 0.3
def test_proposal_is_reversible_with_respect_to_the_prior():
# For the prior N(0, c) and q(u, .) = N(rho u, beta^2 c), the product
# pi_0(u) q(u, v) is symmetric in (u, v).
c, beta = 2.5, 0.4
rho = math.sqrt(1.0 - beta * beta)
def log_joint(u, v):
return -u * u / (2.0 * c) - (v - rho * u) ** 2 / (2.0 * beta * beta * c)
rng = random.Random(3)
for _ in range(50):
u, v = rng.uniform(-4.0, 4.0), rng.uniform(-4.0, 4.0)
assert abs(log_joint(u, v) - log_joint(v, u)) < 1e-12
def test_scalar_linear_gaussian_posterior():
# y = a u + e, u ~ N(0, 1), e ~ N(0, sigma^2): the posterior is
# N(0.96, 0.2) for a = 0.1, sigma = 0.05, y = 0.12.
phi = linear_gaussian_misfit([[0.1]], [0.12], 0.05)
chain, acc = pcn(phi, diagonal_sampler([1.0]), [0.0], 0.5, 12000, random.Random(1))
mean, cov = mean_and_covariance(chain[1000:])
assert 0.5 < acc < 0.9
assert abs(mean[0] - 0.96) < 0.05
assert abs(cov[0][0] - 0.2) < 0.03
def test_correlated_prior_two_dimensional_posterior():
c0 = [[1.0, 0.5], [0.5, 1.0]]
a = [[1.0, 1.0]]
y = [1.0]
sigma = 0.5
prec = solve(c0, [[1.0, 0.0], [0.0, 1.0]])
ata = matmul(transpose(a), a)
post_prec = [[ata[i][j] / sigma ** 2 + prec[i][j] for j in range(2)] for i in range(2)]
c_post = solve(post_prec, [[1.0, 0.0], [0.0, 1.0]])
m_post = matvec(c_post, [v / sigma ** 2 for v in matvec(transpose(a), y)])
chain, _ = pcn(linear_gaussian_misfit(a, y, sigma), gaussian_sampler(c0), [0.0, 0.0], 0.5, 12000, random.Random(7))
mean, cov = mean_and_covariance(chain[1000:])
for i in range(2):
assert abs(mean[i] - m_post[i]) < 0.05
for j in range(2):
assert abs(cov[i][j] - c_post[i][j]) < 0.05
def test_acceptance_does_not_degrade_with_dimension():
# Prior variances 1/k^2 and one observation of sum_k u_k / k. pCN keeps
# its acceptance rate as n grows; random-walk Metropolis with the same
# step does not.
rates = {}
for n in (10, 100):
g = [1.0 / k for k in range(1, n + 1)]
var = [1.0 / k ** 2 for k in range(1, n + 1)]
def phi(u, g=g):
return (sum(p * q for p, q in zip(g, u)) - 0.5) ** 2 / 0.02
_, a_pcn = pcn(phi, diagonal_sampler(var), [0.0] * n, 0.3, 600, random.Random(2))
_, a_rwm = random_walk_metropolis(phi, [1.0 / v for v in var], [0.0] * n, 0.3, 600, random.Random(2), diagonal_sampler(var))
rates[n] = (a_pcn, a_rwm)
assert abs(rates[10][0] - rates[100][0]) < 0.1
assert rates[100][0] > 0.25
assert rates[100][1] < 0.5 * rates[10][1]
def test_beta_must_be_in_the_unit_interval():
for beta in (0.0, -0.1, 1.5):
try:
pcn(lambda u: 0.0, diagonal_sampler([1.0]), [0.0], beta, 10, random.Random(0))
except ValueError:
continue
raise AssertionError("beta out of range was accepted")
def test_rejected_steps_repeat_the_state():
# A huge misfit away from u = 0 makes almost every proposal fail, and a
# failed step stores the previous state again.
chain, acc = pcn(lambda u: 1e6 * u[0] * u[0], diagonal_sampler([1.0]), [0.0], 0.9, 200, random.Random(4))
assert acc < 0.1
repeats = sum(1 for p, q in zip(chain, chain[1:]) if p is q)
assert repeats >= 200 * (1.0 - acc) - 2
History
Crank-Nicolson type proposals that keep a Gaussian reference law invariant appeared in work on sampling diffusion bridges by Beskos, Roberts, Stuart and Voss (2008). Cotter, Roberts, Stuart and White (2013) gave the name pCN, derived it from the Crank-Nicolson scheme, and placed it in the function-space framework of Bayesian inverse problems of Stuart (2010). They note that the same proposal was used earlier by Neal for Gaussian process models. Hairer, Stuart and Vollmer (2014) proved that pCN has a spectral gap that does not depend on the dimension, while that of random-walk Metropolis goes to zero.
References
- S. L. Cotter, G. O. Roberts, A. M. Stuart and D. White, MCMC methods for functions, modifying old algorithms to make them faster, Statistical Science 28(3), 2013, pages 424 to 446
- Alexandros Beskos, Gareth Roberts, Andrew Stuart and Jochen Voss, MCMC methods for diffusion bridges, Stochastics and Dynamics 8(3), 2008, pages 319 to 350
- Martin Hairer, Andrew M. Stuart and Sebastian J. Vollmer, Spectral gaps for a Metropolis-Hastings algorithm in infinite dimensions, Annals of Applied Probability 24(6), 2014, pages 2455 to 2490
- Andrew M. Stuart, Inverse problems, a Bayesian perspective, Acta Numerica 19, 2010, pages 451 to 559
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 63HRT4 Edit this page History Report an error Markdown