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)
- Model
- Real RAM
- Properties
- a posteriorideterministicneeds noise varianceunbiased risk estimate
- Evidence
- Proof sketchCode in 1 languages
- 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 . The quantity it aims at is the predictive risk , which depends on the unknown . For Tikhonov regularization with influence matrix , the function
is computable from the data and satisfies for every . UPRE picks the minimizer of . The residual term alone would always prefer small ; the trace term charges for each effective parameter of the fit. Mallows (1973) introduced the estimate as for linear smoothers, and it is the special case of Stein's unbiased risk estimate for the linear map . The rule is a posteriori in the statistical sense: it needs but not .
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 with an matrix and with a known . The Tikhonov solution for is , so . The page Tikhonov regularization writes for this .
With the thin SVD , , and the filter factors ,
The task is to find the that minimizes on a search interval, by default .
The algorithm
The search is the same as for GCV: a geometric grid in , then golden-section search between the neighbours of the best grid point.
UPRE-TIKHONOV(U, s, V, y, sigma, 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) := (Σ_i (1 - f_i)² b_i² + p²) / m + 2 sigma² Σ_i f_i / m - sigma² 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 in SVD form, at a cost of 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: with , , and with from random.Random(0).gauss(0, 1), so and . The table compares with the true predictive risk .
| 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 |
For this draw of the noise, lies above by about 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 near its minimum follows the shape of .
Line L4 picks grid point 27, , and line L5 brackets it by and . The loop makes 28 steps with and returns with . The predictive risk there is , against the smallest possible at . The error in is , against at the best for the error. The two optimal differ because the predictive risk weights the error by the singular values.
Correctness
The proof is in proofs/correctness.md. Line L2 computes by the SVD form of , the search terminates after golden-section steps for a bracket of width , and the returned value is at most the smallest grid value.
The theorem behind the rule: for every fixed , . The proof is two lines. Write with . Then and . The difference is , which is exactly what the last two terms of remove. The same identity is Stein's lemma for the linear map , whose divergence is . Only the first two moments of the noise are used, so the identity holds for any noise with mean zero and covariance .
Unbiasedness at each fixed does not make the minimizer of the minimizer of . The minimizer depends on the noise, and its risk is a random quantity. Results on asymptotic optimality as (Li 1987, for among others) need further conditions. In the tests, over 20 noise draws on a 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. is a real matrix with thin SVD , . For , and , so . Line L1 computes and . Write .
Claim 1 (the influence matrix). , so and .
Proof. , because acts on as multiplication by . Multiply by on the left. For the norm, write with ; then , and the terms are orthogonal.
Claim 2 (line L2 computes U). By Claim 1, the function of line L2 at equals .
Claim 3 (unbiasedness). Let with fixed, and . For every fixed ,
Proof. For a fixed matrix and fixed vector , . Write , which is symmetric. First, , so
Second, , so
Subtracting, . Divide by and move the terms: , since is not random.
Link with Stein's lemma. For Gaussian noise, Stein's unbiased risk estimate of for a weakly differentiable is . For the divergence is , and dividing by gives . Claim 3 shows that for linear Gaussianity is not needed.
Claim 4 (termination and the grid guarantee). The loop of lines L6 to L8 stops after steps, where is 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 with and , so the width is multiplied by . After steps it is for the stated , 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.
Claim 5 (output). Line L10 returns , the Tikhonov solution for the returned , by the formula in the proof of Claim 1.
What is not proved. Claim 3 holds at each fixed . The returned depends on , and in general is not the expected loss 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 , each value of costs , the grid costs , the loop , and line L10 . The total is with extra space. The SVD itself costs and dominates. Without an SVD, is estimated with random probe vectors, as for GCV.
Properties
- Needs the noise variance but not .
- Unbiased for the predictive risk at every fixed , for any noise with mean zero and covariance .
- Scale free when is scaled with the data: replacing , and by , and multiplies the chosen by .
- Monotone in : a larger puts more weight on the trace, which decreases in , so the minimizer does not move toward smaller .
- The same estimate works for any linear method with fitted data : replace by .
Variants and improvements
- Truncated SVD. With terms, and . This is Mallows' up to scaling, and the implementation includes it.
- SURE for nonlinear estimators. For a nonlinear map , such as soft thresholding of wavelet coefficients, replace by the divergence of . See Stein's unbiased risk estimate.
- Error in x instead of in the data. The risk has no unbiased estimate in general when is ill-conditioned. A projected risk, with the projector on the range of , can be estimated, but with a large variance.
- Colored noise. With noise covariance , whiten first: replace and by and , and use .
- Unknown variance. Replace by an estimate, for example from the residual of a fit with a small . Then the rule is close to GCV, which removes 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 is known, use the discrepancy principle or the balancing principle instead, which have proofs in that setting.
Pitfalls
- A wrong . In the example, instead of makes line L4 pick the lower end of the interval, , with an error of , forty times the best. Overestimating is safer: gives and error . Check where the result lies in the interval.
- Using in place of 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 when it is very flat. The minimum value of can be negative for one noise draw, which is fine, but a flat 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.
# 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 for subset selection in regression and 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 and GCV.
References
- C. L. Mallows, Some comments on C_p, Technometrics 15(4), 1973, pages 661 to 675
- Charles M. Stein, Estimation of the mean of a multivariate normal distribution, Annals of Statistics 9(6), 1981, pages 1135 to 1151
- 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.
| 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 FEKTYX Edit this page History Report an error Markdown