Algorithm Search⌘K

Algorithmadvanced

Quasi-optimality criterion

Also called quasi-optimality rule, quasi-optimality principle.

Choose the parameter on a geometric grid where the distance between successive regularized solutions is smallest, with no noise level needed.

Time
Θ(m n + N n) worst · average · best
Space
Θ(N + n) extra
Where
N = the number of grid steps; m = the number of measurements; n = the number of unknowns (n <= m)
Properties
not convergent regularizationdeterministicheuristicnot needs noise level
Origin
Andrey N. Tikhonov, Vladimir B. Glasko, 1965

The quasi-optimality criterion chooses the parameter of a regularization method from the data alone. Its idea: near the best parameter the regularized solution should be stable, so it should change little when the parameter changes a little. For Tikhonov regularization on a geometric grid αj=α0qj\alpha_j = \alpha_0q^j with 0<q<10 < q < 1, the discrete rule picks the αj\alpha_j that minimizes

dj=∥xαj+1−xαj∥.d_j = \lVert x_{\alpha_{j+1}} - x_{\alpha_j}\rVert.

The continuous form minimizes α∥dxα/dα∥\alpha\lVert dx_\alpha/d\alpha\rVert, which is the limit of dj/(1−q)d_j/(1 - q) as q→1q \to 1. Tikhonov and Glasko proposed the rule in 1965. It needs neither the noise level nor the noise variance, so it is a heuristic rule, and by the Bakushinskii veto it cannot be convergent for all noise. Under conditions on the noise it is: Bauer and Reiss (2008) proved oracle-type results for random noise, and Kindermann and Neubauer proved convergence for deterministic noise that satisfies a noise condition. It is simple, cheap, and works for any method with a parameter, including iteration counts.

In plain words

You want to know how much to smooth, and you do not know how noisy the data are. Compute the result for a sequence of knob settings, each a fixed factor smaller than the last. With too much smoothing, each step brings in new real detail, so the result changes a lot. With too little, each step brings in more noise, so the result also changes a lot. In between, the result hardly moves. The rule picks the setting where two neighbouring results are closest to each other. It needs no noise estimate, it is easy to code, and like every rule of this kind it can be fooled.

The problem

The model is y=Ax†+ey = Ax^\dagger + e with an m×nm \times n matrix AA and unknown noise ee. The Tikhonov solution for α>0\alpha > 0 is xα=(ATA+αI)−1ATyx_\alpha = (A^TA + \alpha I)^{-1}A^Ty. The page Tikhonov regularization writes λ\lambda for this α\alpha. With the thin SVD A=∑i≤rsiuiviTA = \sum_{i \le r} s_iu_iv_i^T and bi=⟨ui,y⟩b_i = \langle u_i, y\rangle,

xα=∑isibisi2+αvi,dj2=∑isi2bi2(1si2+αj+1−1si2+αj)2.x_\alpha = \sum_i \frac{s_ib_i}{s_i^2 + \alpha}v_i, \qquad d_j^2 = \sum_i s_i^2b_i^2\Big(\frac{1}{s_i^2 + \alpha_{j+1}} - \frac{1}{s_i^2 + \alpha_j}\Big)^2.

Given α0\alpha_0, qq and NN, the task is to find the index j∈{0,…,N−1}j \in \{0, \dots, N - 1\} with the smallest djd_j and return xαjx_{\alpha_j}. By default α0=s12\alpha_0 = s_1^2, q=1/2q = 1/2, and NN is the first index with αN≤sr2\alpha_N \le s_r^2.

The algorithm

  1. QUASI-OPTIMALITY(U, s, V, y, alpha_0, q, N) ▷ thin SVD of A, s descending, r positive values
  2. 1b_i ← <u_i, y> for i ≤ r
  3. 2alpha_j ← alpha_0 q^j for j = 0, ..., N
  4. 3d_j ← sqrt(Σ_i (s_i b_i (1/(s_i² + alpha_{j+1}) - 1/(s_i² + alpha_j)))²) for j = 0, ..., N - 1
  5. 4j* ← the index of the smallest d_j
  6. 5return alpha_{j*}, x = Σ_i s_i b_i / (s_i² + alpha_{j*}) · v_i, j*, and the list d

