Solving Ax=b with A∈Rm×n is scientific computing’s most repeated operation, and the textbook case A square and invertible is rare. Usually one of three situations occurs.
The second case is no academic rarity. A linear model with more parameters than data, or a sufficiently wide network, can exactly fit training data: an entire affine subspace of parameters has zero loss. Equations do not select one, but the training algorithm does, and the choice determines generalization. Robotics has the same issue with a redundant arm (more joints than task degrees of freedom): infinitely many joint velocities yield the same gripper movement (differential inverse kinematics).
A fourth case is more treacherous: A is square and invertible, but so ill-conditioned that A−1b is useless. Deblurring an image, measuring temperature through a wall or reconstructing a CT scan are inverse problems of this kind. The inverse exists, but applied to data with noise 0.1% can yield solutions with relative error 109, as a 64-point blur will show.
We construct one tool addressing all four cases. The pseudoinverseA+ gives the canonical answer to the first three: the minimum-norm least-squares solution. For the fourth we modify it with spectral filters, deciding component by component of the SVD how much to trust data. Finally we see gradient descent already applies both ideas implicitly.
The shortest solution
Start with the smallest drawable underdetermined case: two equations and three unknowns.
A=[1−0.5110.51],b=[21].
Each equation is a plane in R3 and solutions form their intersection, a line. Since rows are independent, the null space has dimension 3−2=1 and is generated by their cross product, n∝(2,−5,6). By the four subspaces, every solution is a particular solution plus a null-space vector: x(t)=xp+tn.
Which to choose? A natural criterion is shortest: least ∥x∥. Geometrically it is the perpendicular foot from the origin to the line. That point is perpendicular to n, hence belongs to null(A)⊥=row(A), the row span. The shortest solution is therefore the intersection of the solution line and row space: exactly one, because a line parallel to n intersects a plane perpendicular to n once.
To find it seek the form x=A⊤c (row combination) and impose AA⊤c=b. Here AA⊤=[2.25112.25], giving c=651(56,4) and
You can check n⊤x+=(2⋅54−5⋅60+6⋅32)/65=0. Any other solution x++tn^ (with unit n^) has length, by Pythagoras, ∥x+∥2+t2.
InteractiveThe shortest solution
row space row(A)
null space (dashed) and solutions
x+=A+b
gradient descent
Norm along the line: ∥x(t)∥=∥x+∥2+t2
Gradient descent
Starting point
iteration 0 of 40
∥x(t)∥1.864
∥x+∥=A+b1.336
n⊤xk (null-space component)0.000
∥Axk−b∥2.2361
∥xk−x+∥1.336
Starting from 0, the null-space component starts at 0andneverchanges:thelimitis\vb{x}^+$.
The solid red line gives solutions of Ax=b; dashed line is the null space and blue disk is row space. Move t (or drag below) and watch ∥x(t)∥: the minimum is at t=0, at x+, where the line crosses row space at right angles to x+. Press play: gradient descent from 0 (orange) stays in row space and lands at x+. Choose “From x0” and drag the orange point: n⊤xk never changes across iterations, and limit x∞ is no longer shortest. Increase the step beyond ησ12=2 to see divergence.
The interactive anticipates the lesson’s most surprising result: gradient descent, knowing nothing about minimum norm, finds x+ if started at the origin. The reason is visible: gradient of 21∥Ax−b∥2 is A⊤(Ax−b), a combination of rows of A, so each step stays within row(A) and never touches the component of x in the null space. We prove this below.
The Moore–Penrose pseudoinverse
Formula A⊤(AA⊤)−1 applies only with independent rows, and (A⊤A)−1A⊤ (from the normal equations) only with independent columns. SVD defines a construction that always works.
Recall reduced SVD writes A=∑i=1rσiuivi⊤ with r=rankA and σ1≥⋯≥σr>0. As a map, A takes row space span{v1,…,vr} bijectively to column space span{u1,…,ur}, stretching each vi to σiui, and collapses the null space. The bijection between row and column spaces is the only invertible part. The pseudoinverse reverses it and sends what it cannot invert to zero.
Thus A+ui=vi/σi for i≤r and A+y=0 if y∈null(A⊤). It is the “inverse” of arrow vi↦σiui, existing for every matrix.
The definition uses one SVD, which is not unique. Uniqueness of the result follows from a purely algebraic characterization.
Proof
Existence. With X=VΣ+U⊤ and orthogonal U and V, AXA=U(ΣΣ+Σ)V⊤. Matrix ΣΣ+Σ is diagonal with entries σi⋅σi−1⋅σi=σi if σi>0 and 0 otherwise: it is Σ, giving (1). Similarly Σ+ΣΣ+=Σ+ gives (2). Also AX=U(ΣΣ+)U⊤ and XA=V(Σ+Σ)V⊤, and ΣΣ+, Σ+Σ are diagonal with ones in the first r positions: (3) and (4).
These are orthogonal projections onto column and row spaces. In particular, I−A+A projects onto the null space and appears in gradient descent’s implicit bias. Conditions (1) and (2) say A+ inverts A “where possible”, and (3) and (4) that it does so with orthogonal, not oblique, projections. Without (3) and (4) there are generally infinitely many generalized inverses: any left inverse of a full-rank tall matrix satisfies (1) and (2).
Special cases worth remembering
A
A+
Why
Square invertible
A−1
Σ+=Σ−1
Full column rank (r=n)
(A⊤A)−1A⊤, left inverse: A+A=In
satisfies all four conditions
Full row rank (r=m)
A⊤(AA⊤)−1, right inverse: AA+=Im
likewise
Column vector a=0
a⊤/∥a∥2
case r=n=1
Rank one, uv⊤
vu⊤/(∥u∥2∥v∥2)
one sum term
Diagonal
invert nonzero entries
U and V are identities up to signs and order
Zero matrix m×n
zero matrix n×m
r=0
For example, for a=(3,4)⊤ it is a+=251(3,4), and a+a=1. Some inverse properties survive: (A+)+=A, (A⊤)+=(A+)⊤, (cA)+=c−1A+ for c=0 and rankA+=rankA. Others do not: generally (AB)+=B+A+. With A=[11] and B=[10], AB=1, hence (AB)+=1, but B+A+=[10][0.50.5]=0.5.
The minimum-norm solution
We have the object. The theorem justifying the preceding statements is:
Proof
Take full SVD A=UΣV⊤ and change coordinates: y=V⊤x and c=U⊤b. Orthogonal U preserves norms:
The second sum does not depend on x: it is the part of b outside column space, the irreducible residual. The first vanishes exactly when yi=ci/σi for i≤r, while coordinates yr+1,…,yn do not appear and are free. Thus minimizers are x=Vy with
Since vr+1,…,vn is a basis of null(A), this is x⋆+null(A) with x⋆=∑i≤r(ci/σi)vi=VΣ+U⊤b=A+b, proving 1. Vector x+ combines v1,…,vr, spanning row(A); any other minimizer differs by a nonzero null-space vector outside row(A): this is 2. Finally V preserves norms, ∥x∥2=∥y∥2=∑i≤r(ci/σi)2+∑i>ryi2, minimized uniquely with free yi zero; the stated decomposition is Pythagoras with x+⊥x−x+. This is 3.
∎
The expansion to remember is
x+=i=1∑rσiui⊤bvi,
which constructs the solution: project b onto each output direction ui, divide by stretch σi and place the result in input direction vi. Null-space directions receive nothing. Also Ax+=AA+b=Pcol(A)b: fitted part is the projection of b onto column space, already known from the projections lesson. What is new is which x produces it.
Ill-posed problems: noise divided by σᵢ
Return to the fourth case. Hadamard called a problem well-posed when a solution exists, is unique and continuously depends on data. The pseudoinverse fixes the first two. The third formally holds in finite dimensions, but with a constant potentially 1013.
Our running example is deconvolution. A signal x∈R64 (smooth peak and rectangular pulse) passes through a Gaussian blur of width 0.04: A is matrix 64×64 with Aij∝exp(−(ti−tj)2/(2⋅0.042)), symmetric positive definite. Observe b=Ax+e with small noise e. Singular values fall from σ1≈0.993 to σ64≈4.3⋅10−14: condition numberκ(A)≈2.3⋅1013.
Using the previous expansion and invertibility of A,
A+b=i=1∑nσiui⊤(Ax+e)vi=x+i=1∑nσiui⊤evi.
If noise is white with standard deviation δ per component, ui⊤e also has standard deviation δ (an orthonormal basis does not change an isotropic Gaussian vector’s distribution). Error in component i is order δ/σi: noise is not spread evenly but concentrates in directions of small σi and is multiplied by 1/σi. With relative noise 10−3, exact inversion yields relative error order 109. This is not rounding: it is the exact inverse applied to slightly perturbed data.
When is there hope? Useful signal in each component is ui⊤Ax=σivi⊤x. For exact solution to have reasonable norm, coefficients ui⊤bexacto must decay on average faster than σi. This is the discrete Picard condition (studied in depth in inverse problems). Smooth signals satisfy it: their oscillating-direction coefficients are tiny. Noise breaks it because its coefficients never decay.
Why “oscillating directions”? Under blur, vi changes sign exactly i−1 times: v1 is a hump, v2 a wave, through v64 alternating at every point. These are discrete analogues of Fourier modes, and blur attenuates faster oscillations more, like a low-pass filter. Thus our signal’s smooth part (Gaussian peak) has coefficients vi⊤x falling below 10−5 around i=30, whereas the rectangular pulse with two jumps retains coefficients order 0.1 at those indices. That part cannot be recovered above noise, explaining why every regularized reconstruction rounds jumps.
InteractiveThe Picard plot
Spectral coefficients (logarithmic scale)
σi
ui⊤b
ui⊤b/σi
Truncated SVD reconstruction, k=kP=23
true signal
reconstruction
Without knowing x, the plot suggests kP=23 with an error of 13.2 %; the best cutoff gives 12.3 %. Inverting all 64 components gives a relative error of 2.1⋅109.
Picard cutoff kP23
Relative error at kP13.2 %
Best k (knowing x)29 (12.3 %)
Naive inverse error (k=64)2.1⋅109
Noise level δ per component4.1⋅10−4
Gray shows blur singular values σi; blue, noisy-data coefficients ui⊤b; red, their ratio, the size of each component of A−1b. Blue initially falls with gray (signal), then plateaus at the noise floor and red grows unchecked. Move noise from 10−7 to 10−1: the floor rises or falls and cutoff kP moves. At right, truncated SVD uses that cutoff without knowing the signal and comes close to the best possible cutoff. Enable noiseless coefficients to see Picard’s condition: dashed blue decreases on average at least as fast as gray, keeping their ratio bounded; rectangular-pulse jumps prevent much faster decay.
A Picard plot is a diagnostic instrument, not decoration. Without knowing the solution it reveals noise level (floor height), how many SVD components carry information (those above it), and whether the signal satisfies the Picard condition (coefficients fall faster than σi before the floor). The second supplies a natural cutoff k.
Spectral filters
The expansion of x+ suggests the remedy: do not treat all components equally. A spectral filter multiplies each term by factor φi∈[0,1]:
The idea is φi≈1 where σi is large against noise (trust data) and φi≈0 where small (ignore it). This family is spectral filtering. The pseudoinverse is the trivial filter, φi=1 for every i≤r.
Truncated SVD. The simplest filter is a step: φi=1 if i≤k and 0 otherwise. This replaces A with its best rank-k approximation and applies the pseudoinverse: xk=Ak+b. The parameter is k and the Picard plot suggests the cutoff.
Tikhonov. Instead of cutting off, penalize solution size:
xλ=xargmin∥Ax−b∥2+λ∥x∥2,λ>0.
The objective is a strictly convex quadratic (Hessian 2(A⊤A+λI) is positive definite), so the unique minimizer is given by zero gradient. Expanded in the SVD basis:
2A⊤(Ax−b)+2λx=0
Objective gradient set to zero (first-order condition).
1/6
Tikhonov factor φ(σ)=σ2/(σ2+λ) is 1/2 at σ=λ, approaches 1 as σ≫λ and behaves like σ2/λ when σ≪λ. In variable s=lnσ it is exactly a logistic sigmoid: φ=1/(1+e−2(s−lnλ)). It is a smoothed step centered at λ, with the same logarithmic-scale shape for every λ.
What matters is its effect on noise. Noise component i is multiplied not by 1/σi but σi/(σi2+λ), whose maximum as a function of σ occurs at σ=λ, with value 1/(2λ). Tikhonov bounds noise amplification by 1/(2λ) regardless of the spectrum of A.
The bias–noise tradeoff
With b=Ax+e, any filter’s error separates componentwise into two terms:
xφ−x=sesgo de regularizacioˊn−i∑(1−φi)(vi⊤x)vi+ruido propagadoi∑φiσiui⊤evi.
The first is deterministic; the second has zero mean if noise does, so the cross term vanishes in expectation and E∥xφ−x∥2=∑i(1−φi)2(vi⊤x)2+δ2∑iφi2/σi2 for white noise with standard deviation δ. More filtering (lower k, higher λ) reduces propagated noise and increases bias: signal components are lost. Total error forms a U with an intermediate minimum; the art is finding it without knowing x.
InteractiveFilter factors and deconvolution
Filter factors φ(σ)
Tikhonov
σi of the matrix
Signal and reconstruction
true x
data b
reconstruction xφ
Relative error versus parameter (drag to select)
Too permissive: components pass with σi below the noise, amplified by 1/σi. The error is 8.2 times the minimum.
Filter
Relative error ∥xφ−x∥/∥x∥92.5%
Minimum possible with this filter11.3%
σ cutoff1.0⋅10−4
∥xφ∥5.02
Residual ∥Axφ−b∥ / noise ∥e∥2.4⋅10−3/3.2⋅10−3
Top left shows chosen filter factor φ(σ) logarithmically with 64 blur-matrix singular values as points; right shows true signal (dashed), noisy blurred data (points) and reconstruction. Below is relative error versus parameter: drag the curve. Initial λ passes noise and creates oscillations; raise λ to the U minimum and further to see oversmoothing. Switch to truncated SVD and gradient descent: “Compare” shows all three filters at the same cutoff σ are nearly equal, as are minimum errors.
Choosing the parameter
In the figure you cheat: error is visible because x is known. In a real problem decide from available information. Three classical criteria:
Discrepancy principle (Morozov). Knowing noise level ∥e∥, fitting data better makes no sense: choose λ with ∥Axλ−b∥≈∥e∥. The interactive shows both quantities.
L-curve (Hansen). Plot log∥xλ∥ against log∥Axλ−b∥ as λ varies. An L appears: the vertical branch is noise (norm explodes without better fit), the horizontal oversmoothing (residual grows without reduced norm). Choose the corner of maximum curvature. Noise knowledge is unnecessary.
Generalized cross-validation (GCV) and ordinary cross-validation, as in machine learning.
None is infallible; the deconvolution cell yields different λ values and errors near optimum.
The regularization path and ridge regression
As λ travels from ∞ to 0, xλ traces a continuous regularization path from 0 to x+. The latter holds even if A is rank deficient: for σi>0, σi/(σi2+λ)→1/σi, and for σi=0 the term vanishes for all λ. Thus,
A+=λ→0+lim(A⊤A+λI)−1A⊤,
another pseudoinverse definition explaining its discontinuity: the limit exists for each A, but is not uniform in A.
In statistics this estimator is ridge regression, with design matrix A=X; its spectral expression is ridge shrinkage in the SVD basis. In robotics it is damped least-squares inverse kinematics: near an arm singularity, Jacobian σmin approaches zero and the pseudoinverse would demand enormous joint speeds, whereas damping bounds response by 1/(2λ).
Tikhonov also has a probabilistic reading. If the model is b=Ax+e with noise e∼N(0,δ2I) and prior on the unknown is x∼N(0,τ2I), log posterior density, up to constants, is −2δ21∥Ax−b∥2−2τ21∥x∥2. Maximizing it is Tikhonov with λ=δ2/τ2: noise variance divided by signal variance (MAP–Tikhonov equivalence). Minimum norm is the limit τ→∞ at fixed noise, or δ→0: trusting data without reservation.
A practical detail: Tikhonov is ordinary least squares on an augmented system,
∥Ax−b∥2+λ∥x∥2=[AλI]x−[b0]2,
solved by QR without forming A⊤A (which squares the condition number). For many λ values one SVD is preferable because each xλ then costs only O(rn): the code exercise.
Implicit bias of gradient descent
We turn the first interactive’s observation into a theorem. Let f(x)=21∥Ax−b∥2 have gradient ∇f(x)=A⊤(Ax−b), and run gradient descent with fixed step xk+1=xk−ηA⊤(Axk−b).
Proof
Write yk=V⊤xk and c=U⊤b. Since A⊤A=VΣ⊤ΣV⊤ and A⊤b=VΣ⊤c, iteration decouples coordinatewise:
yk+1,i=yk,i−ησi(σiyk,i−ci).
For i≤r with yi⋆=ci/σi, this is yk+1,i−yi⋆=(1−ησi2)(yk,i−yi⋆). The η assumption gives 1−ησi2<1 for all i≤r (because 0<ησi2≤ησ12<2), so yk,i→ci/σi. For i>r, σi=0 and yk+1,i=yk,i: those coordinates never move and equal y0,i=vi⊤x0. The limit is
and Pnull(A)=I−A+A. This minimizer is nearest to x0 because it is the orthogonal projection of x0 onto affine subspace x++null(A).
∎
This is gradient descent on quadratics with a nuance: the quadratic is not strictly convex, and on flat null-space directions the algorithm simply does not move. Implicit bias is that inertia: nobody requested minimum norm, but the algorithm inherits the initial null-space component, zero if initialized at zero. The same holds for stochastic gradient descent on a consistent system: each stochastic gradient is a multiple of row a~i, iteration stays in x0+row(A) and, if it converges to a solution, it must be A+b+(I−A+A)x0, the unique solution in that affine subspace.
The proof gives more than the limit. From x0=0 after m steps,
xm=i≤r∑[1−(1−ησi2)m]σiui⊤bvi,
a spectral filter with φi(m)=1−(1−ησi2)m (Landweber iteration in inverse problems). Directions with ησi2m≫1 have converged; those with ησi2m≪1 have barely started, with φi≈mησi2. The cutoff is at σ≈1/ηm, like Tikhonov with λ≈1/(ηm): stopping early regularizes (early stopping). This is the previous interactive’s third filter.
The interpolation peak
Combine everything in the motivating scenario: regression with n data and p features, fit using w^=Xp+y. If p<n this is ordinary least squares; if p>n it is the minimum-norm interpolator found by gradient descent from zero.
Near p=n something striking occurs. For independent Gaussian features of variance 1, the Marchenko–Pastur theorem says that for large n and p, singular values of Xp∈Rn×p fill interval [n−p,n+p]. The lower edge vanishes at p=n: a random square matrix is on the verge of singularity, and w^=∑i(ui⊤y/σi)vi divides noise y by nearly zero σmin. For p<n−1 an exact formula quantifies this: if y=Xpw+ε with noise independent of Xp, zero mean and covariance δ2I (we write δ as before to distinguish singular values), then
E∥w^−w∥2=δ2E[tr(Xp⊤Xp)−1]=δ2n−p−1p,
using the inverse Wishart mean, E[(Xp⊤Xp)−1]=I/(n−p−1). This diverges as p approaches n. If the model also omits influential features, their contribution behaves as extra noise and the peak is larger.
Linear regression with n=30 data and the first p of 120 Gaussian features; curves are medians of 5 repetitions. Move p or drag a graph. Near p=n (dotted line), the smallest singular value of Xp (red spectrum mark) approaches zero according to n−p, the norm of w^ shoots up and test error peaks; past p=n all fall again. Raise λ: ridge removes the peak. Change scenario: with distributed signal the largest model wins; with concentrated signal the classical minimum wins.
Three interactive lessons, all consequences of spectral expansion. The peak is not vague “overfitting”: it is division by σmin, visible in the second and third graphs. A little Tikhonov suffices to bound that division and remove it. Whether the overparameterized regime wins depends on the problem: when signal spreads over many features, adding them reduces bias more than the minimum-norm interpolator pays in noise; when concentrated in a few, the classical minimum stays better. Study this in minimum-norm interpolation.
Implementation from scratch
First build the pseudoinverse from SVD with a relative threshold for zero singular values, and check the four Penrose conditions and special cases.
[ ]SVD pseudoinverse and Penrose conditionsBrowser
import numpy as np
def pinv_svd(A, rtol=1e-12):
"""Pseudoinversa de Moore-Penrose a partir de la SVD reducida."""
U, s, Vt = np.linalg.svd(A, full_matrices=False)
keep = s > rtol * s[0] if s.size and s[0] > 0 else np.zeros_like(s, dtype=bool)
s_inv = np.zeros_like(s)
s_inv[keep] = 1 / s[keep]
return (Vt.T * s_inv) @ U.T # V Σ⁺ Uᵀ sin formar matrices diagonales
rng = np.random.default_rng(0)
A = rng.standard_normal((5, 3)) @ rng.standard_normal((3, 4)) # 5×4 de rango 3
X = pinv_svd(A)
penrose = {
"A X A = A": np.linalg.norm(A @ X @ A - A),
"X A X = X": np.linalg.norm(X @ A @ X - X),
"(A X)ᵀ = A X": np.linalg.norm((A @ X).T - A @ X),
"(X A)ᵀ = X A": np.linalg.norm((X @ A).T - X @ A),
}
for k, v in penrose.items():
print(f"{k:16s} error {v:.1e}")
print("rango:", np.linalg.matrix_rank(A), " ‖X − np.linalg.pinv(A)‖ =", f"{np.linalg.norm(X - np.linalg.pinv(A)):.1e}")
print("traza de AA⁺ y de A⁺A (= rango):", round(np.trace(A @ X), 10), round(np.trace(X @ A), 10))
B = rng.standard_normal((6, 3)) # rango de columnas completo
print("columnas completas:", np.allclose(pinv_svd(B), np.linalg.solve(B.T @ B, B.T)))
C = rng.standard_normal((3, 6)) # rango de filas completo
print("filas completas: ", np.allclose(pinv_svd(C), C.T @ np.linalg.inv(C @ C.T)))
print("vector (3, 4): ", pinv_svd(np.array([[3.0], [4.0]])))
An orthogonal projector’s trace is its rank, explaining 3. Now the figure’s 2×3 example: minimum-norm solution, its orthogonality to the null space and other solutions’ norms.
[ ]The shortest solution del sistema 2×3Browser
A = np.array([[1.0, 1.0, 0.5],
[-0.5, 1.0, 1.0]])
b = np.array([2.0, 1.0])
x_plus = pinv_svd(A) @ b
n = np.cross(A[0], A[1]); n = n / np.linalg.norm(n)
print("x⁺ =", x_plus, " 65·x⁺ =", 65 * x_plus)
print("‖x⁺‖ =", np.linalg.norm(x_plus), " nᵀx⁺ =", n @ x_plus)
for t in [-1.0, 0.5, 2.0]:
x = x_plus + t * n
print(f"t = {t:4.1f}: ‖Ax − b‖ = {np.linalg.norm(A @ x - b):.1e}, ‖x‖ = {np.linalg.norm(x):.4f}")
x_ls, *_ = np.linalg.lstsq(A, b, rcond=None)
print("lstsq coincide con A⁺b:", np.allclose(x_ls, x_plus))
for eps in [1e-2, 1e-8, 1e-14, 0.0]:
print(f"ε = {eps:7.0e}: diag(pinv(diag(1, ε))) = {np.diag(np.linalg.pinv(np.diag([1.0, eps])))}")
The last lines show discontinuity: 1/ε grows without bound and at ε=0 jumps to 0.
Lab: deconvolution with spectral filters
The complete Picard-plot problem: blur matrix, noise, naive inverse, default-tolerance pseudoinverse, truncated SVD and Tikhonov with three λ selection criteria (L-curve, discrepancy and optimum, known only because the signal is synthetic).
[ ]Deconvolution: naive inverse, truncated SVD and Tikhonov with three criteriaBrowser
n, s = 64, 0.04
t = (np.arange(n) + 0.5) / n
A = (1 / n) / (np.sqrt(2 * np.pi) * s) * np.exp(-(t[:, None] - t[None, :])**2 / (2 * s**2))
x_true = np.exp(-((t - 0.28) / 0.07)**2) + 0.7 * ((t > 0.55) & (t < 0.8))
b_exact = A @ x_true
rng = np.random.default_rng(1)
e = 1e-3 * np.sqrt(np.mean(b_exact**2)) * rng.standard_normal(n) # ruido relativo 10⁻³
b = b_exact + e
U, sig, Vt = np.linalg.svd(A)
c = U.T @ b
print(f"σ₁ = {sig[0]:.3f}, σ₆₄ = {sig[-1]:.1e}, κ(A) = {sig[0] / sig[-1]:.1e}")
def filtered(phi):
"""x_φ = Σ φᵢ (uᵢᵀb / σᵢ) vᵢ."""
return Vt.T @ (phi * c / sig)
rel = lambda x: np.linalg.norm(x - x_true) / np.linalg.norm(x_true)
print(f"inversa ingenua: error relativo {rel(np.linalg.solve(A, b)):.1e}")
print(f"pinv (rcond por defecto): error relativo {rel(np.linalg.pinv(A) @ b):.1e}")
errs_k = [rel(filtered((np.arange(n) < k).astype(float))) for k in range(1, n + 1)]
k_best = int(np.argmin(errs_k)) + 1
print(f"SVD truncada, mejor k = {k_best}: error {errs_k[k_best - 1]:.3f}")
lams = np.logspace(-12, 0, 121)
X = np.array([filtered(sig**2 / (sig**2 + l)) for l in lams])
res = np.linalg.norm(X @ A.T - b, axis=1) # ‖A x_λ − b‖
sol = np.linalg.norm(X, axis=1) # ‖x_λ‖
err = np.array([rel(x) for x in X])
# esquina de la curva L: máxima curvatura de (log ‖r‖, log ‖x‖) como curva parametrizada por log λ
lr, lx, ll = np.log(res), np.log(sol), np.log(lams)
d1r, d1x = np.gradient(lr, ll), np.gradient(lx, ll)
d2r, d2x = np.gradient(d1r, ll), np.gradient(d1x, ll)
curv = (d1r * d2x - d2r * d1x) / (d1r**2 + d1x**2)**1.5
i_L = int(np.argmax(curv))
i_D = int(np.argmin(np.abs(res - np.linalg.norm(e)))) # principio de discrepancia
i_O = int(np.argmin(err))
for name, i in [("curva L", i_L), ("discrepancia", i_D), ("óptimo (con x)", i_O)]:
print(f"{name:15s} λ = {lams[i]:.1e}, error {err[i]:.3f}")
The L-curve and reconstruction proposed by its corner:
Inspect the third line of deconvolution output: np.linalg.pinv with default tolerance (10−15 relative to σ1) retains all 64 singular values because the smallest is 4.3⋅10−14, giving the same disaster as inverse. Practical criteria choose λ values over two orders of magnitude apart (5⋅10−7 for L-curve, 2⋅10−4 for discrepancy, optimum 6⋅10−6), yet errors lie between 12% and 18% versus 109 for inverse: the U is broad logarithmically, and avoiding a large order-of-magnitude mistake matters most. Here L-curve under-regularizes (passes some noise) and discrepancy slightly over-regularizes, but its error is within one point of optimum; neither wins every problem.
Lab: verifying implicit bias
Gradient descent on an underdetermined problem of 20 equations and 50 unknowns, from zero and three random starts, compared with the theorem’s prediction.
[ ]Gradient descent: A⁺b plus initial null-space projectionBrowser
rng = np.random.default_rng(0)
m_, n_ = 20, 50
A = rng.standard_normal((m_, n_)); b = rng.standard_normal(m_)
A_pinv = np.linalg.pinv(A)
x_plus = A_pinv @ b
P_null = np.eye(n_) - A_pinv @ A
eta = 1 / np.linalg.norm(A, 2)**2 # η = 1/σ₁²
def gd(x0, steps=5000):
x = x0.copy()
for _ in range(steps):
x -= eta * A.T @ (A @ x - b)
return x
print(f"desde 0: ‖x − A⁺b‖ = {np.linalg.norm(gd(np.zeros(n_)) - x_plus):.1e}")
for trial in range(3):
x0 = rng.standard_normal(n_)
x_inf = gd(x0)
pred = x_plus + P_null @ x0
print(f"desde x0 #{trial}: ‖x − A⁺b‖ = {np.linalg.norm(x_inf - x_plus):.2f}, "
f"‖x − (A⁺b + P_N x0)‖ = {np.linalg.norm(x_inf - pred):.1e}, residuo {np.linalg.norm(A @ x_inf - b):.1e}")
All four endpoints interpolate data (residual order 10−15), but only the zero start yields x+; the others lie distance ∥Pnullx0∥ away, exactly as the theorem says.
Verifying the peak formula
Finally, a quick simulation of the inverse Wishart mean explaining the interpolation peak.
[ ]E‖ŵ − w‖² = δ² p / (n − p − 1) in least squares with Gaussian designBrowser
rng = np.random.default_rng(2)
n, delta, trials = 30, 0.5, 2000
for p in [5, 15, 25, 28]:
w = rng.standard_normal(p)
sq = []
for _ in range(trials):
Xp = rng.standard_normal((n, p))
y = Xp @ w + delta * rng.standard_normal(n)
w_hat, *_ = np.linalg.lstsq(Xp, y, rcond=None)
sq.append(np.sum((w_hat - w)**2))
print(f"p = {p:2d}: simulado {np.mean(sq):7.3f} teoría δ²p/(n−p−1) = {delta**2 * p / (n - p - 1):7.3f}")
With p=28 theory gives 0.25⋅28/1=7, about 26 times more than with p=15 (0.27), with the same data count and noise. Simulated mean departs farther from theory as p nears n: ∥w^−w∥2 has a heavy tail there (a few nearly singular matrices dominate the mean), so the interactive shows the median.
The professional version
Task
NumPy / SciPy
Internals
Solve min∥Ax−b∥ at minimum norm
np.linalg.lstsq(A, b, rcond=None)
SVD (LAPACK gelsd); also returns rank and σi
Same, choosing algorithm
scipy.linalg.lstsq(A, b, lapack_driver=...)
gelsd (SVD), gelss (SVD) or gelsy (pivoted QR, faster)
sklearn.linear_model.Ridge(alpha=λ, solver="svd") or augmented system with lstsq
factors σi/(σi2+λ)
On GPU
torch.linalg.lstsq, torch.linalg.pinv
note: on CUDA, lstsq supports only driver gels, assuming full rank
Correspondence with our implementation is direct. np.linalg.pinv(A, rcond=r) is our pinv_svd with rtol=r: it zeros σi≤rσ1, applying truncated SVD with a relative cutoff. Default r=10−15 discards rounding zeros, not noise. In an ill-posed problem choosing rcond chooses k, a modeling decision made from the Picard plot, not by accepting the default.
lstsq with rcond=None uses machine epsilon times max(m,n) as threshold and returns the minimum-norm solution without forming A+. That is the correct way to solve a system. Forming A+ (dense n×m) for one vector costs the same SVD plus a matrix–matrix product and nm memory numbers, with no benefit. For many b or λ, save factorization (U, σ, V⊤) and apply it; explicit pseudoinverse is useful when matrix A+ itself is the object of interest (e.g. reusable projector A+A).
[ ]Libraries versus our implementationBrowser
from scipy import linalg as sla
rng = np.random.default_rng(3)
A = rng.standard_normal((40, 12)) @ rng.standard_normal((12, 60)) # 40×60 de rango 12
b = rng.standard_normal(40)
x1, res, rank, sv = np.linalg.lstsq(A, b, rcond=None)
x2 = sla.lstsq(A, b, lapack_driver="gelsd")[0]
x3 = sla.lstsq(A, b, lapack_driver="gelsy")[0]
x4 = pinv_svd(A) @ b
print("rango detectado por lstsq:", rank)
for name, x in [("scipy gelsd", x2), ("scipy gelsy", x3), ("pinv_svd @ b", x4)]:
print(f"{name:13s} ‖x − x_lstsq‖ = {np.linalg.norm(x - x1):.1e}")
print(f"‖x_lstsq‖ = {np.linalg.norm(x1):.4f}")
# Tikhonov por tres caminos
lam = 0.5
U, s, Vt = np.linalg.svd(A, full_matrices=False)
x_svd = Vt.T @ (s / (s**2 + lam) * (U.T @ b))
x_aug = np.linalg.lstsq(np.vstack([A, np.sqrt(lam) * np.eye(60)]), np.concatenate([b, np.zeros(60)]), rcond=None)[0]
x_ne = np.linalg.solve(A.T @ A + lam * np.eye(60), A.T @ b)
print(f"Tikhonov: SVD vs aumentado {np.linalg.norm(x_svd - x_aug):.1e}, SVD vs ecuaciones normales {np.linalg.norm(x_svd - x_ne):.1e}")
Common mistakes
Ejercicios
Exercises
ProofA⁺b is the minimum-norm solution
Prove: For every A∈Rm×n and every b∈Rm, x+=A+b minimizes ∥Ax−b∥ and is the unique minimum-norm minimizer.
0
Let A=UΣV⊤ be a full SVD, r=rankA, and change coordinates using y=V⊤x and c=U⊤b. Make no assumptions about m, n or r.
Step 1 of 4. What does the squared residual become?
ProofPenrose: existence and uniqueness
Prove: X=VΣ+U⊤ satisfies the four Penrose conditions, (1) AXA=A, (2) XAX=X, (3) (AX)⊤=AX, (4) (XA)⊤=XA, and no other matrix does.
0
Let A=UΣV⊤ be an SVD of A∈Rm×n with rank r.
Step 1 of 3. Check (1).
NumericPseudoinverse of a column
For column matrix A=[12], A+ is a 1×2 matrix. What is its second entry?
NumericA Tikhonov factor
With Tikhonov regularization parameter λ=0.01, what filter factor applies to the component with singular value σ=0.1?
NumericStopping early filters
Gradient descent from 0 at 21∥Ax−b∥2 with step η=1. After m=4 iterations, what filter factor applies to the component with singular value σ=0.5?
NumericThe shortest solution on a plane
What is the norm of the minimum-norm solution to x1+2x2+2x3=9?
NumericTikhonov’s ceiling
With Tikhonov and λ=10−4, what is the maximum over all σ>0, of the factor multiplying noise component ui⊤e in the solution?
QuizGradient descent from another point
Run gradient descent with step 0<η<2/σ12 on 21∥Ax−b∥2, with A having more columns than rows and full row rank, starting at x0=0. What does it converge to? Select all correct expressions.
More than one answer may be correct.
QuizWhat survives from the inverse?
Which claims hold for every real matrix A (and B of compatible size)?
More than one answer may be correct.
QuizReading a Picard plot
In an ill-posed problem’s Picard plot, coefficients ui⊤b fall alongside σi until i≈20 then plateau around 10−4, while σi continues falling to 10−12. Which statements are true?
More than one answer may be correct.
CodeThe Tikhonov path with one SVD
Implement tikhonov_path(A, b, lambdas) returning an array of shape (len(lambdas), n) whose row j is xλj=argminx∥Ax−b∥2+λj∥x∥2. All λj are positive and A∈Rm×n may be tall, wide or rank deficient. Compute one SVD and obtain all solutions with filter factors: tests check that you do not solve a system for every λ.
import numpy as np
def tikhonov_path(A, b, lambdas):
# 1. Una SVD reducida de A.
# 2. Para cada lambda, los factores sigma / (sigma**2 + lambda).
...
Shift+Enter to run
Summary
Pseudoinverse A+=VΣ+U⊤=∑i≤rσi−1viui⊤ reverses the row-to-column-space bijection and annihilates the left null space. It uniquely satisfies the four Penrose conditions, and AA+, A+A are orthogonal projectors onto col(A) and row(A).
x+=A+b is the minimum-norm least-squares solution: the unique minimizer in row(A), with all others x++null(A). It is an inductive-bias choice, not truth, and depends on variable scale.
The pseudoinverse is discontinuous and, in ill-posed problems, divides each component’s noise by σi. A Picard plot shows where data coefficients sink into noise and suggests a cutoff.
Spectral filters xφ=∑iφi(ui⊤b/σi)vi unify truncated SVD (step), Tikhonov or ridge (σ2/(σ2+λ), bounding amplification by 1/(2λ)) and early stopping (1−(1−ησ2)m). The parameter balances bias and noise and is selected by discrepancy, L-curve or validation.
Least-squares gradient descent converges to A+b+(I−A+A)x0: from zero, the minimum-norm solution. Near p=n, near-zero design-matrix σmin makes the minimum-norm interpolator explode (double-descent peak), avoided by some ridge.
Key idea
Every linear-system solution is written in the SVD basis as ∑iφi(ui⊤b/σi)vi: the pseudoinverse sets φi=1, regularizers carefully choose φi and gradient descent raises them from 0 to 1 at each step. Solving a system decides component by component how much to trust data.