Algorithm Search⌘K

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
Properties
deterministiciterativenot linear in datamatrix free
Origin
Dianne P. O'Leary, John A. Simmons, 1981

A hybrid Krylov method solves a large ill-posed least squares problem min⁡x∥Ax−yδ∥\min_x \|A x - y^\delta\| by combining two kinds of regularization. Like LSQR, it runs the Golub-Kahan bidiagonalization, which after kk steps gives an orthonormal basis VkV_k of the Krylov space Kk(A∗A,A∗yδ)\mathcal{K}_k(A^* A, A^* y^\delta) and a small (k+1)×k(k+1) \times k bidiagonal matrix BkB_k. Unlike LSQR, it does not solve the projected least squares problem as it stands. It applies Tikhonov regularization to it, with a parameter λk\lambda_k chosen anew at every step from the small problem alone, by the discrepancy principle or by a weighted form of GCV. The result xk=Vkzkx_k = V_k z_k is exactly the minimizer of the Tikhonov functional ∥Ax−yδ∥2+λk∥x∥2\|A x - y^\delta\|^2 + \lambda_k\|x\|^2 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 k×kk \times k 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 AA (m×nm \times n matrix, or operator between Hilbert spaces) available only through the products x↦Axx \mapsto A x and r↦A∗rr \mapsto A^* r, data yδy^\delta with ∥yδ−Ax†∥≤δ\|y^\delta - A x^\dagger\| \le \delta, and a rule for the Tikhonov parameter, compute for k=1,2,…k = 1, 2, \dots

xk=argmin⁡x∈Kk∥Ax−yδ∥2+λk∥x∥2,Kk=span{A∗yδ,(A∗A)A∗yδ,…,(A∗A)k−1A∗yδ},x_k = \operatorname*{argmin}_{x \in \mathcal{K}_k} \|A x - y^\delta\|^2 + \lambda_k \|x\|^2, \qquad \mathcal{K}_k = \mathrm{span}\{A^* y^\delta, (A^* A) A^* y^\delta, \dots, (A^* A)^{k-1} A^* y^\delta\},

where λk\lambda_k is chosen by the rule from information about the projected problem only. The rules here are a fixed λ\lambda, the discrepancy principle ∥Axk−yδ∥=τδ\|A x_k - y^\delta\| = \tau\delta (which needs δ\delta), and weighted GCV (which does not).

The algorithm

  1. HYBRID-LSQR(A, y, K, rule) ▷ rule: "dp" (needs δ, τ), "wgcv" (weight ω) or a fixed λ ≥ 0
  2. 1β₁ u₁ ← y; α₁ v₁ ← A* u₁ ▷ β₁, α₁ norms; u₁, v₁ unit vectors
  3. 2for k ← 1 to K do
  4. 3β_{k+1} u_{k+1} ← A v_k - α_k u_k ▷ reorthogonalize against u₁, …, u_k
  5. 4α_{k+1} v_{k+1} ← A* u_{k+1} - β_{k+1} v_k ▷ reorthogonalize against v₁, …, v_k
  6. 5P Σ Qᵀ ← SVD of B_k ▷ B_k: α₁…α_k on the diagonal, β₂…β_{k+1} below
  7. 6λ_k ← rule applied to (Σ, β₁ Pᵀ e₁)
  8. 7z_k ← argmin ‖B_k z - β₁ e₁‖² + λ_k ‖z‖²
  9. 8x_k ← V_k z_k ▷ V_k = [v₁, …, v_k]
  10. 9return 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 AVk=Uk+1BkA V_k = U_{k+1} B_k and y=β1Uk+1e1y = \beta_1 U_{k+1} e_1. 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 Bk=PΣQTB_k = P \Sigma Q^T of the small matrix, with PP of size (k+1)×k(k+1) \times k, singular values s1≥⋯≥sks_1 \ge \dots \ge s_k, and coefficients gi=β1(PTe1)ig_i = \beta_1 (P^T e_1)_i. Every quantity the rules need is then a short sum. The projected solution and its residual are

