Algorithm Search⌘K

Algorithmadvanced

Unbiased predictive risk estimator

Also called UPRE, Mallows C_L.

Choose the regularization parameter that minimizes an unbiased estimate of the expected predictive error, using a known noise variance.

Time
Θ(m n + (P + K) n) worst · average · best
Space
Θ(P + n) extra
Where
K = the number of golden-section steps; P = the number of grid points; m = the number of measurements; n = the number of unknowns (n <= m)
Properties
a posteriorideterministicneeds noise varianceunbiased risk estimate
Origin
Colin L. Mallows, 1973

The unbiased predictive risk estimator (UPRE) chooses the parameter of a linear regularization method when the noise is white with a known variance σ2\sigma^2. The quantity it aims at is the predictive risk T(α)=1mE∥Axα−Ax†∥2T(\alpha) = \frac1mE\lVert Ax_\alpha - Ax^\dagger\rVert^2, which depends on the unknown x†x^\dagger. For Tikhonov regularization with influence matrix Hα=A(ATA+αI)−1ATH_\alpha = A(A^TA + \alpha I)^{-1}A^T, the function

U(α)=1m∥(I−Hα)y∥2+2σ2mtrace(Hα)−σ2U(\alpha) = \frac1m\lVert(I - H_\alpha)y\rVert^2 + \frac{2\sigma^2}{m}\mathrm{trace}(H_\alpha) - \sigma^2

is computable from the data and satisfies E U(α)=T(α)E\,U(\alpha) = T(\alpha) for every α\alpha. UPRE picks the minimizer of UU. The residual term alone would always prefer small α\alpha; the trace term charges 2σ2/m2\sigma^2/m for each effective parameter of the fit. Mallows (1973) introduced the estimate as CLC_L for linear smoothers, and it is the special case of Stein's unbiased risk estimate for the linear map y↦Hαyy \mapsto H_\alpha y. The rule is a posteriori in the statistical sense: it needs σ2\sigma^2 but not x†x^\dagger.

In plain words

You want to know how much to smooth, and you know how noisy each measurement is. The best setting is the one whose result predicts the clean data best, but you cannot see the clean data. UPRE estimates that prediction error anyway. It takes the misfit to the noisy data, which is too optimistic because the fit has chased some of the noise, and adds a penalty for each degree of freedom the fit uses. On average the corrected number equals the true prediction error. Then it picks the setting with the smallest corrected number. It works well when the noise level you give it is right, and badly when it is not.

The problem

The model is y=Ax†+ey = Ax^\dagger + e with an m×nm \times n matrix AA and e∼N(0,σ2Im)e \sim N(0, \sigma^2I_m) with a known σ\sigma. The Tikhonov solution for α>0\alpha > 0 is xα=(ATA+αI)−1ATyx_\alpha = (A^TA + \alpha I)^{-1}A^Ty, so Axα=HαyAx_\alpha = H_\alpha y. 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, bi=⟨ui,y⟩b_i = \langle u_i, y\rangle, p2=∥y∥2−∑ibi2p^2 = \lVert y\rVert^2 - \sum_i b_i^2 and the filter factors fi=si2/(si2+α)f_i = s_i^2/(s_i^2 + \alpha),

U(α)=1m(∑i(1−fi)2bi2+p2)+2σ2m∑ifi−σ2.U(\alpha) = \frac1m\Big(\sum_i (1 - f_i)^2b_i^2 + p^2\Big) + \frac{2\sigma^2}{m}\sum_i f_i - \sigma^2.

The task is to find the α\alpha that minimizes UU on a search interval, by default [sr2,s12][s_r^2, s_1^2].

The algorithm