Line L1 projects the data on the left singular vectors. Line L2 builds the grid. Line L3 computes the distance between neighbouring solutions in the coordinates of the viv_i, where it is a sum over rr terms, so no solution vector is formed. Line L4 picks the smallest distance, and line L5 returns the solution at the larger of the two parameters of that pair, αj∗\alpha_{j^\ast}.

Example

Take the same problem as on the GCV page: A=diag(s1,…,s32)A = \mathrm{diag}(s_1, \dots, s_{32}) with si=1/i2s_i = 1/i^2, so U=V=IU = V = I, the true solution xi†=1/i2x^\dagger_i = 1/i^2, and ei=10−3gie_i = 10^{-3}g_i with gig_i from random.Random(0).gauss(0, 1). The defaults give α0=s12=1\alpha_0 = s_1^2 = 1, q=1/2q = 1/2 and N=20N = 20, since α20=2−20=s322\alpha_{20} = 2^{-20} = s_{32}^2.

jj αj\alpha_j djd_j ∥xαj−x†∥\lVert x_{\alpha_j} - x^\dagger\rVert
0 1 0.167317 0.5697
4 0.0625 0.051397 0.1882
7 7.81×10−37.81 \times 10^{-3} 0.023777 0.0902
8 3.91×10−33.91 \times 10^{-3} 0.018896 0.0725
9 1.95×10−31.95 \times 10^{-3} 0.017480 0.0615
10 9.77×10−49.77 \times 10^{-4} 0.022928 0.0583
11 4.88×10−44.88 \times 10^{-4} 0.036868 0.0672
12 2.44×10−42.44 \times 10^{-4} 0.061400 0.0946
14 6.10×10−56.10 \times 10^{-5} 0.160611 0.2430
19 1.91×10−61.91 \times 10^{-6} 0.564121 1.8197

The distances fall while the steps add signal and rise once they add noise. Line L4 picks j∗=9j^\ast = 9, so the rule returns α=2−9=0.001953\alpha = 2^{-9} = 0.001953 with error 0.061460.06146. The best α\alpha on a fine grid gives 0.058170.05817, so the rule loses 6 percent. Its neighbour j=10j = 10 has the smallest error on this grid, and the error curve is flat there. The noise level was not used at any point.

Correctness

The proof is in proofs/correctness.md. It shows that line L3 computes ∥xαj+1−xαj∥\lVert x_{\alpha_{j+1}} - x_{\alpha_j}\rVert, that the derivative is dxα/dα=−(ATA+αI)−1xαdx_\alpha/d\alpha = -(A^TA + \alpha I)^{-1}x_\alpha, so that dj/(1−q)→αj∥dxα/dα∥d_j/(1 - q) \to \alpha_j\lVert dx_\alpha/d\alpha\rVert as q→1q \to 1, and that the rule returns the minimizer over the finite grid. Termination is clear: the loop of line L3 has NN steps.

Why the minimizer is a good parameter is a separate question. Split xαx_\alpha into the noise-free part xˉα\bar x_\alpha and the noise part. The noise-free difference ∥xˉαj+1−xˉαj∥\lVert\bar x_{\alpha_{j+1}} - \bar x_{\alpha_j}\rVert is at most the approximation error at αj\alpha_j, and the noise difference is at most of the size of the noise propagation error at αj+1\alpha_{j+1}. So djd_j is bounded by the sum of the two errors, and a small djd_j is necessary for a good αj\alpha_j. The converse needs assumptions, because a small djd_j can occur by cancellation. Bauer and Reiss (2008) prove for white noise, under conditions on the decay of the singular values and of the coefficients of x†x^\dagger, that the quasi-optimal choice reaches the oracle error up to constant and logarithmic factors with high probability. For deterministic noise the Bakushinskii veto rules out convergence for every ee; Kindermann and Neubauer proved convergence under a condition that excludes noise too regular to tell apart from the signal. The good result in the example is a measurement.

Proof: The SVD formula gives the distances between neighbouring Tikhonov solutions, the discrete rule tends to the continuous one, and the distances are bounded by the two error termsfull