z(λ)=∑isigisi2+λqi,∥Bkz(λ)−β1e1∥2=∑i(λgisi2+λ)2+(β12−∑igi2).z(\lambda) = \sum_i \frac{s_i g_i}{s_i^2 + \lambda} q_i, \qquad \|B_k z(\lambda) - \beta_1 e_1\|^2 = \sum_i \Big(\frac{\lambda g_i}{s_i^2 + \lambda}\Big)^2 + \Big(\beta_1^2 - \sum_i g_i^2\Big).

Line L6 chooses λk\lambda_k:

  • Discrepancy principle ("dp"). The residual grows with λ\lambda, so bisection on log⁡λ\log\lambda finds the λ\lambda with residual τδ\tau\delta. If even λ=0\lambda = 0 gives a residual above τδ\tau\delta, the Krylov space is still too small to fit the data to the noise level, and the code takes λk=0\lambda_k = 0, a plain LSQR step.
  • Weighted GCV ("wgcv"). Minimize G(λ)=∥Bkz(λ)−β1e1∥2/(k+1−ω∑isi2/(si2+λ))2G(\lambda) = \|B_k z(\lambda) - \beta_1 e_1\|^2 / \big(k + 1 - \omega\sum_i s_i^2/(s_i^2 + \lambda)\big)^2, first on a grid of 81 values of log⁡λ\log\lambda and then by golden section. With ω=1\omega = 1 this is GCV for the small problem. Chung, Nagy and O'Leary (2008) introduced the weight ω\omega because plain GCV on the projected problem often picks a λ\lambda that is too small.
  • Fixed λ\lambda. Then xkx_k converges, as kk grows, to the Tikhonov solution of the full problem.

Lines L7 and L8 compute zk=z(λk)z_k = z(\lambda_k) and xk=Vkzkx_k = V_k z_k. The loop also stops if αk+1\alpha_{k+1} or βk+1\beta_{k+1} is zero (to rounding), because then the Krylov space is invariant and later steps add nothing. The function HybridResult.solve(λ) gives Vkz(λ)V_k z(\lambda) for any other λ\lambda without new products with AA.

Example

The test problem of the code: the 48×4848 \times 48 matrix of the integration operator (Aij=hA_{ij} = h for j≤ij \le i, h=1/48h = 1/48), the true solution x†(t)=e−((t−0.5)/0.15)2x^\dagger(t) = e^{-((t - 0.5)/0.15)^2} at the cell centers, and Gaussian noise drawn with random.Random(8) and scaled to δ=0.01 ∥Ax†∥=0.01237\delta = 0.01\,\|A x^\dagger\| = 0.01237. The table gives the relative error ∥xk−x†∥/∥x†∥\|x_k - x^\dagger\|/\|x^\dagger\| and the chosen λk\lambda_k (a measurement).

kk plain LSQR (λ=0\lambda = 0) hybrid, dp (τ=1.01\tau = 1.01) λk\lambda_k (dp) hybrid, wgcv ω=1\omega = 1 hybrid, wgcv ω=1.5\omega = 1.5
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 3.7⋅10−43.7 \cdot 10^{-4} 0.0467 0.4394
6 0.0614 0.0579 4.8⋅10−44.8 \cdot 10^{-4} 0.0572
8 0.1786 0.0818 5.3⋅10−45.3 \cdot 10^{-4} 0.1387 0.2447
10 0.2459 0.0820 5.3⋅10−45.3 \cdot 10^{-4} 0.2335 0.1866
15 0.2634 0.0821 5.3⋅10−45.3 \cdot 10^{-4} 0.2633 0.1155
30 0.2635 0.0821 5.3⋅10−45.3 \cdot 10^{-4} 0.2635 0.0787

