AnyLearn
All lessons
Mathintermediate

SVD and Least Squares

When there's no exact solution, project. When data is high-dimensional, compress. The SVD is the Swiss Army knife that does both — and more. Master orthogonal projection, the normal equations, the Singular Value Decomposition, low-rank approximation, and the pseudoinverse.

Updated · AI-authored, review-gated · how lessons are made

Progress1 / 10

When the system is overdetermined: projection to the rescue

In practice, Ax=bA\mathbf{x}=\mathbf{b} is often inconsistent — more equations than unknowns, and b∉C(A)\mathbf{b}\notin\mathcal{C}(A). We can't solve exactly, but we can do the next best thing: find the x^\hat{\mathbf{x}} that minimizes the residual's squared length:

x^=arg⁡min⁡x∥Ax−b∥2.\hat{\mathbf{x}} = \arg\min_{\mathbf{x}} \|A\mathbf{x} - \mathbf{b}\|^2.

This is least squares. Geometrically: Ax^A\hat{\mathbf{x}} is the orthogonal projection of b\mathbf{b} onto the column space C(A)\mathcal{C}(A). The residual b−Ax^\mathbf{b}-A\hat{\mathbf{x}} is orthogonal to every column of AA:

A⊤(b−Ax^)=0.A^\top(\mathbf{b} - A\hat{\mathbf{x}}) = \mathbf{0}.

The closest point in a subspace is always the orthogonal foot of the perpendicular — this geometric fact is the entire engine of least squares. The projection b^=Ax^\hat{\mathbf{b}}=A\hat{\mathbf{x}} is the "best approximation to b\mathbf{b} that AA can produce."

Sign in free to save your progress and earn certificates.

Full lesson text

All 10 steps on one page, for reading, reference, and search.

Show

1. When the system is overdetermined: projection to the rescue

In practice, Ax=bA\mathbf{x}=\mathbf{b} is often inconsistent — more equations than unknowns, and b∉C(A)\mathbf{b}\notin\mathcal{C}(A). We can't solve exactly, but we can do the next best thing: find the x^\hat{\mathbf{x}} that minimizes the residual's squared length:

x^=arg⁡min⁡x∥Ax−b∥2.\hat{\mathbf{x}} = \arg\min_{\mathbf{x}} \|A\mathbf{x} - \mathbf{b}\|^2.

This is least squares. Geometrically: Ax^A\hat{\mathbf{x}} is the orthogonal projection of b\mathbf{b} onto the column space C(A)\mathcal{C}(A). The residual b−Ax^\mathbf{b}-A\hat{\mathbf{x}} is orthogonal to every column of AA:

A⊤(b−Ax^)=0.A^\top(\mathbf{b} - A\hat{\mathbf{x}}) = \mathbf{0}.

The closest point in a subspace is always the orthogonal foot of the perpendicular — this geometric fact is the entire engine of least squares. The projection b^=Ax^\hat{\mathbf{b}}=A\hat{\mathbf{x}} is the "best approximation to b\mathbf{b} that AA can produce."

2. The normal equations

Rearranging A⊤(b−Ax^)=0A^\top(\mathbf{b}-A\hat{\mathbf{x}})=\mathbf{0} gives the normal equations:

A⊤A x^=A⊤b.A^\top A\,\hat{\mathbf{x}} = A^\top\mathbf{b}.

If AA has full column rank, A⊤AA^\top A is invertible and the unique least-squares solution is:

x^=(A⊤A)−1A⊤b.\hat{\mathbf{x}} = (A^\top A)^{-1}A^\top\mathbf{b}.

The matrix A+=(A⊤A)−1A⊤A^+ = (A^\top A)^{-1}A^\top is called the left pseudoinverse — it satisfies A+A=IA^+A=I when AA has full column rank.

Never solve the normal equations by forming A⊤AA^\top A and inverting it. A⊤AA^\top A squares the condition number of AA: if κ(A)=107\kappa(A)=10^7 then κ(A⊤A)=1014\kappa(A^\top A)=10^{14}, causing catastrophic loss of precision. In practice, use QR decomposition (np.linalg.lstsq) or SVD — both bypass A⊤AA^\top A entirely and are numerically stable.