The search is the same as for GCV: a geometric grid in t=log⁡αt = \log\alpha, then golden-section search between the neighbours of the best grid point.

  1. UPRE-TIKHONOV(U, s, V, y, sigma, P, eps) ▷ thin SVD of A, s descending, r positive values
  2. 1b_i ← <u_i, y> for i ≤ r; p² ← ‖y‖² - Σ b_i²
  3. 2G(t) := (Σ_i (1 - f_i)² b_i² + p²) / m + 2 sigma² Σ_i f_i / m - sigma² with f_i = s_i² / (s_i² + e^t)
  4. 3t_j ← log s_r² + (j / (P - 1)) · (log s_1² - log s_r²) for j = 0, ..., P - 1
  5. 4j* ← the index of the smallest G(t_j)
  6. 5[a, c] ← [t_{j*-1}, t_{j*+1}] ▷ clipped at the ends of the grid
  7. 6while c - a > eps
  8. 7golden-section step on [a, c] that keeps the smaller G inside
  9. 8remember the best (t, G) seen so far
  10. 9alpha ← e^t for the best t
  11. 10return alpha, x = Σ_i s_i b_i / (s_i² + alpha) · v_i, and G at alpha

Line L1 projects the data on the left singular vectors. Line L2 is U(α)U(\alpha) in SVD form, at a cost of Θ(r)\Theta(r) per value. Lines L3 to L5 locate and bracket the smallest grid value. Lines L6 to L8 are a golden-section search for a minimum, and line L8 keeps the best point, so the result is never worse than the best grid point. Line L10 forms the Tikhonov solution.

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, 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), so σ=10−3\sigma = 10^{-3} and p=0p = 0. The table compares UU with the true predictive risk TT.

α\alpha U(α)U(\alpha) T(α)T(\alpha) ∥xα−x†∥\lVert x_\alpha - x^\dagger\rVert trace(Hα)\mathrm{trace}(H_\alpha)
10−710^{-7} 9.595×10−79.595 \times 10^{-7} 9.585×10−79.585 \times 10^{-7} 3.3560 31.32
10−610^{-6} 7.951×10−77.951 \times 10^{-7} 7.570×10−77.570 \times 10^{-7} 2.2930 27.34
10−510^{-5} 6.582×10−76.582 \times 10^{-7} 4.463×10−74.463 \times 10^{-7} 0.8043 18.32
10−410^{-4} 6.220×10−76.220 \times 10^{-7} 2.471×10−72.471 \times 10^{-7} 0.1711 10.51
3×10−43 \times 10^{-4} 5.780×10−75.780 \times 10^{-7} 1.976×10−71.976 \times 10^{-7} 0.0817 7.80
10−310^{-3} 6.090×10−76.090 \times 10^{-7} 2.615×10−72.615 \times 10^{-7} 0.0583 5.74
3×10−33 \times 10^{-3} 1.311×10−61.311 \times 10^{-6} 1.036×10−61.036 \times 10^{-6} 0.0684 4.18
10−210^{-2} 6.818×10−66.818 \times 10^{-6} 6.737×10−66.737 \times 10^{-6} 0.0981 3.01
10−110^{-1} 3.071×10−43.071 \times 10^{-4} 3.088×10−43.088 \times 10^{-4} 0.2224 1.48
11 7.936×10−37.936 \times 10^{-3} 7.926×10−37.926 \times 10^{-3} 0.5697 0.58

For this draw of the noise, UU lies above TT by about 3.8×10−73.8 \times 10^{-7} in the middle of the range. Unbiasedness is a statement about the average over the noise, and one draw scatters around it, but the shape of UU near its minimum follows the shape of TT.

Line L4 picks grid point 27, α=5.427×10−4\alpha = 5.427 \times 10^{-4}, and line L5 brackets it by 4.29×10−44.29 \times 10^{-4} and 6.86×10−46.86 \times 10^{-4}. The loop makes 28 steps with ε=10−6\varepsilon = 10^{-6} and returns α=5.0416×10−4\alpha = 5.0416 \times 10^{-4} with U=5.6956×10−7U = 5.6956 \times 10^{-7}. The predictive risk there is 1.983×10−71.983 \times 10^{-7}, against the smallest possible 1.954×10−71.954 \times 10^{-7} at α≈3.98×10−4\alpha \approx 3.98 \times 10^{-4}. The error in xx is 0.066410.06641, against 0.058170.05817 at the best α\alpha for the error. The two optimal α\alpha differ because the predictive risk weights the error by the singular values.

Correctness

The proof is in proofs/correctness.md. Line L2 computes UU by the SVD form of HαH_\alpha, the search terminates after ⌈log⁡(w/ε)/log⁡1.618⌉\lceil\log(w/\varepsilon)/\log 1.618\rceil golden-section steps for a bracket of width ww, and the returned value is at most the smallest grid value.