Plain LSQR is best at k=5k = 5 (error 0.04660.0466) and then grows by a factor of more than 55. For k≤4k \le 4 even λ=0\lambda = 0 leaves a residual above τδ\tau\delta, so the discrepancy rule takes plain LSQR steps. From k=5k = 5 on it takes λk≈5.3⋅10−4\lambda_k \approx 5.3 \cdot 10^{-4}, and the error stays at 0.08210.0821 for all later kk. For comparison, Tikhonov on the full problem with the best λ\lambda on a grid gives 0.07860.0786, at λ≈7.9⋅10−4\lambda \approx 7.9 \cdot 10^{-4}. Plain GCV (ω=1\omega = 1) fails on this data set: its λk\lambda_k falls to 10−1410^{-14} and the iterates follow plain LSQR. With ω=1.5\omega = 1.5, weighted GCV over-smooths at first and reaches 0.07870.0787 at k=30k = 30. A good weight depends on the problem, which is why Chung, Nagy and O'Leary choose ω\omega adaptively.

Correctness

The proofs are in proofs/correctness.md, in exact arithmetic, as long as no breakdown (αj=0\alpha_j = 0 or βj=0\beta_j = 0) has occurred.

  • Bidiagonalization (theorem). Uk+1U_{k+1} and VkV_k have orthonormal columns, AVk=Uk+1BkA V_k = U_{k+1} B_k, y=β1Uk+1e1y = \beta_1 U_{k+1} e_1, and the columns of VkV_k span Kk(A∗A,A∗y)\mathcal{K}_k(A^* A, A^* y).
  • Projection (theorem). For x=Vkzx = V_k z, ∥Ax−y∥2+λ∥x∥2=∥Bkz−β1e1∥2+λ∥z∥2\|A x - y\|^2 + \lambda\|x\|^2 = \|B_k z - \beta_1 e_1\|^2 + \lambda\|z\|^2. 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). λ=0\lambda = 0 gives the LSQR (and CGLS) iterate. If the Krylov space is invariant under A∗AA^* A (at the latest at k=rank(A)k = \mathrm{rank}(A) for a matrix), xkx_k is the Tikhonov solution of the full problem.
  • Discrepancy rule (theorem). The projected residual is a continuous nondecreasing function of λ\lambda with limit β1=∥y∥\beta_1 = \|y\|, so if ∥Bkz(0)−β1e1∥<τδ<∥y∥\|B_k z(0) - \beta_1 e_1\| < \tau\delta < \|y\|, the bisection finds a λ\lambda with residual τδ\tau\delta to any accuracy.
  • Termination (theorem). The loop runs at most KK 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 δ→0\delta \to 0 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. A:X→YA: X \to Y is a bounded linear operator between Hilbert spaces (a real m×nm \times n matrix in the code), y≠0y \ne 0 are the data, and Kk=span{A∗y,(A∗A)A∗y,…,(A∗A)k−1A∗y}\mathcal{K}_k = \mathrm{span}\{A^* y, (A^* A) A^* y, \dots, (A^* A)^{k-1} A^* y\}. Lines L1, L3 and L4 compute, with v0=0v_0 = 0,

β1u1=y,α1v1=A∗u1,βj+1uj+1=Avj−αjuj,αj+1vj+1=A∗uj+1−βj+1vj,\beta_1 u_1 = y, \quad \alpha_1 v_1 = A^* u_1, \quad \beta_{j+1} u_{j+1} = A v_j - \alpha_j u_j, \quad \alpha_{j+1} v_{j+1} = A^* u_{j+1} - \beta_{j+1} v_j,

where each α\alpha and β\beta is the norm of the vector on the right, after the vector has been reorthogonalized against the earlier uu's or vv's. We say that no breakdown has occurred up to step kk if α1,…,αk\alpha_1, \dots, \alpha_{k} and β1,…,βk+1\beta_1, \dots, \beta_{k+1} are all positive. BkB_k is the (k+1)×k(k+1) \times k matrix with α1,…,αk\alpha_1, \dots, \alpha_k on the diagonal and β2,…,βk+1\beta_2, \dots, \beta_{k+1} just below it, Uk+1=[u1,…,uk+1]U_{k+1} = [u_1, \dots, u_{k+1}] and Vk=[v1,…,vk]V_k = [v_1, \dots, v_k].

