Module contents
Lesson 8 of 25Core 95 min

Projections and least squares

When Ax = b has no solution, find the closest Ax: the orthogonal projection of b onto the column space. Derive projection matrices and normal equations geometrically and by calculus, connect the data-space and column-space views, and understand the numerical danger of AᵀA that motivates QR and SVD.

After this lesson you can

  • Derive projection onto a line and a subspace and prove it minimizes distance.
  • Characterize orthogonal projections by P² = P and Pᵀ = P and distinguish oblique projections.
  • Formulate a linear or polynomial fit as least squares and solve it using normal equations.
  • Interpret the same problem in data space and column space.
  • Explain why normal equations square the condition number.

Before you start

Motivation: more equations than unknowns

Until now, a linear system Ax=b\mat{A}\vb{x} = \vb{b} was a yes-or-no question: either b\vb{b} lies in the column space of A\mat{A} and there is a solution, or it does not and there is none. When data come from measuring the world, the answer is almost always “no”. Fitting a line y=C+Dty = C + Dt to mm noisy points produces mm equations C+Dti=yiC + Dt_i = y_i with only two unknowns, and three noncollinear points suffice to make the system inconsistent. Yet the data carry plenty of information about CC and DD. The question, not the data, is at fault.

The same pattern—many more equations than unknowns and no exact solution—appears throughout practical work:

  • Regression and networks. A linear regression model trained with mean squared error solves exactly this lesson’s problem. So does a linear probe on frozen GPT activations: thousands of examples, hundreds of weights and a closed-form solution.
  • Robotics. To identify a linear model st+1≈Fst+Gut\vb{s}_{t+1} \approx \mat{F}\vb{s}_t + \mat{G}\vb{u}_t from a trajectory, each instant supplies linear equations in the entries of F\mat{F} and G\mat{G}; with hundreds of instants and dozens of unknowns the system is overdetermined. Camera calibration also uses dozens of correspondences between 3D points and pixels for about a dozen parameters.
  • Finance. With fixed decay parameter, the Nelson–Siegel model describes the interest-rate curve as a linear combination of three functions of maturity (level, slope and curvature). Fitting it to yields of dozens of bonds gives three unknowns and dozens of equations.

Change the question. If no x\vb{x} satisfies Ax=b\mat{A}\vb{x} = \vb{b}, seek the x\vb{x} that leaves Ax\mat{A}\vb{x} as close as possible to b\vb{b}. The key is a familiar observation: whichever x\vb{x} you choose, Ax\mat{A}\vb{x} is a combination of the columns, so it lies in col⁡(A)\col(\mat{A}). The problem becomes geometric: which point in subspace col⁡(A)\col(\mat{A}) is closest to b\vb{b}? The entire lesson follows from the answer: orthogonal projection.

We will use a small example throughout. Find the line that best fits points (1,1)(1, 1), (2,2)(2, 2) and (3,2)(3, 2). Requiring it to pass through all three gives

C+D=1C+2D=2C+3D=2\begin{aligned} C + D &= 1\\ C + 2D &= 2\\ C + 3D &= 2 \end{aligned}

or, in matrix form,

[111213]⏟A[CD]⏟x=[122]⏟b.\underbrace{\begin{bmatrix} 1 & 1\\ 1 & 2\\ 1 & 3 \end{bmatrix}}_{\mat{A}} \underbrace{\begin{bmatrix} C\\ D \end{bmatrix}}_{\vb{x}} = \underbrace{\begin{bmatrix} 1\\ 2\\ 2 \end{bmatrix}}_{\vb{b}}.

The first two equations give C=0C = 0 and D=1D = 1, whereupon the third says 3=23 = 2. There is no solution. By the end of the projection section we will have the best line, y=23+12ty = \tfrac{2}{3} + \tfrac{1}{2}t, and know in what sense it is best.

The closest shadow

Start with a case we can draw. Take A\mat{A} with two independent columns a1,a2∈R3\vb{a}_1, \vb{a}_2 \in \R^3, so col⁡(A)\col(\mat{A}) is a plane through the origin, and an b\vb{b} outside that plane. Each x=(x1,x2)\vb{x} = (x_1, x_2) chooses a point Ax=x1a1+x2a2\mat{A}\vb{x} = x_1\vb{a}_1 + x_2\vb{a}_2 on the plane. We seek the closest to b\vb{b}.

InteractiveThe closest shadow
  • b\vb{b}
  • a1\vb{a}_1
  • a2\vb{a}_2
  • plane col⁡(A)\col(\mat{A})
  • p\vb{p}, projection of b\vb{b}
  • error e=b−p\vb{e} = \vb{b} - \vb{p}
  • candidate Ax\mat{A}\vb{x}
Candidate
0.75
0.75
Radius ∥b−Ax∥\norm{\vb{b} - \mat{A}\vb{x}}2.086
Minimum ∥b−p∥\norm{\vb{b} - \vb{p}}1.537
∥p−Ax∥\norm{\vb{p} - \mat{A}\vb{x}}1.411
Pythagoras: 4.35=2.36+1.994.35 = 2.36 + 1.99
A⊤(b−Ax)=[−2.53−1.78]\mat{A}\T(\vb{b} - \mat{A}\vb{x}) = \begin{bmatrix} -2.53 \\ -1.78 \end{bmatrix}
x^\hat{\vb{x}} (the minimum)(0.22, 0.38)
The sphere intersects the plane in a circle through Ax\mat{A}\vb{x}: points inside are closer to b\vb{b}. The circle is always centered at p\vb{p}.
Drag Ax\mat{A}\vb{x} across the plane (or move x1x_1 and x2x_2). The blue sphere is centered at b\vb{b} with radius ∥b−Ax∥\norm{\vb{b} - \mat{A}\vb{x}}, so it always passes through Ax\mat{A}\vb{x} and intersects the plane in a circle. Press ‘Go to minimum’: the circle shrinks to a point, the sphere touches the plane only at p\vb{p}, and error e\vb{e} (red) is perpendicular to the plane. Try the two b\vb{b} buttons and drag the columns.

What you should have seen:

  • Points inside the circle are closer. The sphere consists of points at distance ∥b−Ax∥\norm{\vb{b} - \mat{A}\vb{x}} from b\vb{b}; plane points inside it are better candidates. While the sphere intersects the plane in a circle of positive radius improvement is possible, and the optimum occurs when the circle degenerates to a point: the sphere is tangent to the plane.
  • The circle’s center does not move. However you move Ax\mat{A}\vb{x}, the intersection circle is always centered at p\vb{p}, the foot of the perpendicular from b\vb{b}. The readouts show why: ∥b−Ax∥2=∥b−p∥2+∥p−Ax∥2\norm{\vb{b} - \mat{A}\vb{x}}^2 = \norm{\vb{b} - \vb{p}}^2 + \norm{\vb{p} - \mat{A}\vb{x}}^2. This is Pythagoras for the right triangle with vertices b\vb{b}, p\vb{p} and Ax\mat{A}\vb{x}, and says the circle’s radius is ∥p−Ax∥\norm{\vb{p} - \mat{A}\vb{x}}.
  • Perpendicular to the plane means perpendicular to both columns. At the minimum, a1⊤(b−Ax^)=0\vb{a}_1\T(\vb{b} - \mat{A}\hat{\vb{x}}) = 0 and a2⊤(b−Ax^)=0\vb{a}_2\T(\vb{b} - \mat{A}\hat{\vb{x}}) = 0. Stacked together they give A⊤(b−Ax^)=0\mat{A}\T(\vb{b} - \mat{A}\hat{\vb{x}}) = \vb{0}, the lesson’s central equation.
  • The two extremes. If b\vb{b} lies in the plane, p=b\vb{p} = \vb{b}, error is zero and the system had an exact solution. If b\vb{b} is perpendicular to the plane, p=0\vb{p} = \vb{0} and x^=0\hat{\vb{x}} = \vb{0}: no column combination improves on doing nothing.

The rest turns these four observations into formulas and theorems, first for a line and then any subspace.

Projecting onto a line

The simplest case is a one-dimensional subspace: the line spanned by vector a≠0\vb{a} \neq \vb{0} in Rm\R^m. Candidates are multiples xax\vb{a}, and the figure suggests the condition characterizing the best: error must be orthogonal to the line.

a⊤(b−x^ a)=0  ⟺  x^=a⊤ba⊤a,\vb{a}\T(\vb{b} - \hat{x}\,\vb{a}) = 0 \;\Longleftrightarrow\; \hat{x} = \frac{\vb{a}\T\vb{b}}{\vb{a}\T\vb{a}},

and the projection of b\vb{b} onto the line is

proj⁡ab=a⊤ba⊤a a.\proj_{\vb{a}}\vb{b} = \frac{\vb{a}\T\vb{b}}{\vb{a}\T\vb{a}}\,\vb{a}.