3. The projection matrix

The orthogonal projection of any vector b\mathbf{b} onto C(A)\mathcal{C}(A) is b^=Ax^=A(A⊤A)−1A⊤b\hat{\mathbf{b}}=A\hat{\mathbf{x}}=A(A^\top A)^{-1}A^\top\mathbf{b}. Define the projection matrix:

P=A(A⊤A)−1A⊤.P = A(A^\top A)^{-1}A^\top.

PP has two defining properties:

  • Idempotent: P2=PP^2=P (projecting twice = projecting once).
  • Symmetric: P⊤=PP^\top=P.

The complementary projector I−PI-P projects onto the orthogonal complement N(A⊤)\mathcal{N}(A^\top) (the left null space). For any b\mathbf{b}:

b=Pb⏟∈ C(A)+(I−P)b⏟∈ N(A⊤).\mathbf{b} = \underbrace{P\mathbf{b}}_{\in\,\mathcal{C}(A)} + \underbrace{(I-P)\mathbf{b}}_{\in\,\mathcal{N}(A^\top)}.

This is the orthogonal direct-sum decomposition of Rm\mathbb{R}^m — the four fundamental subspaces (Lesson 2) made concrete and computational. If A=QA=Q is already orthonormal, P=QQ⊤P=QQ^\top and computing the projection is a single matrix multiply.

4. The Singular Value Decomposition (SVD)

Every m×nm\times n matrix AA (no assumptions on shape or rank) factors as:

A=UΣV⊤A = U\Sigma V^\top

where:

  • U∈Rm×mU\in\mathbb{R}^{m\times m} is orthogonal (left singular vectors — orthonormal basis of Rm\mathbb{R}^m).
  • Σ∈Rm×n\Sigma\in\mathbb{R}^{m\times n} is diagonal, non-negative entries σ1≥σ2≥⋯≥σr>0\sigma_1\ge\sigma_2\ge\cdots\ge\sigma_r>0 (singular values).
  • V∈Rn×nV\in\mathbb{R}^{n\times n} is orthogonal (right singular vectors — orthonormal basis of Rn\mathbb{R}^n).

Geometric reading: AA performs three operations in sequence — V⊤V^\top rotates in input space, Σ\Sigma stretches along rr axes (and kills the rest), UU rotates in output space. Every matrix is just stretch-and-rotate, once you find the right axes. The singular values σi\sigma_i are the stretching factors; they are always real and non-negative even when AA is not symmetric.

5. SVD and the four fundamental subspaces

The SVD delivers all four fundamental subspaces cleanly:

SubspaceBasisDimension
Column space C(A)\mathcal{C}(A)First rr columns of UUr=rank⁡(A)r=\operatorname{rank}(A)
Left null space N(A⊤)\mathcal{N}(A^\top)Last m−rm-r columns of UUm−rm-r
Row space C(A⊤)\mathcal{C}(A^\top)First rr columns of VVrr
Null space N(A)\mathcal{N}(A)Last n−rn-r columns of VVn−rn-r

The SVD makes the abstract theory of Lesson 2 numerically concrete: just run np.linalg.svd(A) and read off the four subspaces from the columns of UU and VV. The singular values are the "importance" of each direction — a near-zero singular value signals near-rank-deficiency, which is exactly what the determinant can't tell you reliably.

6. Low-rank approximation: the Eckart-Young theorem

The best rank-kk approximation to AA in both the Frobenius norm and the spectral norm is:

Ak=∑i=1kσiuivi⊤=UkΣkVk⊤A_k = \sum_{i=1}^k \sigma_i \mathbf{u}_i \mathbf{v}_i^\top = U_k \Sigma_k V_k^\top

where Uk,VkU_k, V_k take the first kk columns and Σk\Sigma_k the top-left k×kk\times k block. The approximation error is:

∥A−Ak∥F=σk+12+⋯+σr2.\|A - A_k\|_F = \sqrt{\sigma_{k+1}^2 + \cdots + \sigma_r^2}.

This is the Eckart-Young theorem (1936) — no rank-kk matrix can approximate AA better.