Lemma 1 (Golub-Kahan relations). If no breakdown has occurred up to step kk, then the reorthogonalization subtracts nothing, Uk+1U_{k+1} and Vk+1V_{k+1} (if αk+1>0\alpha_{k+1} > 0) have orthonormal columns, and

AVk=Uk+1Bk,A∗uj=βjvj−1+αjvj (j≤k+1),y=β1Uk+1e1.A V_k = U_{k+1} B_k, \qquad A^* u_j = \beta_j v_{j-1} + \alpha_j v_j \ (j \le k+1), \qquad y = \beta_1 U_{k+1} e_1 .

Moreover the columns of VkV_k form an orthonormal basis of Kk\mathcal{K}_k.

Proof. Induction on kk. For the start, u1=y/β1u_1 = y/\beta_1 and v1=A∗u1/α1v_1 = A^* u_1/\alpha_1 are unit vectors and A∗u1=α1v1A^* u_1 = \alpha_1 v_1.

Assume that u1,…,uku_1, \dots, u_k and v1,…,vkv_1, \dots, v_k are orthonormal, that Avj=αjuj+βj+1uj+1A v_j = \alpha_j u_j + \beta_{j+1} u_{j+1} for j<kj < k, and that A∗uj=βjvj−1+αjvjA^* u_j = \beta_j v_{j-1} + \alpha_j v_j for j≤kj \le k. Let w=Avk−αkukw = A v_k - \alpha_k u_k. For i≤ki \le k,

⟨ui,Avk⟩=⟨A∗ui,vk⟩=βi⟨vi−1,vk⟩+αi⟨vi,vk⟩,\langle u_i, A v_k \rangle = \langle A^* u_i, v_k\rangle = \beta_i \langle v_{i-1}, v_k\rangle + \alpha_i\langle v_i, v_k\rangle,

which is αk\alpha_k for i=ki = k and 00 for i<ki < k. So ⟨ui,w⟩=0\langle u_i, w\rangle = 0 for all i≤ki \le k. The reorthogonalization subtracts the projections of ww on u1,…,uku_1, \dots, u_k, which are zero, so it leaves ww unchanged. Then βk+1=∥w∥>0\beta_{k+1} = \|w\| > 0, uk+1=w/βk+1u_{k+1} = w/\beta_{k+1} is a unit vector orthogonal to u1,…,uku_1, \dots, u_k, and Avk=αkuk+βk+1uk+1A v_k = \alpha_k u_k + \beta_{k+1} u_{k+1}.

Now let w′=A∗uk+1−βk+1vkw' = A^* u_{k+1} - \beta_{k+1} v_k. For i≤ki \le k,

⟨vi,A∗uk+1⟩=⟨Avi,uk+1⟩=αi⟨ui,uk+1⟩+βi+1⟨ui+1,uk+1⟩,\langle v_i, A^* u_{k+1}\rangle = \langle A v_i, u_{k+1}\rangle = \alpha_i \langle u_i, u_{k+1}\rangle + \beta_{i+1}\langle u_{i+1}, u_{k+1}\rangle,

which is βk+1\beta_{k+1} for i=ki = k and 00 for i<ki < k. So w′w' is orthogonal to v1,…,vkv_1, \dots, v_k, the reorthogonalization again subtracts nothing, and A∗uk+1=βk+1vk+αk+1vk+1A^* u_{k+1} = \beta_{k+1} v_k + \alpha_{k+1} v_{k+1} with vk+1v_{k+1} a unit vector orthogonal to the earlier vv's when αk+1>0\alpha_{k+1} > 0. This completes the induction.