That this condition gives the minimum takes one line to check. Write p=x^a\vb{p} = \hat{x}\vb{a} and e=b−p\vb{e} = \vb{b} - \vb{p}. For any xx, b−xa=e+(x^−x)a\vb{b} - x\vb{a} = \vb{e} + (\hat{x} - x)\vb{a}, and the two terms are orthogonal, so

∥b−xa∥2=∥e∥2+(x^−x)2∥a∥2,\norm{\vb{b} - x\vb{a}}^2 = \norm{\vb{e}}^2 + (\hat{x} - x)^2\norm{\vb{a}}^2,

which is never less than ∥e∥2\norm{\vb{e}}^2 and equals it only at x=x^x = \hat{x}. Calculus gives the same: g(x)=∥b∥2−2x a⊤b+x2 a⊤ag(x) = \norm{\vb{b}}^2 - 2x\,\vb{a}\T\vb{b} + x^2\,\vb{a}\T\vb{a} is a parabola with minimum at x=a⊤b/a⊤ax = \vb{a}\T\vb{b}/\vb{a}\T\vb{a}. Both paths agree, and will again in higher dimensions.

Rearranging factors, projection is a matrix applied to b\vb{b}:

p=a a⊤ba⊤a=aa⊤a⊤a⏟P b.\vb{p} = \vb{a}\,\frac{\vb{a}\T\vb{b}}{\vb{a}\T\vb{a}} = \underbrace{\frac{\vb{a}\vb{a}\T}{\vb{a}\T\vb{a}}}_{\mat{P}}\,\vb{b}.

This P\mat{P} has rank one: all columns are multiples of a\vb{a}. It has two properties that will define orthogonal projection: P⊤=P\mat{P}\T = \mat{P}, and P2=P\mat{P}^2 = \mat{P}, since projecting something already on the line does not move it.

Projection also proves the Cauchy–Schwarz inequality. Since p⊥e\vb{p} \perp \vb{e}, Pythagoras gives ∥b∥2=∥p∥2+∥e∥2≥∥p∥2\norm{\vb{b}}^2 = \norm{\vb{p}}^2 + \norm{\vb{e}}^2 \ge \norm{\vb{p}}^2, and ∥p∥=∣a⊤b∣/∥a∥\norm{\vb{p}} = \abs{\vb{a}\T\vb{b}}/\norm{\vb{a}}. Hence ∣a⊤b∣≤∥a∥∥b∥\abs{\vb{a}\T\vb{b}} \le \norm{\vb{a}}\norm{\vb{b}}, with equality if and only if e=0\vb{e} = \vb{0}, that is, if b\vb{b} is a multiple of a\vb{a}. Orthogonal projection never lengthens.

Projecting onto a subspace

Now A∈Rm×n\mat{A} \in \R^{m \times n} has nn linearly independent columns a1,…,an\vb{a}_1, \dots, \vb{a}_n (hence m≥nm \ge n and rank⁡A=n\rank \mat{A} = n). Seek p=Ax^\vb{p} = \mat{A}\hat{\vb{x}} in col⁡(A)\col(\mat{A}) with error e=b−Ax^\vb{e} = \vb{b} - \mat{A}\hat{\vb{x}} perpendicular to all columns: aj⊤(b−Ax^)=0\vb{a}_j\T(\vb{b} - \mat{A}\hat{\vb{x}}) = 0 for j=1,…,nj = 1, \dots, n. Stacked into a vector, those nn conditions are

A⊤(b−Ax^)=0,\mat{A}\T(\vb{b} - \mat{A}\hat{\vb{x}}) = \vb{0},

and rearranging gives a square system:

A⊤A x^=A⊤b.\mat{A}\T\mat{A}\,\hat{\vb{x}} = \mat{A}\T\vb{b}.

These nn equations in nn unknowns are the normal equations. “Normal” here means perpendicular: the error is normal to the subspace.

Condition A⊤e=0\mat{A}\T\vb{e} = \vb{0} has an interpretation in the map of the four fundamental subspaces: it says e∈null⁡(A⊤)\vb{e} \in \nullsp(\mat{A}\T). Since null⁡(A⊤)\nullsp(\mat{A}\T) is the orthogonal complement of col⁡(A)\col(\mat{A}) and Rm=col⁡(A)⊕null⁡(A⊤)\R^m = \col(\mat{A}) \oplus \nullsp(\mat{A}\T), projection decomposes b\vb{b} into two components:

b=p⏟∈ col⁡(A)+e⏟∈ null⁡(A⊤).\vb{b} = \underbrace{\vb{p}}_{\in\, \col(\mat{A})} + \underbrace{\vb{e}}_{\in\, \nullsp(\mat{A}\T)}.

This decomposition is unique and independent of which columns describe the subspace. Hence the definition uses no matrices.

To solve for x^\hat{\vb{x}} invert A⊤A\mat{A}\T\mat{A}, a symmetric n×nn \times n matrix: the columns’ Gram matrix, with entries ai⊤aj\vb{a}_i\T\vb{a}_j. Its invertibility is exactly column independence. Prove it.

ProofWhen AᵀA is invertible
Prove: For A∈Rm×n\mat{A} \in \R^{m \times n}, matrix A⊤A\mat{A}\T\mat{A} is invertible if and only if the columns of A\mat{A} are linearly independent.
0
A⊤A\mat{A}\T\mat{A} is square, so it is invertible if and only if its null space is {0}\{\vb{0}\}. The columns of A\mat{A} are independent if and only if null⁡(A)={0}\nullsp(\mat{A}) = \{\vb{0}\}.

Step 1 of 4. What suffices to prove?

With independent columns solve for x^\hat{\vb{x}} to obtain projection as a matrix applied to b\vb{b}:

x^=(A⊤A)−1A⊤b,p=Ax^=Pb,P=A(A⊤A)−1A⊤.\begin{aligned} \hat{\vb{x}} &= (\mat{A}\T\mat{A})\inv\mat{A}\T\vb{b},\\ \vb{p} &= \mat{A}\hat{\vb{x}} = \mat{P}\vb{b},\\ \mat{P} &= \mat{A}(\mat{A}\T\mat{A})\inv\mat{A}\T. \end{aligned}

P∈Rm×m\mat{P} \in \R^{m \times m} is the projection matrix onto col⁡(A)\col(\mat{A}). With n=1n = 1 and A=a\mat{A} = \vb{a} it reduces to aa⊤/a⊤a\vb{a}\vb{a}\T/\vb{a}\T\vb{a}. These formulas aid understanding, not computation: in practice solve the system and never form (A⊤A)−1(\mat{A}\T\mat{A})\inv (see common mistakes).

We can now prove what the sphere showed: p\vb{p} is the unique point of col⁡(A)\col(\mat{A}) closest to b\vb{b}.

ProofThe proof, using Pythagoras
Prove: For every x\vb{x}, ∥b−Ax∥≥∥b−p∥\norm{\vb{b} - \mat{A}\vb{x}} \ge \norm{\vb{b} - \vb{p}}, with equality if and only if x=x^\vb{x} = \hat{\vb{x}}.
0
You know x^\hat{\vb{x}} satisfies the normal equations, A⊤(b−Ax^)=0\mat{A}\T(\vb{b} - \mat{A}\hat{\vb{x}}) = \vb{0}. Fix any x\vb{x}.

Step 1 of 4. How do you start?

A special case shows why the general formula has (A⊤A)−1(\mat{A}\T\mat{A})\inv in the middle. If the columns form an orthonormal basis q1,…,qn\vb{q}_1, \dots, \vb{q}_n, matrix Q=[q1⋯qn]\mat{Q} = [\vb{q}_1 \cdots \vb{q}_n] satisfies Q⊤Q=In\mat{Q}\T\mat{Q} = \mat{I}_n and everything simplifies:

x^=Q⊤b,P=QQ⊤,\hat{\vb{x}} = \mat{Q}\T\vb{b}, \qquad \mat{P} = \mat{Q}\mat{Q}\T,

and projection becomes

p=QQ⊤b=∑j=1n(qj⊤b) qj.\vb{p} = \mat{Q}\mat{Q}\T\vb{b} = \sum_{j=1}^n (\vb{q}_j\T\vb{b})\,\vb{q}_j.

The coefficients are dot products and projection is the sum of projections onto each line. For nonorthogonal columns that sum is wrong, and (A⊤A)−1(\mat{A}\T\mat{A})\inv supplies the correction. For example, in R2\R^2 with a1=(1,0)\vb{a}_1 = (1, 0) and a2=(1,1)\vb{a}_2 = (1, 1) the column space is the entire plane, so the projection of b=(0,1)\vb{b} = (0, 1) is b\vb{b} itself. But proj⁡a1b+proj⁡a2b=(0,0)+(12,12)≠b\proj_{\vb{a}_1}\vb{b} + \proj_{\vb{a}_2}\vb{b} = (0, 0) + \left(\tfrac{1}{2}, \tfrac{1}{2}\right) \neq \vb{b}. Finding an orthonormal basis of column space to stay in the easy case is the aim of QR factorization in the next lesson.