Setting. AA is a real m×nm \times n matrix with thin SVD A=∑i=1rsiuiviTA = \sum_{i=1}^r s_iu_iv_i^T, s1≥⋯≥sr>0s_1 \ge \dots \ge s_r > 0. For α>0\alpha > 0, xα=(ATA+αI)−1ATyx_\alpha = (A^TA + \alpha I)^{-1}A^Ty. Line L1 computes bi=⟨ui,y⟩b_i = \langle u_i, y\rangle. The grid is αj=α0qj\alpha_j = \alpha_0q^j with α0>0\alpha_0 > 0, 0<q<10 < q < 1 and j=0,…,Nj = 0, \dots, N.

Claim 1 (solutions and distances). xα=∑isibi/(si2+α) vix_\alpha = \sum_i s_ib_i/(s_i^2 + \alpha)\,v_i, and the number djd_j of line L3 equals ∥xαj+1−xαj∥\lVert x_{\alpha_{j+1}} - x_{\alpha_j}\rVert.

Proof. In the basis viv_i the normal equations (ATA+αI)x=ATy(A^TA + \alpha I)x = A^Ty read (si2+α)ξi=sibi(s_i^2 + \alpha)\xi_i = s_ib_i for i≤ri \le r and αξ=0\alpha\xi = 0 on the null space of AA. So the coefficient of viv_i in xαj+1−xαjx_{\alpha_{j+1}} - x_{\alpha_j} is sibi(1/(si2+αj+1)−1/(si2+αj))s_ib_i(1/(s_i^2 + \alpha_{j+1}) - 1/(s_i^2 + \alpha_j)), and the viv_i are orthonormal. □\square

Claim 2 (termination and output). Line L3 computes NN numbers with Θ(r)\Theta(r) work each, line L4 returns an index j∗j^\ast with dj∗=min⁡jdjd_{j^\ast} = \min_j d_j, and line L5 returns xαj∗x_{\alpha_{j^\ast}} by Claim 1. There is no loop with an open end. □\square

Claim 3 (the derivative). xαx_\alpha is differentiable in α\alpha with dxα/dα=−(ATA+αI)−1xα=−∑isibi/(si2+α)2 vidx_\alpha/d\alpha = -(A^TA + \alpha I)^{-1}x_\alpha = -\sum_i s_ib_i/(s_i^2 + \alpha)^2\,v_i.

Proof. Differentiate (ATA+αI)xα=ATy(A^TA + \alpha I)x_\alpha = A^Ty: xα+(ATA+αI)xα′=0x_\alpha + (A^TA + \alpha I)x_\alpha' = 0. The SVD form follows from differentiating each coefficient sibi/(si2+α)s_ib_i/(s_i^2 + \alpha). □\square

Claim 4 (continuous limit). For fixed α\alpha, ∥xqα−xα∥/(1−q)→α∥dxα/dα∥\lVert x_{q\alpha} - x_\alpha\rVert/(1 - q) \to \alpha\lVert dx_\alpha/d\alpha\rVert as q→1q \to 1.

Proof. xqα−xα=xα′(qα−α)+o(∣1−q∣α)=−(1−q)αxα′+o(1−q)x_{q\alpha} - x_\alpha = x'_\alpha(q\alpha - \alpha) + o(|1 - q|\alpha) = -(1 - q)\alpha x'_\alpha + o(1 - q), since xαx_\alpha is smooth in α>0\alpha > 0 by Claim 3. Divide by 1−q1 - q and take norms. □\square

Claim 5 (scaling). If AA, yy and α0\alpha_0 are replaced by cAcA, cycy and c2α0c^2\alpha_0 for c>0c > 0, the distances djd_j are unchanged, so the rule picks the same j∗j^\ast, the parameter c2αj∗c^2\alpha_{j^\ast} and the same solution.

Proof. The singular values become csics_i and the coefficients cbicb_i, with the same viv_i. Each coefficient csicbi/(c2si2+c2αj)=sibi/(si2+αj)cs_icb_i/(c^2s_i^2 + c^2\alpha_j) = s_ib_i/(s_i^2 + \alpha_j) is unchanged. □\square

Claim 6 (the distances are bounded by the errors). Let y=yˉ+ey = \bar y + e with yˉ=Ax†\bar y = Ax^\dagger, let xˉα\bar x_\alpha be the Tikhonov solution for yˉ\bar y, φ(α)=∥xˉα−x†∥\varphi(\alpha) = \lVert\bar x_\alpha - x^\dagger\rVert the approximation error and ψe(α)=∥xα−xˉα∥\psi_e(\alpha) = \lVert x_\alpha - \bar x_\alpha\rVert the propagated noise. Assume x†x^\dagger lies in the span of the viv_i (the minimum norm solution). Then