The relations Avj=αjuj+βj+1uj+1A v_j = \alpha_j u_j + \beta_{j+1} u_{j+1}, j=1,…,kj = 1, \dots, k, are the columns of AVk=Uk+1BkA V_k = U_{k+1} B_k, and y=β1u1=β1Uk+1e1y = \beta_1 u_1 = \beta_1 U_{k+1} e_1.

For the span, v1∈K1v_1 \in \mathcal{K}_1. If v1,…,vj∈Kjv_1, \dots, v_j \in \mathcal{K}_j, then αj+1vj+1=A∗uj+1−βj+1vj\alpha_{j+1} v_{j+1} = A^* u_{j+1} - \beta_{j+1} v_j and βj+1A∗uj+1=A∗Avj−αjA∗uj=A∗Avj−αj(βjvj−1+αjvj)\beta_{j+1} A^* u_{j+1} = A^* A v_j - \alpha_j A^* u_j = A^* A v_j - \alpha_j(\beta_j v_{j-1} + \alpha_j v_j), which lies in Kj+1\mathcal{K}_{j+1} because A∗AKj⊆Kj+1A^* A \mathcal{K}_j \subseteq \mathcal{K}_{j+1}. So vj+1∈Kj+1v_{j+1} \in \mathcal{K}_{j+1}. The kk orthonormal vectors v1,…,vkv_1, \dots, v_k lie in Kk\mathcal{K}_k, whose dimension is at most kk, so they are a basis of it. □\square

Lemma 2 (projection). Under the assumption of Lemma 1, for every z∈Rkz \in \mathbb{R}^k and x=Vkzx = V_k z,

∥Ax−y∥=∥Bkz−β1e1∥,∥x∥=∥z∥.\|A x - y\| = \|B_k z - \beta_1 e_1\|, \qquad \|x\| = \|z\| .

Hence for λ≥0\lambda \ge 0, x=Vkzx = V_k z minimizes ∥Ax−y∥2+λ∥x∥2\|A x - y\|^2 + \lambda\|x\|^2 over Kk\mathcal{K}_k if and only if zz minimizes ∥Bkz−β1e1∥2+λ∥z∥2\|B_k z - \beta_1 e_1\|^2 + \lambda\|z\|^2 over Rk\mathbb{R}^k.

Proof. By Lemma 1, Ax−y=AVkz−β1Uk+1e1=Uk+1(Bkz−β1e1)A x - y = A V_k z - \beta_1 U_{k+1} e_1 = U_{k+1}(B_k z - \beta_1 e_1), and Uk+1U_{k+1} has orthonormal columns, so it preserves norms. Also ∥Vkz∥=∥z∥\|V_k z\| = \|z\| because VkV_k has orthonormal columns. Since z↦Vkzz \mapsto V_k z is a bijection of Rk\mathbb{R}^k onto Kk\mathcal{K}_k (Lemma 1), the two minimization problems correspond. □\square

Lemma 3 (the small problem in closed form). Let Bk=PΣQTB_k = P \Sigma Q^T be a thin SVD, with PP of size (k+1)×k(k+1) \times k and orthonormal columns pip_i, QQ orthogonal with columns qiq_i, and Σ=diag(s1,…,sk)\Sigma = \mathrm{diag}(s_1, \dots, s_k). Put gi=β1⟨pi,e1⟩g_i = \beta_1 \langle p_i, e_1\rangle. Under the assumption of Lemma 1, all si>0s_i > 0, and for λ≥0\lambda \ge 0 the unique minimizer of ∥Bkz−β1e1∥2+λ∥z∥2\|B_k z - \beta_1 e_1\|^2 + \lambda\|z\|^2 is