Projection matrices

Matrix P=A(A⊤A)−1A⊤\mat{P} = \mat{A}(\mat{A}\T\mat{A})\inv\mat{A}\T has a rigid structure. Each property has a one-line calculation and a geometric interpretation:

  1. P2=P\mat{P}^2 = \mat{P}. P2=A(A⊤A)−1(A⊤A)(A⊤A)−1A⊤=P\mat{P}^2 = \mat{A}(\mat{A}\T\mat{A})\inv(\mat{A}\T\mat{A})(\mat{A}\T\mat{A})\inv\mat{A}\T = \mat{P}. Anything already in col⁡(A)\col(\mat{A}) stays put when projected.
  2. P⊤=P\mat{P}\T = \mat{P}. The transpose of a symmetric matrix’s inverse is the inverse of its transpose, which is itself.
  3. I−P\mat{I} - \mat{P} is also an orthogonal projection, onto null⁡(A⊤)=col⁡(A)⊥\nullsp(\mat{A}\T) = \col(\mat{A})^\perp: (I−P)b=e(\mat{I} - \mat{P})\vb{b} = \vb{e}. Together they split b\vb{b}.
  4. Its eigenvalues are 00 and 11. If Pv=λv\mat{P}\vb{v} = \lambda\vb{v} with v≠0\vb{v} \neq \vb{0}, then λv=P2v=λ2v\lambda\vb{v} = \mat{P}^2\vb{v} = \lambda^2\vb{v}, hence λ∈{0,1}\lambda \in \{0, 1\}. Vectors in col⁡(A)\col(\mat{A}) have eigenvalue 11 and those in null⁡(A⊤)\nullsp(\mat{A}\T) eigenvalue 00.
  5. tr⁡P=n=rank⁡P\tr \mat{P} = n = \rank \mat{P}. By cyclicity of the trace, tr⁡(A(A⊤A)−1A⊤)=tr⁡((A⊤A)−1A⊤A)=tr⁡In=n\tr\big(\mat{A}(\mat{A}\T\mat{A})\inv\mat{A}\T\big) = \tr\big((\mat{A}\T\mat{A})\inv\mat{A}\T\mat{A}\big) = \tr \mat{I}_n = n. Trace counts the dimensions projected onto.

Property 3 has a direct machine-learning use: to remove information carried by embeddings in unit direction u\vb{u}, apply I−uu⊤\mat{I} - \vb{u}\vb{u}\T to each vector. What remains is exactly the part orthogonal to u\vb{u}: the component in that direction becomes zero for all vectors. Note the limitation: if the same information is also distributed across other directions correlated with u\vb{u}, it remains.

The first two properties actually characterize orthogonal projections. To see why, separate two ideas that are often confused.

Proof

1. Every b\vb{b} can be written b=Pb+(I−P)b\vb{b} = \mat{P}\vb{b} + (\mat{I} - \mat{P})\vb{b}. The first term lies in col⁡(P)\col(\mat{P}) and the second in null⁡(P)\nullsp(\mat{P}) because P(I−P)=P−P2=0\mat{P}(\mat{I} - \mat{P}) = \mat{P} - \mat{P}^2 = \mat{0}. The sum is direct: if v=Pw\vb{v} = \mat{P}\vb{w} and also Pv=0\mat{P}\vb{v} = \vb{0}, then v=Pw=P2w=Pv=0\vb{v} = \mat{P}\vb{w} = \mat{P}^2\vb{w} = \mat{P}\vb{v} = \vb{0}.

2. If P⊤=P\mat{P}\T = \mat{P}, for all y,b\vb{y}, \vb{b} we have (Py)⊤(b−Pb)=y⊤P⊤(I−P)b=y⊤(P−P2)b=0(\mat{P}\vb{y})\T(\vb{b} - \mat{P}\vb{b}) = \vb{y}\T\mat{P}\T(\mat{I} - \mat{P})\vb{b} = \vb{y}\T(\mat{P} - \mat{P}^2)\vb{b} = 0, so the error is orthogonal to col⁡(P)\col(\mat{P}). Conversely, if (Py)⊤(I−P)b=0(\mat{P}\vb{y})\T(\mat{I} - \mat{P})\vb{b} = 0 for all y,b\vb{y}, \vb{b}, matrix P⊤(I−P)\mat{P}\T(\mat{I} - \mat{P}) is zero, i.e. P⊤=P⊤P\mat{P}\T = \mat{P}\T\mat{P}. The right side is symmetric, hence P⊤\mat{P}\T is too, and P=P⊤\mat{P} = \mat{P}\T.

3. For each b\vb{b}, both Pb\mat{P}\vb{b} and A(A⊤A)−1A⊤b\mat{A}(\mat{A}\T\mat{A})\inv\mat{A}\T\vb{b} are vectors p∈col⁡(A)\vb{p} \in \col(\mat{A}) with b−p⊥col⁡(A)\vb{b} - \vb{p} \perp \col(\mat{A}), and by definition that vector is unique. Two matrices that agree on every b\vb{b} are equal.

∎

Thus orthogonal projections are exactly symmetric idempotent matrices, and projection onto a subspace is a unique matrix regardless of which columns describe the subspace. Also, any projector’s trace is its rank: in a basis consisting of a basis of col⁡(P)\col(\mat{P}) followed by one of null⁡(P)\nullsp(\mat{P}), the matrix of P\mat{P} is diag⁡(1,…,1,0,…,0)\diag(1, \dots, 1, 0, \dots, 0), and similar matrices have the same trace.

Oblique projectors exist and are useful, but do not give the closest point. The simplest is

P=[1100],P2=P,P⊤≠P.\mat{P} = \begin{bmatrix} 1 & 1\\ 0 & 0 \end{bmatrix}, \quad \mat{P}^2 = \mat{P}, \quad \mat{P}\T \neq \mat{P}.

Its column space is the xx axis and its null space the line x+y=0x + y = 0: it projects onto the horizontal axis along the diagonal, like a shadow with an angled sun. It maps b=(0,1)\vb{b} = (0, 1) to (1,0)(1, 0), at distance 2\sqrt{2} from b\vb{b}, whereas the nearest point on the axis is (0,0)(0, 0), at distance 11. Generally, if B∈Rm×n\mat{B} \in \R^{m \times n} satisfies that B⊤A\mat{B}\T\mat{A} is invertible,

P=A(B⊤A)−1B⊤\mat{P} = \mat{A}(\mat{B}\T\mat{A})\inv\mat{B}\T

is the projector onto col⁡(A)\col(\mat{A}) along null⁡(B⊤)\nullsp(\mat{B}\T) (check P2=P\mat{P}^2 = \mat{P}). It is orthogonal exactly when null⁡(B⊤)=col⁡(A)⊥\nullsp(\mat{B}\T) = \col(\mat{A})^\perp, meaning col⁡(B)=col⁡(A)\col(\mat{B}) = \col(\mat{A}), and then one may equivalently take B=A\mat{B} = \mat{A}.

InteractiveOblique versus orthogonal projection
  • b\vb{b}
  • shadow Pb\mat{P}\vb{b}
  • b−Pb\vb{b} - \mat{P}\vb{b}
  • line col⁡(P)\col(\mat{P})
  • light direction null⁡(P)\nullsp(\mat{P})
  • orthogonal projection p\vb{p}
−35°
P=[0.660.940.240.34]\mat{P} = \begin{bmatrix} 0.66 & 0.94 \\ 0.24 & 0.34 \end{bmatrix}
∥P2−P∥F\norm{\mat{P}^2 - \mat{P}}_F0.000
∥P−P⊤∥F\norm{\mat{P} - \mat{P}\T}_F0.990
Distance to shadow ∥b−Pb∥\norm{\vb{b} - \mat{P}\vb{b}}2.190
Minimum distance ∥b−p∥\norm{\vb{b} - \vb{p}}1.794
∥P∥2=1/cos⁡φ\norm{\mat{P}}_2 = 1/\cos\varphi1.221
P2=P\mat{P}^2 = \mat{P}, but P≠P⊤\mat{P} \neq \mat{P}\T: oblique projection. Points on the line inside the circle are closer to b\vb{b} than its shadow. Also ∥Pb∥>∥b∥\norm{\mat{P}\vb{b}} > \norm{\vb{b}}: the shadow is longer than the vector.
Light falls at angle φ\varphi to the perpendicular to line col⁡(P)\col(\mat{P}) and the shadow of b\vb{b} is Pb\mat{P}\vb{b}; the light's direction is null⁡(P)\nullsp(\mat{P}). For any φ\varphi, P2=P\mat{P}^2 = \mat{P}. But the circle centered at b\vb{b} through the shadow crosses the line again, and points in the blue band are closer to b\vb{b} than the shadow. Set φ\varphi to 00: simultaneously P\mat{P} becomes symmetric, the circle tangent, and ∥P∥2\norm{\mat{P}}_2 falls to 11.