Image compression. A 1000×10001000\times 1000 grayscale image needs 10610^6 numbers. Taking k=50k=50 singular values: store U1000×50U_{1000\times 50}, Σ50×50\Sigma_{50\times 50}, V50×1000V_{50\times 1000} — just 105,000105{,}000 numbers, a 9.5×9.5\times compression. Visual quality is often indistinguishable from the original if the singular values decay rapidly.

7. The pseudoinverse

The Moore-Penrose pseudoinverse A+A^+ exists for any matrix and satisfies four conditions (Moore-Penrose axioms):

AA+A=A,A+AA+=A+,(AA+)⊤=AA+,(A+A)⊤=A+A.AA^+A=A, \quad A^+AA^+=A^+, \quad (AA^+)^\top=AA^+, \quad (A^+A)^\top=A^+A.

Via SVD it's clean: flip the roles of UU and VV, invert the nonzero singular values:

A+=VΣ+U⊤,Σ+=diag(1/σ1,…,1/σr,0,…,0).A^+ = V\Sigma^+U^\top, \quad \Sigma^+ = \text{diag}(1/\sigma_1, \dots, 1/\sigma_r, 0, \dots, 0).

Unified behavior:

  • AA square invertible: A+=A−1A^+ = A^{-1}.
  • AA full column rank: A+=(A⊤A)−1A⊤A^+ = (A^\top A)^{-1}A^\top (left inverse).
  • AA full row rank: A+=A⊤(AA⊤)−1A^+ = A^\top(AA^\top)^{-1} (right inverse).
  • AA rank-deficient: A+bA^+\mathbf{b} gives the minimum-norm least-squares solution — the unique solution with smallest ∥x^∥\|\hat{\mathbf{x}}\|.

np.linalg.pinv(A) computes this via SVD with automatic tolerance for small singular values.

8. NumPy: least squares and SVD in practice

import numpy as np

# Overdetermined system: 5 equations, 2 unknowns
rng = np.random.default_rng(42)
m, n = 5, 2
A = rng.standard_normal((m, n))
true_x = np.array([3.0, -1.0])
b = A @ true_x + 0.1 * rng.standard_normal(m)  # noisy observations

# Stable least squares (QR internally)
x_hat, residuals, rank, sv = np.linalg.lstsq(A, b, rcond=None)
print(f"Estimated x: {x_hat}")     # close to [3, -1]
print(f"Singular values: {sv}")

# Full SVD
U, S, Vt = np.linalg.svd(A, full_matrices=True)
print(f"Singular values from SVD: {S}")

# Low-rank approximation of a matrix
B = rng.standard_normal((100, 80))
Ub, Sb, Vtb = np.linalg.svd(B, full_matrices=False)  # economy SVD
k = 10
Bk = (Ub[:, :k] * Sb[:k]) @ Vtb[:k, :]             # rank-k approx
error = np.linalg.norm(B - Bk, 'fro')
print(f"Frobenius error (rank-{k} approx): {error:.4f}")
print(f"Theoretical min: {np.sqrt(np.sum(Sb[k:]**2)):.4f}")

Use full_matrices=False (economy SVD) when m≫nm\gg n — it skips the m−nm-n columns of UU that are orthogonal to C(A)\mathcal{C}(A) and never used.

9. Applications: compression and recommender systems

Two landmark uses of SVD in engineering:

Image / data compression. The singular values of natural images decay rapidly (smooth images have most energy in few singular vectors). Truncated SVD at rank kk gives near-perfect perceptual quality at a fraction of the storage. JPEG-style compression uses a discrete cosine transform (a fixed unitary basis), but SVD is optimal — it finds the data-specific best basis.

Recommender systems. Netflix / Spotify: build a users×\timesitems rating matrix RR (mostly missing). Approximate R≈UkΣkVk⊤R\approx U_k\Sigma_k V_k^\top — the kk latent factors represent taste dimensions. User row ii of UkU_k is a "taste fingerprint"; item row jj of VkV_k is a "genre fingerprint". Predicted rating R^ij=ui⊤Σkvj\hat{R}_{ij}=\mathbf{u}_i^\top\Sigma_k\mathbf{v}_j. The Netflix Prize was won with SVD-based matrix factorization.

The unifying theme: singular values rank-order importance. Chop below a threshold, keep what matters, discard the noise. This is information compression at its most principled.