z(λ)=∑i=1ksigisi2+λqi,with∥Bkz(λ)−β1e1∥2=∑i=1k(λgisi2+λ)2+(β12−∑i=1kgi2).z(\lambda) = \sum_{i=1}^k \frac{s_i g_i}{s_i^2 + \lambda} q_i, \qquad \text{with} \qquad \|B_k z(\lambda) - \beta_1 e_1\|^2 = \sum_{i=1}^k \Big(\frac{\lambda g_i}{s_i^2 + \lambda}\Big)^2 + \Big(\beta_1^2 - \sum_{i=1}^k g_i^2\Big).

These are the formulas of Projected.z and Projected.res2 (lines L5 and L7).

Proof. BkB_k is lower bidiagonal with nonzero diagonal α1,…,αk\alpha_1, \dots, \alpha_k, so its top k×kk \times k block is nonsingular and BkB_k has full column rank; hence all si>0s_i > 0. The functional is strictly convex in zz and its gradient vanishes exactly when (BkTBk+λI)z=BkTβ1e1(B_k^T B_k + \lambda I) z = B_k^T \beta_1 e_1. In the coordinates z=∑iciqiz = \sum_i c_i q_i this reads (si2+λ)ci=sigi(s_i^2 + \lambda) c_i = s_i g_i, which gives z(λ)z(\lambda). For the residual, write β1e1=∑igipi+r⊥\beta_1 e_1 = \sum_i g_i p_i + r_\perp with r⊥r_\perp orthogonal to all pip_i, so ∥r⊥∥2=β12−∑igi2\|r_\perp\|^2 = \beta_1^2 - \sum_i g_i^2. Then Bkz(λ)=∑isi2gisi2+λpiB_k z(\lambda) = \sum_i \frac{s_i^2 g_i}{s_i^2 + \lambda} p_i and

Bkz(λ)−β1e1=−∑iλgisi2+λpi−r⊥,B_k z(\lambda) - \beta_1 e_1 = -\sum_i \frac{\lambda g_i}{s_i^2 + \lambda} p_i - r_\perp,

whose squared norm is the stated sum, by Pythagoras. □\square

Theorem 1 (what line L8 returns). Under the assumption of Lemma 1, for the λk\lambda_k chosen at line L6, the vector xk=Vkz(λk)x_k = V_k z(\lambda_k) of line L8 is the unique minimizer of ∥Ax−y∥2+λk∥x∥2\|A x - y\|^2 + \lambda_k\|x\|^2 over Kk\mathcal{K}_k, and ∥Axk−y∥\|A x_k - y\| equals the projected residual of Lemma 3. For λk=0\lambda_k = 0 it is the iterate of LSQR and CGLS, the minimizer of ∥Ax−y∥\|A x - y\| over Kk\mathcal{K}_k.

Proof. Lemmas 2 and 3. □\square

Theorem 2 (invariant Krylov space). Suppose that the loop stops at step kk because αk+1=0\alpha_{k+1} = 0 or βk+1=0\beta_{k+1} = 0 (in the second case, the relations of Lemma 1 hold with uk+1u_{k+1} omitted). Then A∗AKk⊆KkA^* A \mathcal{K}_k \subseteq \mathcal{K}_k, and for λ>0\lambda > 0, xkx_k is the Tikhonov solution xλ=(A∗A+λI)−1A∗yx_\lambda = (A^* A + \lambda I)^{-1} A^* y of the full problem. For a matrix, this happens at some k≤rank(A)k \le \mathrm{rank}(A).