In the plane, with unit s\vb{s} along the line and unit w\vb{w} perpendicular to the light, the projector is P=sw⊤/(w⊤s)\mat{P} = \vb{s}\vb{w}\T/(\vb{w}\T\vb{s}), the n=1n = 1 case of the formula above, with spectral norm ∥P∥2=∥s∥∥w∥/∣w⊤s∣=1/cos⁡φ\norm{\mat{P}}_2 = \norm{\vb{s}}\norm{\vb{w}}/\abs{\vb{w}\T\vb{s}} = 1/\cos\varphi. An oblique projection can lengthen vectors: you saw this when the shadow became longer than b\vb{b}. An orthogonal one never does, because ∥Pb∥2=∥b∥2−∥e∥2\norm{\mat{P}\vb{b}}^2 = \norm{\vb{b}}^2 - \norm{\vb{e}}^2. Numerically this matters: transformations that do not lengthen also do not amplify rounding errors, so stable algorithms use orthogonal projections and reflections.

Least squares

We have the geometry. Now put it in optimization language, without assuming independent columns.

Before deriving anything, see what “squares” means. In fitting a line, each residual is a point’s vertical distance to the line, and its square is literally the area of a square.

InteractiveActual squares
  • data (ti,yi)(t_i, y_i)
  • your line y=C+Dty = C + Dt
  • squares ri2r_i^2
The data and the line: (t,y)(t, y) plane
The parameters: (C,D)(C, D) plane and area contours
2.30
0.000
Total area ∑iri2\sum_i r_i^23.350
Minimum possible?
∑iri\sum_i r_i−0.300
∑itiri\sum_i t_i r_i5.310
Largest square30 % of the area
If the sums ∑iri\sum_i r_i and ∑itiri\sum_i t_i r_i are not zero, the line can still be improved: apart from the factor −2-2, they are the two components of the area gradient.
Each residual ri=yi−(C+Dti)r_i = y_i - (C + Dt_i) is drawn as a square of side ∣ri∣\abs{r_i} (the plane has the same scale on both axes), and the goal is to minimize total red area. Adjust CC and DD with sliders or by dragging (C,D)(C, D) in the right panel, where area is a quadratic function with elliptical contours. When ready, press ‘Go to optimum’ and inspect the two sums below. Finally create an outlier and enable the ℓ1\ell_1 line.

Three things to notice:

  • Area is a quadratic in (C,D)(C, D) with a unique minimum. Its contours are elongated tilted ellipses. The tilt means CC and DD compensate: increasing slope and decreasing intercept can cost little. This occurs because tit_i are not centered; with tˉ=0\bar{t} = 0, matrix A⊤A\mat{A}\T\mat{A} would be diagonal and ellipse axes aligned.
  • At the optimum, both ∑iri=0\sum_i r_i = 0 and ∑itiri=0\sum_i t_i r_i = 0 hold. These are the two rows of A⊤r=0\mat{A}\T\vb{r} = \vb{0} for A=[ 1  t ]\mat{A} = [\,\vb{1}\;\vb{t}\,]: the residual is orthogonal to the column of ones and the column of tit_i. The first implies the optimal line passes through the data’s center of gravity (tˉ,yˉ)(\bar{t}, \bar{y}).
  • An outlier pulls the line. A residual twice as large weighs four times as much, so the line bends to shrink the largest square even at the expense of all others. The ℓ1\ell_1 line, minimizing ∑i∣ri∣\sum_i \abs{r_i}, barely moves; the price is no closed formula, and it is computed as a linear program.

Why squares?

If squares are so sensitive to outliers, why are they the default? There are three reasons, each a different view of the same problem.

  • Geometry. Sum of squares is squared Euclidean distance in Rm\R^m, which comes from an inner product. This yields perpendicularity and Pythagoras, and the solution depends linearly on the data: p=Pb\vb{p} = \mat{P}\vb{b}. With ∑i∣ri∣\sum_i \abs{r_i} or max⁡i∣ri∣\max_i \abs{r_i}, the ℓ1\ell_1 and ℓ∞\ell_\infty norms, the unit ball has corners, there is no underlying inner product, and no linear formula.
  • Statistics. If bi=(Ax)i+εib_i = (\mat{A}\vb{x})_i + \varepsilon_i with independent εi\varepsilon_i and N(0,σ2)\Normal(0, \sigma^2), log-likelihood is −12σ2∥b−Ax∥2-\frac{1}{2\sigma^2}\norm{\vb{b} - \mat{A}\vb{x}}^2 plus a constant: the maximum-likelihood estimator under Gaussian noise is least squares. With Laplace noise maximum likelihood leads to ℓ1\ell_1. Without assuming normality, if noise has zero mean, constant variance and is uncorrelated, the Gauss–Markov theorem guarantees least squares is the best linear unbiased estimator.
  • Calculus. The objective is a differentiable convex quadratic with linear gradient. Its exact minimum comes from a linear system; when the system is too large, gradient descent, including stochastic descent, converges to the global minimum because there are no spurious local minima.

The price is the outlier sensitivity you just saw. Robust losses, such as ℓ1\ell_1 or Huber loss, quadratic near zero and linear farther away, trade that sensitivity for the closed-form solution.

Two derivations of the same equation

By geometry. As x\vb{x} ranges over Rn\R^n, Ax\mat{A}\vb{x} ranges over col⁡(A)\col(\mat{A}); distance ∥Ax−b∥\norm{\mat{A}\vb{x} - \vb{b}} is minimal exactly when Ax\mat{A}\vb{x} is projection p\vb{p} of b\vb{b}, i.e. when A⊤(b−Ax)=0\mat{A}\T(\vb{b} - \mat{A}\vb{x}) = \vb{0}.

By calculus. Function f(x)=∥Ax−b∥2f(\vb{x}) = \norm{\mat{A}\vb{x} - \vb{b}}^2 is differentiable and its gradient is calculated by expanding the square. Try to predict each step before revealing it.

f(x)=(Ax−b)⊤(Ax−b)f(\vb{x}) = (\mat{A}\vb{x} - \vb{b})\T(\mat{A}\vb{x} - \vb{b})
The squared norm of Ax−b\mat{A}\vb{x} - \vb{b} is its dot product with itself.
1/5

The first-order condition plus convexity suffice, but a more direct argument also works with dependent columns. If x^\hat{\vb{x}} satisfies the normal equations, for every x\vb{x}:

∥Ax−b∥2=∥Ax^−b∥2+∥A(x−x^)∥2.\begin{aligned} \norm{\mat{A}\vb{x} - \vb{b}}^2 &= \norm{\mat{A}\hat{\vb{x}} - \vb{b}}^2\\ &\quad + \norm{\mat{A}(\vb{x} - \hat{\vb{x}})}^2. \end{aligned}

Write Ax−b=(Ax^−b)+A(x−x^)\mat{A}\vb{x} - \vb{b} = (\mat{A}\hat{\vb{x}} - \vb{b}) + \mat{A}(\vb{x} - \hat{\vb{x}}) and observe the cross term is 2(x−x^)⊤A⊤(Ax^−b)=02(\vb{x} - \hat{\vb{x}})\T\mat{A}\T(\mat{A}\hat{\vb{x}} - \vb{b}) = 0. This is Pythagoras written as “completing the square”. It solves the problem completely.

Proof

1. If x^\hat{\vb{x}} satisfies the normal equations, the identity above gives ∥Ax−b∥≥∥Ax^−b∥\norm{\mat{A}\vb{x} - \vb{b}} \ge \norm{\mat{A}\hat{\vb{x}} - \vb{b}} for every x\vb{x}. Conversely, a minimizer makes the gradient zero, and that gradient is −2A⊤(b−Ax^)-2\mat{A}\T(\vb{b} - \mat{A}\hat{\vb{x}}).

2. The previous section’s exercise proved null⁡(A⊤A)=null⁡(A)\nullsp(\mat{A}\T\mat{A}) = \nullsp(\mat{A}) (without using independence). By rank-nullity, rank⁡(A⊤A)=n−dim⁡null⁡(A)=rank⁡A=rank⁡A⊤\rank(\mat{A}\T\mat{A}) = n - \dim\nullsp(\mat{A}) = \rank\mat{A} = \rank\mat{A}\T. Since col⁡(A⊤A)⊆col⁡(A⊤)\col(\mat{A}\T\mat{A}) \subseteq \col(\mat{A}\T) and dimensions coincide, col⁡(A⊤A)=col⁡(A⊤)\col(\mat{A}\T\mat{A}) = \col(\mat{A}\T). The right side A⊤b\mat{A}\T\vb{b} lies in col⁡(A⊤)\col(\mat{A}\T), so the system is consistent.

3. The solution set is x^+null⁡(A⊤A)=x^+null⁡(A)\hat{\vb{x}} + \nullsp(\mat{A}\T\mat{A}) = \hat{\vb{x}} + \nullsp(\mat{A}), a single point if and only if null⁡(A)={0}\nullsp(\mat{A}) = \{\vb{0}\}.