The theorem behind the rule: for every fixed α\alpha, E U(α)=T(α)E\,U(\alpha) = T(\alpha). The proof is two lines. Write y=g+ey = g + e with g=Ax†g = Ax^\dagger. Then E∥(I−H)y∥2=∥(I−H)g∥2+σ2trace((I−H)2)E\lVert(I - H)y\rVert^2 = \lVert(I - H)g\rVert^2 + \sigma^2\mathrm{trace}((I - H)^2) and mT=∥(I−H)g∥2+σ2trace(H2)mT = \lVert(I - H)g\rVert^2 + \sigma^2\mathrm{trace}(H^2). The difference is σ2(m−2 trace(H))\sigma^2(m - 2\,\mathrm{trace}(H)), which is exactly what the last two terms of UU remove. The same identity is Stein's lemma for the linear map y↦Hαyy \mapsto H_\alpha y, whose divergence is trace(Hα)\mathrm{trace}(H_\alpha). Only the first two moments of the noise are used, so the identity holds for any noise with mean zero and covariance σ2I\sigma^2I.

Unbiasedness at each fixed α\alpha does not make the minimizer of UU the minimizer of TT. The minimizer depends on the noise, and its risk is a random quantity. Results on asymptotic optimality as m→∞m \to \infty (Li 1987, for CLC_L among others) need further conditions. In the tests, over 20 noise draws on a 64×6464 \times 64 problem, the risk at the UPRE choice was at most 1.3 times the smallest possible risk in the median and at most 3 times in the worst draw. That is a measurement.

Proof: The SVD formula computes the UPRE function, the function is an unbiased estimate of the predictive risk, and the search terminatesfull

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 and Hα=A(ATA+αI)−1ATH_\alpha = A(A^TA + \alpha I)^{-1}A^T, so Axα=HαyAx_\alpha = H_\alpha y. Line L1 computes bi=⟨ui,y⟩b_i = \langle u_i, y\rangle and p2=∥y∥2−∑ibi2p^2 = \lVert y\rVert^2 - \sum_i b_i^2. Write fi=si2/(si2+α)f_i = s_i^2/(s_i^2 + \alpha).

Claim 1 (the influence matrix). Hα=∑ifiuiuiTH_\alpha = \sum_i f_iu_iu_i^T, so trace(Hα)=∑ifi\mathrm{trace}(H_\alpha) = \sum_i f_i and ∥(I−Hα)y∥2=∑i(1−fi)2bi2+p2\lVert(I - H_\alpha)y\rVert^2 = \sum_i (1 - f_i)^2b_i^2 + p^2.

Proof. (ATA+αI)−1AT=∑isi/(si2+α) viuiT(A^TA + \alpha I)^{-1}A^T = \sum_i s_i/(s_i^2 + \alpha)\,v_iu_i^T, because ATA+αIA^TA + \alpha I acts on viv_i as multiplication by si2+αs_i^2 + \alpha. Multiply by A=∑isiuiviTA = \sum_i s_iu_iv_i^T on the left. For the norm, write y=∑ibiui+y⊥y = \sum_i b_iu_i + y_\perp with ∥y⊥∥=p\lVert y_\perp\rVert = p; then (I−Hα)y=∑i(1−fi)biui+y⊥(I - H_\alpha)y = \sum_i (1 - f_i)b_iu_i + y_\perp, and the terms are orthogonal. □\square

Claim 2 (line L2 computes U). By Claim 1, the function GG of line L2 at t=log⁡αt = \log\alpha equals U(α)=1m∥(I−Hα)y∥2+2σ2mtrace(Hα)−σ2U(\alpha) = \frac1m\lVert(I - H_\alpha)y\rVert^2 + \frac{2\sigma^2}{m}\mathrm{trace}(H_\alpha) - \sigma^2. □\square

Claim 3 (unbiasedness). Let y=g+ey = g + e with g=Ax†g = Ax^\dagger fixed, Ee=0Ee = 0 and E eeT=σ2ImE\,ee^T = \sigma^2I_m. For every fixed α>0\alpha > 0,