dj≤φ(αj)+ψe(αj+1).d_j \le \varphi(\alpha_j) + \psi_e(\alpha_{j+1}).

Proof. Write ξi=⟨x†,vi⟩\xi_i = \langle x^\dagger, v_i\rangle and ϵi=⟨ui,e⟩\epsilon_i = \langle u_i, e\rangle, so bi=siξi+ϵib_i = s_i\xi_i + \epsilon_i. The coefficient of xˉα−x†\bar x_\alpha - x^\dagger on viv_i is −αξi/(si2+α)-\alpha\xi_i/(s_i^2 + \alpha), and that of xα−xˉαx_\alpha - \bar x_\alpha is siϵi/(si2+α)s_i\epsilon_i/(s_i^2 + \alpha). With β=αj+1<α=αj\beta = \alpha_{j+1} < \alpha = \alpha_j, the coefficient of xβ−xαx_\beta - x_\alpha is the sum of

(αsi2+α−βsi2+β)ξiand(sisi2+β−sisi2+α)ϵi.\Big(\frac{\alpha}{s_i^2 + \alpha} - \frac{\beta}{s_i^2 + \beta}\Big)\xi_i \quad\text{and}\quad \Big(\frac{s_i}{s_i^2 + \beta} - \frac{s_i}{s_i^2 + \alpha}\Big)\epsilon_i.

The first factor lies in [0,α/(si2+α)][0, \alpha/(s_i^2 + \alpha)], because β/(si2+β)≥0\beta/(s_i^2 + \beta) \ge 0 and the map γ↦γ/(si2+γ)\gamma \mapsto \gamma/(s_i^2 + \gamma) is increasing. The second factor lies in [0,si/(si2+β)][0, s_i/(s_i^2 + \beta)]. So the first vector has norm at most φ(α)\varphi(\alpha) and the second at most ψe(β)\psi_e(\beta), and the triangle inequality gives the claim. □\square

What Claim 6 means. By Claim 6, min⁡jdj≤min⁡j(φ(αj)+ψe(αj+1))\min_j d_j \le \min_j(\varphi(\alpha_j) + \psi_e(\alpha_{j+1})), so the smallest distance is never larger than an error-like quantity at the best grid point. A small djd_j is necessary for αj\alpha_j to be good. It is not sufficient: djd_j can be small by cancellation, or because all filter factors are close to 00 or 11 at the two parameters. That is why the rule is a heuristic. Convergence and oracle results need conditions on the noise (Bauer and Reiss 2008 for white noise; Kindermann and Neubauer for deterministic noise), and by the Bakushinskii veto some condition is unavoidable. The near-optimal error in the example of the page is a measurement.

Complexity

With the thin SVD given, line L1 costs Θ(mn)\Theta(mn), line L3 costs Θ(Nr)⊆O(Nn)\Theta(Nr) \subseteq O(Nn), and line L5 costs Θ(n2)⊆O(mn)\Theta(n^2) \subseteq O(mn). The total is Θ(mn+Nn)\Theta(mn + Nn) with Θ(N+n)\Theta(N + n) extra space. With the default grid, N=⌈log⁡(s12/sr2)/log⁡(1/q)⌉N = \lceil\log(s_1^2/s_r^2)/\log(1/q)\rceil, which is 2020 in the example. The SVD itself costs O(mn2)O(mn^2). Without an SVD the rule needs N+1N + 1 regularized solutions, but they can share work: for Landweber or CG the iterates come in order anyway.

Properties

  • Heuristic: it uses only AA and yy.
  • Scale free: replacing AA and yy by cAcA and cycy, with the grid scaled by c2c^2, multiplies the chosen α\alpha by c2c^2 and leaves xx unchanged. The default grid scales this way because it starts at s12s_1^2.
  • Works for any family of regularized solutions with an ordered parameter: Tikhonov, truncated SVD, iteration counts of Landweber or CGLS.
  • The result is always one of the grid points. A ratio qq between 1/21/2 and 0.90.9 is typical; very small qq makes the grid coarse, very large qq makes djd_j small everywhere and sensitive to noise.