4. If x^1\hat{\vb{x}}_1 and x^2\hat{\vb{x}}_2 are solutions, apply the identity with x^=x^1\hat{\vb{x}} = \hat{\vb{x}}_1 and x=x^2\vb{x} = \hat{\vb{x}}_2; since both minimize, this gives ∥A(x^2−x^1)∥2=0\norm{\mat{A}(\hat{\vb{x}}_2 - \hat{\vb{x}}_1)}^2 = 0. Thus Ax^\mat{A}\hat{\vb{x}} is independent of the chosen solution, and residual b−Ax^\vb{b} - \mat{A}\hat{\vb{x}} is orthogonal to col⁡(A)\col(\mat{A}) by the normal equations: Ax^\mat{A}\hat{\vb{x}} is the projection.

∎

With dependent columns there are infinitely many x^\hat{\vb{x}} but only one p\vb{p}. Choosing the minimum-norm solution leads to the pseudoinverse in lesson 18.

For line y=C+Dty = C + Dt the normal equations can be solved by hand. With A=[ 1  t ]\mat{A} = [\,\vb{1}\;\vb{t}\,] they are

[m∑iti∑iti∑iti2][CD]=[∑iyi∑itiyi].\begin{bmatrix} m & \sum_i t_i\\ \sum_i t_i & \sum_i t_i^2 \end{bmatrix} \begin{bmatrix} C\\ D \end{bmatrix} = \begin{bmatrix} \sum_i y_i\\ \sum_i t_i y_i \end{bmatrix}.

Dividing the first by mm gives C+Dtˉ=yˉC + D\bar{t} = \bar{y}, the line through the center of gravity, and substituting into the second gives

D^=∑i(ti−tˉ)(yi−yˉ)∑i(ti−tˉ)2,\hat{D} = \frac{\sum_i (t_i - \bar{t})(y_i - \bar{y})}{\sum_i (t_i - \bar{t})^2},

and then C^=yˉ−D^ tˉ\hat{C} = \bar{y} - \hat{D}\,\bar{t}.

Two views of the same problem

A line fit can be drawn in two different spaces; moving fluently between them distinguishes applying the formula from understanding it.

Data space, plane (t,y)(t, y)Observation space, Rm\R^m
mm points (ti,yi)(t_i, y_i)one vector b=(y1,…,ym)\vb{b} = (y_1, \dots, y_m)
a line y=C+Dty = C + Dta point C1+DtC\vb{1} + D\vb{t} on plane col⁡(A)\col(\mat{A})
line heights at tit_icoordinates of Ax\mat{A}\vb{x}
vertical residuals eie_icomponents of vector e\vb{e}
sum of squares ∑iei2\sum_i e_i^2∥e∥2\norm{\vb{e}}^2, Pythagoras in Rm\R^m
optimal lineprojection p=Pb\vb{p} = \mat{P}\vb{b}
∑iei=0\sum_i e_i = 0 and ∑itiei=0\sum_i t_i e_i = 0e⊥1\vb{e} \perp \vb{1} and e⊥t\vb{e} \perp \vb{t}

With three points, observation space is R3\R^3 and can be visualized.

InteractiveTwo views of regression
  • data: b=(y1,y2,y3)\vb{b} = (y_1, y_2, y_3)
  • fit: p=Ax^\vb{p} = \mat{A}\hat{\vb{x}}
  • residuals: e=b−p\vb{e} = \vb{b} - \vb{p}
  • column 1\vb{1}
  • column t\vb{t}
Data space: three points and a line
The same problem in R3\R^3: one axis per observation
b=[0.803.202.00],p=[1.402.002.60],e=[−0.601.20−0.60]\vb{b} = \begin{bmatrix} 0.80 \\ 3.20 \\ 2.00 \end{bmatrix}, \quad \vb{p} = \begin{bmatrix} 1.40 \\ 2.00 \\ 2.60 \end{bmatrix}, \quad \vb{e} = \begin{bmatrix} -0.60 \\ 1.20 \\ -0.60 \end{bmatrix}
C^\hat C1.000
D^\hat D0.500
∥e∥2=e12+e22+e32\norm{\vb{e}}^2 = e_1^2 + e_2^2 + e_3^22.160
1⊤e\vb{1}\T\vb{e}0.000
t⊤e\vb{t}\T\vb{e}0.000
Drag the points on the left. Each controls one coordinate of b\vb{b} (height yiy_i) and one of t\vb{t} (abscissa tit_i), so on the right both b\vb{b} and the plane col⁡(A)\col(\mat{A}) spanned by 1\vb{1} and t\vb{t} move. The three red residuals on the left are the three components of red vector e\vb{e} on the right, perpendicular to the plane; readouts 1⊤e\vb{1}\T\vb{e} and t⊤e\vb{t}\T\vb{e} are always 00. The right scene is rotated so the initial plane is horizontal; labeled axes represent the three observations.

The right-hand picture scales. With a million data points and a thousand features the data plane cannot be drawn, but the picture in Rm\R^m stays the same: a vector b\vb{b}, a subspace col⁡(A)\col(\mat{A}) of dimension nn, and the perpendicular between them. The decomposition of p\vb{p} in the figure, first C^\hat{C} times 1\vb{1} then D^\hat{D} times t\vb{t}, reminds us fitted coefficients are coordinates of p\vb{p} in the basis formed by the columns.

In this picture, the statistical analysis-of-variance table is Pythagoras. If the model has an intercept, yˉ1\bar{y}\vb{1} lies in col⁡(A)\col(\mat{A}), so p−yˉ1\vb{p} - \bar{y}\vb{1} does too, and is orthogonal to e\vb{e}:

∥b−yˉ1∥2⏟variacioˊn total=∥p−yˉ1∥2⏟explicada por el modelo+∥e∥2⏟residual.\underbrace{\norm{\vb{b} - \bar{y}\vb{1}}^2}_{\text{variación total}} = \underbrace{\norm{\vb{p} - \bar{y}\vb{1}}^2}_{\text{explicada por el modelo}} + \underbrace{\norm{\vb{e}}^2}_{\text{residual}}.

The coefficient of determination R2R^2 is the ratio of explained to total variation, i.e. cos⁡2θ\cos^2\theta, with θ\theta the angle between centered vectors b−yˉ1\vb{b} - \bar{y}\vb{1} and p−yˉ1\vb{p} - \bar{y}\vb{1}. For a line, p−yˉ1=D^(t−tˉ1)\vb{p} - \bar{y}\vb{1} = \hat{D}(\vb{t} - \bar{t}\vb{1}), so cosine between centered data b−yˉ1\vb{b} - \bar{y}\vb{1} and t−tˉ1\vb{t} - \bar{t}\vb{1}, which is correlation coefficient ρ\rho between tt and yy, equals ±cos⁡θ\pm\cos\theta with the sign of D^\hat{D}. Hence in simple regression R2=ρ2R^2 = \rho^2: squared correlation.

The picture in Rm\R^m also explains statistical “degrees of freedom”. The residual lives in null⁡(A⊤)\nullsp(\mat{A}\T), of dimension m−nm - n. If data are b=Ax⋆+ε\vb{b} = \mat{A}\vb{x}_\star + \boldsymbol{\varepsilon} with zero-mean noise and covariance σ2I\sigma^2\mat{I}, then e=(I−P)ε\vb{e} = (\mat{I} - \mat{P})\boldsymbol{\varepsilon} because (I−P)A=0(\mat{I} - \mat{P})\mat{A} = \mat{0}, and

E∥e∥2=E[ε⊤(I−P)ε]=σ2 tr⁡(I−P)=σ2(m−n).\begin{aligned} \E\norm{\vb{e}}^2 &= \E\big[\boldsymbol{\varepsilon}\T(\mat{I} - \mat{P})\boldsymbol{\varepsilon}\big]\\ &= \sigma^2\,\tr(\mat{I} - \mat{P}) = \sigma^2(m - n). \end{aligned}

That is why noise variance is estimated with ∥e∥2/(m−n)\norm{\vb{e}}^2/(m - n) rather than ∥e∥2/m\norm{\vb{e}}^2/m: the residual can move in only m−nm - n directions. The sampling distribution of coefficients is studied in module 5.

Design matrix, polynomial fitting and leverage