E U(α)=T(α):=1mE∥Hαy−g∥2.E\,U(\alpha) = T(\alpha) := \tfrac1mE\lVert H_\alpha y - g\rVert^2.

Proof. For a fixed matrix MM and fixed vector cc, E∥c+Me∥2=∥c∥2+2⟨c,M Ee⟩+E trace(MTMeeT)=∥c∥2+σ2trace(MTM)E\lVert c + Me\rVert^2 = \lVert c\rVert^2 + 2\langle c, M\,Ee\rangle + E\,\mathrm{trace}(M^TMee^T) = \lVert c\rVert^2 + \sigma^2\mathrm{trace}(M^TM). Write H=HαH = H_\alpha, which is symmetric. First, (I−H)y=(I−H)g+(I−H)e(I - H)y = (I - H)g + (I - H)e, so

E∥(I−H)y∥2=∥(I−H)g∥2+σ2 trace((I−H)2)=∥(I−H)g∥2+σ2(m−2 trace(H)+trace(H2)).E\lVert(I - H)y\rVert^2 = \lVert(I - H)g\rVert^2 + \sigma^2\,\mathrm{trace}((I - H)^2) = \lVert(I - H)g\rVert^2 + \sigma^2(m - 2\,\mathrm{trace}(H) + \mathrm{trace}(H^2)).

Second, Hy−g=−(I−H)g+HeHy - g = -(I - H)g + He, so

mT=∥(I−H)g∥2+σ2 trace(H2).mT = \lVert(I - H)g\rVert^2 + \sigma^2\,\mathrm{trace}(H^2).

Subtracting, E∥(I−H)y∥2−mT=σ2(m−2 trace(H))E\lVert(I - H)y\rVert^2 - mT = \sigma^2(m - 2\,\mathrm{trace}(H)). Divide by mm and move the terms: T=1mE∥(I−H)y∥2+2σ2mtrace(H)−σ2=E U(α)T = \frac1mE\lVert(I - H)y\rVert^2 + \frac{2\sigma^2}{m}\mathrm{trace}(H) - \sigma^2 = E\,U(\alpha), since trace(H)\mathrm{trace}(H) is not random. □\square

Link with Stein's lemma. For Gaussian noise, Stein's unbiased risk estimate of E∥h(y)−g∥2E\lVert h(y) - g\rVert^2 for a weakly differentiable hh is ∥h(y)−y∥2+2σ2 div h(y)−mσ2\lVert h(y) - y\rVert^2 + 2\sigma^2\,\mathrm{div}\,h(y) - m\sigma^2. For h(y)=Hαyh(y) = H_\alpha y the divergence is ∑k∂(Hαy)k/∂yk=trace(Hα)\sum_k \partial(H_\alpha y)_k/\partial y_k = \mathrm{trace}(H_\alpha), and dividing by mm gives UU. Claim 3 shows that for linear hh Gaussianity is not needed.

Claim 4 (termination and the grid guarantee). The loop of lines L6 to L8 stops after ⌈log⁡(w/ε)/log⁡(1/φ)⌉\lceil\log(w/\varepsilon)/\log(1/\varphi)\rceil steps, where ww is the width of the bracket of line L5 and φ=(5−1)/2\varphi = (\sqrt5 - 1)/2. The returned value of GG is at most min⁡jG(tj)\min_j G(t_j), and it is the value at the returned α\alpha.

Proof. Each golden-section step replaces [a,c][a, c] by [a,t2][a, t_2] or [t1,c][t_1, c] with t1=c−φ(c−a)t_1 = c - \varphi(c - a) and t2=a+φ(c−a)t_2 = a + \varphi(c - a), so the width is multiplied by φ\varphi. After KK steps it is wφK≤εw\varphi^K \le \varepsilon for the stated KK, and the loop condition fails. Line L8 starts from the best grid point and only replaces it by a point with a smaller value; lines L9 and L10 return that point. □\square

Claim 5 (output). Line L10 returns xα=∑isibi/(si2+α) vix_\alpha = \sum_i s_ib_i/(s_i^2 + \alpha)\,v_i, the Tikhonov solution for the returned α\alpha, by the formula in the proof of Claim 1.

