Algorithmcore
Truncated singular value decomposition
Also called TSVD, truncated SVD.
Regularize A x = y by keeping the k largest singular components of the pseudoinverse solution and dropping the rest. Choose k from the noise level, for example by the discrepancy principle.
- Time
- O(m n^2 + k (m + n)) worst
- Space
- O(m n) extra
- Where
- k = the truncation index; m = the number of rows of A; n = the number of columns of A with m >= n
- Properties
- deterministicdirectnot iterativelinear in data
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Per Christian Hansen, 1987
The truncated singular value decomposition (TSVD) solves an ill-conditioned linear system by keeping the largest singular components of the pseudoinverse solution and dropping the rest: . Dropping the components with small removes the ones that amplify noise most, at the cost of a bias, and the index is the regularization parameter. It costs one SVD, for , after which each costs and all residual norms together . It is the simplest regularization method and the sharp-cutoff case of spectral filter factors; Tikhonov regularization is the smooth-cutoff case, and on discrete ill-posed problems the two give solutions of similar quality.
In plain words
The SVD splits a matrix into independent channels, each with a gain. Solving the system means dividing the data in each channel by its gain. The channels with tiny gains are the trouble: the true signal in them is tiny too, so what you measure there is mostly noise, and dividing by a tiny gain makes that noise huge. The truncated method simply ignores those channels. You keep the strong channels, where the signal is well above the noise, and set the rest of the answer to zero. The number of channels you keep is the one knob. A good rule is to keep adding channels until the solution explains the data about as well as the noise level allows, and then stop.
The problem
Given an real matrix , data with , and either a noise bound or a target rank, find an approximation of the minimum norm solution of the noise-free problem that is stable against . Typically is the discretization of a compact operator, such as a Fredholm integral equation of the first kind, and its singular values decay with no gap. The same algorithm also computes the minimum norm least squares solution of a rank-deficient system when equals the numerical rank.
The algorithm
Write the thin SVD as with and . Let be the number of positive .
TSVD(A, y, k) ▷ 0 ≤ k ≤ r- 1
(U, Σ, V) ← SVD(A) ▷ σ_1 ≥ σ_2 ≥ … ≥ σ_p - 2
x ← 0 ∈ ℝ^n - 3
for i ← 1 to k do - 4
c ← (u_iᵀ y) / σ_i - 5
x ← x + c · v_i - 6
return x TSVD-PATH(U, Σ, y, δ, τ) ▷ residual norms ρ_k = ‖A x_k - y‖ for k = 0 … r- 7
β_i ← u_iᵀ y for i = 1 … r; ρ_r² ← ‖y - Σ_{i ≤ r} β_i u_i‖² - 8
for k ← r - 1 down to 0 do - 9
ρ_k² ← ρ_{k+1}² + β_{k+1}² - 10
return the smallest k with ρ_k ≤ τ δ, or "none"
TSVD computes the SVD once (L1) and then sums the first terms of the pseudoinverse expansion (L2 to L5). TSVD-PATH uses the same SVD to get the residual norm for every at once. The part of the data lies outside the range of ; no can fit it. Each extra component removes from the squared residual. Line L10 is the discrepancy principle: stop at the first whose residual is at the noise level, with a safety factor (the code uses ; the factor is a choice).
Example
A trace. Let , so that , and , with . The data are .
| 0 | 1.7321 | 1.00609 | ||
| 1 | 1 | 1.4142 | 0.11055 | |
| 2 | 1.1 | 1.0050 | 0.011 | |
| 3 | 11 | 10.0005 | 0 |
Line L7 gives and , since is square and nonsingular. Lines L8 and L9 add , then , then . With , line L10 returns . The third component has , and its datum is ten parts noise to one part signal; dividing by turns the noise into an error of .
A discretized integral equation. Take the rectangle-rule matrix of the integration operator with ( on and below the diagonal), with singular values from down to . Let at the midpoints , so , and add Gaussian noise (seed 15) scaled to .
| 0 | 3 | 6 | 9 | 12 | 18 | 24 | |
|---|---|---|---|---|---|---|---|
| 3.464 | 0.245 | 0.108 | 0.063 | 0.118 | 0.221 | 0.416 | |
| 1.964 | 0.0216 | 0.0103 | 0.0096 | 0.0089 | 0.0075 | 0 |
The error falls while adds signal and rises when adds mostly noise; the best is . The discrepancy principle with stops at (), with an error within a factor of the best. A Picard plot of this problem is on the page Picard condition.
Correctness
TSVD returns , where is the truncated matrix: is the minimum norm minimizer of . By the Eckart-Young theorem, is the closest matrix of rank at most to in the 2-norm (error ) and in the Frobenius norm (error ); Mirsky extended this to every unitarily invariant norm. The residual and the solution norm are and , so L7 to L9 compute the residuals exactly, the residual does not increase with , and L10 finds the first crossing. For noisy data with and ,
and under the source condition with , the choice of the largest with gives an error at most , for every . The proofs are in proofs/correctness.md.
Proof: TSVD returns the minimum norm solution of the truncated problem, its residuals are exact, and it converges at the optimal ratefull
Setting. Let be a real matrix with SVD , , where are orthonormal in , are orthonormal in , and . For let , and . All statements are in exact arithmetic. In floating point they hold for the exact SVD of a nearby matrix with , if the SVD is backward stable.
Step 1: the output of TSVD. Lines L2 to L5 return . The loop adds one term per pass, and makes each positive, so no division by zero occurs.
Step 2: is the minimum norm minimizer of . Complete to an orthonormal basis of and write . Since ,
The second term does not depend on , so the minimizers are exactly the with for , and the other coordinates of are free. The norm is smallest when the free coordinates are zero, which gives . So . For , and , the minimum norm least squares solution.
Step 3: the residual and the solution norm. Let , which is orthogonal to every with . Then
and by orthogonality
For the sum is empty, so , which is line L7. For , , which is line L9. Line L8 runs from down to , so every is computed from after that value is known. Both formulas show that does not increase and does not decrease as grows. Line L10 scans and returns the first with ; by the monotony, every larger also satisfies the test, and if no does, so "none" is correct.
Step 4: the error for noisy data. Let with , so for and . Let and let be the TSVD solution for . Then
The two sums are orthogonal. The first has norm squared , by Bessel's inequality. So
the propagated noise plus the truncation error. For the first term is absent.
Step 5: the rate under a source condition. Assume with and . Then , and the truncation error is
with . Let and let be the largest index with , or if . Then , so the truncation error is at most . The noise term is if and at most otherwise. Hence
The bound holds for every , so there is no saturation: the qualification of TSVD is infinite. In this is the order that no method can beat on this set (see the order optimality statement on the page regularization method).
Step 6: convergence for an operator. The same computation holds for a compact operator with singular system and in the domain of ; the sums become series, which converge by the Picard condition. If and as , both terms of Step 4 tend to zero: the first by assumption, the second because it is the tail of a convergent series. The bound does not depend on which was chosen, so TSVD with such a rule is a regularization method.
Step 7: is the best rank- approximation (Eckart-Young). First the 2-norm. . Let have rank at most . Its null space has dimension at least , and the span of has dimension , so the two spaces share a unit vector with . Then
so .
Next the Frobenius norm, through Weyl's inequality . To prove it, let and be the truncations of and . Their sum has rank at most , so by the 2-norm result
Apply it with , and . Since , we get for every . Squaring and adding over gives
So is a closest matrix of rank at most in both norms.
Complexity
- The SVD (L1). flops for with the Golub-Kahan bidiagonalization and the QR iteration (see Golub-Kahan SVD algorithm). The reference code uses one-sided Jacobi, which costs per sweep and needs a small number of sweeps in practice. If , apply the method to ; the cost is .
- One solution (L2 to L6). inner products of length and vector updates of length : .
- All residuals (L7 to L10). for the coefficients and the out-of-range part, then for the tail sums and the search. Every solution norm also costs in total. So the whole L-curve or discrepancy curve costs after the SVD.
- Space. for and ; the thin SVD stores numbers.
For one value of and a large sparse , a full SVD is wasteful. A partial SVD by Lanczos bidiagonalization, or an iterative method such as LSQR, costs only products with and .
Properties
- Linear in the data. for a fixed . With the discrepancy principle, depends on and the map is no longer linear.
- Filter factors. for and otherwise. The noise amplification is .
- Infinite qualification. Under the source condition the bias is at most for every , so TSVD does not saturate as Tikhonov does at (see qualification of regularization).
- Monotone curves. As grows, does not increase and does not decrease.
- Resolution. The resolution matrix is an orthogonal projection of trace .
- Sign invariance. Each term is unchanged if the SVD returns and , so the arbitrary signs of a computed SVD do not matter.
Variants and improvements
- Truncated GSVD. With a regularization matrix (for example a difference operator), truncate the generalized SVD of the pair instead. This penalizes roughness rather than size.
- Damped or smoothed truncation. Replace the sharp cutoff by a smooth one; Tikhonov is the standard choice, with .
- Truncated rank-revealing QR. A rank-revealing factorization gives a cheaper approximation of the dominant subspace when there is a clear gap.
- Partial and randomized SVD. For a large , compute only the first triples by Lanczos bidiagonalization or by a randomized range finder.
- Other parameter rules. The L-curve and generalized cross-validation choose without ; they are heuristics (see Bakushinskii veto).
When to use it
Use TSVD on small and medium dense problems, where one SVD is affordable (up to a few thousand unknowns), and when you want to see the problem: the singular values, the Picard plot and the effect of each all come from the same SVD. It is the natural method when the singular values have a clear gap, because then the numerical rank is well defined. When the singular values decay without a gap, Tikhonov regularization gives similar errors with a smoother solution and a continuous parameter. For large or sparse problems use an iterative method such as LSQR or CGLS, which regularize by the number of steps.
Pitfalls
- Forming . Computing the SVD from the eigenvalues of squares the condition number. Singular values below , with , are then lost. Use an SVD of itself.
- Truncating below the rounding level. In the floating-point model, a backward stable SVD returns the exact SVD of with , so each computed has an absolute error of about . Components with near are rounding noise even for exact data; never choose beyond them.
- Close singular values at the cut. If and are close, the individual vectors and are ill determined, and changes a lot with small changes of . The space of the first vectors is stable only when the gap is large compared with the perturbation (see Davis-Kahan theorem).
- Looking for a gap that is not there. For a discretized compact operator the singular values decay smoothly. The choice of must come from the noise level, not from a gap.
- Gibbs-like ringing. The sharp cutoff makes the rows of the resolution matrix oscillate, with negative side lobes, so TSVD solutions can ring near jumps. A smooth filter rings less.
- Out-of-range data. If , the part of outside the range of stays in every residual. The discrepancy principle then needs to include it, or no satisfies L10.
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/.
"""Small images and signals for the imaging and inverse problems pages.
Conventions:
- A signal is a list of numbers. An image is a list of rows, img[i][j], with
row i from the top and column j from the left.
- An n x n image covers the square [-1, 1]^2. The center of pixel (i, j) is
x_j = -1 + (2 j + 1) / n and y_i = 1 - (2 i + 1) / n, so y goes up.
- DFT: X_k = sum_j x_j exp(-2 pi i j k / n), unnormalized; the inverse has
the factor 1 / n. Index k stands for frequency k for k < n / 2 and k - n
otherwise. fftshift moves the zero frequency to position n // 2.
- Periodic convolution kernels are stored with their center at index 0
(wrapped around), so a delta kernel gives the identity and no shift.
"""
import cmath
import math
# ------------------------------------------------------------------ images
def new_image(n1, n2, value=0.0):
"""An n1 x n2 image (n1 rows, n2 columns) filled with value."""
return [[value] * n2 for _ in range(n1)]
def img_add(a, b):
"""The pixelwise sum a + b."""
return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
def img_scale(a, c):
"""The image c a."""
return [[c * x for x in row] for row in a]
def img_dot(a, b):
"""<a, b> = sum conj(a_ij) b_ij."""
return sum(x.conjugate() * y for ra, rb in zip(a, b) for x, y in zip(ra, rb))
def img_norm(a):
"""The Euclidean (Frobenius) norm of an image."""
return math.sqrt(sum(abs(x) ** 2 for row in a for x in row))
def flatten(img):
"""Row-major vector of an image."""
return [x for row in img for x in row]
def unflatten(v, n1, n2):
"""The n1 x n2 image of a row-major vector."""
return [list(v[i * n2:(i + 1) * n2]) for i in range(n1)]
# ------------------------------------------------------------------ DFT
def _is_pow2(n):
return n > 0 and n & (n - 1) == 0
def _fft_pow2(x):
"""Iterative radix-2 FFT, unnormalized forward transform."""
n = len(x)
a = [complex(v) for v in x]
j = 0
for i in range(1, n):
bit = n >> 1
while j & bit:
j ^= bit
bit >>= 1
j |= bit
if i < j:
a[i], a[j] = a[j], a[i]
size = 2
while size <= n:
half = size // 2
tw = [cmath.exp(-2j * math.pi * k / size) for k in range(half)]
for start in range(0, n, size):
for k in range(half):
u = a[start + k]
v = a[start + k + half] * tw[k]
a[start + k] = u + v
a[start + k + half] = u - v
size *= 2
return a
def dft(x):
"""X_k = sum_j x_j exp(-2 pi i j k / n). Radix-2 FFT when n is a power of 2."""
n = len(x)
if n == 0:
return []
if _is_pow2(n):
return _fft_pow2(x)
w = [cmath.exp(-2j * math.pi * t / n) for t in range(n)]
return [sum(x[j] * w[(j * k) % n] for j in range(n)) for k in range(n)]
def idft(xf):
"""x_j = (1/n) sum_k X_k exp(2 pi i j k / n)."""
n = len(xf)
if n == 0:
return []
y = dft([complex(v).conjugate() for v in xf])
return [v.conjugate() / n for v in y]
def _rows_then_cols(img, f):
rows = [f(row) for row in img]
cols = [f(list(col)) for col in zip(*rows)]
return [list(r) for r in zip(*cols)]
def dft2(img):
"""2D DFT: X_kl = sum_jq x_jq exp(-2 pi i (j k / n1 + q l / n2))."""
return _rows_then_cols(img, dft)
def idft2(img):
"""Inverse 2D DFT, with the factor 1 / (n1 n2)."""
return _rows_then_cols(img, idft)
def _shift1(x, s):
return list(x[s:]) + list(x[:s])
def fftshift(x):
"""Move the zero frequency to position n // 2 (1D, or both axes of an image)."""
if x and isinstance(x[0], (list, tuple)):
rows = [fftshift(r) for r in x]
return _shift1(rows, (len(rows) + 1) // 2)
return _shift1(x, (len(x) + 1) // 2)
def ifftshift(x):
"""The inverse of fftshift (1D, or both axes of an image)."""
if x and isinstance(x[0], (list, tuple)):
rows = [ifftshift(r) for r in x]
return _shift1(rows, len(rows) // 2)
return _shift1(x, len(x) // 2)
def circ_conv(x, h):
"""Periodic convolution y_i = sum_j h_j x_{(i - j) mod n}, kernel centered at index 0."""
n = len(x)
nz = [(j, hj) for j, hj in enumerate(h) if hj != 0]
return [sum(hj * x[(i - j) % n] for j, hj in nz) for i in range(n)]
def circ_conv2(img, h):
"""Periodic 2D convolution with the kernel h centered at index (0, 0)."""
n1, n2 = len(img), len(img[0])
nz = [(p, q, h[p][q]) for p in range(len(h)) for q in range(len(h[0])) if h[p][q] != 0]
out = new_image(n1, n2)
for i in range(n1):
for j in range(n2):
out[i][j] = sum(v * img[(i - p) % n1][(j - q) % n2] for p, q, v in nz)
return out
# ------------------------------------------------------------------ phantoms
def pixel_centers(n):
"""(xs, ys): xs[j] = -1 + (2 j + 1) / n and ys[i] = 1 - (2 i + 1) / n."""
xs = [-1.0 + (2 * j + 1) / n for j in range(n)]
ys = [1.0 - (2 * i + 1) / n for i in range(n)]
return xs, ys
# Rows: rho, A, B, x0, y0, phi (degrees). A is the semi-axis along the
# direction phi (counterclockwise from the x axis), B the other semi-axis.
# Geometry and densities of Shepp and Logan (1974), as reproduced in Kak and
# Slaney, Principles of Computerized Tomographic Imaging, Table 3.1. The value
# at the center (0, 0) is 2 - 0.98 = 1.02.
SHEPP_LOGAN = [
(2.0, 0.92, 0.69, 0.0, 0.0, 90.0),
(-0.98, 0.874, 0.6624, 0.0, -0.0184, 90.0),
(-0.02, 0.31, 0.11, 0.22, 0.0, 72.0),
(-0.02, 0.41, 0.16, -0.22, 0.0, 108.0),
(0.01, 0.25, 0.21, 0.0, 0.35, 90.0),
(0.01, 0.046, 0.046, 0.0, 0.1, 0.0),
(0.01, 0.046, 0.046, 0.0, -0.1, 0.0),
(0.01, 0.046, 0.023, -0.08, -0.605, 0.0),
(0.01, 0.023, 0.023, 0.0, -0.605, 0.0),
(0.01, 0.046, 0.023, 0.06, -0.605, 90.0),
]
# The same ellipses with the gray levels of Toft (1996), which give more
# contrast. The value at the center is 1 - 0.8 = 0.2.
MODIFIED_SHEPP_LOGAN = [
(rho, a, b, x0, y0, phi)
for rho, (_, a, b, x0, y0, phi) in zip(
(1.0, -0.8, -0.2, -0.2, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1), SHEPP_LOGAN
)
]
def ellipse_value(x, y, table):
"""The phantom value at the point (x, y): the sum of rho over the ellipses that hold it."""
total = 0.0
for rho, a, b, x0, y0, phi in table:
c, s = math.cos(math.radians(phi)), math.sin(math.radians(phi))
dx, dy = x - x0, y - y0
u = dx * c + dy * s
v = -dx * s + dy * c
if (u / a) ** 2 + (v / b) ** 2 <= 1.0:
total += rho
return total
def ellipse_phantom(n, table):
"""The n x n image of an ellipse table, sampled at the pixel centers."""
xs, ys = pixel_centers(n)
return [[ellipse_value(x, y, table) for x in xs] for y in ys]
def disk_phantom(n, radius):
"""1 at pixel centers with x^2 + y^2 <= radius^2, 0 elsewhere."""
xs, ys = pixel_centers(n)
r2 = radius * radius
return [[1.0 if x * x + y * y <= r2 else 0.0 for x in xs] for y in ys]
def spikes_1d(n, positions, amplitudes):
"""A signal of length n with the given amplitudes at the given positions."""
out = [0.0] * n
for p, a in zip(positions, amplitudes):
out[p] += a
return out
# ------------------------------------------------------------------ projector
def parallel_beam_matrix(n, angles, nbins):
"""Pixel-driven discrete Radon transform of an n x n image on [-1, 1]^2.
Each pixel center (x, y) projects to s = x cos(theta) + y sin(theta). Its
value times the pixel area over the bin width is split linearly between
the two nearest bin centers. The bins cover [-sqrt(2), sqrt(2)]. Row
a * nbins + b holds angle a and bin b; column i * n + j holds pixel (i, j).
Returns the sparse rows, each a list of (column, weight) pairs.
Pixel-driven projection has a ripple: with a bin width close to the pixel
size, a disk projection is off by up to about 10 percent in some bins. A
bin of about twice the pixel size (nbins = 23 for n = 32) keeps it near
1 percent.
"""
xs, ys = pixel_centers(n)
smax = math.sqrt(2.0)
width = 2.0 * smax / nbins
scale = (2.0 / n) ** 2 / width
rows = []
for theta in angles:
c, s = math.cos(theta), math.sin(theta)
acc = [dict() for _ in range(nbins)]
for i, y in enumerate(ys):
for j, x in enumerate(xs):
t = (x * c + y * s + smax) / width - 0.5
b0 = math.floor(t)
frac = t - b0
col = i * n + j
for b, w in ((b0, 1.0 - frac), (b0 + 1, frac)):
if 0 <= b < nbins and w > 0.0:
acc[b][col] = acc[b].get(col, 0.0) + w * scale
rows.extend(sorted(d.items()) for d in acc)
return rows
def sp_matvec(rows, x):
"""y = A x for sparse rows of (column, weight) pairs."""
return [sum(w * x[c] for c, w in row) for row in rows]
def sp_rmatvec(rows, y, ncols):
"""x = A^H y for sparse rows of (column, weight) pairs and ncols columns."""
out = [0.0] * ncols
for row, yi in zip(rows, y):
if yi == 0:
continue
for c, w in row:
out[c] += w.conjugate() * yi
return out
# ------------------------------------------------------------------ noise
def gauss_noise(rng, shape, sigma):
"""Independent N(0, sigma^2) values: a list for an int shape, an image for (n1, n2)."""
if isinstance(shape, int):
return [rng.gauss(0.0, sigma) for _ in range(shape)]
n1, n2 = shape
return [[rng.gauss(0.0, sigma) for _ in range(n2)] for _ in range(n1)]
def _poisson_small(rng, lam):
"""Knuth's product method, exact for a mean lam <= 30."""
limit = math.exp(-lam)
k, p = 0, rng.random()
while p > limit:
k += 1
p *= rng.random()
return k
def poisson_sample(rng, lam):
"""An exact Poisson(lam) sample: a sum of Knuth samples with means at most 30."""
if lam < 0:
raise ValueError("negative mean")
total = 0
while lam > 30.0:
total += _poisson_small(rng, 30.0)
lam -= 30.0
if lam > 0.0:
total += _poisson_small(rng, lam)
return total
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
truncated_svd.py 69 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/truncated-svd/. The authors are listed in prov/7EBBWK.jsonl.
"""Truncated singular value decomposition (TSVD) for a real linear system A x = y.
The regularized solution is x_k = sum_{i=1}^{k} (<u_i, y> / sigma_i) v_i, with
the singular triples of A in descending order of sigma_i.
"""
import math
from imgla import svd
def tsvd(a, y, k):
"""The TSVD solution x_k of A x = y. Computes one SVD of A."""
u, s, v = svd(a) # @line L1
return tsvd_from_svd(u, s, v, y, k)
def tsvd_from_svd(u, s, v, y, k):
"""x_k from a thin SVD (U, S, V) of A, S descending. Costs O(k (m + n))."""
if not 0 <= k <= len(s):
raise ValueError("k must be between 0 and min(m, n)")
if k > 0 and not s[k - 1] > 0.0:
raise ValueError("k is larger than the rank")
m, n = len(u), len(v)
x = [0.0] * n # @line L2
for i in range(k): # @line L3
c = sum(u[r][i] * y[r] for r in range(m)) / s[i] # @line L4
for j in range(n): # @line L5
x[j] += c * v[j][i]
return x # @line L6
def tsvd_path(u, s, y):
"""Residual norms and solution norms of x_k for k = 0, 1, ..., r.
With beta_i = <u_i, y>: ||A x_k - y||^2 = ||y_perp||^2 + sum_{i>k} beta_i^2,
where y_perp is the part of y outside the range of A, and
||x_k||^2 = sum_{i<=k} (beta_i / sigma_i)^2. r is the number of positive
singular values. Costs O(m r) for the coefficients, then O(1) per k.
"""
m = len(u)
r = sum(1 for si in s if si > 0.0)
beta = [sum(u[q][i] * y[q] for q in range(m)) for i in range(r)] # @line L7
perp = [y[q] - sum(beta[i] * u[q][i] for i in range(r)) for q in range(m)]
tail = [0.0] * (r + 1)
tail[r] = sum(v * v for v in perp)
for i in range(r - 1, -1, -1): # @line L8
tail[i] = tail[i + 1] + beta[i] * beta[i] # @line L9
sol2 = 0.0
norms = [0.0]
for i in range(r):
sol2 += (beta[i] / s[i]) ** 2
norms.append(math.sqrt(sol2))
return [math.sqrt(t) for t in tail], norms
def discrepancy_index(residuals, delta, tau=1.1):
"""The smallest k with ||A x_k - y|| <= tau delta, or None if no k qualifies."""
for k, rk in enumerate(residuals): # @line L10
if rk <= tau * delta:
return k
return None
def filter_factors(k, p):
"""The TSVD filter factors f_i = 1 for i <= k and 0 for k < i <= p."""
return [1.0 if i < k else 0.0 for i in range(p)]
test_truncated_svd.py 385 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/truncated-svd/. The authors are listed in prov/7EBBWK.jsonl.
# This file also tests the shared helpers imgla.py and imgkit.py.
import cmath
import math
import random
from fractions import Fraction
import imgkit as ik
import imgla as la
from truncated_svd import discrepancy_index, filter_factors, tsvd, tsvd_from_svd, tsvd_path
def rand_matrix(rng, m, n):
return [[rng.gauss(0.0, 1.0) for _ in range(n)] for _ in range(m)]
def max_abs_diff(a, b):
return max(abs(x - y) for ra, rb in zip(a, b) for x, y in zip(ra, rb))
def integration_matrix(n):
"""Rectangle rule for (A x)(s) = int_0^s x(t) dt on [0, 1]: h on and below the diagonal."""
h = 1.0 / n
return [[h if j <= i else 0.0 for j in range(n)] for i in range(n)]
# ------------------------------------------------------------------ imgla
def test_svd_reconstructs() -> None:
rng = random.Random(1)
for m, n in ((6, 4), (4, 6), (5, 5)):
a = rand_matrix(rng, m, n)
u, s, v = la.svd(a)
p = min(m, n)
assert len(s) == p and all(s[i] >= s[i + 1] for i in range(p - 1))
us = [[u[i][j] * s[j] for j in range(p)] for i in range(m)]
assert max_abs_diff(la.matmul(us, la.transpose(v)), a) < 1e-10
assert max_abs_diff(la.matmul(la.transpose(u), u), la.eye(p)) < 1e-10
assert max_abs_diff(la.matmul(la.transpose(v), v), la.eye(p)) < 1e-10
def test_svd_rank_deficient() -> None:
a = [[1.0, 2.0, 3.0], [2.0, 4.0, 6.0], [1.0, 0.0, 1.0], [0.0, 0.0, 0.0]]
u, s, v = la.svd(a)
assert s[2] < 1e-12
assert max_abs_diff(la.matmul(la.transpose(u), u), la.eye(3)) < 1e-10
z = la.zeros(3, 2)
u0, s0, v0 = la.svd(z)
assert s0 == [0.0, 0.0]
assert max_abs_diff(la.matmul(la.transpose(u0), u0), la.eye(2)) < 1e-12
def test_sym_eig_reconstructs() -> None:
rng = random.Random(2)
b = rand_matrix(rng, 5, 5)
a = [[b[i][j] + b[j][i] for j in range(5)] for i in range(5)]
w, q = la.sym_eig(a)
assert all(w[i] <= w[i + 1] for i in range(4))
qw = [[q[i][j] * w[j] for j in range(5)] for i in range(5)]
assert max_abs_diff(la.matmul(qw, la.transpose(q)), a) < 1e-10
assert max_abs_diff(la.matmul(la.transpose(q), q), la.eye(5)) < 1e-10
def test_adjoint_gap_matrix() -> None:
rng = random.Random(3)
a = [[complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(4)] for _ in range(6)]
x = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(4)]
y = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(6)]
gap = la.adjoint_gap(lambda t: la.matvec(a, t), lambda t: la.rmatvec(a, t), x, y)
assert gap < 1e-12
ah = la.conj_transpose(a)
assert max(abs(p - q) for p, q in zip(la.matvec(ah, y), la.rmatvec(a, y))) < 1e-12
wrong = la.adjoint_gap(lambda t: la.matvec(a, t), lambda t: la.matvec(la.transpose(a), t), x, y)
assert wrong > 1e-3
def test_solve_and_cholesky() -> None:
a = [[Fraction(2), Fraction(1), Fraction(0)], [Fraction(4), Fraction(3), Fraction(1)], [Fraction(0), Fraction(1), Fraction(5)]]
x = la.solve(a, [Fraction(3), Fraction(8), Fraction(6)])
assert x == [Fraction(1), Fraction(1), Fraction(1)]
rng = random.Random(4)
b = rand_matrix(rng, 5, 5)
spd = la.matmul(la.transpose(b), b)
for i in range(5):
spd[i][i] += 1.0
rhs = [rng.gauss(0, 1) for _ in range(5)]
low = la.cholesky(spd)
assert max_abs_diff(la.matmul(low, la.transpose(low)), spd) < 1e-10
x1 = la.cho_solve(low, rhs)
x2 = la.solve(spd, rhs)
assert max(abs(p - q) for p, q in zip(x1, x2)) < 1e-10
xm = la.solve(spd, [[1.0, 0.0], [0.0, 1.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0]])
assert len(xm) == 5 and len(xm[0]) == 2
assert abs(la.dot([1j, 2.0], [1j, 1.0]) - 3.0) < 1e-15
assert abs(la.norm2([[3.0, 0.0], [0.0, 4.0]]) - 5.0) < 1e-15
# ------------------------------------------------------------------ imgkit
def test_dft_check_value_and_inverse() -> None:
xf = ik.dft([1, 2, 3, 4])
for got, want in zip(xf, (10, -2 + 2j, -2, -2 - 2j)):
assert abs(got - want) < 1e-12
rng = random.Random(5)
for n in (8, 12, 16):
x = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(n)]
back = ik.idft(ik.dft(x))
assert max(abs(p - q) for p, q in zip(back, x)) < 1e-12
xf = ik.dft(x)
assert abs(sum(abs(v) ** 2 for v in xf) - n * sum(abs(v) ** 2 for v in x)) < 1e-9
direct = [sum(x[j] * cmath.exp(-2j * math.pi * j * k / n) for j in range(n)) for k in range(n)]
assert max(abs(p - q) for p, q in zip(xf, direct)) < 1e-10
def test_dft2_and_shift() -> None:
rng = random.Random(6)
img = [[rng.gauss(0, 1) for _ in range(6)] for _ in range(4)]
back = ik.idft2(ik.dft2(img))
assert max_abs_diff(back, img) < 1e-12
xf = ik.dft2(img)
assert abs(xf[0][0] - sum(map(sum, img))) < 1e-12
assert ik.fftshift([0, 1, 2, 3]) == [2, 3, 0, 1]
assert ik.fftshift([0, 1, 2, 3, 4]) == [3, 4, 0, 1, 2]
for n in (4, 5):
assert ik.ifftshift(ik.fftshift(list(range(n)))) == list(range(n))
sh = ik.fftshift([[0, 1], [2, 3]])
assert sh == [[3, 2], [1, 0]]
assert ik.ifftshift(sh) == [[0, 1], [2, 3]]
def test_circ_conv() -> None:
rng = random.Random(7)
n = 12
x = [rng.gauss(0, 1) for _ in range(n)]
h = [rng.gauss(0, 1) for _ in range(n)]
y = ik.circ_conv(x, h)
yf = ik.idft([a * b for a, b in zip(ik.dft(x), ik.dft(h))])
assert max(abs(p - q) for p, q in zip(y, yf)) < 1e-12
delta = ik.spikes_1d(n, [0], [1.0])
assert ik.circ_conv(x, delta) == x
img = [[rng.gauss(0, 1) for _ in range(4)] for _ in range(4)]
k2 = [[rng.gauss(0, 1) for _ in range(4)] for _ in range(4)]
c2 = ik.circ_conv2(img, k2)
f2 = ik.idft2([[a * b for a, b in zip(ra, rb)] for ra, rb in zip(ik.dft2(img), ik.dft2(k2))])
assert max_abs_diff(c2, f2) < 1e-12
d2 = ik.new_image(4, 4)
d2[0][0] = 1.0
assert ik.circ_conv2(img, d2) == img
def test_image_ops() -> None:
a = [[1.0, 2.0], [3.0, 4.0]]
b = ik.img_scale(a, 2.0)
assert ik.img_add(a, b) == [[3.0, 6.0], [9.0, 12.0]]
assert ik.img_dot(a, a) == 30.0
assert abs(ik.img_norm(a) - math.sqrt(30.0)) < 1e-15
assert ik.unflatten(ik.flatten(a), 2, 2) == a
xs, ys = ik.pixel_centers(4)
assert xs == [-0.75, -0.25, 0.25, 0.75] and ys == [0.75, 0.25, -0.25, -0.75]
def test_shepp_logan_centers() -> None:
assert len(ik.SHEPP_LOGAN) == 10 and len(ik.MODIFIED_SHEPP_LOGAN) == 10
assert abs(ik.ellipse_value(0.0, 0.0, ik.SHEPP_LOGAN) - 1.02) < 1e-12
assert abs(ik.ellipse_value(0.0, 0.0, ik.MODIFIED_SHEPP_LOGAN) - 0.2) < 1e-12
img = ik.ellipse_phantom(33, ik.MODIFIED_SHEPP_LOGAN)
assert abs(img[16][16] - 0.2) < 1e-12
assert img[0][0] == 0.0
# The large dark ellipse on the right of the image (x = 0.22) lies inside the brain.
assert abs(ik.ellipse_value(0.22, 0.0, ik.SHEPP_LOGAN) - 1.0) < 1e-12
def test_parallel_beam_matrix() -> None:
# A bin about twice the pixel size keeps the ripple of pixel-driven projection small.
n, nbins = 32, 23
angles = [math.pi * a / 8 for a in range(8)]
rows = ik.parallel_beam_matrix(n, angles, nbins)
assert len(rows) == len(angles) * nbins
rng = random.Random(8)
x = [rng.gauss(0, 1) for _ in range(n * n)]
y = [rng.gauss(0, 1) for _ in range(len(rows))]
gap = la.adjoint_gap(lambda t: ik.sp_matvec(rows, t), lambda t: ik.sp_rmatvec(rows, t, n * n), x, y)
assert gap < 1e-12
disk = ik.flatten(ik.disk_phantom(n, 1.0))
proj = ik.sp_matvec(rows, disk)
width = 2.0 * math.sqrt(2.0) / nbins
for a in range(len(angles)):
for b in range(nbins // 2 - 3, nbins // 2 + 4):
s = -math.sqrt(2.0) + (b + 0.5) * width
exact = 2.0 * math.sqrt(1.0 - s * s)
assert abs(proj[a * nbins + b] - exact) <= 0.05 * exact
def test_noise() -> None:
rng = random.Random(9)
draws = [ik.poisson_sample(rng, 4.0) for _ in range(2000)]
assert abs(sum(draws) / 2000 - 4.0) < 0.2
big = [ik.poisson_sample(rng, 75.0) for _ in range(400)]
assert abs(sum(big) / 400 - 75.0) < 2.0
assert ik.poisson_sample(rng, 0.0) == 0
g = ik.gauss_noise(rng, (3, 4), 0.5)
assert len(g) == 3 and len(g[0]) == 4
v = ik.gauss_noise(random.Random(10), 4000, 2.0)
var = sum(t * t for t in v) / len(v)
assert abs(var - 4.0) < 0.3
# ------------------------------------------------------------------ TSVD
def test_integration_operator_singular_values() -> None:
# The lower triangular matrix of ones has singular values 1 / (2 sin((2k - 1) pi / (4n + 2))).
n = 24
_, s, _ = la.svd(integration_matrix(n))
for k in range(1, n + 1):
assert abs(s[k - 1] - 1.0 / (2 * n * math.sin((2 * k - 1) * math.pi / (4 * n + 2)))) < 1e-12
# They approach the continuous values 2 / ((2k - 1) pi); sigma_1 tends to 2 / pi = 0.63662.
for k in range(1, 4):
assert abs(s[k - 1] - 2.0 / ((2 * k - 1) * math.pi)) < 0.15 * 2.0 / ((2 * k - 1) * math.pi)
assert abs(2.0 / math.pi - 0.63662) < 5e-6
def test_tsvd_matches_eigen_route() -> None:
# Reference: the eigen decomposition of A^T A (a different algorithm) gives
# x_k = sum_{i<=k} (<v_i, A^T y> / lambda_i) v_i over the k largest eigenvalues.
rng = random.Random(11)
m, n = 9, 6
a = rand_matrix(rng, m, n)
y = [rng.gauss(0, 1) for _ in range(m)]
w, q = la.sym_eig(la.matmul(la.transpose(a), a))
aty = la.rmatvec(a, y)
for k in range(n + 1):
x = tsvd(a, y, k)
ref = [0.0] * n
for idx in range(n - 1, n - 1 - k, -1):
vi = [q[j][idx] for j in range(n)]
c = sum(p * t for p, t in zip(vi, aty)) / w[idx]
ref = [r + c * t for r, t in zip(ref, vi)]
assert max(abs(p - t) for p, t in zip(x, ref)) < 1e-9
def test_full_rank_is_least_squares() -> None:
rng = random.Random(12)
a = rand_matrix(rng, 8, 5)
y = [rng.gauss(0, 1) for _ in range(8)]
x = tsvd(a, y, 5)
ref = la.solve(la.matmul(la.transpose(a), a), la.rmatvec(a, y))
assert max(abs(p - t) for p, t in zip(x, ref)) < 1e-10
def test_minimum_norm_on_rank_deficient() -> None:
# Two equal columns: rank 1. The minimum norm solution splits the weight equally.
a = [[1.0, 1.0], [1.0, 1.0], [0.0, 0.0]]
u, s, v = la.svd(a)
x = tsvd_from_svd(u, s, v, [2.0, 2.0, 5.0], 1)
assert abs(x[0] - 1.0) < 1e-12 and abs(x[1] - 1.0) < 1e-12
try:
tsvd_from_svd(u, s, v, [2.0, 2.0, 5.0], 2)
except ValueError:
pass
else:
raise AssertionError("k above the rank must be rejected")
def test_path_norms_and_filters() -> None:
rng = random.Random(13)
m, n = 10, 7
a = rand_matrix(rng, m, n)
y = [rng.gauss(0, 1) for _ in range(m)]
u, s, v = la.svd(a)
res, nrm = tsvd_path(u, s, y)
for k in range(n + 1):
x = tsvd_from_svd(u, s, v, y, k)
r = [p - t for p, t in zip(la.matvec(a, x), y)]
assert abs(la.norm2(r) - res[k]) < 1e-10
assert abs(la.norm2(x) - nrm[k]) < 1e-10
assert all(res[k] >= res[k + 1] - 1e-15 for k in range(n))
assert filter_factors(2, 4) == [1.0, 1.0, 0.0, 0.0]
def test_eckart_young() -> None:
rng = random.Random(14)
m, n, k = 6, 5, 2
a = rand_matrix(rng, m, n)
u, s, v = la.svd(a)
ak = [[sum(u[i][t] * s[t] * v[j][t] for t in range(k)) for j in range(n)] for i in range(m)]
diff = [[a[i][j] - ak[i][j] for j in range(n)] for i in range(m)]
_, sd, _ = la.svd(diff)
assert abs(sd[0] - s[k]) < 1e-10
best_f = la.norm2(diff)
assert abs(best_f - math.sqrt(sum(t * t for t in s[k:]))) < 1e-10
for _ in range(100):
left = rand_matrix(rng, m, k)
right = rand_matrix(rng, k, n)
cand = la.matmul(left, right)
d = [[a[i][j] - cand[i][j] for j in range(n)] for i in range(m)]
assert la.norm2(d) >= best_f - 1e-12
_, sc, _ = la.svd(d)
assert sc[0] >= s[k] - 1e-12
def test_noise_amplification_and_discrepancy() -> None:
n = 24
a = integration_matrix(n)
u, s, v = la.svd(a)
t = [(j + 0.5) / n for j in range(n)]
x_true = [math.sin(math.pi * tj) for tj in t]
y_exact = la.matvec(a, x_true)
rng = random.Random(15)
e = [rng.gauss(0, 1) for _ in range(n)]
delta = 1e-2
scale = delta / la.norm2(e)
y = [p + scale * q for p, q in zip(y_exact, e)]
errs = [la.norm2([p - q for p, q in zip(tsvd_from_svd(u, s, v, y, k), x_true)]) for k in range(n + 1)]
best = min(range(n + 1), key=lambda k: errs[k])
assert 0 < best < n
assert errs[n] > 2.0 * errs[best]
res, _ = tsvd_path(u, s, y)
k_dp = discrepancy_index(res, delta, tau=1.1)
assert k_dp is not None
assert res[k_dp] <= 1.1 * delta and (k_dp == 0 or res[k_dp - 1] > 1.1 * delta)
assert errs[k_dp] <= 3.0 * errs[best]
def worst_case_error(sigma, delta, nu, rho):
"""TSVD error for the worst pair of a source element and a noise vector of a diagonal problem.
k is the largest index with sigma_k >= delta^(1/(2 nu + 1)). The exact solution is
rho sigma_{k+1}^(2 nu) e_{k+1} (it satisfies the source condition with ||w|| = rho)
and the noise is delta e_k. Returns (error, k).
"""
p = len(sigma)
u = la.eye(p)
level = delta ** (1.0 / (2 * nu + 1))
k = max(i + 1 for i in range(p) if sigma[i] >= level)
x_true = [0.0] * p
x_true[k] = rho * sigma[k] ** (2 * nu)
y = [sigma[i] * x_true[i] for i in range(p)]
y[k - 1] += delta
x = tsvd_from_svd(u, sigma, u, y, k)
return la.norm2([p_ - q for p_, q in zip(x, x_true)]), k
def test_convergence_rate() -> None:
sigma = [1.0 / i for i in range(1, 161)]
deltas = [1e-1, 1e-2, 1e-3, 1e-4]
rho = 1.0
for nu in (0.5, 1.0):
rate = 2 * nu / (2 * nu + 1)
errs = []
for d in deltas:
err, _ = worst_case_error(sigma, d, nu, rho)
assert err <= (1 + rho) * d ** rate + 1e-15
errs.append(err)
xs = [math.log(d) for d in deltas]
ys = [math.log(e) for e in errs]
mx, my = sum(xs) / len(xs), sum(ys) / len(ys)
slope = sum((p - mx) * (q - my) for p, q in zip(xs, ys)) / sum((p - mx) ** 2 for p in xs)
assert abs(slope - rate) < 0.15
def test_rate_bound_random_noise() -> None:
# Error <= delta / sigma_k + rho sigma_{k+1}^(2 nu) for any noise with ||e|| <= delta.
rng = random.Random(16)
p, nu, rho = 60, 0.5, 1.0
sigma = [1.0 / i for i in range(1, p + 1)]
u = la.eye(p)
w = [rng.gauss(0, 1) for _ in range(p)]
wn = la.norm2(w)
w = [rho * t / wn for t in w]
x_true = [sigma[i] ** (2 * nu) * w[i] for i in range(p)]
for d in (1e-2, 1e-3, 1e-4):
e = [rng.gauss(0, 1) for _ in range(p)]
en = la.norm2(e)
y = [sigma[i] * x_true[i] + d * e[i] / en for i in range(p)]
k = max(i + 1 for i in range(p) if sigma[i] >= d ** (1.0 / (2 * nu + 1)))
x = tsvd_from_svd(u, sigma, u, y, k)
err = la.norm2([a - b for a, b in zip(x, x_true)])
bound = d / sigma[k - 1] + (rho * sigma[k] ** (2 * nu) if k < p else 0.0)
assert err <= bound + 1e-14
assert bound <= (1 + rho) * d ** (2 * nu / (2 * nu + 1)) + 1e-15
History
Erhard Schmidt proved in 1907 that the truncated singular expansion gives the best approximation of an integral operator by one of finite rank. Eckart and Young proved the matrix version in 1936, and Mirsky extended it to all unitarily invariant norms in 1960. After Golub and Kahan made the SVD computable in 1965, Hanson (1971) and others solved discretized first-kind integral equations from their leading singular components. Hansen (1987) analyzed TSVD as a regularization method, gave its perturbation bounds and showed that under the discrete Picard condition it gives solutions close to those of Tikhonov regularization.
References
- Per Christian Hansen, The truncated SVD as a method for regularization, BIT 27(4), 1987, 534 to 553, the TSVD solution, its perturbation bounds, and its relation to Tikhonov regularization
- Carl Eckart and Gale Young, The approximation of one matrix by another of lower rank, Psychometrika 1(3), 1936, 211 to 218, the best approximation of lower rank by truncating the canonical (singular value) form
- L. Mirsky, Symmetric gauge functions and unitarily invariant norms, Quarterly Journal of Mathematics 11(1), 1960, 50 to 59, the extension of the best low-rank approximation to every unitarily invariant norm
- Richard J. Hanson, A numerical method for solving Fredholm integral equations of the first kind using singular values, SIAM Journal on Numerical Analysis 8(3), 1971, 616 to 622, the solution of a discretized first-kind equation from its leading singular components
- Per Christian Hansen, Rank-Deficient and Discrete Ill-Posed Problems, Numerical Aspects of Linear Inversion, SIAM, 1998, Chapter 3 (numerical rank and truncated SVD) and Chapter 7 (the discrepancy principle)
- Heinz W. Engl, Martin Hanke and Andreas Neubauer, Regularization of Inverse Problems, Kluwer, 1996, Chapters 3 and 4 (truncated singular value expansion as a regularization method, its infinite qualification)
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 7EBBWK Edit this page History Report an error Markdown