Nothing above requires the model to be a line. It suffices to be linear in parameters: y≈x1ϕ1(t)+⋯+xnϕn(t)y \approx x_1\phi_1(t) + \dots + x_n\phi_n(t) with fixed functions ϕj\phi_j, called features in machine learning. Matrix A\mat{A} with entries aij=ϕj(ti)a_{ij} = \phi_j(t_i) is the design matrix: one row per observation and one column per feature.

  • Polynomials. With ϕj(t)=tj−1\phi_j(t) = t^{j-1}, the design matrix is a Vandermonde matrix. Fitting a parabola is linear least squares although the curve is not a line: linear refers to coefficients. This is polynomial regression in module 11.
  • Other bases. Sines and cosines for periodic signals, splines, Nelson–Siegel’s three curves or frozen network activations: the design matrix changes, not the theory.
  • Multiple targets. If instead of one vector b\vb{b} there are kk (the columns of B∈Rm×k\mat{B} \in \R^{m \times k}), minimizing Frobenius norm ∥AX−B∥F2\norm{\mat{A}\mat{X} - \mat{B}}_F^2 separately minimizes the sum of squares of each column, and X^=(A⊤A)−1A⊤B\hat{\mat{X}} = (\mat{A}\T\mat{A})\inv\mat{A}\T\mat{B}. The same P\mat{P} projects all kk columns. This fits a linear probe with kk outputs in closed form, or a linear layer mimicking another from its activations.

In statistics the projection matrix is called the hat matrix, written H\mat{H} because it “puts a hat” on the data: fitted values are y^=Hy\hat{\vb{y}} = \mat{H}\vb{y}, with y=b\vb{y} = \vb{b} and y^=p\hat{\vb{y}} = \vb{p}. Its diagonal measures something specific. Since y^i=∑jhijyj\hat{y}_i = \sum_j h_{ij}y_j, derivative ∂y^i∂yi\pd{\hat{y}_i}{y_i} is hiih_{ii}: leverage hiih_{ii} of observation ii measures how much its own fitted value moves when it moves. Projection properties yield:

  • 0≤hii≤10 \le h_{ii} \le 1. Since H=H2=H⊤H\mat{H} = \mat{H}^2 = \mat{H}\T\mat{H}, we have hii=∑jhij2=hii2+∑j≠ihij2≥hii2h_{ii} = \sum_j h_{ij}^2 = h_{ii}^2 + \sum_{j \ne i} h_{ij}^2 \ge h_{ii}^2.
  • ∑ihii=tr⁡H=n\sum_i h_{ii} = \tr\mat{H} = n. Mean leverage is n/mn/m. A common rule marks points with hii>2n/mh_{ii} > 2n/m, twice the mean, as high leverage.
  • With an intercept, hii≥1/mh_{ii} \ge 1/m and each row sums to 11. If 1∈col⁡(A)\vb{1} \in \col(\mat{A}), then H1=1\mat{H}\vb{1} = \vb{1}: each y^i\hat{y}_i is a weighted average of all yjy_j, with weights hijh_{ij} summing to 11 that may be negative. Also H−1m11⊤\mat{H} - \tfrac{1}{m}\vb{1}\vb{1}\T is symmetric and idempotent (check using H1=1\mat{H}\vb{1} = \vb{1}), so its diagonal hii−1/mh_{ii} - 1/m is nonnegative.
  • For a line, leverage grows with distance from the center. Columns 1\vb{1} and t−tˉ1\vb{t} - \bar{t}\vb{1} are orthogonal and span the same plane, so H\mat{H} is the sum of their projections:
hii=1m+(ti−tˉ)2∑j(tj−tˉ)2.h_{ii} = \frac{1}{m} + \frac{(t_i - \bar{t})^2}{\sum_j (t_j - \bar{t})^2}.

In the line example, P\mat{P} had diagonal (56,13,56)\left(\tfrac{5}{6}, \tfrac{1}{3}, \tfrac{5}{6}\right): endpoints matter more than the center, as the formula confirms: 13+12=56\tfrac{1}{3} + \tfrac{1}{2} = \tfrac{5}{6}.

InteractiveLeverage and the hat matrix
  • data
  • degree-1 fit
  • fit without point ii
  • residuals
Leverage hjjh_{jj} of each point, below its tjt_j; dashed: threshold 2n/m2n/m
1
9
Bars
Parameters n=k+1n = k + 12
tr⁡H=∑jhjj\tr \mat{H} = \sum_j h_{jj}2.000
hiih_{ii} of point 90.721
Threshold 2n/m2n/m0.444
Residual eie_i−0.683
y^i\hat y_i with and without the point2.58 → 4.35
High-leverage point: h99=0.72>2n/m=0.44h_{99} = 0.72 > 2n/m = 0.44. Raising its yy by one raises its fitted value by 0.720.72.
Nine points and a degree-kk polynomial fit. The bars below, aligned with points, show leverage hjjh_{jj} of each or, in the other mode, row ii of H\mat{H}: weights with which y^i\hat{y}_i averages all yjy_j. Point 9, far from the rest, starts selected: its leverage exceeds threshold 2n/m2n/m and removing it completely changes the fit (dashed line). Increase the degree, drag points horizontally, and check the bars always sum to n=k+1n = k + 1.

A point with hiih_{ii} close to 11 nearly determines its own fitted value, so its residual is misleadingly small. Two formulas quantify this. If noise has covariance σ2I\sigma^2\mat{I}, the variance of residual ii is σ2(1−hii)\sigma^2(1 - h_{ii}): high-leverage points have small residuals by construction, so detect outliers using standardized residuals, as in regression diagnostics. If refitted without observation ii, its prediction becomes y^(i)\hat{y}_{(i)}, with

yi−y^(i)=ei1−hii,y^i−y^(i)=hii ei1−hii,\begin{aligned} y_i - \hat{y}_{(i)} &= \frac{e_i}{1 - h_{ii}},\\ \hat{y}_i - \hat{y}_{(i)} &= \frac{h_{ii}\,e_i}{1 - h_{ii}}, \end{aligned}

a consequence of the Sherman–Morrison formula (lesson 14). The first allows leave-one-out cross-validation error to be computed with one fit rather than repeating it mm times.

When AᵀA is nearly singular

Normal equations are the shortest way to write the solution and often the worst way to compute it. The problem is the condition number. For A\mat{A} with independent columns, let

σmax⁡=max⁡∥x∥=1∥Ax∥,σmin⁡=min⁡∥x∥=1∥Ax∥,\begin{aligned} \sigma_{\max} &= \max_{\norm{\vb{x}} = 1}\norm{\mat{A}\vb{x}},\\ \sigma_{\min} &= \min_{\norm{\vb{x}} = 1}\norm{\mat{A}\vb{x}}, \end{aligned}

be the maximum and minimum stretch of a unit vector, and κ(A)=σmax⁡/σmin⁡\kappa(\mat{A}) = \sigma_{\max}/\sigma_{\min} their ratio. Since x⊤(A⊤A)x=∥Ax∥2\vb{x}\T(\mat{A}\T\mat{A})\vb{x} = \norm{\mat{A}\vb{x}}^2, the quadratic form of A⊤A\mat{A}\T\mat{A} takes exactly the interval [σmin⁡2,σmax⁡2][\sigma_{\min}^2, \sigma_{\max}^2] on the unit sphere. For a symmetric positive semidefinite matrix these extremes are its largest and smallest eigenvalues (the Rayleigh quotient in lesson 12), and its condition number is their ratio. Therefore

κ(A⊤A)=κ(A)2.\kappa(\mat{A}\T\mat{A}) = \kappa(\mat{A})^2.

In double precision the unit roundoff is u≈1.1×10−16u \approx 1.1 \times 10^{-16}, and a stable method solving a system with condition κ\kappa can lose on the order of log⁡10κ\log_{10}\kappa digits. Normal equations lose 2log⁡10κ(A)2\log_{10}\kappa(\mat{A}): if κ(A)=108\kappa(\mat{A}) = 10^8, then κ(A⊤A)=1016≈1/u\kappa(\mat{A}\T\mat{A}) = 10^{16} \approx 1/u and no digits are guaranteed.

There is a nuance: sensitivity of the least-squares problem itself to perturbations in A\mat{A} is of order κ(A)+κ(A)2tan⁡θ\kappa(\mat{A}) + \kappa(\mat{A})^2\tan\theta, where θ\theta is the angle between b\vb{b} and col⁡(A)\col(\mat{A}). If the residual is small, θ≈0\theta \approx 0 and the problem is only as sensitive as κ(A)\kappa(\mat{A}): normal equations waste half the available digits. If the residual is large, term κ2\kappa^2 is already in the problem and normal equations lose little more. Detailed analysis appears in numerical least squares (module 9).

Normal equations have cost in their favor: forming A⊤A\mat{A}\T\mat{A} takes about mn2mn^2 operations exploiting symmetry, and Cholesky solution n3/3n^3/3; QR with Householder reflections costs about 2mn2−23n32mn^2 - \tfrac{2}{3}n^3. With m≫nm \gg n, normal equations are roughly twice as fast. The stable route, seen next lesson, factorizes A=QR\mat{A} = \mat{Q}\mat{R} with Q\mat{Q} having orthonormal columns and R\mat{R} invertible upper triangular. Then A⊤A=R⊤R\mat{A}\T\mat{A} = \mat{R}\T\mat{R} and normal equations reduce to