What is not proved. Claim 3 holds at each fixed α\alpha. The returned α^\hat\alpha depends on ee, and in general E U(α^)E\,U(\hat\alpha) is not the expected loss 1mE∥Hα^y−g∥2\frac1mE\lVert H_{\hat\alpha}y - g\rVert^2 at the data-dependent parameter. The closeness of the risk at the UPRE choice to the smallest risk, seen in the tests, is a measurement. Asymptotic results of this kind exist (Li 1987) under further conditions.

Complexity

With the thin SVD given, line L1 costs Θ(mn)\Theta(mn), each value of UU costs Θ(r)⊆O(n)\Theta(r) \subseteq O(n), the grid costs Θ(Pn)\Theta(Pn), the loop Θ(Kn)\Theta(Kn), and line L10 Θ(n2)⊆O(mn)\Theta(n^2) \subseteq O(mn). The total is Θ(mn+(P+K)n)\Theta(mn + (P + K)n) with Θ(P+n)\Theta(P + n) extra space. The SVD itself costs O(mn2)O(mn^2) and dominates. Without an SVD, trace(Hα)\mathrm{trace}(H_\alpha) is estimated with random probe vectors, as for GCV.

Properties

  • Needs the noise variance σ2\sigma^2 but not x†x^\dagger.
  • Unbiased for the predictive risk at every fixed α\alpha, for any noise with mean zero and covariance σ2I\sigma^2I.
  • Scale free when σ\sigma is scaled with the data: replacing AA, yy and σ\sigma by cAcA, cycy and cσc\sigma multiplies the chosen α\alpha by c2c^2.
  • Monotone in σ\sigma: a larger σ\sigma puts more weight on the trace, which decreases in α\alpha, so the minimizer does not move toward smaller α\alpha.
  • The same estimate works for any linear method x=Rαyx = R_\alpha y with fitted data ARαyAR_\alpha y: replace HαH_\alpha by ARαAR_\alpha.

Variants and improvements

  • Truncated SVD. With kk terms, trace(Hk)=k\mathrm{trace}(H_k) = k and U(k)=1m∥y−Hky∥2+2σ2k/m−σ2U(k) = \frac1m\lVert y - H_ky\rVert^2 + 2\sigma^2k/m - \sigma^2. This is Mallows' CpC_p up to scaling, and the implementation includes it.
  • SURE for nonlinear estimators. For a nonlinear map y↦g(y)y \mapsto g(y), such as soft thresholding of wavelet coefficients, replace trace(H)\mathrm{trace}(H) by the divergence of gg. See Stein's unbiased risk estimate.
  • Error in x instead of in the data. The risk E∥xα−x†∥2E\lVert x_\alpha - x^\dagger\rVert^2 has no unbiased estimate in general when AA is ill-conditioned. A projected risk, E∥P(xα−x†)∥2E\lVert P(x_\alpha - x^\dagger)\rVert^2 with PP the projector on the range of ATA^T, can be estimated, but with a large variance.
  • Colored noise. With noise covariance Σ\Sigma, whiten first: replace AA and yy by Σ−1/2A\Sigma^{-1/2}A and Σ−1/2y\Sigma^{-1/2}y, and use σ=1\sigma = 1.
  • Unknown variance. Replace σ2\sigma^2 by an estimate, for example from the residual of a fit with a small α\alpha. Then the rule is close to GCV, which removes σ2\sigma^2 from the problem altogether.

When to use it

Use it when the noise is white or can be whitened and its variance is known well, for example from the physics of a detector. It is then usually more accurate than the discrepancy principle, which uses only the size of the noise and tends to over-smooth, and more reliable than GCV on small problems. If only a deterministic bound ∥e∥≤δ\lVert e\rVert \le \delta is known, use the discrepancy principle or the balancing principle instead, which have proofs in that setting.

