Algorithmresearch
Randomize-then-optimize
Also called RTO sampler, RTO, RTO-MH.
Draw posterior samples for an inverse problem by solving perturbed optimization problems and correcting with a Metropolis step or importance weights.
- Time
- Θ(N k (T + M n^2)) worst · averageΘ(N (T + M n^2)) best
- Space
- Θ(M n + N n) extra
- Where
- M = the number of rows of the stacked residual (data plus prior); N = the number of samples; T = the cost of one evaluation of F and its Jacobian; k = the Newton steps per sample; n = the number of unknowns
- Model
- Real RAM
- Properties
- exact with correctionneeds gradientsparallel proposalsrandomized
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Johnathan M. Bardsley, Antti Solonen, Heikki Haario, Marko Laine, 2014
Randomize-then-optimize (RTO) makes posterior samples by optimization. It applies to posteriors of least squares form, , which covers a nonlinear forward model with Gaussian noise and a Gaussian prior. Each sample perturbs the data, with , and solves a projected version of the least squares problem, , where is an orthonormal basis of the range of the Jacobian at the MAP point. For a linear model these solutions are exact, independent posterior samples. For a nonlinear model they come from a known density , and the ratio can be computed, so a Metropolis-Hastings step or importance weights remove the bias. Bardsley, Solonen, Haario and Laine introduced the method in 2014. Its proposals are independent of each other, so they can be computed in parallel, and it uses the optimization tools that a MAP estimate needs anyway.
In plain words
To find the single most likely answer, you solve one least squares problem. To get a spread of plausible answers, RTO adds random noise to the data and to the prior guess, solves the problem again, and repeats. For a linear problem the spread of these answers is exactly the right one. For a nonlinear problem it is a little off. RTO knows by how much, because it can compute the density of its own proposals. A Metropolis-Hastings step then keeps or rejects each answer so that the final set has the right distribution.
The problem
Sample on , with , , smooth, with Jacobian . For a Bayesian inverse problem with forward map , noise and prior , ,
The output is a Markov chain with invariant law .
The algorithm
RTO-MH(F, J, ybar, x_0, N)- 1
xbar ← argmin_x ||F(x) - ybar||² by Gauss-Newton from x_0 ▷ the MAP point - 2
Q ← orthonormal basis of the columns of J(xbar) ▷ thin QR, M × n - 3
x ← xbar, w ← weight(xbar) - 4
for k = 1, ..., N - 5
eps ← N(0, I_M) - 6
x' ← solution of Q^T F(x') = Q^T (ybar + eps), Newton from xbar - 7
w' ← |det(Q^T J(x'))|^(-1) exp(-½||F(x') - ybar||² + ½||Q^T (F(x') - ybar)||²) - 8
with probability min(1, w' / w): x ← x', w ← w' - 9
append x to the chain - 10
return the chain and the acceptance rate
Line L1 computes the MAP point, the minimizer of the Tikhonov type functional , with the Gauss-Newton algorithm. Line L2 takes a QR decomposition of the Jacobian there. Lines L5 and L6 are the "randomize" and "optimize" steps: the solution of line L6 is a stationary point of . Line L7 is the weight , where
is the density of the points made by line L6. It follows from the change of variables , since is . Line L8 is the independence Metropolis-Hastings test, done with logarithms in the code. If line L6 fails, the state stays.
For a linear , line L6 is the least squares problem , the weight is constant, and line L8 accepts every proposal. So for linear Gaussian inverse problems, RTO is the classical "perturb the data and the prior mean, then solve" method for Gaussian sampling.
Example
A scalar nonlinear problem: , noise standard deviation , observed , prior . So and . The posterior mean and variance, by quadrature on 40001 points in , are and .
| method, 5000 draws, seed 3 | mean | variance |
|---|---|---|
| quadrature (reference) | 0.7572 | 0.04321 |
| MAP point (line L1) | 0.8400 | none |
| line L6 proposals, no correction | 0.8141 | 0.03122 |
| proposals with importance weights | 0.7530 | 0.04375 |
| RTO-MH, acceptance rate 0.836 | 0.7598 | 0.03982 |
The uncorrected proposals are biased toward the MAP point and too narrow. Both corrections remove the bias up to Monte Carlo error. The effective sample size of the importance weights, , is 4417 of 5000, which shows that is close to here.
For the linear version, with noise , and prior , RTO-MH accepts all 5000 proposals (seed 1) and gives mean and variance ; the exact posterior is . All numbers are measurements with fixed seeds.
Correctness
The proof is in proofs/correctness.md. Under the assumption that is one-to-one with nonsingular derivative and that the solver of line L6 finds its solution when there is one, the points of line L6 have the density above (change of variables), is proportional to the weight of line L7, and the independence Metropolis-Hastings step satisfies detailed balance for . For an affine the assumption holds, the weight is constant, and the proposals are exact independent posterior samples. The procedure stops: every loop in it has a fixed bound. The choice of at the MAP point is for efficiency; any that satisfies the assumption gives a correct chain. How fast the chain mixes depends on how close is to , which is a property of the problem, not a theorem.
Proof: RTO-MH stops after the given number of steps, its proposal has the stated density, and the chain leaves the posterior invariantfull
Setting. with is continuously differentiable with Jacobian , , and the target density is
For a Gaussian prior with and noise , and give the posterior. is an matrix with orthonormal columns (line L2). Write , so .
Assumption (A). is one-to-one on , for all , and whenever lies in the image the solver of line L6 returns the solution . When the target is not in the image, line L6 returns no point.
Claim 1 (termination). For the procedure stops and returns a chain of states and an acceptance rate in .
Proof. The Gauss-Newton loop of line L1 has at most a fixed number of outer steps (100 in the code), and each step halves its step length at most 34 times before it stops. The Gram-Schmidt step of line L2 has columns. The Newton solver of line L6 has at most a fixed number of steps (50). The loop of line L4 has passes, and each appends one state in line L9.
Claim 2 (the proposal density). Under (A), the points returned by line L6 have the sub-probability density
and the remaining mass is the probability that line L6 returns no point.
Proof. Let . Then is Gaussian with mean and covariance , so it has density . By (A), line L6 returns exactly when . is a bijection from onto the open set with nonsingular derivative, so by the change of variables formula has density on . Since , this is .
Claim 3 (the weight). The ratio is, up to a constant factor,
and line L7 computes .
Proof. Divide by from Claim 2 and drop the constant . The function log_weight computes the three terms of directly.
Claim 4 (detailed balance). Under (A), one pass of lines L5 to L9 has the kernel
where collects the rejections and the failed solves, and . So is invariant.
Proof. Line L8 accepts with probability : as in Metropolis-Hastings, with uniform on , the event has this probability. If line L6 returns no point, the state stays. For the moving part, using for a constant ,
which is symmetric in . The staying part is concentrated on and is symmetric too. Integrate over to get invariance.
This is the independence Metropolis-Hastings sampler with proposal . Under (A), for every , also when its total mass is below one, and is finite and positive. So every set of positive -measure is reached in one step with positive probability, the chain is -irreducible, and averages along the chain converge to posterior expectations for -almost every start (the standard law of large numbers for Markov chains).
Claim 5 (the linear case is exact without correction). Let be affine with of full column rank , and let the columns of span the range of . Then (A) holds, is constant, every proposal is accepted, and the proposals are independent draws from , which is .
Proof. Write with invertible. Then is an affine bijection, so (A) holds, and Newton's method solves it in one step. The determinant is constant. With ,
since . So is constant and the ratio in line L8 is . The equation is equivalent to the normal equations , because and is invertible. So is the least squares solution of the perturbed problem, a Gaussian vector with mean and covariance , which are the mean and covariance of .
The choice of at the MAP point in line L1 is not needed for correctness: any with orthonormal columns for which (A) holds gives an exact chain. It matters for efficiency, since it makes close to near the mode. Assumption (A) is a real restriction. If is not one-to-one or the solver misses solutions, the weight of Claim 3 is wrong and the chain is biased; the page lists this as a pitfall.
Complexity
Line L1 is one Gauss-Newton solve, and line L2 a QR factorization in . Each Newton step of line L6 evaluates and (cost ), forms in , and solves an system in . Line L7 needs one more and a determinant. With Newton steps per sample, samples cost after the MAP point. In the linear case and one factorization can be reused for all samples. Memory is for and plus for the chain. The optimizations are independent and run in parallel; only line L8 is sequential, and it is cheap.
Properties
- Exact for linear Gaussian problems with no rejection; exact with the correction for nonlinear ones under the injectivity assumption.
- The proposals do not depend on the current state, so they can be computed in parallel and in advance.
- Uses optimization software: a Gauss-Newton or Newton solver, Jacobians, and a QR factorization.
- Needs the least squares form of the posterior. A non-Gaussian prior must first be transformed into this form.
- Works well when the posterior is close to Gaussian near the MAP point; the acceptance rate falls as the nonlinearity grows.
Variants and improvements
- Importance sampling. Use the weights of line L7 directly as self-normalized importance weights instead of line L8. All samples are used, and the importance sampling effective sample size measures the quality.
- Linear RTO for Gaussian sampling. Perturb the data and the prior mean and solve the regularized least squares problem. With conjugate gradients this samples high-dimensional Gaussian posteriors with only matrix-vector products.
- l1 and other non-Gaussian priors. Wang, Bardsley, Solonen, Cui and Marzouk (2017) map an type prior to a Gaussian reference by a change of variables and apply RTO in the new variables.
- Subspace versions. For large , restrict the nonlinear solve to a low-dimensional subspace informed by the data and treat the rest as the prior, which reduces and the cost of line L6.
- Randomized maximum likelihood. A related method from petroleum reservoir modeling perturbs the data and the prior sample and solves the full, unprojected problem. It is exact only in the linear case and has no simple density for a correction.
When to use it
Use RTO when the posterior has least squares form, a MAP solver with Jacobians is available, and the posterior is not far from Gaussian, so that is close to . It is attractive when many processors are available, because samples are independent optimizations. For linear Gaussian problems it is the method of choice for exact samples. If the posterior is strongly multimodal, the map fails to be one-to-one, or Jacobians are not available, use pCN or another MCMC method instead.
Pitfalls
- Treating the proposals of line L6 as posterior samples for a nonlinear model. They are biased; skip lines L7 and L8 only for linear models.
- A solve in line L6 that converges to a different root, or fails, when is not one-to-one. Then the density of line L7 is wrong and the chain is biased without warning. Check the residual of the solve and monitor failures.
- Solving the unprojected problem in line L6. Its solutions do not have the density of line L7.
- Forgetting the determinant in line L7, or computing it for instead of . In the linear case it is constant and the mistake is invisible; in the nonlinear case it biases the result.
- Working with instead of in line L8. The exponentials overflow for realistic problems.
- A rank-deficient Jacobian in line L2. Then has fewer than columns and the method is not defined; the prior part of prevents this when it is present.
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
randomize_then_optimize.py 163 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/randomize-then-optimize/. The authors are listed in prov/27EKVH.jsonl.
"""Randomize-then-optimize (RTO) with a Metropolis-Hastings correction.
The posterior is written as pi(x) proportional to exp(-||F(x) - ybar||^2 / 2),
where F stacks the whitened forward map and the whitened prior:
F(x) = [Gamma^{-1/2} G(x); L (x - m0)], ybar = [Gamma^{-1/2} y; 0], with
L^T L = C^{-1} for a Gaussian prior N(m0, C). F maps R^n to R^M, M >= n.
RTO fixes Q, an M x n matrix with orthonormal columns that span the range of
the Jacobian J(xbar) at the MAP point xbar. A proposal is the solution x of
Q^T F(x) = Q^T (ybar + eps), eps ~ N(0, I_M). If x -> Q^T F(x) is one-to-one
and smooth, the proposal has density
q(x) proportional to |det(Q^T J(x))| exp(-||Q^T (F(x) - ybar)||^2 / 2),
and the importance weight pi / q is
w(x) = |det(Q^T J(x))|^{-1} exp(-||F(x) - ybar||^2 / 2 + ||Q^T (F(x) - ybar)||^2 / 2).
An independence Metropolis-Hastings step with ratio w(x') / w(x) makes the
chain exact. For a linear F the weight is constant and every proposal is an
exact posterior sample.
"""
import math
from imgla import matvec, solve, transpose
def det(a):
"""Determinant of a square matrix by Gaussian elimination with pivoting."""
n = len(a)
m = [list(map(float, row)) for row in a]
d = 1.0
for c in range(n):
p = max(range(c, n), key=lambda r: abs(m[r][c]))
if m[p][c] == 0.0:
return 0.0
if p != c:
m[c], m[p] = m[p], m[c]
d = -d
d *= m[c][c]
for r in range(c + 1, n):
f = m[r][c] / m[c][c]
for j in range(c, n):
m[r][j] -= f * m[c][j]
return d
def thin_qr_q(j):
"""Q with orthonormal columns spanning the columns of the M x n matrix j
(modified Gram-Schmidt, applied twice). Raises ValueError if the rank is
below n."""
mrows, n = len(j), len(j[0])
cols = [[j[i][k] for i in range(mrows)] for k in range(n)]
q = []
for c in cols:
v = list(c)
for _ in range(2):
for e in q:
h = sum(a * b for a, b in zip(e, v))
v = [a - h * b for a, b in zip(v, e)]
nrm = math.sqrt(sum(a * a for a in v))
if nrm <= 1e-13 * max(1.0, math.sqrt(sum(a * a for a in c))):
raise ValueError("Jacobian does not have full column rank")
q.append([a / nrm for a in v])
return [[q[k][i] for k in range(n)] for i in range(mrows)]
def gauss_newton_map(f, jac, ybar, x0, iters=100, tol=1e-12):
"""Minimize ||F(x) - ybar||^2 / 2 by Gauss-Newton with step halving."""
x = list(x0)
r = [a - b for a, b in zip(f(x), ybar)]
val = 0.5 * sum(t * t for t in r)
for _ in range(iters):
jx = jac(x)
jt = transpose(jx)
g = matvec(jt, r)
if math.sqrt(sum(t * t for t in g)) <= tol:
break
jtj = [[sum(a * b for a, b in zip(ri, rk)) for rk in jt] for ri in jt]
step = solve(jtj, g)
t = 1.0
while t > 1e-10:
xn = [a - t * s for a, s in zip(x, step)]
rn = [a - b for a, b in zip(f(xn), ybar)]
vn = 0.5 * sum(e * e for e in rn)
if vn <= val:
break
t *= 0.5
else:
break
x, r, val = xn, rn, vn
return x
def solve_projected(f, jac, q, target, x0, iters=50, tol=1e-11):
"""Solve Q^T F(x) = target by Newton's method from x0. Returns x, or None
if Newton does not reach the tolerance."""
qt = transpose(q)
x = list(x0)
for _ in range(iters):
res = [a - b for a, b in zip(matvec(qt, f(x)), target)]
if math.sqrt(sum(t * t for t in res)) <= tol * (1.0 + math.sqrt(sum(t * t for t in target))):
return x
jq = [matvec(qt, col) for col in transpose(jac(x))] # columns of Q^T J
try:
step = solve(transpose(jq), res)
except ValueError:
return None
x = [a - s for a, s in zip(x, step)]
res = [a - b for a, b in zip(matvec(qt, f(x)), target)]
if math.sqrt(sum(t * t for t in res)) <= tol * (1.0 + math.sqrt(sum(t * t for t in target))):
return x
return None
def log_weight(f, jac, q, ybar, x):
"""log w(x) = -log|det(Q^T J(x))| - ||F(x) - ybar||^2 / 2 + ||Q^T (F(x) - ybar)||^2 / 2."""
qt = transpose(q)
r = [a - b for a, b in zip(f(x), ybar)]
qr = matvec(qt, r)
qtj = [matvec(qt, col) for col in transpose(jac(x))]
d = abs(det(qtj))
if d == 0.0:
return -math.inf
return -math.log(d) - 0.5 * sum(t * t for t in r) + 0.5 * sum(t * t for t in qr)
def rto_mh(f, jac, ybar, x0, steps, rng):
"""RTO-MH. Returns (chain, acceptance_rate, xbar)."""
xbar = gauss_newton_map(f, jac, ybar, x0) # @line L1
q = thin_qr_q(jac(xbar)) # @line L2
qt = transpose(q)
x, lw = xbar, log_weight(f, jac, q, ybar, xbar) # @line L3
chain = []
accepted = 0
for _ in range(steps): # @line L4
eps = [rng.gauss(0.0, 1.0) for _ in ybar] # @line L5
target = matvec(qt, [a + e for a, e in zip(ybar, eps)])
xp = solve_projected(f, jac, q, target, xbar) # @line L6
if xp is not None:
lwp = log_weight(f, jac, q, ybar, xp) # @line L7
if math.log(1.0 - rng.random()) < lwp - lw: # @line L8
x, lw = xp, lwp
accepted += 1
chain.append(x) # @line L9
return chain, accepted / steps, xbar # @line L10
def linear_problem(a, y, sigma, prior_sd, m0=None):
"""F and its Jacobian for G(x) = A x, noise N(0, sigma^2 I) and prior
N(m0, prior_sd^2 I)."""
n = len(a[0])
if m0 is None:
m0 = [0.0] * n
h = [[v / sigma for v in row] for row in a] + [[(1.0 / prior_sd if i == k else 0.0) for k in range(n)] for i in range(n)]
ybar = [v / sigma for v in y] + [0.0] * n
def f(x):
return [sum(v * xk for v, xk in zip(row, x)) / sigma for row in a] + [(xi - mi) / prior_sd for xi, mi in zip(x, m0)]
def jac(x):
return h
return f, jac, ybar
test_randomize_then_optimize.py 142 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/randomize-then-optimize/. The authors are listed in prov/27EKVH.jsonl.
import math
import random
from imgla import eye, matmul, matvec, solve, transpose
from randomize_then_optimize import (
det,
gauss_newton_map,
linear_problem,
log_weight,
rto_mh,
solve_projected,
thin_qr_q,
)
def cubic_problem(c=1.0, sigma=0.5, y=1.5):
"""G(x) = x + c x^3, noise N(0, sigma^2), prior N(0, 1)."""
def f(x):
return [(x[0] + c * x[0] ** 3) / sigma, x[0]]
def jac(x):
return [[(1.0 + 3.0 * c * x[0] ** 2) / sigma], [1.0]]
return f, jac, [y / sigma, 0.0]
def quadrature_moments(c=1.0, sigma=0.5, y=1.5):
xs = [-4.0 + 8.0 * i / 40000 for i in range(40001)]
p = [math.exp(-((y - x - c * x ** 3) ** 2) / (2.0 * sigma * sigma) - 0.5 * x * x) for x in xs]
z = sum(p)
m = sum(x * w for x, w in zip(xs, p)) / z
v = sum((x - m) ** 2 * w for x, w in zip(xs, p)) / z
return m, v
def moments(chain):
k = len(chain)
n = len(chain[0])
m = [sum(c[i] for c in chain) / k for i in range(n)]
cov = [[sum((c[i] - m[i]) * (c[j] - m[j]) for c in chain) / (k - 1) for j in range(n)] for i in range(n)]
return m, cov
def test_determinant_and_orthonormal_basis():
assert abs(det([[2.0, 1.0], [1.0, 3.0]]) - 5.0) < 1e-12
assert abs(det([[0.0, 1.0], [1.0, 0.0]]) + 1.0) < 1e-12
assert det([[1.0, 2.0], [2.0, 4.0]]) == 0.0
j = [[1.0, 2.0], [0.5, -1.0], [3.0, 0.0], [0.0, 1.0]]
q = thin_qr_q(j)
qtq = matmul(transpose(q), q)
for i in range(2):
for k in range(2):
assert abs(qtq[i][k] - (1.0 if i == k else 0.0)) < 1e-12
# Every column of J is reproduced by its projection Q Q^T J.
for col in transpose(j):
proj = matvec(q, matvec(transpose(q), col))
assert max(abs(a - b) for a, b in zip(proj, col)) < 1e-12
try:
thin_qr_q([[1.0, 2.0], [2.0, 4.0]])
except ValueError:
pass
else:
raise AssertionError("rank-deficient Jacobian was accepted")
def test_map_point_is_the_tikhonov_solution_for_a_linear_problem():
a = [[1.0, 0.5], [0.2, 1.0], [0.3, 0.3]]
y = [1.0, 0.5, 0.2]
f, jac, ybar = linear_problem(a, y, 0.3, 1.0)
xbar = gauss_newton_map(f, jac, ybar, [0.0, 0.0])
# (A^T A + (sigma / prior_sd)^2 I) x = A^T y
ata = matmul(transpose(a), a)
lhs = [[ata[i][k] + (0.09 if i == k else 0.0) for k in range(2)] for i in range(2)]
x = solve(lhs, matvec(transpose(a), y))
assert max(abs(p - q) for p, q in zip(xbar, x)) < 1e-10
def test_linear_problem_has_constant_weight_and_accepts_everything():
f, jac, ybar = linear_problem([[0.1]], [0.12], 0.05, 1.0)
q = thin_qr_q(jac(None))
w0 = log_weight(f, jac, q, ybar, [0.0])
for x in (-3.0, 0.5, 0.96, 4.0):
assert abs(log_weight(f, jac, q, ybar, [x]) - w0) < 1e-9
chain, acc, xbar = rto_mh(f, jac, ybar, [0.0], 4000, random.Random(1))
assert abs(xbar[0] - 0.96) < 1e-10
assert acc > 0.999
m, cov = moments(chain)
assert abs(m[0] - 0.96) < 0.03
assert abs(cov[0][0] - 0.2) < 0.02
def test_linear_two_dimensional_posterior_moments():
a = [[1.0, 0.5], [0.2, 1.0], [0.3, 0.3]]
y = [1.0, 0.5, 0.2]
f, jac, ybar = linear_problem(a, y, 0.3, 1.0)
h = jac(None)
c_post = solve(matmul(transpose(h), h), eye(2))
m_post = matvec(c_post, matvec(transpose(h), ybar))
chain, _, _ = rto_mh(f, jac, ybar, [0.0, 0.0], 3000, random.Random(4))
m, cov = moments(chain)
for i in range(2):
assert abs(m[i] - m_post[i]) < 0.03
for k in range(2):
assert abs(cov[i][k] - c_post[i][k]) < 0.02
def test_proposals_solve_the_projected_equation():
f, jac, ybar = cubic_problem()
xbar = gauss_newton_map(f, jac, ybar, [0.0])
q = thin_qr_q(jac(xbar))
qt = transpose(q)
rng = random.Random(9)
for _ in range(20):
eps = [rng.gauss(0.0, 1.0) for _ in ybar]
target = matvec(qt, [p + e for p, e in zip(ybar, eps)])
x = solve_projected(f, jac, q, target, xbar)
assert x is not None
res = [p - t for p, t in zip(matvec(qt, f(x)), target)]
assert max(abs(r) for r in res) < 1e-9
def test_nonlinear_posterior_matches_quadrature_and_correction_matters():
f, jac, ybar = cubic_problem()
m_true, v_true = quadrature_moments()
chain, acc, xbar = rto_mh(f, jac, ybar, [0.0], 5000, random.Random(3))
m, cov = moments(chain)
assert 0.6 < acc < 0.99
assert abs(m[0] - m_true) < 0.02
assert abs(cov[0][0] - v_true) < 0.008
# Without the Metropolis-Hastings step the proposals are biased.
q = thin_qr_q(jac(xbar))
qt = transpose(q)
rng = random.Random(3)
raw = []
for _ in range(3000):
eps = [rng.gauss(0.0, 1.0) for _ in ybar]
raw.append(solve_projected(f, jac, q, matvec(qt, [p + e for p, e in zip(ybar, eps)]), xbar)[0])
assert sum(raw) / len(raw) - m_true > 0.03
History
The idea of sampling a linear Gaussian posterior by perturbing the data and the prior and solving the least squares problem is older, and appears in statistics, in geostatistics and in signal processing under several names. Randomized maximum likelihood applied the same idea, without a correction, to nonlinear reservoir models in the 1990s. Bardsley, Solonen, Haario and Laine (2014) introduced the projection with , derived the proposal density and added the Metropolis-Hastings correction, which made the method exact for nonlinear problems. Wang, Bardsley, Solonen, Cui and Marzouk (2017) extended RTO to type priors, and later work studied scalable and subspace versions.
References
- Johnathan M. Bardsley, Antti Solonen, Heikki Haario and Marko Laine, Randomize-then-optimize, a method for sampling from posterior distributions in nonlinear inverse problems, SIAM Journal on Scientific Computing 36(4), 2014, pages A1895 to A1910
- Zheng Wang, Johnathan M. Bardsley, Antti Solonen, Tiangang Cui and Youssef M. Marzouk, Bayesian inverse problems with l1 priors, a randomize-then-optimize approach, SIAM Journal on Scientific Computing 39(5), 2017, pages S140 to S166
- 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 27EKVH Edit this page History Report an error Markdown