Algorithmcore
Generalized cross-validation
Also called GCV, GCV criterion.
Choose the parameter that minimizes V, which is (1/m) times the squared residual norm divided by the square of (1/m) trace(I minus the influence matrix). It needs no noise level.
- 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)
- Model
- Real RAM
- Properties
- not convergent regularizationdeterministicheuristicnot needs noise levelrotation invariant
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Peter Craven, Grace Wahba, Gene H. Golub, Michael Heath, 1979
Generalized cross-validation (GCV) chooses the parameter of a linear regularization method from the data alone. For Tikhonov regularization the fitted data are with the influence matrix . GCV minimizes
the mean squared residual divided by the square of the mean of the diagonal of . The idea comes from leave-one-out cross-validation: predict each measurement from the others and pick the with the smallest prediction error. GCV is the version of this that does not change when the data space is rotated. Craven and Wahba (1979) introduced it for smoothing splines and Golub, Heath and Wahba (1979) for ridge regression. It needs neither the noise level nor the variance , so it is a heuristic rule in the sense of the Bakushinskii veto. For white noise, Golub, Heath and Wahba proved that is close to the predictive risk when the effective number of parameters is a small part of , which explains why it works well on large problems.
In plain words
You want to know how much to smooth, but you do not know how noisy the data are. Cross-validation answers this by testing: hide one measurement, fit the rest, and see how well the fit predicts the hidden value. Repeat for every measurement and add up the misses. Too little smoothing fits the noise and predicts badly. Too much smoothing misses real structure and also predicts badly. GCV is a fast shortcut for this test. It divides the misfit by a factor that grows when the fit uses many degrees of freedom. Then it picks the knob setting with the smallest value. It needs no noise estimate, but on small or square problems it can pick far too little smoothing.
The problem
The model is with an matrix , , and noise . GCV is designed for white noise, with unknown , but the algorithm does not use . The Tikhonov solution for is . The page Tikhonov regularization writes for this , and the page hat matrix treats in least squares, where .
With the thin SVD , , and the filter factors ,
The sum is the effective number of parameters of the fit. The task is to find the that minimizes on a search interval, by default .
The algorithm
The search works in . A coarse geometric grid finds the region of the smallest , and golden-section search refines the minimum between the two grid neighbours.
GCV-TIKHONOV(U, s, V, y, P, eps) ▷ thin SVD of A, s descending, r positive values- 1
b_i ← <u_i, y> for i ≤ r; p² ← ‖y‖² - Σ b_i² - 2
G(t) := m (Σ_i (1 - f_i)² b_i² + p²) / (m - Σ_i f_i)² with f_i = s_i² / (s_i² + e^t) - 3
t_j ← log s_r² + (j / (P - 1)) · (log s_1² - log s_r²) for j = 0, ..., P - 1 - 4
j* ← the index of the smallest G(t_j) - 5
[a, c] ← [t_{j*-1}, t_{j*+1}] ▷ clipped at the ends of the grid - 6
while c - a > eps - 7
golden-section step on [a, c] that keeps the smaller G inside - 8
remember the best (t, G) seen so far - 9
alpha ← e^t for the best t - 10
return 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 written with the SVD; the factors cancel into one factor . Each value costs . Lines L3 and L4 locate the smallest value on a grid, and line L5 brackets it. Lines L6 to L8 are a golden-section search for a minimum, with one evaluation per step. 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 with , so , the true solution , and white noise with drawn by random.Random(0).gauss(0, 1). Then and . The table shows , the predictive risk , the error for this draw of the noise, and .
| 3.3560 | 31.32 | |||
| 2.2930 | 27.34 | |||
| 0.8043 | 18.32 | |||
| 0.1711 | 10.51 | |||
| 0.0817 | 7.80 | |||
| 0.0583 | 5.74 | |||
| 0.0684 | 4.18 | |||
| 0.0981 | 3.01 | |||
| 0.2224 | 1.48 | |||
| 0.5697 | 0.58 |
Line L3 uses with , a step of in . Line L4 picks grid point 28, with , and line L5 brackets it by and . With the loop makes 28 steps and returns with . The error is , against for the best on a fine grid, at . The predictive risk at the GCV choice is , against the smallest possible . At this the value is not close to : here is not small, and the theorem in Correctness gives only a loose bound. The minimizer is still good.
With the noise from seed 2 instead of seed 0, the same code returns the lower end , with an error 25 times the best. See Pitfalls.
Correctness
The proof is in proofs/correctness.md. It has three parts.
The first part shows that line L2 computes : in the SVD basis is diagonal with entries on the range of and on its orthogonal complement. The second part shows that the loop terminates after steps, where is the width of the bracket, and returns a value of at most the smallest grid value.
The third part is the theorem behind the rule, by Golub, Heath and Wahba (1979, Theorem 1). Let , let be the predictive risk, and let and . Then
So when the fit uses few effective parameters compared with , the expected GCV function is the predictive risk plus a constant, and its minimizer is close to the minimizer of the risk. This is a statement about expectations. It does not bound the error of the minimizer of for one draw of the noise, and it is about the predictive risk , not about the error . Results by Li (1987) show asymptotic optimality of the GCV choice for the predictive risk as under conditions. In the deterministic setting with , GCV is not a convergent rule.
Proof: The SVD formula computes the GCV function, the search terminates, and the expected GCV function is the predictive risk plus the noise variance up to a relative error bounded by the trace of the influence matrixfull
Setting. is a real matrix with thin SVD , . For the Tikhonov solution is and the influence matrix is , so . Line L1 computes and . Write .
Claim 1 (the influence matrix). . Hence , whenever or , and
Proof. with the projector on the null space of , and maps into the span of the . So and . The trace of is . Each , so . Write with ; then , and Pythagoras gives the norm.
Claim 2 (line L2 computes V). For , the function of line L2 equals .
Proof. By Claim 1, with and . That is .
Claim 3 (termination and the grid guarantee). The loop of lines L6 to L8 stops after steps, with the width of the bracket of line L5 and . The returned value of is at most , and it is the value at the returned .
Proof. Each golden-section step replaces by or , where and , so the width is multiplied by ; since the kept interior point is at a golden position of the new bracket. After steps the width is , which is at most for the stated . Line L8 starts from the best grid point and only replaces it by a point with a smaller value, and lines L9 and L10 return that point and its value.
Claim 4 (output). Line L10 returns , the Tikhonov solution, by the formula in the proof of Claim 1.
Claim 5 (expected GCV function; Golub, Heath and Wahba 1979, Theorem 1). Let with and , or more generally and . Fix with , and let and . Then
and
Proof. Write , which is symmetric and does not depend on . The denominator of is the constant , so is divided by it. For any fixed matrix , . With , , which gives the formula for . With applied to and subtracted, , so the same computation gives .
Now compute the numerator of over the common denominator :
Substitute . The terms cancel, the terms cancel, and what is left is
Both and are nonnegative because , so the absolute value is at most their sum. Since , we have , so the sum is at most . Divide by .
What Claim 5 means and does not mean. If and along a family of problems, for example when the effective number of parameters grows more slowly than , then , and the minimizer of the expected GCV function is close to the minimizer of the predictive risk. The claim is about the expectation of at a fixed . It does not bound the risk at the random minimizer of for one draw of the noise; results of that kind, such as Li (1987), need further conditions. The claim is about the predictive risk and not about . And for a deterministic noise model it gives nothing: by the Bakushinskii veto, a rule that does not use the noise level cannot be convergent for all noise. The near-optimal errors in the example of the page and in the tests are measurements.
Complexity
With the thin SVD given, line L1 costs , each value of costs , the grid costs , the loop , and line L10 . The total is with extra space, and with . The SVD costs and dominates. For large problems without an SVD the trace is the hard part: it is estimated with random vectors through (Hutchinson, Girard), or from the Lanczos bidiagonalization of a Krylov method.
Properties
- Heuristic: it uses only and , not or .
- Rotation invariant: replacing and by and for an orthogonal leaves unchanged. Ordinary leave-one-out cross-validation does not have this property.
- Scale free: replacing and by and multiplies the chosen by .
- Targets the predictive risk , which weights the error by the singular values. The error in can prefer a somewhat larger .
- With as for a square invertible , has a finite limit at that can be below the interior minimum.
Variants and improvements
- Truncated SVD. For truncated SVD with terms the filter factors are and , so and , minimized over . The implementation includes this rule.
- Ordinary cross-validation. Leave-one-out minimizes . GCV replaces each by their mean.
- Weighted GCV. Chung, Nagy and O'Leary (2008) multiply the trace term by a weight to make GCV choose larger in hybrid Krylov methods, where plain GCV often under-regularizes.
- Randomized trace. For large sparse problems, estimate with a few random vectors.
- Known variance. If is known, UPRE estimates the same risk without bias, and the discrepancy principle gives a convergent rule.
When to use it
Use it for white noise of unknown variance, when is large compared with the effective number of parameters, for example in image deblurring, spline smoothing or ridge regression. It is often the most accurate of the rules that need no noise level. On small or square problems, or with correlated noise, also compute the L-curve or the quasi-optimality criterion, and look at a plot of : a very flat minimum or a minimum at the lower end of the interval is a warning.
Pitfalls
- The minimum at the lower end. For a square invertible the residual and both go to zero as , and tends to a finite value that can be the smallest one. In the example with seed 2, line L4 picks the first grid point. Check whether the result sits at the end of the interval of line L3.
- Correlated noise. The theory assumes white noise. With correlated noise GCV often under-smooths, sometimes badly. Whiten the data first if the covariance is known.
- A flat . Near its minimum, can be very flat, so a small change of the data moves by a large factor. The variance of the GCV choice is known to be large on small problems.
- Dropping the square in the denominator of line L2, or dropping the factor , changes the minimizer. The two factors in the definition do not cancel out of the ratio; they leave the factor .
- Using instead of , or forgetting the part of the trace when . The trace of is , not .
- Using from rounding. If is square, should be but can come out slightly negative or positive; line L1 clamps it at .
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/generalized-cross-validation/. The authors are listed in prov/7S65BE.jsonl.
"""Generalized cross-validation (GCV) for Tikhonov regularization and TSVD.
Tikhonov: x_alpha minimizes ||A x - y||^2 + alpha ||x||^2. The influence
matrix is H_alpha = A (A^T A + alpha I)^(-1) A^T, so A x_alpha = H_alpha y.
GCV picks the alpha that minimizes
V(alpha) = (1/m) ||(I - H_alpha) y||^2 / [(1/m) trace(I - H_alpha)]^2.
With the thin SVD A = U diag(s) V^T, b_i = <u_i, y> and the filter factors
f_i = s_i^2 / (s_i^2 + alpha), the numerator is the squared residual norm
sum_i (1 - f_i)^2 b_i^2 + p2 and trace(I - H_alpha) = m - sum_i f_i.
"""
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 gcv_function(s, b, p2, m, alpha):
"""V(alpha) = m ||(I - H) y||^2 / trace(I - H)^2 for Tikhonov, from the SVD data."""
res2 = p2
tr = float(m)
for si, bi in zip(s, b):
f = si * si / (si * si + alpha)
res2 += (1.0 - f) ** 2 * bi * bi
tr -= f
return m * res2 / (tr * tr)
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 gcv_tikhonov(u, s, v, y, alpha_min=None, alpha_max=None, points=60, eps=1e-6):
"""Return (alpha, x, V(alpha)) for the GCV choice of the Tikhonov parameter.
The search is 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 gcv_function(s, b, p2, m, 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 gcv_tikhonov_matrix(a, y, **kw):
"""The same for a dense matrix: compute the SVD, then call gcv_tikhonov."""
u, s, v = svd(a)
return gcv_tikhonov(u, s, v, y, **kw)
def gcv_tsvd(u, s, y):
"""The discrete rule for TSVD: the k in 0..min(r, m - 1) that minimizes m ||r_k||^2 / (m - k)^2.
Returns (k, list of G(k)). The filter factors of TSVD are 1 for i <= k and 0
after, so trace(I - H_k) = m - k.
"""
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, min(len(s), m - 1) + 1):
if k > 0:
res2 -= b[k - 1] ** 2
vals.append(m * max(res2, 0.0) / ((m - k) ** 2))
k = min(range(len(vals)), key=lambda i: vals[i])
return k, vals
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_generalized_cross_validation.py 160 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/generalized-cross-validation/. The authors are listed in prov/7S65BE.jsonl.
import math
import random
from imgla import eye, matmul, matvec, norm2, solve, svd, transpose
from generalized_cross_validation import (
coefficients,
gcv_function,
gcv_tikhonov,
gcv_tikhonov_matrix,
gcv_tsvd,
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 risk(s, xt, sigma, alpha):
"""(1/m) E ||A x_alpha - A x||^2 for the diagonal problem."""
tot = 0.0
for si, xi in zip(s, xt):
f = si * si / (si * si + alpha)
tot += ((1.0 - f) * si * xi) ** 2 + sigma * sigma * f * f
return tot / len(s)
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 hat_matrix(a, alpha):
"""H = A (A^T A + alpha I)^(-1) A^T, column by column."""
at = transpose(a)
ata = matmul(at, a)
n = len(ata)
for i in range(n):
ata[i][i] += alpha
m = len(a)
cols = []
for k in range(m):
ek = [1.0 if i == k else 0.0 for i in range(m)]
cols.append(matvec(a, solve(ata, matvec(at, ek))))
return [[cols[j][i] for j in range(m)] for i in range(m)]
def test_page_example():
s, xt, y = diag_problem(0)
eye32 = eye(32)
alpha, x, v = gcv_tikhonov(eye32, s, eye32, y)
assert abs(alpha / 7.08667e-4 - 1.0) < 1e-3
assert abs(v - 1.83444e-6) < 1e-10
assert abs(math.dist(x, xt) - 0.06056) < 1e-4
best = min(math.dist(tikhonov_svd(s, eye32, y, 10 ** (k / 100.0)), xt) for k in range(-700, 1))
assert abs(best - 0.05817) < 1e-4
assert math.dist(x, xt) <= 1.05 * best
def test_function_matches_dense_hat_matrix():
rng = random.Random(3)
a = random_matrix(rng, 9, 6)
y = [rng.gauss(0.0, 1.0) for _ in range(9)]
u, s, v = svd(a)
b, p2 = coefficients(u, s, y)
for alpha in (1e-4, 1e-2, 0.3):
h = hat_matrix(a, alpha)
r = [yi - hy for yi, hy in zip(y, matvec(h, y))]
tr = 9.0 - sum(h[i][i] for i in range(9))
direct = (norm2(r) ** 2 / 9.0) / (tr / 9.0) ** 2
assert abs(gcv_function(s, b, p2, 9, alpha) - direct) <= 1e-9 * direct
def test_invariant_under_rotation_of_the_data_space():
rng = random.Random(5)
a = random_matrix(rng, 8, 5)
y = [rng.gauss(0.0, 1.0) for _ in range(8)]
q, _, _ = svd([[rng.gauss(0.0, 1.0) for _ in range(8)] for _ in range(8)])
qa = matmul(q, a)
qy = matvec(q, y)
al1, x1, v1 = gcv_tikhonov_matrix(a, y, alpha_min=1e-6, alpha_max=10.0)
al2, x2, v2 = gcv_tikhonov_matrix(qa, qy, alpha_min=1e-6, alpha_max=10.0)
assert abs(al1 / al2 - 1.0) < 1e-4
assert abs(v1 / v2 - 1.0) < 1e-8
assert math.dist(x1, x2) <= 1e-4 * norm2(x1)
def test_result_is_not_above_any_grid_value():
s, xt, y = diag_problem(1)
eye32 = eye(32)
b, p2 = coefficients(eye32, s, y)
alpha, _, v = gcv_tikhonov(eye32, s, eye32, y)
lo, hi = math.log(s[-1] ** 2), math.log(s[0] ** 2)
grid = [gcv_function(s, b, p2, 32, math.exp(lo + (hi - lo) * j / 999)) for j in range(1000)]
assert v <= min(grid) * (1.0 + 1e-9)
assert abs(gcv_function(s, b, p2, 32, alpha) - v) <= 1e-15
def test_predictive_risk_close_to_the_best_on_average():
ratios = []
for seed in range(20):
s, xt, y = diag_problem(100 + seed, n=64)
e = eye(64)
alpha, _, _ = gcv_tikhonov(e, s, e, y)
best = min(risk(s, xt, 1e-3, 10 ** (k / 50.0)) for k in range(-500, 1))
ratios.append(risk(s, xt, 1e-3, alpha) / best)
ratios.sort()
assert ratios[10] <= 1.3
assert sum(1 for r in ratios if r <= 2.0) >= 16
def test_expected_gcv_function_and_the_golub_heath_wahba_bound():
n, sigma = 32, 1e-3
s = [1.0 / i ** 2 for i in range(1, n + 1)]
g = [si / i ** 2 for i, si in enumerate(s, 1)]
rng = random.Random(12)
for alpha in (1e-4, 1e-3, 1e-2):
f = [si * si / (si * si + alpha) for si in s]
mu1 = sum(f) / n
mu2 = sum(t * t for t in f) / n
beta2 = sum(((1.0 - fi) * gi) ** 2 for fi, gi in zip(f, g)) / n
expected = (beta2 + sigma * sigma * (1.0 - 2.0 * mu1 + mu2)) / (1.0 - mu1) ** 2
t_risk = beta2 + sigma * sigma * mu2
assert abs(expected - sigma * sigma - t_risk) <= t_risk * (2 * mu1 + mu1 * mu1 / mu2) / (1.0 - mu1) ** 2
vals = []
for _ in range(2000):
y = [gi + sigma * rng.gauss(0.0, 1.0) for gi in g]
vals.append(gcv_function(s, y, 0.0, n, alpha))
mean = sum(vals) / len(vals)
sd = math.sqrt(sum((t - mean) ** 2 for t in vals) / (len(vals) - 1))
assert abs(mean - expected) <= 4.0 * sd / math.sqrt(len(vals))
def test_square_system_can_fail_at_the_lower_end():
s, xt, y = diag_problem(2)
eye32 = eye(32)
alpha, x, _ = gcv_tikhonov(eye32, s, eye32, y)
assert abs(alpha / s[-1] ** 2 - 1.0) < 1e-3
best = min(math.dist(tikhonov_svd(s, eye32, y, 10 ** (k / 100.0)), xt) for k in range(-700, 1))
assert math.dist(x, xt) > 10.0 * best
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 = gcv_tsvd(u, s, y)
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] - 10.0 * r2 / (10 - kk) ** 2) <= 1e-10 * max(1.0, vals[kk])
assert vals[k] == min(vals)
History
Wahba (1977) used cross-validation to choose the parameter in the regularized solution of linear operator equations. Craven and Wahba (1979) defined generalized cross-validation for smoothing splines and studied how well it estimates the predictive risk for large . Golub, Heath and Wahba (1979) studied it for ridge regression and gave the bound on the expected GCV function. Li (1986, 1987) proved asymptotic optimality under general conditions. Wahba's 1990 monograph on spline models made it standard in statistics, and Vogel (2002) and Hansen (2010) describe its use for inverse problems.
References
- Peter Craven and Grace Wahba, Smoothing noisy data with spline functions, Numerische Mathematik 31(4), 1979, pages 377 to 403
- Gene H. Golub, Michael Heath and Grace Wahba, Generalized cross-validation as a method for choosing a good ridge parameter, Technometrics 21(2), 1979, pages 215 to 223
- Curtis R. Vogel, Computational Methods for Inverse Problems, SIAM, 2002, chapter 7 (regularization parameter selection methods)
- Per Christian Hansen, Discrete Inverse Problems, Insight and Algorithms, SIAM, 2010, chapter 5 (choosing the regularization parameter)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 7S65BE Edit this page History Report an error Markdown