Pitfalls

  • A wrong σ\sigma. In the example, σ=0.5×10−3\sigma = 0.5 \times 10^{-3} instead of 10−310^{-3} makes line L4 pick the lower end of the interval, α=9.5×10−7\alpha = 9.5 \times 10^{-7}, with an error of 2.332.33, forty times the best. Overestimating is safer: σ=2×10−3\sigma = 2 \times 10^{-3} gives α=1.31×10−3\alpha = 1.31 \times 10^{-3} and error 0.05850.0585. Check where the result lies in the interval.
  • Using δ2=E∥e∥2=mσ2\delta^2 = E\lVert e\rVert^2 = m\sigma^2 in place of σ2\sigma^2 in line L2, or the reverse. The formula wants the variance of one component.
  • Forgetting the factor 2 on the trace term in line L2. Without it, the estimate is biased and the rule under-smooths.
  • Correlated noise used as if it were white. The trace correction is then wrong, and the rule usually under-smooths. Whiten first.
  • Minimizing UU when it is very flat. The minimum value of UU can be negative for one noise draw, which is fine, but a flat UU makes the choice sensitive to the noise. Plot it.

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
unbiased_predictive_risk_estimator.py 124 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/unbiased-predictive-risk-estimator/. The authors are listed in prov/FEKTYX.jsonl.
"""The unbiased predictive risk estimator (UPRE) for Tikhonov regularization and TSVD.

Model: y = A x + e with e ~ N(0, sigma^2 I_m) and a known sigma. Tikhonov:
x_alpha minimizes ||A x - y||^2 + alpha ||x||^2, and A x_alpha = H_alpha y with
the influence matrix H_alpha = A (A^T A + alpha I)^(-1) A^T. UPRE minimizes

    U(alpha) = (1/m) ||(I - H_alpha) y||^2 + (2 sigma^2 / m) trace(H_alpha) - sigma^2,

an unbiased estimate of the predictive risk (1/m) E ||A x_alpha - A x||^2.
With the thin SVD, trace(H_alpha) = sum_i s_i^2 / (s_i^2 + alpha).
"""

import math

from imgla import norm2, svd

INV_PHI = (math.sqrt(5.0) - 1.0) / 2.0


def coefficients(u, s, y):
    """b_i = <u_i, y> for the s_i > 0, and p2 = ||y||^2 - sum b_i^2 (clamped at 0)."""
    m = len(y)
    b = [sum(u[i][k] * y[i] for i in range(m)) for k in range(len(s)) if s[k] > 0.0]
    p2 = max(norm2(y) ** 2 - sum(t * t for t in b), 0.0)
    return b, p2


def upre_function(s, b, p2, m, sigma, alpha):
    """U(alpha) from the SVD data."""
    res2 = p2
    tr = 0.0
    for si, bi in zip(s, b):
        f = si * si / (si * si + alpha)
        res2 += (1.0 - f) ** 2 * bi * bi
        tr += f
    return res2 / m + 2.0 * sigma * sigma * tr / m - sigma * sigma


def predictive_risk(s, c, m, sigma, alpha):
    """The exact predictive risk (1/m) E ||A x_alpha - A x||^2 when c_i = <u_i, A x> are known.

    It equals (1/m) [sum_i (1 - f_i)^2 c_i^2 + sigma^2 sum_i f_i^2].
    """
    tot = 0.0
    for si, ci in zip(s, c):
        f = si * si / (si * si + alpha)
        tot += (1.0 - f) ** 2 * ci * ci + sigma * sigma * f * f
    return tot / m


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 upre_tikhonov(u, s, v, y, sigma, alpha_min=None, alpha_max=None, points=60, eps=1e-6):
    """Return (alpha, x, U(alpha)) for the UPRE choice of the Tikhonov parameter.

    A geometric grid of `points` values on [alpha_min, alpha_max] (by default
    [s_r^2, s_1^2]), then golden-section search in log alpha between the
    neighbours of the best grid point.
    """
    m = len(y)
    s = [si for si in s if si > 0.0]
    b, p2 = coefficients(u, s, y)  # @line L1

    def g(t):  # @line L2
        return upre_function(s, b, p2, m, sigma, math.exp(t))

    lo_t = math.log(alpha_min if alpha_min is not None else s[-1] ** 2)
    hi_t = math.log(alpha_max if alpha_max is not None else s[0] ** 2)
    ts = [lo_t + (hi_t - lo_t) * j / (points - 1) for j in range(points)]  # @line L3
    gs = [g(t) for t in ts]
    j = min(range(points), key=lambda i: gs[i])  # @line L4
    a, c = ts[max(j - 1, 0)], ts[min(j + 1, points - 1)]  # @line L5
    best_t, best_g = ts[j], gs[j]
    t1, t2 = c - INV_PHI * (c - a), a + INV_PHI * (c - a)
    g1, g2 = g(t1), g(t2)
    while c - a > eps:  # @line L6
        if g1 <= g2:  # @line L7
            c, t2, g2 = t2, t1, g1
            t1 = c - INV_PHI * (c - a)
            g1 = g(t1)
        else:
            a, t1, g1 = t1, t2, g2
            t2 = a + INV_PHI * (c - a)
            g2 = g(t2)
        for t, gv in ((t1, g1), (t2, g2)):  # @line L8
            if gv < best_g:
                best_t, best_g = t, gv
    alpha = math.exp(best_t)  # @line L9
    return alpha, tikhonov_svd(s, v, b, alpha), best_g  # @line L10


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