Rx^=Q⊤b,P=QQ⊤,\mat{R}\hat{\vb{x}} = \mat{Q}\T\vb{b}, \qquad \mat{P} = \mat{Q}\mat{Q}\T,

and since κ(R)=κ(A)\kappa(\mat{R}) = \kappa(\mat{A}), nothing is squared. When columns are dependent or nearly so, use SVD, which gives the pseudoinverse and determines which directions are noise; when changing the problem is appropriate, ridge regression solves (A⊤A+λI)x=A⊤b(\mat{A}\T\mat{A} + \lambda\mat{I})\vb{x} = \mat{A}\T\vb{b}, whose condition number (σmax⁡2+λ)/(σmin⁡2+λ)(\sigma_{\max}^2 + \lambda)/(\sigma_{\min}^2 + \lambda) no longer explodes.

Implementation from scratch

First, projection onto a line and onto a subspace, with the lesson’s example. The normal equations are solved; no inverse is computed.

[ ]Projections from scratchBrowser
import numpy as np
np.set_printoptions(precision=4, suppress=True)

def proyectar_en_recta(a, b):
    """Proyección ortogonal de b sobre la recta de a (a no nulo)."""
    return (a @ b) / (a @ a) * a

b = np.array([1.0, 2.0, 2.0])
uno = np.ones(3)
p = proyectar_en_recta(uno, b)
print("p =", p, " (la media de b, repetida)")
print("e =", b - p, " uno·e =", uno @ (b - p))

A = np.array([[1.0, 1.0],
              [1.0, 2.0],
              [1.0, 3.0]])
# ecuaciones normales: se resuelven, no se invierte AᵀA
x_hat = np.linalg.solve(A.T @ A, A.T @ b)
p = A @ x_hat
e = b - p
print("x̂ =", x_hat, " p =", p, " e =", e)
print("Aᵀe =", A.T @ e, " ‖e‖² =", e @ e)

If uno·e comes out on the order of 10−1610^{-16} instead of 00, that is rounding: orthogonality holds to machine precision. Next examine projection-matrix properties on a random A\mat{A} of 8×38 \times 3, and leverage computed two ways: as the diagonal of P\mat{P} and as squared row norms of an orthonormal basis Q\mat{Q} of col⁡(A)\col(\mat{A}), since P=QQ⊤\mat{P} = \mat{Q}\mat{Q}\T implies hii=∥fila i de Q∥2h_{ii} = \norm{\text{fila } i \text{ de } \mat{Q}}^2. The second method forms no m×mm \times m matrix.

[ ]Projectors and leverageBrowser
rng = np.random.default_rng(0)
m, n = 8, 3
A = rng.normal(size=(m, n))
# P = A (AᵀA)⁻¹ Aᵀ, sin formar ninguna inversa
P = A @ np.linalg.solve(A.T @ A, A.T)
print("‖P² − P‖ =", np.linalg.norm(P @ P - P))
print("‖P − Pᵀ‖ =", np.linalg.norm(P - P.T))
print("tr P =", round(np.trace(P), 12),
      " rango de A =", np.linalg.matrix_rank(A))
autovalores = np.sort(np.linalg.eigvalsh(P))[::-1]
print("autovalores de P:", np.round(autovalores, 10))

# base ortonormal de col(A) (lección 9): P = QQᵀ
Q, R = np.linalg.qr(A)
print("‖P − QQᵀ‖ =", np.linalg.norm(P - Q @ Q.T))
# diag(QQᵀ) = normas al cuadrado de las filas de Q
h = np.sum(Q**2, axis=1)
print("apalancamientos:", h, " suma:", h.sum())

The eigenvalues are three ones and five zeros, and trace equals rank. Now consider data with a distant point: the closed leverage formula for a line agrees with QR, and the distant point alone exceeds threshold 2n/m2n/m.

[ ]The most influential pointBrowser
t = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 25.0])
A = np.column_stack([np.ones_like(t), t])
Q, _ = np.linalg.qr(A)
h = np.sum(Q**2, axis=1)
tc = t - t.mean()
formula = 1 / len(t) + tc**2 / np.sum(tc**2)
print("h       :", h)
print("fórmula :", formula)
umbral = 2 * A.shape[1] / len(t)
print("umbral 2n/m =", round(umbral, 4),
      " puntos por encima:", np.where(h > umbral)[0])

The main experiment solves normal equations using LU factorization with partial pivoting from lesson 4. This compact version stores L\mat{L} and U\mat{U} in one matrix and the permutation as an index vector.

[ ]Custom LU and normal equationsBrowser
def lu_factor(M):
    """PM = LU con pivoteo parcial.

    Devuelve L (sin su diagonal de unos) y U en una sola matriz,
    y la permutación P como vector de índices.
    """
    U = np.array(M, dtype=float)
    k_max = U.shape[0]
    perm = np.arange(k_max)
    for k in range(k_max - 1):
        # pivote: el mayor en valor absoluto de la columna k
        i = k + np.argmax(np.abs(U[k:, k]))
        if i != k:
            U[[k, i]] = U[[i, k]]
            perm[[k, i]] = perm[[i, k]]
        # multiplicadores (columna k de L) y actualización
        U[k + 1:, k] /= U[k, k]
        U[k + 1:, k + 1:] -= np.outer(U[k + 1:, k], U[k, k + 1:])
    return U, perm

def lu_solve(LU, perm, rhs):
    y = np.array(rhs, dtype=float)[perm]
    k_max = len(y)
    for i in range(k_max):            # L y = P rhs
        y[i] -= LU[i, :i] @ y[:i]
    for i in reversed(range(k_max)):  # U x = y
        y[i] = (y[i] - LU[i, i + 1:] @ y[i + 1:]) / LU[i, i]
    return y

def lstsq_normales(A, b):
    """Mínimos cuadrados por ecuaciones normales con la LU propia."""
    LU, perm = lu_factor(A.T @ A)
    return lu_solve(LU, perm, A.T @ b)

A = np.array([[1.0, 1.0], [1.0, 2.0], [1.0, 3.0]])
print(lstsq_normales(A, np.array([1.0, 2.0, 2.0])))

The experiment fits polynomials of degree d=1,…,15d = 1, \dots, 15 to 5050 points in [0,1][0, 1] using monomial basis 1,t,…,td1, t, \dots, t^d. Data are generated without noise from known coefficients (all equal to 11), so the exact solution has zero residual and all measured error is numerical. Compare normal equations with np.linalg.lstsq, which uses SVD.

[ ]The cost of squaring the condition numberBrowser
import matplotlib.pyplot as plt

m = 50
t = np.linspace(0, 1, m)
grados = np.arange(1, 16)
kA, kN, err_ne, err_ls = [], [], [], []
for d in grados:
    # columnas 1, t, t², ..., t^d; coeficientes verdaderos, todos 1
    A = np.vander(t, d + 1, increasing=True)
    c = np.ones(d + 1)
    b = A @ c        # sin ruido: el residuo óptimo es 0
    x_ne = lstsq_normales(A, b)
    x_ls = np.linalg.lstsq(A, b, rcond=None)[0]
    kA.append(np.linalg.cond(A))
    kN.append(np.linalg.cond(A.T @ A))
    err_ne.append(np.linalg.norm(x_ne - c) / np.linalg.norm(c))
    err_ls.append(np.linalg.norm(x_ls - c) / np.linalg.norm(c))

kA = np.array(kA)
print(" d    κ(A)     κ(A)²   κ(AᵀA)  err normales  err lstsq")
filas = zip(grados, kA, kN, err_ne, err_ls)
for d, a, nn, en, el in filas:
    print(f"{d:2d}  {a:7.1e}  {a**2:7.1e}  {nn:7.1e}"
          f"  {en:11.1e}  {el:9.1e}")

u = np.finfo(float).eps / 2
plt.figure(figsize=(7, 4))
plt.semilogy(grados, err_ne, "o-", label="normales (LU propia)")
plt.semilogy(grados, err_ls, "s-", label="lstsq (SVD)")
plt.semilogy(grados, u * kA**2, "--", label="u·κ(A)²")
plt.semilogy(grados, u * kA, ":", label="u·κ(A)")
plt.xlabel("grado d del polinomio")
plt.ylabel("error relativo de los coeficientes")
plt.ylim(1e-17, 1e3)
plt.legend()
plt.title("Elevar al cuadrado el condicionamiento cuesta dígitos")
plt.show()

Three observations. Column κ(A)2\kappa(\mat{A})^2 matches computed κ(A⊤A)\kappa(\mat{A}\T\mat{A}) while below 1/u≈10161/u \approx 10^{16}; above that, the computed figure loses meaning because stored A⊤A\mat{A}\T\mat{A} is already numerically singular. Normal-equation error follows line u κ(A)2u\,\kappa(\mat{A})^2 and exceeds 100 %100\,\% around degree 1111 or 1212. Error from lstsq follows, and here even stays below, line u κ(A)u\,\kappa(\mat{A}): around degree 1515 it retains five or six correct digits. The monomial basis causes κ(A)\kappa(\mat{A}) to grow this way; orthogonal polynomial bases avoid it, hence numpy.polynomial.