10. Putting it all together: the linear algebra toolkit

Across this four-lesson arc you've built the complete engineer's linear algebra toolkit:

LessonCore ideaKey formula
1Vectors & spansspan⁡,dim⁡,u⊤v=∥u∥∥v∥cos⁡θ\operatorname{span}, \dim, \mathbf{u}^\top\mathbf{v}=\|\mathbf{u}\|\|\mathbf{v}\|\cos\theta
2Matrices as mapsFour subspaces, rank-nullity, det⁡\det = volume scale
3EigenstructureAv=λvA\mathbf{v}=\lambda\mathbf{v}, Ak=PDkP−1A^k=PD^kP^{-1}
4SVD & least squaresA=UΣV⊤A=U\Sigma V^\top, x^=(A⊤A)−1A⊤b\hat{\mathbf{x}}=(A^\top A)^{-1}A^\top\mathbf{b}, A+=VΣ+U⊤A^+=V\Sigma^+U^\top

The SVD is the capstone: it reveals the eigenstructure of any matrix (not just square symmetric ones), delivers all four fundamental subspaces numerically, provides the best low-rank approximation provably, and unifies the pseudoinverse and least squares in a single computation. Every serious numerical algorithm in machine learning and scientific computing — PCA, linear regression, image compression, recommender systems — traces back to these ideas.

Check your understanding

The lesson ends with a 5-question quiz. Take it in the player above to see your score.

  1. In the least-squares problem $\min_\mathbf{x}\|A\mathbf{x}-\mathbf{b}\|^2$, the solution $\hat{\mathbf{x}}$ makes the residual $\mathbf{b}-A\hat{\mathbf{x}}$ satisfy:
    • $A(\mathbf{b}-A\hat{\mathbf{x}})=\mathbf{0}$, i.e., the residual is in the null space of $A$.
    • $A^\top(\mathbf{b}-A\hat{\mathbf{x}})=\mathbf{0}$, i.e., the residual is orthogonal to every column of $A$.
    • $\|\mathbf{b}-A\hat{\mathbf{x}}\|=0$, i.e., the system is exactly solved.
    • $\mathbf{b}-A\hat{\mathbf{x}}=\mathbf{b}$, i.e., $A\hat{\mathbf{x}}=\mathbf{0}$.
  2. Why should you avoid computing the least-squares solution as $(A^\top A)^{-1}A^\top\mathbf{b}$ by forming and inverting $A^\top A$ explicitly?
    • Because $A^\top A$ is never invertible for overdetermined systems.
    • Because forming $A^\top A$ squares the condition number of $A$, causing severe numerical instability.
    • Because $(A^\top A)^{-1}$ has complexity $O(n^4)$, which is too slow.
    • Because $A^\top A$ is asymmetric and standard inversion algorithms require symmetric input.
  3. In the SVD $A=U\Sigma V^\top$, the best rank-2 approximation to $A$ is:
    • $U\Sigma V^\top$ with all but the two largest singular values zeroed in $\Sigma$.
    • The matrix formed by the first 2 rows of $U$ times $\Sigma$.
    • $\sigma_1 \mathbf{u}_1\mathbf{v}_1^\top + \sigma_2 \mathbf{u}_2\mathbf{v}_2^\top$, a sum of two rank-1 outer products.
    • The matrix formed by zeroing all but the first 2 rows of $A$.
  4. The Moore-Penrose pseudoinverse $A^+$ of a full-column-rank matrix $A$ equals:
    • $A^\top(AA^\top)^{-1}$ — the right inverse.
    • $(A^\top A)^{-1}A^\top$ — the left inverse.
    • $A^{-1}$ — the standard inverse.
    • $V\Sigma U^\top$ — the SVD with $U$ and $V$ swapped but $\Sigma$ unchanged.
  5. A matrix $A$ has singular values $10, 3, 0.001$. Which property does this reveal?
    • $A$ is orthogonal, since all singular values are positive.
    • $A$ is nearly rank-2 — the third singular direction contributes almost nothing and the matrix is close to singular.
    • $A$ has eigenvalues $10, 3, 0.001$.
    • $A$'s determinant is positive, confirming invertibility.

Related lessons