Algorithmresearch
Hybrid Krylov regularization
Also called hybrid LSQR method, hybrid projection method.
Project the problem onto a growing Krylov subspace by bidiagonalization and apply Tikhonov regularization to the small projected problem at each step.
- Time
- O(k a + k^2 (m + n) + k^4) totalO(a + k (m + n) + k^3) per_iteration
- Space
- O(k (m + n)) extra
- Where
- a = the cost of one product with A plus one product with A*; k = the number of steps; m = the number of data values; n = the number of unknowns
- Model
- Real RAM
- Properties
- deterministiciterativenot linear in datamatrix free
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Dianne P. O'Leary, John A. Simmons, 1981
A hybrid Krylov method solves a large ill-posed least squares problem by combining two kinds of regularization. Like LSQR, it runs the Golub-Kahan bidiagonalization, which after steps gives an orthonormal basis of the Krylov space and a small bidiagonal matrix . Unlike LSQR, it does not solve the projected least squares problem as it stands. It applies Tikhonov regularization to it, with a parameter chosen anew at every step from the small problem alone, by the discrepancy principle or by a weighted form of GCV. The result is exactly the minimizer of the Tikhonov functional over the Krylov space. Plain LSQR shows semi-convergence, so its result depends strongly on the stopping index. In the hybrid method the error levels off instead, and the stopping index matters much less. The parameter choice costs only work on matrices.
In plain words
Krylov methods such as LSQR build a small model of a large problem, one direction at a time, using only products with the forward operator and its adjoint. The small model captures the large, well-measured features first. If one runs too long, the model starts to include noisy directions, and the answer gets worse.
A hybrid method adds a safety brake inside the small model. At every step it solves the small model with a Tikhonov penalty, and it picks the penalty weight from the small model, which is cheap. Noisy directions that enter the model later get damped by the penalty. So the answer stops getting worse, and you can run a few extra steps without harm. This makes the method much easier to use than plain LSQR on large imaging problems.
The problem
Given a linear operator ( matrix, or operator between Hilbert spaces) available only through the products and , data with , and a rule for the Tikhonov parameter, compute for
where is chosen by the rule from information about the projected problem only. The rules here are a fixed , the discrepancy principle (which needs ), and weighted GCV (which does not).
The algorithm
HYBRID-LSQR(A, y, K, rule) ▷ rule: "dp" (needs δ, τ), "wgcv" (weight ω) or a fixed λ ≥ 0- 1
β₁ u₁ ← y; α₁ v₁ ← A* u₁ ▷ β₁, α₁ norms; u₁, v₁ unit vectors - 2
for k ← 1 to K do - 3
β_{k+1} u_{k+1} ← A v_k - α_k u_k ▷ reorthogonalize against u₁, …, u_k - 4
α_{k+1} v_{k+1} ← A* u_{k+1} - β_{k+1} v_k ▷ reorthogonalize against v₁, …, v_k - 5
P Σ Qᵀ ← SVD of B_k ▷ B_k: α₁…α_k on the diagonal, β₂…β_{k+1} below - 6
λ_k ← rule applied to (Σ, β₁ Pᵀ e₁) - 7
z_k ← argmin ‖B_k z - β₁ e₁‖² + λ_k ‖z‖² - 8
x_k ← V_k z_k ▷ V_k = [v₁, …, v_k] - 9
return x_K and the history (x_j, λ_j, ‖y - A x_j‖)
Lines L1, L3 and L4 are the Golub-Kahan bidiagonalization, as in LSQR. In exact arithmetic they give and . The code reorthogonalizes each new vector twice against all previous ones (classical Gram-Schmidt, run twice). Without this the bases lose orthogonality in floating point, and the small problem no longer matches the large one.
Line L5 computes the SVD of the small matrix, with of size , singular values , and coefficients . Every quantity the rules need is then a short sum. The projected solution and its residual are
Line L6 chooses :
- Discrepancy principle ("dp"). The residual grows with , so bisection on finds the with residual . If even gives a residual above , the Krylov space is still too small to fit the data to the noise level, and the code takes , a plain LSQR step.
- Weighted GCV ("wgcv"). Minimize , first on a grid of 81 values of and then by golden section. With this is GCV for the small problem. Chung, Nagy and O'Leary (2008) introduced the weight because plain GCV on the projected problem often picks a that is too small.
- Fixed . Then converges, as grows, to the Tikhonov solution of the full problem.
Lines L7 and L8 compute and . The loop also stops if or is zero (to rounding), because then the Krylov space is invariant and later steps add nothing. The function HybridResult.solve(λ) gives for any other without new products with .
Example
The test problem of the code: the matrix of the integration operator ( for , ), the true solution at the cell centers, and Gaussian noise drawn with random.Random(8) and scaled to . The table gives the relative error and the chosen (a measurement).
| plain LSQR () | hybrid, dp () | (dp) | hybrid, wgcv | hybrid, wgcv | |
|---|---|---|---|---|---|
| 1 | 0.7433 | 0.7433 | 0 | 0.7494 | |
| 3 | 0.1887 | 0.1887 | 0 | 0.1972 | |
| 4 | 0.0738 | 0.0738 | 0 | 0.0762 | |
| 5 | 0.0466 | 0.0514 | 0.0467 | 0.4394 | |
| 6 | 0.0614 | 0.0579 | 0.0572 | ||
| 8 | 0.1786 | 0.0818 | 0.1387 | 0.2447 | |
| 10 | 0.2459 | 0.0820 | 0.2335 | 0.1866 | |
| 15 | 0.2634 | 0.0821 | 0.2633 | 0.1155 | |
| 30 | 0.2635 | 0.0821 | 0.2635 | 0.0787 |
Plain LSQR is best at (error ) and then grows by a factor of more than . For even leaves a residual above , so the discrepancy rule takes plain LSQR steps. From on it takes , and the error stays at for all later . For comparison, Tikhonov on the full problem with the best on a grid gives , at . Plain GCV () fails on this data set: its falls to and the iterates follow plain LSQR. With , weighted GCV over-smooths at first and reaches at . A good weight depends on the problem, which is why Chung, Nagy and O'Leary choose adaptively.
Correctness
The proofs are in proofs/correctness.md, in exact arithmetic, as long as no breakdown ( or ) has occurred.
- Bidiagonalization (theorem). and have orthonormal columns, , , and the columns of span .
- Projection (theorem). For , . So line L8 returns the minimizer of the Tikhonov functional over the Krylov space, and the projected residual equals the true residual.
- Special cases (theorem). gives the LSQR (and CGLS) iterate. If the Krylov space is invariant under (at the latest at for a matrix), is the Tikhonov solution of the full problem.
- Discrepancy rule (theorem). The projected residual is a continuous nondecreasing function of with limit , so if , the bisection finds a with residual to any accuracy.
- Termination (theorem). The loop runs at most times, and the bisection and the golden section search run a fixed number of steps.
That the hybrid method with the discrepancy rule converges as at the rate of Tikhonov regularization is not proved here. Once the Krylov space is invariant, the method is Tikhonov with the discrepancy principle, whose rates are on the page Tikhonov convergence rates.
Proof: Correctness of the hybrid LSQR methodfull
Exact arithmetic. is a bounded linear operator between Hilbert spaces (a real matrix in the code), are the data, and . Lines L1, L3 and L4 compute, with ,
where each and is the norm of the vector on the right, after the vector has been reorthogonalized against the earlier 's or 's. We say that no breakdown has occurred up to step if and are all positive. is the matrix with on the diagonal and just below it, and .
Lemma 1 (Golub-Kahan relations). If no breakdown has occurred up to step , then the reorthogonalization subtracts nothing, and (if ) have orthonormal columns, and
Moreover the columns of form an orthonormal basis of .
Proof. Induction on . For the start, and are unit vectors and .
Assume that and are orthonormal, that for , and that for . Let . For ,
which is for and for . So for all . The reorthogonalization subtracts the projections of on , which are zero, so it leaves unchanged. Then , is a unit vector orthogonal to , and .
Now let . For ,
which is for and for . So is orthogonal to , the reorthogonalization again subtracts nothing, and with a unit vector orthogonal to the earlier 's when . This completes the induction.
The relations , , are the columns of , and .
For the span, . If , then and , which lies in because . So . The orthonormal vectors lie in , whose dimension is at most , so they are a basis of it.
Lemma 2 (projection). Under the assumption of Lemma 1, for every and ,
Hence for , minimizes over if and only if minimizes over .
Proof. By Lemma 1, , and has orthonormal columns, so it preserves norms. Also because has orthonormal columns. Since is a bijection of onto (Lemma 1), the two minimization problems correspond.
Lemma 3 (the small problem in closed form). Let be a thin SVD, with of size and orthonormal columns , orthogonal with columns , and . Put . Under the assumption of Lemma 1, all , and for the unique minimizer of is
These are the formulas of Projected.z and Projected.res2 (lines L5 and L7).
Proof. is lower bidiagonal with nonzero diagonal , so its top block is nonsingular and has full column rank; hence all . The functional is strictly convex in and its gradient vanishes exactly when . In the coordinates this reads , which gives . For the residual, write with orthogonal to all , so . Then and
whose squared norm is the stated sum, by Pythagoras.
Theorem 1 (what line L8 returns). Under the assumption of Lemma 1, for the chosen at line L6, the vector of line L8 is the unique minimizer of over , and equals the projected residual of Lemma 3. For it is the iterate of LSQR and CGLS, the minimizer of over .
Proof. Lemmas 2 and 3.
Theorem 2 (invariant Krylov space). Suppose that the loop stops at step because or (in the second case, the relations of Lemma 1 hold with omitted). Then , and for , is the Tikhonov solution of the full problem. For a matrix, this happens at some .
Proof. By Lemma 1, for . For : if , then and . If , then and . So is invariant under . For the map is injective on the finite-dimensional invariant space , hence maps it onto itself, and since , also . The minimizer over the whole space lies in , so it is the minimizer over , which is by Theorem 1. For a matrix, , whose dimension is ; by Lemma 1 as long as there is no breakdown, so a breakdown occurs at some .
Theorem 3 (the discrepancy rule). Let and . Then is continuous and nondecreasing on with as . If , there is a with , and it is unique if some . The function choose_dp returns when ; otherwise, if at the two ends of its search interval, every bisection step keeps this property, so after steps the returned is within a factor of a solution of .
Proof. By Lemma 3, . Each map is continuous and increasing from to because , so is continuous, nondecreasing, strictly increasing if some , and tends to . The intermediate value theorem gives . The bisection replaces the lower end by the midpoint when and the upper end otherwise, which keeps ; by continuity and monotonicity a solution lies in , and the length of halves at each step.
Theorem 4 (termination). hybrid_lsqr returns after at most passes of the loop at line L2. Each pass does a finite amount of work: two operator products, two reorthogonalizations against at most vectors, one SVD of a matrix, and at most bisection steps or grid points plus golden section steps, each costing .
Proof. The loop is a counted loop over with an early exit on breakdown, and the parameter searches are counted loops.
What is not proved here. The behavior in floating point without reorthogonalization, and rates as for the hybrid method before the Krylov space becomes invariant. After that point the method is Tikhonov regularization with the chosen rule.
Complexity
- Per step. Lines L3 and L4 cost one product with and one with , plus for the reorthogonalization. Line L5 costs for the SVD of (an SVD that uses the bidiagonal structure would cost ). Line L6 costs per evaluation of the residual or of , times a fixed number of evaluations. Line L8 costs .
- Total. time for steps, where is the cost of one product with plus one with , and space for the two bases.
- In practice is a few tens to a few hundred, much less than , so the products with and the reorthogonalization dominate. Plain LSQR without reorthogonalization needs only space, which is the price of the hybrid method's stability.
Properties
- Stable in . Once the Krylov space contains the components that the data determine well, settles and the error levels off (the table above). The method keeps the cheap Krylov projection and adds a guard against semi-convergence.
- Nonlinear in the data. Both the Krylov space and depend on .
- Matrix-free. Only products with and .
- The parameter is cheap. Trying another costs , with no product with .
- Rules without are heuristics. Weighted GCV does not use , so by the Bakushinskii veto it cannot work for all noise; the example shows it failing with .
Variants and improvements
- Other projected rules. The L-curve, the discrepancy principle with an estimated , or UPRE, each applied to the small problem.
- Truncated SVD of the small problem. Replace Tikhonov at line L7 by truncating the SVD of .
- General-form penalty. For a penalty with , transform the problem to standard form first, or use a joint bidiagonalization.
- Arnoldi hybrids. For square , use the Arnoldi process (as in GMRES) instead of Golub-Kahan, which avoids products with .
- Flexible and sparse hybrids. Iteratively reweighted penalties give hybrid methods for and total variation regularization.
- Without reorthogonalization. Cheaper, but the projected problem then has repeated copies of singular values, and the rules can be misled.
When to use it
Use a hybrid method for large problems, such as image deblurring and tomography, where is available only through products and an SVD of is out of reach, and where you do not want to tune the stopping index of LSQR by hand. With a good estimate of , use the discrepancy rule. Without one, use weighted GCV and check the result. For small dense problems, Tikhonov with the SVD is simpler. If memory for the bases is short, use plain LSQR or CGLS with a stopping rule.
Pitfalls
- No reorthogonalization at lines L3 and L4. In floating point the bases lose orthogonality after a few tens of steps on ill-conditioned problems, and the projected residual is no longer the true residual.
- Plain GCV on the projected problem. It tends to pick a that is too small, as in the example. Use a weight or check the result.
- A residual target that is never reached. If is below the smallest residual possible in the full space (for example because is underestimated), the rule takes at every step, and the method is plain LSQR with its semi-convergence.
- Stopping too early. For small the Krylov space misses part of the solution, and no choice of can fix that. Run until and have settled.
- A wrong adjoint. The theory needs to be the true adjoint of the code for . Check on random vectors.
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/hybrid-krylov-regularization/. The authors are listed in prov/WCZ0JJ.jsonl.
"""A hybrid LSQR method: Golub-Kahan bidiagonalization with Tikhonov on the projected problem.
After k steps, A V_k = U_{k+1} B_k with B_k lower bidiagonal of size (k+1) x k
and y = beta_1 U_{k+1} e_1. For a Tikhonov parameter lam the projected problem
z_k = argmin ||B_k z - beta_1 e_1||^2 + lam ||z||^2, x_k = V_k z_k,
gives the minimizer of ||A x - y||^2 + lam ||x||^2 over x in V_k = K_k(A^T A, A^T y).
The parameter is chosen again at every step from the small problem only:
"dp" is the projected discrepancy principle, "wgcv" is weighted GCV, and a
number is a fixed parameter. Both rules use the SVD of B_k, which costs
O(k^3) and is small next to the products with A when k is much less than n.
Full reorthogonalization keeps U and V orthonormal in floating point. Without
it the projected problem drifts from the true one.
"""
import math
from imgla import matvec, rmatvec, svd
def _norm(v):
return math.sqrt(sum(t * t for t in v))
def _reorth(w, basis):
for _ in range(2):
for b in basis:
h = sum(p * q for p, q in zip(b, w))
w = [p - h * q for p, q in zip(w, b)]
return w
def bidiag_matrix(alphas, betas, k):
"""B_k: alphas[0..k-1] on the diagonal, betas[1..k] below it."""
b = [[0.0] * k for _ in range(k + 1)]
for i in range(k):
b[i][i] = alphas[i]
b[i + 1][i] = betas[i + 1]
return b
class Projected:
"""The SVD of B_k and the coefficients g_i = beta_1 (P^T e_1)_i, with the
part of beta_1 e_1 outside range(B_k) (zero in exact arithmetic only if
the Krylov space holds the least squares solution)."""
def __init__(self, bk, beta1):
p, s, q = svd(bk)
self.s, self.q, self.k = s, q, len(s)
self.g = [beta1 * p[0][i] for i in range(self.k)]
self.out2 = max(beta1 * beta1 - sum(t * t for t in self.g), 0.0)
def z(self, lam):
"""z = sum_i s_i g_i / (s_i^2 + lam) q_i, the projected Tikhonov solution."""
coef = [si * gi / (si * si + lam) if si * si + lam > 0 else 0.0
for si, gi in zip(self.s, self.g)]
return [sum(c * self.q[j][i] for i, c in enumerate(coef)) for j in range(self.k)]
def res2(self, lam):
"""||B_k z_lam - beta_1 e_1||^2 = ||A x_lam - y||^2."""
tot = self.out2
for si, gi in zip(self.s, self.g):
if si * si + lam > 0:
tot += (lam * gi / (si * si + lam)) ** 2
else:
tot += gi * gi
return tot
def gcv(self, lam, omega=1.0):
"""Weighted GCV: ||res||^2 / (k + 1 - omega sum_i s_i^2 / (s_i^2 + lam))^2."""
tr = self.k + 1 - omega * sum(si * si / (si * si + lam) for si in self.s if si * si + lam > 0)
return self.res2(lam) / (tr * tr) if tr > 0 else math.inf
def choose_dp(proj, delta, tau):
"""The lam with ||B_k z_lam - beta_1 e_1|| = tau delta, by bisection on log lam.
The residual grows with lam. If tau delta is below the residual at lam = 0,
the Krylov space is still too small and lam = 0 is returned.
"""
target = (tau * delta) ** 2
if proj.res2(0.0) >= target:
return 0.0
smax = proj.s[0] if proj.s and proj.s[0] > 0 else 1.0
lo, hi = math.log(smax * smax * 1e-30), math.log(smax * smax * 1e6)
if proj.res2(math.exp(hi)) <= target:
return math.exp(hi)
for _ in range(200):
mid = 0.5 * (lo + hi)
if proj.res2(math.exp(mid)) < target:
lo = mid
else:
hi = mid
if hi - lo < 1e-12:
break
return math.exp(0.5 * (lo + hi))
def choose_wgcv(proj, omega=1.0, points=81):
"""Minimize the weighted GCV function over a log grid, then refine by golden section."""
smax = proj.s[0] if proj.s and proj.s[0] > 0 else 1.0
lo, hi = math.log(smax * smax * 1e-14), math.log(smax * smax)
grid = [lo + (hi - lo) * i / (points - 1) for i in range(points)]
vals = [proj.gcv(math.exp(t), omega) for t in grid]
i = min(range(points), key=lambda j: vals[j])
a, b = grid[max(i - 1, 0)], grid[min(i + 1, points - 1)]
ratio = (math.sqrt(5.0) - 1.0) / 2.0
for _ in range(60):
c, d = b - ratio * (b - a), a + ratio * (b - a)
if proj.gcv(math.exp(c), omega) < proj.gcv(math.exp(d), omega):
b = d
else:
a = c
return math.exp(0.5 * (a + b))
class HybridResult:
"""x: the last iterate; k: steps done; iterates: x_1, ..., x_k; lams: the
parameter chosen at each step; resnorms: ||y - A x_j||; stopped:
"breakdown" (the Krylov space is invariant) or "maxit"; proj and basis: the
projected problem and V_k of the last step."""
def __init__(self, **kw):
self.__dict__.update(kw)
def solve(self, lam):
"""x = V_k z_lam for any lam >= 0, with no new products with A."""
z = self.proj.z(lam)
return [sum(z[j] * self.basis[j][i] for j in range(len(z)))
for i in range(len(self.basis[0]))]
def hybrid_lsqr(apply_a, apply_at, y, kmax, rule="dp", delta=None, tau=1.01, omega=1.0):
"""Run kmax steps of the hybrid method; rule is "dp", "wgcv" or a fixed lam >= 0."""
if rule == "dp" and delta is None:
raise ValueError("the discrepancy rule needs delta")
beta1 = _norm(y)
u = [t / beta1 for t in y]
v = apply_at(u)
alpha = _norm(v)
v = [t / alpha for t in v] # @line L1
us, vs, alphas, betas = [u], [v], [alpha], [beta1]
iterates, lams, resnorms = [], [], []
stopped = "maxit"
for k in range(1, kmax + 1): # @line L2
w = _reorth([p - alpha * q for p, q in zip(apply_a(v), u)], us)
beta = _norm(w)
u = [t / beta for t in w] if beta > 0 else [0.0] * len(w) # @line L3
w = _reorth([p - beta * q for p, q in zip(apply_at(u), v)], vs)
alpha = _norm(w)
v = [t / alpha for t in w] if alpha > 0 else [0.0] * len(w) # @line L4
us.append(u)
vs.append(v)
alphas.append(alpha)
betas.append(beta)
proj = Projected(bidiag_matrix(alphas, betas, k), beta1) # @line L5
if rule == "dp":
lam = choose_dp(proj, delta, tau)
elif rule == "wgcv":
lam = choose_wgcv(proj, omega)
else:
lam = float(rule) # @line L6
z = proj.z(lam) # @line L7
x = [sum(z[j] * vs[j][i] for j in range(k)) for i in range(len(v))] # @line L8
iterates.append(x)
lams.append(lam)
resnorms.append(math.sqrt(proj.res2(lam)))
if alpha <= 1e-14 * alphas[0] or beta <= 1e-14 * beta1:
stopped = "breakdown"
break
return HybridResult(x=iterates[-1], k=len(iterates), iterates=iterates, lams=lams, # @line L9
resnorms=resnorms, stopped=stopped, proj=proj, basis=vs[:len(iterates)])
def hybrid_matrix(a, y, kmax, rule="dp", delta=None, tau=1.01, omega=1.0):
"""The hybrid method for a dense matrix A (a list of rows)."""
return hybrid_lsqr(lambda x: matvec(a, x), lambda r: rmatvec(a, r), y, kmax,
rule=rule, delta=delta, tau=tau, omega=omega)
imgla.py 259 lines
# 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
test_hybrid_krylov_regularization.py 148 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hybrid-krylov-regularization/. The authors are listed in prov/WCZ0JJ.jsonl.
import math
import random
import unittest
from hybrid_krylov_regularization import choose_wgcv, hybrid_lsqr, hybrid_matrix
from imgla import adjoint_gap, matmul, matvec, norm2, rmatvec, solve, transpose
def rand_matrix(rng, m, n):
return [[rng.uniform(-1.0, 1.0) for _ in range(n)] for _ in range(m)]
def krylov_basis(a, y, k):
"""Orthonormal basis of K_k(A^T A, A^T y) by Gram-Schmidt, twice."""
ata = matmul(transpose(a), a)
q, w = [], rmatvec(a, y)
for _ in range(k):
for _ in range(2):
for b in q:
h = sum(p * t for p, t in zip(b, w))
w = [p - h * t for p, t in zip(w, b)]
nw = norm2(w)
q.append([p / nw for p in w])
w = matvec(ata, q[-1])
return q
def restricted_tikhonov(a, y, q, lam):
"""Brute force: minimize ||A x - y||^2 + lam ||x||^2 over x = Q c."""
aq = [matvec(a, b) for b in q]
k = len(q)
gram = [[sum(p * t for p, t in zip(aq[i], aq[j])) + (lam if i == j else 0.0)
for j in range(k)] for i in range(k)]
c = solve(gram, [sum(p * t for p, t in zip(u, y)) for u in aq])
return [sum(c[j] * q[j][i] for j in range(k)) for i in range(len(a[0]))]
def integration_problem(n, rel, seed):
h = 1.0 / n
a = [[h if j <= i else 0.0 for j in range(n)] for i in range(n)]
xt = [math.exp(-(((i + 0.5) * h - 0.5) / 0.15) ** 2) for i in range(n)]
y = matvec(a, xt)
rng = random.Random(seed)
e = [rng.gauss(0.0, 1.0) for _ in range(n)]
ne = norm2(e)
delta = rel * norm2(y)
return a, xt, [p + delta * q / ne for p, q in zip(y, e)], delta
def rel_err(x, xt):
return norm2([p - q for p, q in zip(x, xt)]) / norm2(xt)
class TestHybrid(unittest.TestCase):
def test_projected_tikhonov_is_restricted_tikhonov(self):
rng = random.Random(41)
a = rand_matrix(rng, 9, 6)
y = [rng.gauss(0.0, 1.0) for _ in range(9)]
for lam in (0.0, 0.1, 2.0):
res = hybrid_matrix(a, y, 4, rule=lam)
for k in range(1, 5):
ref = restricted_tikhonov(a, y, krylov_basis(a, y, k), lam)
gap = norm2([p - q for p, q in zip(res.iterates[k - 1], ref)])
self.assertLess(gap, 1e-8 * norm2(ref))
def test_full_space_gives_tikhonov(self):
rng = random.Random(42)
a = rand_matrix(rng, 8, 5)
y = [rng.gauss(0.0, 1.0) for _ in range(8)]
lam = 0.3
x = hybrid_matrix(a, y, 5, rule=lam).x
ata = matmul(transpose(a), a)
for i in range(5):
ata[i][i] += lam
ref = solve(ata, rmatvec(a, y))
for p, q in zip(x, ref):
self.assertAlmostEqual(p, q, places=9)
def test_projected_residual_is_true_residual(self):
rng = random.Random(43)
a = rand_matrix(rng, 10, 7)
y = [rng.gauss(0.0, 1.0) for _ in range(10)]
res = hybrid_matrix(a, y, 5, rule=0.05)
for x, rn in zip(res.iterates, res.resnorms):
true = norm2([p - q for p, q in zip(matvec(a, x), y)])
self.assertAlmostEqual(rn, true, places=10)
def test_discrepancy_rule(self):
a, xt, yd, delta = integration_problem(48, 0.01, 7)
tau = 1.01
res = hybrid_matrix(a, yd, 15, rule="dp", delta=delta, tau=tau)
for lam, rn in zip(res.lams, res.resnorms):
if lam > 0.0:
self.assertAlmostEqual(rn / (tau * delta), 1.0, places=6)
# Within a factor 1.5 of the best parameter on a grid, for the same Krylov space.
best = min(rel_err(res.solve(10.0 ** (-p / 8.0)), xt) for p in range(0, 120))
self.assertLess(rel_err(res.x, xt), 1.5 * best)
def test_no_semi_convergence_in_k(self):
a, xt, yd, delta = integration_problem(48, 0.01, 8)
dp = hybrid_matrix(a, yd, 15, rule="dp", delta=delta)
plain = hybrid_matrix(a, yd, 15, rule=0.0)
e10, e15 = rel_err(dp.iterates[9], xt), rel_err(dp.iterates[14], xt)
self.assertLess(abs(e15 - e10), 0.05 * e10)
self.assertGreater(rel_err(plain.x, xt), 2.0 * e15)
def test_wgcv_minimizes_its_function(self):
a, xt, yd, delta = integration_problem(48, 0.001, 9)
res = hybrid_matrix(a, yd, 10, rule="wgcv")
proj = res.proj
for omega in (1.0, 1.5):
lam = choose_wgcv(proj, omega)
s1 = proj.s[0] ** 2
fine = min(proj.gcv(s1 * 10.0 ** (-14.0 * i / 2000.0), omega) for i in range(2001))
self.assertLessEqual(proj.gcv(lam, omega), fine * (1.0 + 1e-9))
def test_matrix_free_operator(self):
n = 30
h = 1.0 / n
rng = random.Random(44)
def op(x):
out, acc = [], 0.0
for t in x:
acc += h * t
out.append(acc)
return out
def opt(y):
out, acc = [0.0] * n, 0.0
for i in range(n - 1, -1, -1):
acc += h * y[i]
out[i] = acc
return out
x = [rng.gauss(0.0, 1.0) for _ in range(n)]
z = [rng.gauss(0.0, 1.0) for _ in range(n)]
self.assertLess(adjoint_gap(op, opt, x, z), 1e-12)
a = [[h if j <= i else 0.0 for j in range(n)] for i in range(n)]
free = hybrid_lsqr(op, opt, z, 6, rule=1e-4).x
dense = hybrid_matrix(a, z, 6, rule=1e-4).x
self.assertLess(norm2([p - q for p, q in zip(free, dense)]), 1e-8 * norm2(dense))
if __name__ == "__main__":
unittest.main()
History
O'Leary and Simmons (1981) proposed to regularize the small bidiagonal problem from the Lanczos bidiagonalization instead of the large problem. Paige and Saunders (1982) published LSQR on the same bidiagonalization. Later work studied how to choose the parameter of the projected problem; Kilmer and O'Leary (2001) compared several rules, and Chung, Nagy and O'Leary (2008) introduced weighted GCV. Hybrid methods are now a standard tool in large-scale imaging.
References
- D. P. O'Leary and J. A. Simmons, A bidiagonalization-regularization procedure for large scale discretizations of ill-posed problems, SIAM Journal on Scientific and Statistical Computing 2(4), 1981, 474 to 489, the idea of regularizing the projected bidiagonal problem (general locator)
- M. E. Kilmer and D. P. O'Leary, Choosing regularization parameters in iterative methods for ill-posed problems, SIAM Journal on Matrix Analysis and Applications 22(4), 2001, 1204 to 1221, parameter choice rules applied to the projected problem (general locator)
- J. Chung, J. G. Nagy and D. P. O'Leary, A weighted GCV method for Lanczos hybrid regularization, Electronic Transactions on Numerical Analysis 28, 2008, 149 to 167, the weighted GCV function of the projected problem and the choice of its weight (general locator)
- Christopher C. Paige and Michael A. Saunders, LSQR, an algorithm for sparse linear equations and sparse least squares, ACM Transactions on Mathematical Software 8(1), 1982, 43 to 71, the Golub-Kahan bidiagonalization and its relations
- Per Christian Hansen, Discrete Inverse Problems, Insight and Algorithms, SIAM, 2010, Chapter 6 (iterative regularization with Krylov methods) (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 WCZ0JJ Edit this page History Report an error Markdown