Finally, the example where forming A⊤A\mat{A}\T\mat{A} destroys information:

[ ]Forming AᵀA can be irreversibleBrowser
eps = 1e-8
A = np.array([[1.0, 1.0],
              [eps, 0.0],
              [0.0, eps]])
# la solución exacta es x = (1, 1), con residuo 0
b = np.array([2.0, eps, eps])
N = A.T @ A
print("AᵀA calculada =\n", N)
print("¿1 + eps² == 1?", 1 + eps**2 == 1)
try:
    print("normales:", np.linalg.solve(N, A.T @ b))
except np.linalg.LinAlgError as err:
    print("normales: LinAlgError,", err)
Q, R = np.linalg.qr(A)
print("QR    :", np.linalg.solve(R, Q.T @ b))
print("lstsq :", np.linalg.lstsq(A, b, rcond=None)[0])

Depending on the LAPACK library used to compile NumPy, solve on that singular matrix raises LinAlgError (on the laptop) or silently returns nan (in the browser); neither recovers anything. QR and lstsq, which never form A⊤A\mat{A}\T\mat{A}, recover x=(1,1)\vb{x} = (1, 1).

The professional version

In practice normal equations are not written by hand. These are the usual tools and what they do internally.

[ ]Least squares with librariesBrowser
from scipy import linalg as sla
from numpy.polynomial import Polynomial

rng = np.random.default_rng(1)
t = np.sort(rng.uniform(0, 10, 40))
y = 1.5 + 0.8 * t + rng.normal(scale=1.0, size=t.size)
A = np.column_stack([np.ones_like(t), t])

x1, rss, rango, sv = np.linalg.lstsq(A, y, rcond=None)
x2 = sla.lstsq(A, y)[0]          # LAPACK gelsd por defecto
print("numpy   :", x1, " RSS =", rss, " rango =", rango)
print("scipy   :", x2)
print("normales:", lstsq_normales(A, y))

# Polynomial.fit reescala t a [-1, 1] antes de ajustar
pf = Polynomial.fit(t, y, deg=3)
print("cúbica en la base 1, t, t², t³:", pf.convert().coef)

In scikit-learn, the same fit needs no column of ones (the first library import takes a few seconds in the browser):

[ ]The same fit with scikit-learnBrowser
from sklearn.linear_model import LinearRegression

# LinearRegression añade él solo el término independiente
modelo = LinearRegression().fit(t[:, None], y)
print("sklearn :", np.array([modelo.intercept_, modelo.coef_[0]]))
  • np.linalg.lstsq(A, b, rcond=None) uses SVD (LAPACK routine gelsd) and returns solution, residual sum of squares (an empty vector if rank is below nn or if m≤nm \le n), numerical rank and singular values. Singular values below rcond times the largest are treated as zero, giving the minimum-norm solution.
  • scipy.linalg.lstsq selects the algorithm with lapack_driver: 'gelsd' (SVD, default), 'gelsy' (column-pivoted QR, faster) or 'gelss'.
  • sklearn.linear_model.LinearRegression adds the intercept by default without creating a ones column (fit_intercept=True), and with dense data solves using scipy.linalg.lstsq.
  • numpy.polynomial.Polynomial.fit rescales tt to [−1,1][-1, 1] before building the design matrix, greatly improving conditioning; .convert() returns coefficients in the original monomial basis.
  • PyTorch: torch.linalg.lstsq(A, B) solves batches. On GPU only the QR-based 'gels' driver is supported, assuming A\mat{A} has full rank.
  • Leverage: with statsmodels, sm.OLS(y, A).fit().get_influence().hat_matrix_diag.
From scratch in this lessonProfessional equivalentMethod
lstsq_normales (Gram and custom LU)scipy.linalg.cho_solve on A⊤A\mat{A}\T\mat{A}normal equations
Rx^=Q⊤b\mat{R}\hat{\vb{x}} = \mat{Q}\T\vb{b}np.linalg.qr and scipy.linalg.solve_triangularQR (lesson 9)
none yetnp.linalg.lstsq, scipy.linalg.lstsqSVD (lessons 15 and 18)
np.sum(Q**2, axis=1)statsmodels hat_matrix_diagleverage

Common mistakes

Exercises

Quiz
Which matrices are orthogonal projections?

More than one answer may be correct.

Numeric
Fit line y=C+Dty = C + Dt by least squares to points (0,6)(0, 6), (1,0)(1, 0) and (2,0)(2, 0). What is CC?
Numeric
What is the trace of the orthogonal projection matrix onto a three-dimensional subspace of R10\R^{10}?
Numeric
Let A\mat{A} have columns (1,1,0)(1, 1, 0) and (0,1,1)(0, 1, 1), and b=(1,0,0)\vb{b} = (1, 0, 0). How far is b\vb{b} from plane col⁡(A)\col(\mat{A})?
Quiz
You fit a line through the origin, y≈Dty \approx Dt, by least squares (the design matrix has only column t\vb{t}). What is guaranteed about residuals rir_i?
Quiz
You add a new column c\vb{c} to A\mat{A} (one feature) and solve again. What happens to minimum residual ∥b−Ax^∥\norm{\vb{b} - \mat{A}\hat{\vb{x}}}?
Numeric
Fit a line y=C+Dty = C + Dt to five points with abscissas t=0,1,2,3,10t = 0, 1, 2, 3, 10. What is the leverage h55h_{55} of the point at t=10t = 10?
Quiz
A least-squares problem with small residual has κ(A)≈106\kappa(\mat{A}) \approx 10^6 and uses double precision (u≈10−16u \approx 10^{-16}). Approximately how many correct digits would you expect from normal equations and QR?
Quiz
If P\mat{P} is an orthogonal projection on Rm\R^m, what is R=I−2P\mat{R} = \mat{I} - 2\mat{P}?
Numeric
In a least-squares fit, observation ii has leverage hii=0.9h_{ii} = 0.9 and residual ei=0.2e_i = 0.2. When refitting without it, what is y^i−y^(i)\hat{y}_i - \hat{y}_{(i)}, the difference between its fitted value with it and prediction without it?
Code
Implement projection_matrix(A), returning the m×mm \times m matrix of orthogonal projection onto col⁡(A)\col(\mat{A}), and lstsq_normal(A, b), returning tuple (x_hat, h): the normal-equation least-squares solution and leverages hiih_{ii}. Assume independent columns, do not compute explicit inverses (use np.linalg.solve), and obtain h without forming the m×mm \times m matrix.
import numpy as np

def projection_matrix(A):
  """Proyección ortogonal (m x m) sobre col(A)."""
  # tu código
  pass

def lstsq_normal(A, b):
  """Devuelve (x_hat, h) por ecuaciones normales."""
  # tu código
  pass
Shift+Enter to run

Summary

  • When Ax=b\mat{A}\vb{x} = \vb{b} has no solution, find Ax\mat{A}\vb{x} closest to b\vb{b}. Since Ax\mat{A}\vb{x} ranges over col⁡(A)\col(\mat{A}), the answer is the orthogonal projection p\vb{p} of b\vb{b} onto col⁡(A)\col(\mat{A}), and its optimality is Pythagoras.
  • Error e=b−p\vb{e} = \vb{b} - \vb{p} is perpendicular to every column: A⊤(b−Ax^)=0\mat{A}\T(\vb{b} - \mat{A}\hat{\vb{x}}) = \vb{0}. This gives normal equations A⊤Ax^=A⊤b\mat{A}\T\mat{A}\hat{\vb{x}} = \mat{A}\T\vb{b}, which calculus obtains by setting the gradient to zero and which always have a solution.
  • With independent columns, P=A(A⊤A)−1A⊤\mat{P} = \mat{A}(\mat{A}\T\mat{A})\inv\mat{A}\T. Orthogonal projections are exactly matrices satisfying P2=P\mat{P}^2 = \mat{P} and P⊤=P\mat{P}\T = \mat{P}; their eigenvalues are 00 and 11, and trace is subspace dimension. Nonsymmetric idempotents are oblique and do not give the closest point.
  • The same fit can be viewed as mm points and a line in the data plane, or as vector b\vb{b} projected onto a subspace of Rm\R^m. Residuals are coordinates of e\vb{e}, and the diagonal of P\mat{P}, leverage, measures how much each observation determines its own fit.
  • κ(A⊤A)=κ(A)2\kappa(\mat{A}\T\mat{A}) = \kappa(\mat{A})^2: forming A⊤A\mat{A}\T\mat{A} can destroy half the digits or all information. Hence solve with QR or SVD.
Key idea
Solving Ax≈b\mat{A}\vb{x} \approx \vb{b} by least squares means orthogonally projecting b\vb{b} onto the column space. Everything else—normal equations, projection matrix, regression line and leverage—follows from one condition: error is perpendicular to each column.