Variants and improvements

  • Continuous form. Minimize α∥dxα/dα∥=∥α(ATA+αI)−1xα∥\alpha\lVert dx_\alpha/d\alpha\rVert = \lVert\alpha(A^TA + \alpha I)^{-1}x_\alpha\rVert, the limit of the discrete rule as q→1q \to 1, divided by 1−q1 - q. The implementation includes it.
  • Iterative methods. For Landweber or semi-convergent iterations, use ∥x2k−xk∥\lVert x_{2k} - x_k\rVert or ∥xk+1−xk∥\lVert x_{k+1} - x_k\rVert over kk.
  • Truncated SVD. The distance between neighbouring truncations is ∣bk∣/sk|b_k|/s_k, so the rule picks the smallest ∣bk∣/sk|b_k|/s_k over kk, a test of the Picard condition.
  • Residual-based heuristic rules. Other heuristic rules minimize a function of the residual instead of a difference of solutions. The heuristic discrepancy rule minimizes ∥Axα−y∥/α\lVert Ax_\alpha - y\rVert/\sqrt\alpha, and the Hanke-Raus rule is of the same type. They share the same theory of noise conditions.
  • Restricted search. Limit jj to a range where xαjx_{\alpha_j} is not dominated by rounding, for example αj≥sr2\alpha_j \ge s_r^2 as in the default grid.

When to use it

Use it when the noise level is unknown and you want a rule that is easy to apply to any regularization method, including iterations. It is often more reliable than GCV on small or square problems and less sensitive to the shape of the curve than the L-curve. If the noise level is known, prefer the discrepancy principle or the balancing principle, which have proofs without conditions on the noise.

Pitfalls

  • Local minima. The sequence djd_j can have several local minima, and a spurious one at small α\alpha when the noise happens to be small in a few components. Line L4 takes the global minimum; look at the whole sequence.
  • Too small parameters. If the grid in line L2 runs far below sr2s_r^2, the solutions stop changing because every filter factor is close to 1, and djd_j tends to zero there. The rule then picks the noisiest solution. Stop the grid at sr2s_r^2.
  • Returning the wrong member of the pair in line L5. The pair (αj,αj+1)(\alpha_j, \alpha_{j+1}) has two solutions; the classical rule returns xαjx_{\alpha_j}. Mixing the two conventions shifts the result by one grid step.
  • Measuring the distance in the wrong norm. If the solution is regularized with a penalty ∥Lx∥\lVert Lx\rVert, the distance in line L3 is often measured in the same seminorm; mixing norms changes the rule.
  • No noise level does not mean no assumptions. The rule fails when the noise looks like signal, for example for very smooth noise.

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.

imgla.pyI0RawGitHub
# 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
quasi_optimality_criterion.py 79 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/quasi-optimality-criterion/. The authors are listed in prov/4809JZ.jsonl.
"""The quasi-optimality criterion of Tikhonov and Glasko, in its discrete form.

Tikhonov: x_alpha minimizes ||A x - y||^2 + alpha ||x||^2. On the geometric
grid alpha_j = alpha_0 q^j (0 < q < 1, j = 0..N), the rule picks the alpha_j
for which ||x_{alpha_{j+1}} - x_{alpha_j}|| is smallest. With the thin SVD,
x_alpha = sum_i s_i b_i / (s_i^2 + alpha) v_i, so the distance needs only
the coefficients s_i b_i.
"""

import math

from imgla import norm2, svd


def coefficients(u, s, y):
    """b_i = <u_i, y> for the s_i > 0."""
    m = len(y)
    return [sum(u[i][k] * y[i] for i in range(m)) for k in range(len(s)) if s[k] > 0.0]


def step_norm(s, b, a1, a2):
    """||x_{a2} - x_{a1}|| from the SVD data."""
    tot = 0.0
    for si, bi in zip(s, b):
        d = si * bi * (1.0 / (si * si + a2) - 1.0 / (si * si + a1))
        tot += d * d
    return math.sqrt(tot)


def tikhonov_svd(s, v, b, alpha):
    """x_alpha = sum_i s_i b_i / (s_i^2 + alpha) v_i."""
    n = len(v)
    x = [0.0] * n
    for k, (si, bi) in enumerate(zip(s, b)):
        c = si * bi / (si * si + alpha)
        for j in range(n):
            x[j] += c * v[j][k]
    return x