Proof. By Lemma 1, A∗Avj∈Kj+1⊆KkA^* A v_j \in \mathcal{K}_{j+1} \subseteq \mathcal{K}_k for j<kj < k. For j=kj = k: if βk+1=0\beta_{k+1} = 0, then Avk=αkukA v_k = \alpha_k u_k and A∗Avk=αk(βkvk−1+αkvk)∈KkA^* A v_k = \alpha_k(\beta_k v_{k-1} + \alpha_k v_k) \in \mathcal{K}_k. If αk+1=0\alpha_{k+1} = 0, then A∗uk+1=βk+1vkA^* u_{k+1} = \beta_{k+1} v_k and A∗Avk=αkA∗uk+βk+1A∗uk+1=αk(βkvk−1+αkvk)+βk+12vk∈KkA^* A v_k = \alpha_k A^* u_k + \beta_{k+1} A^* u_{k+1} = \alpha_k(\beta_k v_{k-1} + \alpha_k v_k) + \beta_{k+1}^2 v_k \in \mathcal{K}_k. So Kk\mathcal{K}_k is invariant under A∗AA^* A. For λ>0\lambda > 0 the map A∗A+λIA^* A + \lambda I is injective on the finite-dimensional invariant space Kk\mathcal{K}_k, hence maps it onto itself, and since A∗y∈KkA^* y \in \mathcal{K}_k, also xλ=(A∗A+λI)−1A∗y∈Kkx_\lambda = (A^* A + \lambda I)^{-1} A^* y \in \mathcal{K}_k. The minimizer over the whole space lies in Kk\mathcal{K}_k, so it is the minimizer over Kk\mathcal{K}_k, which is xkx_k by Theorem 1. For a matrix, Kk⊆R(A∗)\mathcal{K}_k \subseteq R(A^*), whose dimension is rank(A)\mathrm{rank}(A); by Lemma 1 dim⁡Kk=k\dim \mathcal{K}_k = k as long as there is no breakdown, so a breakdown occurs at some k≤rank(A)k \le \mathrm{rank}(A). □\square

Theorem 3 (the discrepancy rule). Let ϕ(λ)=∥Bkz(λ)−β1e1∥2\phi(\lambda) = \|B_k z(\lambda) - \beta_1 e_1\|^2 and T=(τδ)2T = (\tau\delta)^2. Then ϕ\phi is continuous and nondecreasing on [0,∞)[0, \infty) with ϕ(λ)→β12=∥y∥2\phi(\lambda) \to \beta_1^2 = \|y\|^2 as λ→∞\lambda \to \infty. If ϕ(0)<T<∥y∥2\phi(0) < T < \|y\|^2, there is a λ∗>0\lambda^* > 0 with ϕ(λ∗)=T\phi(\lambda^*) = T, and it is unique if some gi≠0g_i \ne 0. The function choose_dp returns 00 when ϕ(0)≥T\phi(0) \ge T; otherwise, if ϕ(λlo)<T≤ϕ(λhi)\phi(\lambda_{lo}) < T \le \phi(\lambda_{hi}) at the two ends of its search interval, every bisection step keeps this property, so after jj steps the returned λ\lambda is within a factor e(log⁡λhi−log⁡λlo)/2j+1e^{(\log\lambda_{hi} - \log\lambda_{lo})/2^{j+1}} of a solution of ϕ(λ)=T\phi(\lambda) = T.

Proof. By Lemma 3, ϕ(λ)=∑igi2(λ/(si2+λ))2+∥r⊥∥2\phi(\lambda) = \sum_i g_i^2 (\lambda/(s_i^2 + \lambda))^2 + \|r_\perp\|^2. Each map λ↦λ/(si2+λ)\lambda \mapsto \lambda/(s_i^2 + \lambda) is continuous and increasing from 00 to 11 because si>0s_i > 0, so ϕ\phi is continuous, nondecreasing, strictly increasing if some gi≠0g_i \ne 0, and tends to ∑igi2+∥r⊥∥2=β12\sum_i g_i^2 + \|r_\perp\|^2 = \beta_1^2. The intermediate value theorem gives λ∗\lambda^*. The bisection replaces the lower end by the midpoint when ϕ(mid)<T\phi(\text{mid}) < T and the upper end otherwise, which keeps ϕ(λlo)<T≤ϕ(λhi)\phi(\lambda_{lo}) < T \le \phi(\lambda_{hi}); by continuity and monotonicity a solution lies in [λlo,λhi][\lambda_{lo}, \lambda_{hi}], and the length of [log⁡λlo,log⁡λhi][\log\lambda_{lo}, \log\lambda_{hi}] halves at each step. □\square