def upre_tsvd(u, s, y, sigma):
    """The discrete rule for TSVD (Mallows' C_L): minimize (1/m) ||r_k||^2 + 2 sigma^2 k / m - sigma^2.

    Returns (k, list of U(k)) for k = 0..r.
    """
    m = len(y)
    s = [si for si in s if si > 0.0]
    b, p2 = coefficients(u, s, y)
    res2 = p2 + sum(t * t for t in b)
    vals = []
    for k in range(0, len(s) + 1):
        if k > 0:
            res2 -= b[k - 1] ** 2
        vals.append(max(res2, 0.0) / m + 2.0 * sigma * sigma * k / m - sigma * sigma)
    k = min(range(len(vals)), key=lambda i: vals[i])
    return k, vals
test_unbiased_predictive_risk_estimator.py 138 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/unbiased-predictive-risk-estimator/. The authors are listed in prov/FEKTYX.jsonl.

import math
import random

from imgla import eye, matmul, matvec, norm2, solve, svd, transpose
from unbiased_predictive_risk_estimator import (
    coefficients,
    predictive_risk,
    tikhonov_svd,
    upre_function,
    upre_tikhonov,
    upre_tikhonov_matrix,
    upre_tsvd,
)

SIGMA = 1e-3


def diag_problem(seed, n=32, sigma=SIGMA):
    """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 test_page_example():
    s, xt, y = diag_problem(0)
    e = eye(32)
    alpha, x, val = upre_tikhonov(e, s, e, y, SIGMA)
    assert abs(alpha / 5.04162e-4 - 1.0) < 1e-3
    assert abs(val - 5.69561e-7) < 1e-11
    assert abs(math.dist(x, xt) - 0.06641) < 1e-4
    c0 = [si * xi for si, xi in zip(s, xt)]
    grid = [10 ** (k / 100.0) for k in range(-700, 1)]
    rmin = min(predictive_risk(s, c0, 32, SIGMA, a) for a in grid)
    assert abs(rmin - 1.954e-7) < 1e-10
    assert predictive_risk(s, c0, 32, SIGMA, alpha) <= 1.02 * rmin


def test_function_matches_dense_formula():
    rng = random.Random(3)
    m, n = 9, 6
    a = random_matrix(rng, m, n)
    y = [rng.gauss(0.0, 1.0) for _ in range(m)]
    u, s, v = svd(a)
    b, p2 = coefficients(u, s, y)
    at = transpose(a)
    for alpha in (1e-4, 1e-2, 0.3):
        ata = matmul(at, a)
        for i in range(n):
            ata[i][i] += alpha
        x = solve(ata, matvec(at, y))
        r = [yi - ax for yi, ax in zip(y, matvec(a, x))]
        tr = 0.0
        for k in range(m):
            ek = [1.0 if i == k else 0.0 for i in range(m)]
            tr += matvec(a, solve(ata, matvec(at, ek)))[k]
        sig = 0.2
        direct = norm2(r) ** 2 / m + 2.0 * sig * sig * tr / m - sig * sig
        assert abs(upre_function(s, b, p2, m, sig, alpha) - direct) <= 1e-9 * max(1.0, abs(direct))


def test_unbiased_by_monte_carlo():
    s = [1.0 / i ** 2 for i in range(1, 33)]
    xt = [1.0 / i ** 2 for i in range(1, 33)]
    c0 = [si * xi for si, xi in zip(s, xt)]
    rng = random.Random(11)
    for alpha in (1e-5, 1e-3, 1e-1):
        vals = []
        for _ in range(3000):
            y = [ci + SIGMA * rng.gauss(0.0, 1.0) for ci in c0]
            vals.append(upre_function(s, y, 0.0, 32, SIGMA, alpha))
        mean = sum(vals) / len(vals)
        sd = math.sqrt(sum((t - mean) ** 2 for t in vals) / (len(vals) - 1))
        true = predictive_risk(s, c0, 32, SIGMA, alpha)
        assert abs(mean - true) <= 4.0 * sd / math.sqrt(len(vals))


def test_predictive_risk_close_to_the_best():
    ratios = []
    for seed in range(20):
        s, xt, y = diag_problem(100 + seed, n=64)
        e = eye(64)
        c0 = [si * xi for si, xi in zip(s, xt)]
        alpha, _, _ = upre_tikhonov(e, s, e, y, SIGMA)
        best = min(predictive_risk(s, c0, 64, SIGMA, 10 ** (k / 50.0)) for k in range(-500, 1))
        ratios.append(predictive_risk(s, c0, 64, SIGMA, alpha) / best)
    ratios.sort()
    assert ratios[10] <= 1.3
    assert ratios[-1] <= 3.0


def test_dense_and_svd_paths_agree():
    rng = random.Random(4)
    a = random_matrix(rng, 10, 6)
    y = [rng.gauss(0.0, 1.0) for _ in range(10)]
    u, s, v = svd(a)
    al1, x1, v1 = upre_tikhonov(u, s, v, y, 0.1, alpha_min=1e-6, alpha_max=10.0)
    al2, x2, v2 = upre_tikhonov_matrix(a, y, 0.1, alpha_min=1e-6, alpha_max=10.0)
    assert abs(al1 / al2 - 1.0) < 1e-9
    assert math.dist(x1, x2) <= 1e-12 * max(1.0, norm2(x1))
    b, p2 = coefficients(u, s, y)
    assert abs(upre_function(s, b, p2, 10, 0.1, al1) - v1) <= 1e-15


def test_tsvd_rule_matches_direct_projections():
    rng = random.Random(7)
    a = random_matrix(rng, 10, 6)
    y = [rng.gauss(0.0, 1.0) for _ in range(10)]
    u, s, v = svd(a)
    k, vals = upre_tsvd(u, s, y, 0.3)
    for kk in range(7):
        proj = [sum(u[i][c] * sum(u[j][c] * y[j] for j in range(10)) for c in range(kk)) for i in range(10)]
        r2 = sum((yi - pi) ** 2 for yi, pi in zip(y, proj))
        assert abs(vals[kk] - (r2 / 10 + 2 * 0.09 * kk / 10 - 0.09)) <= 1e-10
    assert vals[k] == min(vals)


def test_tikhonov_svd_solves_the_normal_equations():
    rng = random.Random(8)
    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)
    at = transpose(a)
    ata = matmul(at, a)
    for i in range(5):
        ata[i][i] += 0.01
    x = solve(ata, matvec(at, y))
    assert math.dist(tikhonov_svd(s, v, b, 0.01), x) <= 1e-9 * norm2(x)

History

Mallows (1973) gave CpC_p for subset selection in regression and CLC_L for general linear estimators, both unbiased estimates of the prediction error. Stein (1981) extended the idea to nonlinear, weakly differentiable estimators. Under the name unbiased predictive risk estimator the rule entered the inverse problems literature, where Vogel (2002) treats it next to GCV and the discrepancy principle for Tikhonov and iterative methods. Li (1987) proved asymptotic optimality results for CLC_L and GCV.

References

  1. C. L. Mallows, Some comments on C_p, Technometrics 15(4), 1973, pages 661 to 675
  2. Charles M. Stein, Estimation of the mean of a multivariate normal distribution, Annals of Statistics 9(6), 1981, pages 1135 to 1151
  3. Curtis R. Vogel, Computational Methods for Inverse Problems, SIAM, 2002, chapter 7 (regularization parameter selection methods)

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