Algorithmcore
L-curve method
Also called L-curve criterion, L-curve corner rule.
Plot the log solution norm against the log residual norm over the parameter and choose the parameter at the corner of maximum curvature.
- 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 level
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Per Christian Hansen, Dianne P. O'Leary, Charles L. Lawson, Richard J. Hanson, 1992
The L-curve method chooses the parameter of Tikhonov regularization from the data alone. For each it takes the point . As runs from large to small, the residual falls and the solution norm grows, and for many discrete ill-posed problems the curve has the shape of the letter L. On the flat part, the solution is over-smoothed: a smaller buys a much smaller residual at little cost in norm. On the steep part, the solution fits noise: a smaller makes the norm explode for almost no gain in residual. The rule takes the corner between the two, defined as the point of largest curvature. Hansen and O'Leary proposed it in 1993, after Hansen's 1992 analysis of the curve. It needs neither the noise level nor the noise variance, so it is a heuristic rule. By the Bakushinskii veto no such rule can converge for every problem, and Hanke and Vogel gave explicit examples where the L-curve choice does not converge. In practice it is robust to correlated noise and easy to inspect by eye.
In plain words
A smoothing method has a knob. For each setting you can measure two numbers: how far the result is from the data, and how wild the result is. Draw these two numbers against each other on log scales, one point per setting. For many problems you get an L. Along one arm, turning the knob makes the result much closer to the data and only a little wilder. Along the other arm, it makes the result much wilder and only a little closer. The best compromise sits at the bend. The method finds the bend as the point where the curve turns most sharply. It does not need to know how much noise there is, which is its strength, and it can be fooled, which is its weakness.
The problem
The model is with an matrix and unknown noise . The Tikhonov solution for is
The page Tikhonov regularization writes for this . With the thin SVD , and , write
The L-curve is the plane curve . Its signed curvature is
It is positive where the curve turns like the corner of an L. The task is to find the that maximizes on a search interval, by default .
The algorithm
The search works in . A coarse geometric grid finds the region of the largest curvature, and golden-section search refines the maximum between the two grid neighbours.
L-CURVE-CORNER(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
t_j ← log s_r² + (j / (P - 1)) · (log s_1² - log s_r²) for j = 0, ..., P - 1 - 3
k_j ← κ(e^{t_j}) for every j ▷ η, ρ, η' from b, p² in Θ(r) - 4
j* ← the index of the largest k_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 larger κ inside - 8
remember the best (t, κ) 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 its curvature
Line L1 projects the data on the left singular vectors. After that, every value of , and costs , so line L3 is cheap even with a fine grid. Line L4 picks the grid point of largest curvature, and line L5 brackets it by its neighbours. Lines L6 to L8 are a golden-section search for a maximum: each step evaluates once and shrinks the bracket by the factor . Line L8 keeps the best point, so the result is never worse than the best grid point. Line L10 forms the Tikhonov solution from the SVD.
Example
Take the test problem deriv2 with : is the discretized Green's function of on with zero boundary values, at the midpoints , with entries for and . The true solution has two bumps, , and . The noise is Gaussian from random.Random(0), scaled so that . The singular values run from to , and because is square and invertible.
| 0.00404 | 21.3866 | -0.3935 | 21.2693 | |
| 0.01186 | 7.4657 | -0.3572 | 7.1273 | |
| 0.01590 | 2.4850 | 0.2798 | 1.3985 | |
| 0.01694 | 2.0287 | 2.1954 | 0.8312 | |
| 0.01799 | 1.8573 | 4.4166 | 0.9049 | |
| 0.02001 | 1.7423 | 1.4294 | 1.0462 | |
| 0.02638 | 1.5990 | 0.0332 | 1.1602 | |
| 0.08996 | 0.8802 | -0.6814 | 1.5090 | |
| 0.16138 | 0.1619 | -0.1089 | 2.0110 |
Read the table from the bottom up. From to the residual falls by a factor of 6 and the norm grows by a factor of 10. From to the residual falls by a factor of 4 and the norm grows by a factor of 9. In between, from to , the residual barely moves and the norm grows slowly: that is the corner. The curvature is negative on both arms, where the log-log curve bends the other way.
Line L2 uses the default interval with points, so neighbouring grid points are apart in . Line L4 picks grid point 33, with , and line L5 brackets it by and . With the golden-section loop makes 27 steps and returns with , residual and . The error is . On a fine grid the smallest error is , at , so the corner costs 8 percent here. For comparison, the discrepancy principle with the true and gives and error . The residual at the corner, , is close to , which is what the rule hopes for when it has no .
Correctness
The proof is in proofs/correctness.md. It shows three things. First, is strictly decreasing and is strictly increasing in when some , and , so the L-curve is a graph that runs from upper left to lower right. Second, the closed form of above is the signed curvature of the curve : the second derivative cancels out of the numerator once and are substituted. The curvature of a plane curve does not depend on the parameter, so computing it in or in gives the same value. Third, the search terminates after golden-section steps, where is the width of the initial bracket, and returns a point whose curvature is at least the largest curvature on the grid. If is unimodal on the bracket, the result is within of the local maximum in .
None of this says that the corner gives a good . That claim is a heuristic. For a solution that satisfies the discrete Picard condition and noise that is not too small, Hansen (1992) explains why the curve has a corner near the where the noise starts to dominate the solution. There is no theorem that it converges, and there are proofs that it does not in some settings (see Pitfalls).
Proof: The L-curve is monotone, the closed-form curvature is its signed curvature, and the corner search terminates with a point at least as curved as the best grid pointfull
Setting. is a real matrix with thin SVD and . For data , line L1 computes and , the squared norm of the part of outside the range of . For the Tikhonov solution is . Assume some ; otherwise for every and there is no curve.
Claim 1 (the two norms). With ,
Proof. In the basis the normal equations are diagonal, with for and on the null space of . Then with , and Pythagoras gives both norms.
Claim 2 (monotonicity). and . So as grows, the curve moves strictly right and strictly down.
Proof. Differentiate term by term: , and . The second is times the first. Some , so .
Claim 3 (the curvature formula). The signed curvature of the curve, with the derivative in , equals
Proof. We have , , and . By Claim 2, and so . Substitute:
The two terms with cancel. Over the common denominator the rest is . Also
So
and by Claim 2.
The sign convention: the curve runs right and down as grows, and means that it turns counterclockwise, from steep to flat, which is the turn at the corner of an L.
Claim 4 (invariance). The value of at a point of the curve does not depend on the parameter. In particular, computed in equals computed in .
Proof. Let with . Then and , and the same for . So , because the terms cancel, and . The factors cancel.
Claim 5 (scaling). Replacing and by and with maps the curvature at to the curvature at of the new problem, and the solution is unchanged.
Proof. The new singular values are and the new coefficients . At each term of is unchanged and each term of is multiplied by . So the new curve is the old one shifted by , a rigid motion, and the curvature is unchanged. The solution is the old one.
Claim 6 (termination and the guarantee of the search). Let be the width of the bracket from line L5 (at most ). The loop of lines L6 to L8 stops after steps, with . The returned satisfies . If is unimodal on the bracket, the returned is within of the maximizer on the bracket.
Proof. The search keeps two interior points of at the golden ratio positions and . If it replaces by , otherwise by . Since , the kept interior point is at a golden position of the new bracket, so one new evaluation per step suffices, and the width is multiplied by in every step. After steps it is , so the loop stops. Line L8 starts from the best grid point and replaces it only by a point with a larger value, so the returned value is at least , and line L9 returns the where it was attained. If the function is unimodal on , each step discards a part of the bracket that contains no point larger than the kept interior point, so the maximizer stays in . The returned was evaluated inside the final bracket or is at least as good as all points evaluated in it, so it lies within the final width of the maximizer when the function is unimodal.
Claim 7 (the output). Line L10 returns , the Tikhonov solution for the chosen , by Claim 1.
What is not proved. The claims above make the algorithm a correct and terminating maximizer of the curvature. They do not say that the corner gives a small error. By the Bakushinskii veto, no rule that does not use the noise level can make for all and all noise as the noise goes to zero, and Hanke (1996) and Vogel (1996) give explicit model problems where the L-curve choice fails to converge. The good behaviour in the example of the page is a measurement.
Complexity
With the thin SVD given, line L1 costs . Each curvature value costs , so line L3 costs and the loop costs for golden-section steps. Line L10 costs . The total is with extra space. The bracket has width , and . In the example , and . The SVD itself costs by a standard dense method and dominates. Without an SVD, each point of the curve needs one Tikhonov solve and needs one more solve, so large problems use a few points of the curve and a Krylov method, as in hybrid Krylov regularization.
Properties
- Heuristic: it uses only and , not or .
- Not convergent in general. By the Bakushinskii veto, a rule that ignores the noise level cannot converge for every and every noise sequence.
- Scale free: replacing and by and multiplies the chosen by and leaves and unchanged, because a scaling of and is a shift of the log-log curve.
- The curvature is a property of the curve and not of the parameter. The same corner is found in , or .
- The corner need not exist. On mildly ill-posed problems the curve can be convex the wrong way everywhere, and then line L4 returns the least negative curvature, which is not a corner (see Pitfalls).
Variants and improvements
- Discrete L-curve. For truncated SVD, CGLS or other methods with a discrete parameter the curve is a set of points. Hansen, Jensen and Rodriguez (2007) choose the corner by an adaptive pruning of the points. A simpler choice is the point of largest angle change.
- Triangle and maximum distance rules. Pick the point farthest from the line through the two ends of the curve. This needs no derivatives.
- Krylov approximations. Calvetti, Golub and Reichel (1999) bound the curve with Gauss quadrature from Lanczos bidiagonalization, the L-ribbon, so the corner can be found without the SVD.
- General form. With a penalty the vertical axis becomes . The same formulas hold with the generalized SVD of .
- Other heuristic rules. GCV and the quasi-optimality criterion also work without . They fail in different situations, so computing two of them is a cheap check.
When to use it
Use it when the noise level is unknown, the problem is severely ill-posed and the noise is not tiny, and you want a picture that a person can check. It is a good first rule in exploratory work because the plot shows at once whether the problem has a clear corner. If is known, use the discrepancy principle or the balancing principle, which have proofs. If the noise is white with known variance, use UPRE. For large white-noise problems, GCV is often more accurate.
Pitfalls
- A curve with no corner. For a mildly ill-posed problem, such as a integration matrix with percent noise, the curvature is negative on the whole interval. Line L4 still returns a point. Check that the returned is positive and look at the plot.
- Smooth solutions and small noise. Hanke (1996) showed in a model problem that the L-curve choice does not converge in the right way when the true solution is very smooth. Vogel (1996) showed that the chosen parameter does not converge as the discretization is refined in a statistical setting. Treat the rule as a heuristic, not as a regularization method.
- A grid that is too coarse in line L2. The peak of can be narrow, and a coarse grid can miss it and lock line L5 onto a second, smaller local maximum. With on this rarely happens, but more points cost little.
- A search interval that is too narrow or too wide. Below the curve is nearly a straight line and can have spurious bends caused by rounding. Above the curvature is near zero. The default in line L2 avoids both.
- Using the plain norms instead of their logarithms. The corner is a feature of the log-log plot. In linear scales the curvature formula and the maximum are different.
- Computing the curvature with finite differences of the plotted points instead of the closed form in line L3. The second differences lose many digits when the points are close, and is available exactly.
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
l_curve_method.py 110 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/l-curve-method/. The authors are listed in prov/W03DNM.jsonl.
"""The L-curve corner rule for Tikhonov regularization.
The L-curve is the curve (log ||A x_alpha - y||, log ||x_alpha||) for
alpha > 0, where x_alpha minimizes ||A x - y||^2 + alpha ||x||^2. The rule
picks the alpha of largest curvature. With eta = ||x_alpha||^2,
rho = ||A x_alpha - y||^2 and eta' = d eta / d alpha, the curvature is
kappa = -2 eta rho (alpha eta' rho + alpha^2 eta' eta + eta rho)
/ (eta' (alpha^2 eta^2 + rho^2)^(3/2)),
so it needs no second derivative. Everything comes from the thin SVD.
"""
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 norms(s, b, p2, alpha):
"""(eta, rho, eta') at alpha: ||x_alpha||^2, ||A x_alpha - y||^2 and d eta / d alpha."""
eta = rho = deta = 0.0
for si, bi in zip(s, b):
q = si * si + alpha
eta += si * si * bi * bi / (q * q)
rho += (alpha / q) ** 2 * bi * bi
deta -= 2.0 * si * si * bi * bi / (q * q * q)
return eta, rho + p2, deta
def curvature(s, b, p2, alpha):
"""The signed curvature of the L-curve at alpha (positive at the corner)."""
eta, rho, deta = norms(s, b, p2, alpha)
num = alpha * deta * rho + alpha * alpha * deta * eta + eta * rho
return -2.0 * eta * rho * num / (deta * (alpha * alpha * eta * eta + rho * rho) ** 1.5)
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 l_curve_corner(u, s, v, y, alpha_min=None, alpha_max=None, points=60, eps=1e-6):
"""Return (alpha, x, kappa) at the point of largest curvature of the L-curve.
The search is over [alpha_min, alpha_max], by default [s_r^2, s_1^2]: a
geometric grid of the given number of points, then golden-section search
in log alpha between the neighbours of the best grid point.
"""
s = [si for si in s if si > 0.0]
b, p2 = coefficients(u, s, y) # @line L1
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 L2
def kappa(t):
return curvature(s, b, p2, math.exp(t))
ks = [kappa(t) for t in ts] # @line L3
j = max(range(points), key=lambda i: ks[i]) # @line L4
a, c = ts[max(j - 1, 0)], ts[min(j + 1, points - 1)] # @line L5
best_t, best_k = ts[j], ks[j]
t1, t2 = c - INV_PHI * (c - a), a + INV_PHI * (c - a)
k1, k2 = kappa(t1), kappa(t2)
while c - a > eps: # @line L6
if k1 >= k2: # @line L7
c, t2, k2 = t2, t1, k1
t1 = c - INV_PHI * (c - a)
k1 = kappa(t1)
else:
a, t1, k1 = t1, t2, k2
t2 = a + INV_PHI * (c - a)
k2 = kappa(t2)
for t, k in ((t1, k1), (t2, k2)): # @line L8
if k > best_k:
best_t, best_k = t, k
alpha = math.exp(best_t) # @line L9
return alpha, tikhonov_svd(s, v, b, alpha), best_k # @line L10
def l_curve_corner_matrix(a, y, **kw):
"""The same for a dense matrix: compute the SVD, then call l_curve_corner."""
u, s, v = svd(a)
return l_curve_corner(u, s, v, y, **kw)
def l_curve_points(s, b, p2, alphas):
"""The points (log ||A x_alpha - y||, log ||x_alpha||) for a list of alphas."""
out = []
for al in alphas:
eta, rho, _ = norms(s, b, p2, al)
out.append((0.5 * math.log(rho), 0.5 * math.log(eta)))
return out
test_l_curve_method.py 160 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/l-curve-method/. The authors are listed in prov/W03DNM.jsonl.
import math
import random
from imgla import matmul, matvec, norm2, rmatvec, solve, svd, transpose
from l_curve_method import (
coefficients,
curvature,
l_curve_corner,
l_curve_corner_matrix,
l_curve_points,
norms,
tikhonov_svd,
)
def deriv2(n):
"""Discretized Green's function of -u'' on [0, 1] with zero boundary values."""
h = 1.0 / n
t = [(i + 0.5) * h for i in range(n)]
return [[h * (t[i] * (t[j] - 1.0) if t[i] < t[j] else t[j] * (t[i] - 1.0)) for j in range(n)] for i in range(n)]
def integration_matrix(n):
h = 1.0 / n
return [[h if j <= i else 0.0 for j in range(n)] for i in range(n)]
def bumps(n):
t = [(j + 0.5) / n for j in range(n)]
return [math.exp(-80.0 * (x - 0.3) ** 2) + 0.6 * math.exp(-80.0 * (x - 0.7) ** 2) for x in t]
def noisy(a, xt, rel, seed):
y0 = matvec(a, xt)
rng = random.Random(seed)
e = [rng.gauss(0.0, 1.0) for _ in y0]
c = rel * norm2(y0) / norm2(e)
return [p + c * q for p, q in zip(y0, e)], c * norm2(e)
def tikhonov_solve(a, y, alpha):
ata = matmul(transpose(a), a)
for i in range(len(ata)):
ata[i][i] += alpha
return solve(ata, rmatvec(a, y))
def best_on_grid(s, v, b, xt):
return min(math.dist(tikhonov_svd(s, v, b, 10.0 ** (k / 40.0)), xt) for k in range(-400, 40))
def test_page_example():
a, xt = deriv2(24), bumps(24)
y, delta = noisy(a, xt, 0.1, 0)
u, s, v = svd(a)
alpha, x, kappa = l_curve_corner(u, s, v, y)
assert abs(alpha / 8.5477e-5 - 1.0) < 1e-3
assert abs(kappa - 4.4994) < 1e-3
assert abs(math.dist(x, xt) - 0.8850) < 1e-3
b, p2 = coefficients(u, s, y)
assert abs(math.sqrt(norms(s, b, p2, alpha)[1]) - 0.01782) < 1e-5
assert abs(delta - 0.01754) < 1e-5
def test_norms_match_direct_solves():
a = deriv2(10)
y, _ = noisy(a, bumps(10), 0.05, 3)
u, s, v = svd(a)
b, p2 = coefficients(u, s, y)
for alpha in (1e-6, 1e-4, 1e-2):
x = tikhonov_solve(a, y, alpha)
r = [p - q for p, q in zip(matvec(a, x), y)]
eta, rho, _ = norms(s, b, p2, alpha)
assert abs(eta - norm2(x) ** 2) <= 1e-8 * eta
assert abs(rho - norm2(r) ** 2) <= 1e-8 * rho
assert math.dist(tikhonov_svd(s, v, b, alpha), x) <= 1e-8 * norm2(x)
def test_derivative_and_curvature_match_finite_differences():
a = deriv2(12)
y, _ = noisy(a, bumps(12), 0.05, 4)
u, s, v = svd(a)
b, p2 = coefficients(u, s, y)
for t in (-14.0, -11.0, -9.0, -6.0):
h = 1e-4
ep = norms(s, b, p2, math.exp(t + h))[0]
em = norms(s, b, p2, math.exp(t - h))[0]
deta = norms(s, b, p2, math.exp(t))[2]
assert abs((ep - em) / (math.exp(t + h) - math.exp(t - h)) - deta) <= 1e-6 * abs(deta)
# curvature of the parametric curve (log rho / 2, log eta / 2) in t = log alpha
(x0, y0), (x1, y1), (x2, y2) = l_curve_points(s, b, p2, [math.exp(t - h), math.exp(t), math.exp(t + h)])
dx, dy = (x2 - x0) / (2 * h), (y2 - y0) / (2 * h)
ddx, ddy = (x2 - 2 * x1 + x0) / h ** 2, (y2 - 2 * y1 + y0) / h ** 2
k_fd = (dx * ddy - ddx * dy) / (dx * dx + dy * dy) ** 1.5
k = curvature(s, b, p2, math.exp(t))
assert abs(k_fd - k) <= 1e-4 * max(1.0, abs(k))
def test_curve_is_monotone():
a = deriv2(10)
y, _ = noisy(a, bumps(10), 0.02, 5)
u, s, v = svd(a)
b, p2 = coefficients(u, s, y)
pts = l_curve_points(s, b, p2, [10.0 ** (k / 4.0) for k in range(-40, 0)])
assert all(pts[i][0] < pts[i + 1][0] for i in range(len(pts) - 1))
assert all(pts[i][1] > pts[i + 1][1] for i in range(len(pts) - 1))
def test_corner_is_a_local_maximum_above_the_grid():
a = deriv2(16)
u, s, v = svd(a)
for seed in range(3):
y, _ = noisy(a, bumps(16), 0.05, 10 + seed)
b, p2 = coefficients(u, s, y)
alpha, _, kappa = l_curve_corner(u, s, v, y)
assert abs(curvature(s, b, p2, alpha) - kappa) <= 1e-12 * abs(kappa)
lo, hi = math.log(s[-1] ** 2), math.log(s[0] ** 2)
grid = [curvature(s, b, p2, math.exp(lo + (hi - lo) * j / 59)) for j in range(60)]
assert kappa >= max(grid)
for f in (0.999, 1.001):
assert curvature(s, b, p2, alpha * f) <= kappa + 1e-9
def test_error_close_to_best_on_a_favourable_problem():
a, xt = deriv2(24), bumps(24)
u, s, v = svd(a)
for rel, factor in ((0.1, 1.6), (0.01, 2.0)):
for seed in range(3):
y, _ = noisy(a, xt, rel, seed)
b, _ = coefficients(u, s, y)
_, x, _ = l_curve_corner(u, s, v, y)
assert math.dist(x, xt) <= factor * best_on_grid(s, v, b, xt)
def test_scaling_moves_alpha_by_c_squared():
a = deriv2(12)
y, _ = noisy(a, bumps(12), 0.05, 6)
alpha, x, kappa = l_curve_corner_matrix(a, y)
c = 7.0
ac = [[c * t for t in row] for row in a]
alpha_c, x_c, kappa_c = l_curve_corner_matrix(ac, [c * t for t in y])
assert abs(alpha_c / (c * c * alpha) - 1.0) < 1e-4
assert math.dist(x, x_c) <= 1e-4 * norm2(x)
assert abs(kappa - kappa_c) <= 1e-6 * abs(kappa)
def test_no_corner_on_a_mildly_ill_posed_problem():
n = 16
a = integration_matrix(n)
xt = [math.sin(math.pi * (j + 0.5) / n) for j in range(n)]
y, _ = noisy(a, xt, 0.01, 1)
u, s, v = svd(a)
b, p2 = coefficients(u, s, y)
_, _, kappa = l_curve_corner(u, s, v, y)
assert kappa < 0.0
lo, hi = math.log(s[-1] ** 2), math.log(s[0] ** 2)
assert all(curvature(s, b, p2, math.exp(lo + (hi - lo) * j / 99)) < 0.0 for j in range(100))
History
Lawson and Hanson (1974) plotted the solution norm against the residual norm to choose a truncation level. Hansen (1992) studied the curve in log-log scale for discrete ill-posed problems and explained its L shape from the SVD and the Picard condition. Hansen and O'Leary (1993) turned the picture into a rule, the corner of maximum curvature, and gave the curvature formula in terms of , and . Hanke (1996) and Vogel (1996) showed limits of the rule: it is not convergent in general. It remains one of the most used heuristic rules, mainly because the plot is easy to read.
References
- Per Christian Hansen, Analysis of discrete ill-posed problems by means of the L-curve, SIAM Review 34(4), 1992, pages 561 to 580
- Per Christian Hansen and Dianne P. O'Leary, The use of the L-curve in the regularization of discrete ill-posed problems, SIAM Journal on Scientific Computing 14(6), 1993, pages 1487 to 1503
- Martin Hanke, Limitations of the L-curve method in ill-posed problems, BIT 36(2), 1996, pages 287 to 301
- Curtis R. Vogel, Non-convergence of the L-curve regularization parameter selection method, Inverse Problems 12(4), 1996, pages 535 to 547
- 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 W03DNM Edit this page History Report an error Markdown