Theorem 4 (termination). hybrid_lsqr returns after at most KK passes of the loop at line L2. Each pass does a finite amount of work: two operator products, two reorthogonalizations against at most K+1K + 1 vectors, one SVD of a (K+1)×K(K + 1) \times K matrix, and at most 200200 bisection steps or 8181 grid points plus 6060 golden section steps, each costing O(k)O(k).

Proof. The loop is a counted loop over k=1,…,Kk = 1, \dots, K with an early exit on breakdown, and the parameter searches are counted loops. □\square

What is not proved here. The behavior in floating point without reorthogonalization, and rates as δ→0\delta \to 0 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 AA and one with A∗A^*, plus O(k(m+n))O(k(m + n)) for the reorthogonalization. Line L5 costs O(k3)O(k^3) for the SVD of BkB_k (an SVD that uses the bidiagonal structure would cost O(k2)O(k^2)). Line L6 costs O(k)O(k) per evaluation of the residual or of GG, times a fixed number of evaluations. Line L8 costs O(nk)O(n k).
  • Total. O(ka+k2(m+n)+k4)O(k a + k^2(m + n) + k^4) time for kk steps, where aa is the cost of one product with AA plus one with A∗A^*, and O(k(m+n))O(k(m + n)) space for the two bases.
  • In practice kk is a few tens to a few hundred, much less than nn, so the products with AA and the reorthogonalization dominate. Plain LSQR without reorthogonalization needs only O(m+n)O(m + n) space, which is the price of the hybrid method's stability.

Properties

  • Stable in kk. Once the Krylov space contains the components that the data determine well, λk\lambda_k 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 λk\lambda_k depend on yδy^\delta.
  • Matrix-free. Only products with AA and A∗A^*.
  • The parameter is cheap. Trying another λ\lambda costs O(k2)O(k^2), with no product with AA.
  • Rules without δ\delta are heuristics. Weighted GCV does not use δ\delta, so by the Bakushinskii veto it cannot work for all noise; the example shows it failing with ω=1\omega = 1.

Variants and improvements

  • Other projected rules. The L-curve, the discrepancy principle with an estimated δ\delta, or UPRE, each applied to the small problem.
  • Truncated SVD of the small problem. Replace Tikhonov at line L7 by truncating the SVD of BkB_k.
  • General-form penalty. For a penalty ∥Lx∥\|L x\| with L≠IL \ne I, transform the problem to standard form first, or use a joint bidiagonalization.
  • Arnoldi hybrids. For square AA, use the Arnoldi process (as in GMRES) instead of Golub-Kahan, which avoids products with A∗A^*.
  • Flexible and sparse hybrids. Iteratively reweighted penalties give hybrid methods for ℓ1\ell_1 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 AA is available only through products and an SVD of AA is out of reach, and where you do not want to tune the stopping index of LSQR by hand. With a good estimate of δ\delta, 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 λ\lambda that is too small, as in the example. Use a weight or check the result.
  • A residual target that is never reached. If τδ\tau\delta is below the smallest residual possible in the full space (for example because δ\delta is underestimated), the rule takes λ=0\lambda = 0 at every step, and the method is plain LSQR with its semi-convergence.
  • Stopping too early. For small kk the Krylov space misses part of the solution, and no choice of λ\lambda can fix that. Run until λk\lambda_k and xkx_k have settled.
  • A wrong adjoint. The theory needs A∗A^* to be the true adjoint of the code for AA. Check ⟨Ax,r⟩=⟨x,A∗r⟩\langle A x, r\rangle = \langle x, A^* r\rangle 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.

hybrid_krylov_regularization.pyI0RawGitHub
# 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

  1. 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)
  2. 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)
  3. 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)
  4. 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
  5. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.per_iteration
  • a full proof of time.total
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example