def quasi_optimality(u, s, v, y, alpha0=None, q=0.5, count=None):
    """Return (alpha, x, j, d) for the discrete quasi-optimality rule.

    The grid is alpha_j = alpha0 q^j for j = 0..count. By default alpha0 = s_1^2
    and the grid stops at the first alpha_j below s_r^2. d[j] is
    ||x_{alpha_{j+1}} - x_{alpha_j}|| and j is the index of the smallest d[j].
    """
    s = [si for si in s if si > 0.0]
    b = coefficients(u, s, y)  # @line L1
    if alpha0 is None:
        alpha0 = s[0] ** 2
    if count is None:
        count = max(1, math.ceil(math.log(s[-1] ** 2 / alpha0) / math.log(q)))
    alphas = [alpha0 * q ** j for j in range(count + 1)]  # @line L2
    d = [step_norm(s, b, alphas[j], alphas[j + 1]) for j in range(count)]  # @line L3
    j = min(range(count), key=lambda i: d[i])  # @line L4
    alpha = alphas[j]
    return alpha, tikhonov_svd(s, v, b, alpha), j, d  # @line L5


def quasi_optimality_matrix(a, y, **kw):
    """The same for a dense matrix: compute the SVD, then call quasi_optimality."""
    u, s, v = svd(a)
    return quasi_optimality(u, s, v, y, **kw)


def continuous_measure(s, b, alpha):
    """alpha ||d x_alpha / d alpha||, the continuous form of the criterion.

    d x_alpha / d alpha = -(A^T A + alpha I)^(-1) x_alpha, so the measure is
    sqrt(sum_i (alpha s_i b_i / (s_i^2 + alpha)^2)^2).
    """
    tot = 0.0
    for si, bi in zip(s, b):
        t = alpha * si * bi / (si * si + alpha) ** 2
        tot += t * t
    return math.sqrt(tot)
test_quasi_optimality_criterion.py 115 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/quasi-optimality-criterion/. The authors are listed in prov/4809JZ.jsonl.

import math
import random

from imgla import eye, matmul, matvec, norm2, solve, svd, transpose
from quasi_optimality_criterion import (
    coefficients,
    continuous_measure,
    quasi_optimality,
    quasi_optimality_matrix,
    step_norm,
    tikhonov_svd,
)


def diag_problem(seed, n=32, sigma=1e-3):
    """A = diag(1/i^2), x_i = 1/i^2, white noise of standard deviation sigma."""
    s = [1.0 / i ** 2 for i in range(1, n + 1)]
    xt = [1.0 / i ** 2 for i in range(1, n + 1)]
    rng = random.Random(seed)
    y = [si * xi + sigma * rng.gauss(0.0, 1.0) for si, xi in zip(s, xt)]
    return s, xt, y


def random_matrix(rng, m, n):
    return [[rng.gauss(0.0, 1.0) / (j + 1) ** 2 for j in range(n)] for _ in range(m)]


def tikhonov_solve(a, y, alpha):
    at = transpose(a)
    ata = matmul(at, a)
    for i in range(len(ata)):
        ata[i][i] += alpha
    return solve(ata, matvec(at, y))


def test_page_example():
    s, xt, y = diag_problem(0)
    e = eye(32)
    alpha, x, j, d = quasi_optimality(e, s, e, y)
    assert len(d) == 20
    assert j == 9 and alpha == 0.5 ** 9
    assert abs(d[9] - 0.017480) < 1e-6
    assert abs(d[8] - 0.018896) < 1e-6 and abs(d[10] - 0.022928) < 1e-6
    assert abs(math.dist(x, xt) - 0.06146) < 1e-5
    best = min(math.dist(tikhonov_svd(s, e, y, 10 ** (k / 100.0)), xt) for k in range(-700, 1))
    assert math.dist(x, xt) <= 1.06 * best


def test_step_norm_matches_dense_solves():
    rng = random.Random(2)
    a = random_matrix(rng, 8, 6)
    y = [rng.gauss(0.0, 1.0) for _ in range(8)]
    u, s, v = svd(a)
    b = coefficients(u, s, y)
    for a1, a2 in ((0.1, 0.05), (1e-3, 5e-4), (1e-5, 1e-6)):
        x1, x2 = tikhonov_solve(a, y, a1), tikhonov_solve(a, y, a2)
        assert abs(step_norm(s, b, a1, a2) - math.dist(x1, x2)) <= 1e-8 * max(1.0, norm2(x1))
        assert math.dist(tikhonov_svd(s, v, b, a1), x1) <= 1e-8 * max(1.0, norm2(x1))


def test_derivative_formula_and_continuous_limit():
    rng = random.Random(4)
    a = random_matrix(rng, 7, 5)
    y = [rng.gauss(0.0, 1.0) for _ in range(7)]
    u, s, v = svd(a)
    b = coefficients(u, s, y)
    alpha = 2e-3
    x = tikhonov_solve(a, y, alpha)
    at = transpose(a)
    ata = matmul(at, a)
    for i in range(5):
        ata[i][i] += alpha
    dx = [-t for t in solve(ata, x)]
    h = 1e-6 * alpha
    fd = [(p - q) / (2 * h) for p, q in zip(tikhonov_solve(a, y, alpha + h), tikhonov_solve(a, y, alpha - h))]
    assert math.dist(dx, fd) <= 1e-5 * norm2(dx)
    assert abs(continuous_measure(s, b, alpha) - alpha * norm2(dx)) <= 1e-8 * alpha * norm2(dx)
    q = 0.999
    ratio = step_norm(s, b, alpha, q * alpha) / ((1.0 - q) * continuous_measure(s, b, alpha))
    assert abs(ratio - 1.0) < 2e-3


def test_error_close_to_best_over_seeds():
    e = eye(32)
    for seed in range(5):
        s, xt, y = diag_problem(seed)
        alpha, x, _, _ = quasi_optimality(e, s, e, y)
        best = min(math.dist(tikhonov_svd(s, e, y, 10 ** (k / 100.0)), xt) for k in range(-700, 1))
        assert math.dist(x, xt) <= 1.5 * best


def test_chosen_index_is_the_minimum_and_matrix_path_agrees():
    rng = random.Random(6)
    a = random_matrix(rng, 9, 6)
    xt = [1.0, -0.5, 0.25, 0.1, -0.05, 0.02]
    y = [p + 1e-3 * rng.gauss(0.0, 1.0) for p in matvec(a, xt)]
    u, s, v = svd(a)
    al1, x1, j1, d1 = quasi_optimality(u, s, v, y, q=0.7)
    al2, x2, j2, d2 = quasi_optimality_matrix(a, y, q=0.7)
    assert j1 == j2 and d1[j1] == min(d1)
    assert math.dist(x1, x2) <= 1e-12 * norm2(x1)
    assert math.dist(x1, tikhonov_solve(a, y, al1)) <= 1e-8 * norm2(x1)


def test_scaling_multiplies_alpha_by_c_squared():
    s, xt, y = diag_problem(1)
    e = eye(32)
    c = 3.0
    al1, x1, j1, _ = quasi_optimality(e, s, e, y)
    al2, x2, j2, _ = quasi_optimality(e, [c * t for t in s], e, [c * t for t in y])
    assert j1 == j2 and abs(al2 / (c * c * al1) - 1.0) < 1e-12
    assert math.dist(x1, x2) <= 1e-12 * norm2(x1)

History

Tikhonov and Glasko (1965) introduced the quasi-optimal choice of the regularization parameter, in a paper on nonlinear problems, as the parameter where the solution is least sensitive to the parameter. It became one of the standard heuristic rules in the Russian school of regularization. Bakushinskii (1984) showed that no rule of this kind can be convergent for all noise, and the question became under which noise conditions it converges. Bauer and Reiss (2008) gave an analysis for white noise, and Kindermann and Neubauer gave a convergence analysis for deterministic noise under noise conditions.

References

  1. A. N. Tikhonov and V. B. Glasko, Use of the regularization method in non-linear problems, USSR Computational Mathematics and Mathematical Physics 5(3), 1965, pages 93 to 107
  2. Frank Bauer and Markus Reiss, Regularization independent of the noise level, an analysis of quasi-optimality, Inverse Problems 24(5), 2008, article 055009
  3. Heinz W. Engl, Martin Hanke and Andreas Neubauer, Regularization of Inverse Problems, Kluwer, 1996, chapter 4 (heuristic parameter choice rules and the Bakushinskii result)

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.average
  • a full proof of time.best
  • a full proof of time.worst
  • 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