Survey of Mathematics

2.10 Least squares and regression as projection

When Ax = b has no solution, the best we can do is the point of the column space closest to b. The error of that best choice is perpendicular to every column, and that single fact gives the normal equations, the projection matrix, and the line of best fit.

Taught in 375/376Beyond the courseSpagnolie, Lecture 1 (opening) and Lecture 6 (best approximation)MATH 375 HW4 (Apostol 1.16 #8 bonus note)Strang, Introduction to Linear Algebra, ch. 4Axler, Linear Algebra Done Right, 6C

Spagnolie opened Lecture 1 with three equations in two unknowns that cannot all be true at once, and said “we’ll have to decide how to make sense of this”. Real data always looks like that: more measurements than unknowns, each measurement a little off. This chapter makes sense of it. When no exact answer exists, we ask for the closest answer, and the closest answer turns out to be a projection, which Lecture 6 already taught us how to find.

Before you start

2.6: systems of linear equations and the column space. 2.5: matrix multiplication and the transpose. 2.4: inverses. 2.9: the inner product, orthogonal vectors, and projection. 2.3: null space. 2.2: linear independence. In this chapter vectors are columns of real numbers, and the inner product of u,vu, v in Rm\mathbb R^m is the dot product u⋅v=uTv=∑iuiviu \cdot v = u^{\mathsf T} v = \sum_i u_i v_i.

Quick checkAA is a 3×23 \times 2 matrix and xx is in R2\mathbb R^2. Where does AxAx live?
Quick checkTwo vectors u,vu, v satisfy u⋅v=0u \cdot v = 0. What does that say?
Quick checkThe columns of AA are linearly independent. What is the null space of AA?

The picture

Four data points sit in the plane. A line y=c+mty = c + mt cannot pass through all four, so we ask for the line whose vertical misses are smallest overall. Each miss is drawn as a segment, and its square as a small square. The best line is the one for which the total area of the squares is as small as it can be. Drag the points and watch it re-fit. Then tick “try your own line” and try to beat it. You cannot.

That is the picture in the data plane. There is a second picture, in a different space, and it is the one that makes the problem solvable. Think of the four heights y1,…,y4y_1, \dots, y_4 as ONE vector bb in R4\mathbb R^4. The heights that ANY line could produce at those four tt values also form vectors in R4\mathbb R^4, and they fill out a plane (a 2-dimensional subspace). So fitting a line means finding the point of that plane closest to bb. Here is the same idea one dimension down, where the “plane” is a line through the origin: the green arrow is the closest point, and the red dashed error meets the line at a right angle.

The idea, in words

Write Spagnolie’s three equations as one matrix equation:

3x1+x2=12x1−x2=04x1+7x2=2that is[312−147]⏟A[x1x2]=[102]⏟b.\begin{aligned} 3x_1 + x_2 &= 1 \\ 2x_1 - x_2 &= 0 \\ 4x_1 + 7x_2 &= 2 \end{aligned} \qquad\text{that is}\qquad \underbrace{\begin{bmatrix} 3 & 1 \\ 2 & -1 \\ 4 & 7 \end{bmatrix}}_{A} \begin{bmatrix} x_1 \\ x_2 \end{bmatrix} = \underbrace{\begin{bmatrix} 1 \\ 0 \\ 2 \end{bmatrix}}_{b}.

The first two equations force x1=1/5x_1 = 1/5 and x2=2/5x_2 = 2/5. The third then reads 4/5+14/5=18/54/5 + 14/5 = 18/5, not 22. So no xx works.

Chapter 2.6 told us why: Ax=x1a1+x2a2Ax = x_1 a_1 + x_2 a_2, where a1=(3,2,4)a_1 = (3, 2, 4) and a2=(1,−1,7)a_2 = (1, -1, 7) are the columns of AA. So Ax=bAx = b has a solution exactly when bb is in the column space of AA, the set of all combinations of the columns. Here the column space is a plane in R3\mathbb R^3, and b=(1,0,2)b = (1, 0, 2) is not on it.

If we cannot hit bb, we can at least get as close as possible. Every vector AxAx lies in the plane, so we want the xx for which AxAx is nearest to bb. The leftover b−Axb - Ax is the residual (the amount by which we miss). Its length is the miss distance. Making the squared length small means making the sum of the squares of its entries small. That sum of squares is where the name comes from.

Why· Why squares, and why closest means perpendicular

There are three reasons to use the squared length, and they agree.

  1. Geometry. The closest point of a plane to bb is the foot of the perpendicular dropped from bb. Lecture 6 proved this with Pythagoras. Pythagoras speaks in squares, so squares are the natural way to measure.
  2. Calculus. The squared length ∥Ax−b∥2\lVert Ax - b \rVert^2 is a smooth function of xx whose gradient is 2AT(Ax−b)2A^{\mathsf T}(Ax - b). Setting the gradient to zero gives exactly the equations we derive below by geometry. Spagnolie’s bonus note in HW4 says the same: the calculus route and the projection route give one answer, and he calls projection “by far the most elegant approach”.
  3. Statistics (B). If each measurement is the true value plus independent Gaussian noise, the most likely xx is the one minimizing the sum of squares. This is why least squares is the default tool of experimental science.
Where this came from· Ceres, Gauss and Legendre

On 1 January 1801 Giuseppe Piazzi found a new body, Ceres, and followed it for about forty days before it was lost in the Sun’s glare. Astronomers had a short, noisy arc of observations and needed to say where to point their telescopes months later. Gauss, aged 24, computed an orbit from the observations (he later said he had used least squares in the calculation), and Ceres was seen again near his prediction at the end of 1801. Legendre published the method in 1805, in a work on the orbits of comets, as a way to use more measurements than unknowns. In 1809 Gauss claimed he had used it since 1795, which began a priority dispute, and in the same book he tied the method to the normal distribution of errors. The problem (more observations than unknowns, each a little off) is exactly Spagnolie’s three equations in two unknowns.

The plan for the chapter: (1) show that the closest point is the one whose error is perpendicular to the plane; (2) turn “perpendicular to every column” into the matrix equation ATA x=ATbA^{\mathsf T}A\,x = A^{\mathsf T}b; (3) find when that equation has exactly one solution; (4) package the answer as a matrix PP that drops any bb onto the plane; (5) see how computers do it without ever forming ATAA^{\mathsf T}A.

Definitions and theorems

Throughout, AA is an m×nm \times n matrix of real numbers with columns a1,…,ana_1, \dots, a_n, bb is in Rm\mathbb R^m, and ∥v∥=v⋅v\lVert v \rVert = \sqrt{v \cdot v}. Two facts about AA are used all the time.

  • Ax=x1a1+⋯+xnanAx = x_1 a_1 + \dots + x_n a_n, so the column space of AA is exactly {Ax:x∈Rn}\{Ax : x \in \mathbb R^n\}.
  • The jj-th entry of ATrA^{\mathsf T} r is aj⋅ra_j \cdot r: row jj of ATA^{\mathsf T} is column jj of AA. So ATr=OA^{\mathsf T} r = O says that rr is perpendicular to every column of AA.
Definition B

Least squares solution

A vector x^∈Rn\hat x \in \mathbb R^n is a least squares solution of Ax=bAx = b if

∥b−Ax^∥≤∥b−Ax∥for every x∈Rn.\lVert b - A\hat x \rVert \le \lVert b - Ax \rVert \quad \text{for every } x \in \mathbb R^n.

The vector r=b−Ax^r = b - A\hat x is the residual. Its squared length ∥r∥2=r12+⋯+rm2\lVert r \rVert^2 = r_1^2 + \dots + r_m^2 is the sum of the squared residuals. If Ax=bAx = b has an exact solution, it is a least squares solution with residual OO.

In one lineA vector x^\hat x that makes ∥b−Ax^∥\lVert b - A\hat x \rVert as small as possible, even when Ax=bAx = b has no solution.

Why it existsReal systems are overdetermined and slightly inconsistent. This says what answer to give anyway.

The first theorem is Lecture 6’s best approximation theorem, stated for the situation we need and proved again so the chapter stands on its own.

Theorem T Spagnolie Lecture 6; Apostol Thm 1.16

Perpendicular error means closest point

Let WW be a subspace of Rm\mathbb R^m, let b∈Rmb \in \mathbb R^m, and let p∈Wp \in W with (b−p)⋅w=0(b - p) \cdot w = 0 for every w∈Ww \in W. Then for every w∈Ww \in W,

∥b−w∥2=∥b−p∥2+∥p−w∥2.\lVert b - w \rVert^2 = \lVert b - p \rVert^2 + \lVert p - w \rVert^2 .

So ∥b−w∥≥∥b−p∥\lVert b - w \rVert \ge \lVert b - p \rVert, with equality only when w=pw = p.

In one lineIf pp is in a subspace WW and b−pb - p is perpendicular to all of WW, then pp is the closest point of WW to bb, and no other point of WW is as close.

Why it is trueAny other point ww of WW forms a right triangle with bb and pp, and the hypotenuse is longer than a leg.

ProofSpagnolie Lecture 6, page 2
The idea: Split the vector b - w into the part b - p, which is perpendicular to W, and the part p - w, which lies in W. Then Pythagoras applies.
b−w=(b−p)+(p−w)b - w = (b - p) + (p - w).
Add and subtract pp. This is the move from Lecture 6: the vector from ww up to bb is the vector from ww to pp followed by the vector from pp to bb.
p−w∈Wp - w \in W.
WW is a subspace, so it is closed under subtraction. Both pp and ww are in WW.
(b−p)⋅(p−w)=0(b - p) \cdot (p - w) = 0.
The hypothesis: b−pb - p is perpendicular to every vector of WW, and p−wp - w is one of them.
∥b−w∥2=∥b−p∥2+∥p−w∥2\lVert b - w \rVert^2 = \lVert b - p \rVert^2 + \lVert p - w \rVert^2.
Expand ∥u+v∥2=(u+v)⋅(u+v)=∥u∥2+2 u⋅v+∥v∥2\lVert u + v \rVert^2 = (u + v)\cdot(u + v) = \lVert u \rVert^2 + 2\,u \cdot v + \lVert v \rVert^2 with u=b−pu = b - p and v=p−wv = p - w. The middle term is the zero from the line above. This is Pythagoras.
So ∥b−w∥2≥∥b−p∥2\lVert b - w \rVert^2 \ge \lVert b - p \rVert^2, with equality only when w=pw = p.
A square is never negative, and ∥p−w∥2=0\lVert p - w \rVert^2 = 0 only when p−w=Op - w = O.
Proof workshopGive the reason for each line: the perpendicular error is the shortest

Each line of the proof is shown in order. Choose the reason that justifies it, then press Check.

  1. b−w=(b−p)+(p−w)b - w = (b - p) + (p - w)
  2. p−w∈Wp - w \in W
  3. (b−p)⋅(p−w)=0(b - p) \cdot (p - w) = 0
  4. ∥b−w∥2=∥b−p∥2+2 (b−p)⋅(p−w)+∥p−w∥2=∥b−p∥2+∥p−w∥2\lVert b - w \rVert^2 = \lVert b - p \rVert^2 + 2\,(b - p)\cdot(p - w) + \lVert p - w \rVert^2 = \lVert b - p \rVert^2 + \lVert p - w \rVert^2
  5. ∥b−w∥2≥∥b−p∥2\lVert b - w \rVert^2 \ge \lVert b - p \rVert^2, with equality only if w=pw = p
Why· The picture behind the proof

Here is the proof as a picture, with WW the line through uu. Think of the arrow vv as our bb and drag it anywhere. The green arrow is pp, and the red dashed segment is b−pb - p, at a right angle to the line. The orange point is some other point ww of the line; slide it with the slider. The orange dashed segment is b−wb - w, the hypotenuse of a right triangle whose legs are the red segment (b−pb - p) and the stretch of the line between pp and ww (p−wp - w). That is the Pythagoras step of the proof, and the hypotenuse is always longer than the red leg.

Quick checkWhat tells you that a point pp of a subspace WW is the closest point of WW to bb?

The theorem is about points of a subspace WW. Our subspace is the column space of AA, and the points of it are the vectors AxAx. Now we translate “the error is perpendicular to the column space” into a matrix equation.

Definition B

Normal equations

The normal equations for Ax=bAx = b are

ATA x=ATb.A^{\mathsf T}A\,x = A^{\mathsf T}b .

Here ATAA^{\mathsf T}A is n×nn \times n and ATbA^{\mathsf T}b is in Rn\mathbb R^n. (‘Normal’ is the old word for perpendicular.)

In one lineThe square system ATA x=ATbA^{\mathsf T}A\,x = A^{\mathsf T}b. Its solutions are exactly the least squares solutions of Ax=bAx = b.

Why it existsIt turns 'the residual is perpendicular to every column' into an ordinary linear system with as many equations as unknowns, which elimination can solve.

Theorem B Strang 4.3; Axler 6C

Least squares solutions solve the normal equations

For x^∈Rn\hat x \in \mathbb R^n and r=b−Ax^r = b - A\hat x, the following are equivalent:

  1. x^\hat x is a least squares solution of Ax=bAx = b;
  2. ATr=OA^{\mathsf T}r = O, that is, aj⋅r=0a_j \cdot r = 0 for every column aja_j;
  3. ATA x^=ATbA^{\mathsf T}A\,\hat x = A^{\mathsf T}b.

Moreover, for every xx, ∥b−Ax∥2=∥r∥2+∥Ax^−Ax∥2\lVert b - Ax \rVert^2 = \lVert r \rVert^2 + \lVert A\hat x - Ax \rVert^2 whenever (2) holds.

In one linex^\hat x is a least squares solution of Ax=bAx = b exactly when ATA x^=ATbA^{\mathsf T}A\,\hat x = A^{\mathsf T}b, which says the residual is perpendicular to every column of AA.

Why it is trueMoving x^\hat x along a column changes the residual along that column. If the residual is not perpendicular to a column you can shrink it by moving that way, and if it is perpendicular to all of them the previous theorem says you are done.

ProofStrang 4.3
The idea: (2) and (3) are the same line of algebra. To show (2) implies (1), use the previous theorem with W the column space. To show (1) implies (2), suppose the residual is NOT perpendicular to some column and slide along that column to make it shorter, which contradicts (1).
(2) and (3) are equivalent.
Expand ATr=AT(b−Ax^)=ATb−ATAx^A^{\mathsf T}r = A^{\mathsf T}(b - A\hat x) = A^{\mathsf T}b - A^{\mathsf T}A\hat x. This is zero exactly when (3) holds.
Then r⋅(Ax)=∑jxj (aj⋅r)=0r \cdot (Ax) = \sum_j x_j\,(a_j \cdot r) = 0 for every xx: the residual is perpendicular to the whole column space.
Suppose (2). Any vector in the column space is Ax=∑xjajAx = \sum x_j a_j, and dot products distribute over sums.
So ∥b−Ax∥2=∥r∥2+∥Ax^−Ax∥2≥∥r∥2\lVert b - Ax \rVert^2 = \lVert r \rVert^2 + \lVert A\hat x - Ax \rVert^2 \ge \lVert r \rVert^2 for every xx. This proves (2) implies (1), and the ‘moreover’ formula.
Apply the previous theorem with WW the column space, p=Ax^p = A\hat x (which is in WW), and w=Axw = Ax. Here b−p=rb - p = r.
Fix jj with aj⋅r≠0a_j \cdot r \ne 0. For a number tt, the residual at x^+tej\hat x + t e_j is r−tajr - t a_j.
Now suppose (1) holds but (2) fails. Then some column has aj⋅r≠0a_j \cdot r \ne 0. We will move x^\hat x along that column. The new vector x^+tej\hat x + t e_j (with eje_j the jj-th standard basis vector) has residual b−Ax^−taj=r−tajb - A\hat x - t a_j = r - t a_j.
∥r−taj∥2=∥r∥2−2t (aj⋅r)+t2∥aj∥2\lVert r - t a_j \rVert^2 = \lVert r \rVert^2 - 2t\,(a_j \cdot r) + t^2 \lVert a_j \rVert^2.
Expand the square as in the previous proof. The cross term is linear in tt and the last term is quadratic in tt.
Take t=aj⋅r∥aj∥2t = \dfrac{a_j \cdot r}{\lVert a_j \rVert^2}. Then ∥r−taj∥2=∥r∥2−(aj⋅r)2∥aj∥2<∥r∥2\lVert r - t a_j \rVert^2 = \lVert r \rVert^2 - \dfrac{(a_j \cdot r)^2}{\lVert a_j \rVert^2} < \lVert r \rVert^2.
Choose tt to make the right side as small as possible. Because aj⋅r≠0a_j \cdot r \ne 0 we have aj≠Oa_j \ne O, so we may divide by ∥aj∥2\lVert a_j \rVert^2.This is where the idea comes from: a downhill step along one direction. The best step is the bottom of a parabola in t.
So (1) forces aj⋅r=0a_j \cdot r = 0 for every jj, which is (2). All three are equivalent.
This contradicts (1): x^+tej\hat x + t e_j would do strictly better than x^\hat x.
Proof workshopRebuild the hard direction: a least squares solution has a residual perpendicular to every column

Tap the lines in the order a proof would write them. Each line can only use what is already above it.

    Why· The picture behind the proof

    Go back to the best-fit line picture at the top and tick “try your own line”. The two sliders cc and mm move x^\hat x along the two columns of AA: cc moves along the all-ones column and mm along the tt column. The sum of squares is smallest exactly when neither slider can improve it. That is the first half of the proof: if the residual were not perpendicular to some column, the slider for that column could still lower the total. At the best line, the residual (the vertical segments) is perpendicular to both columns, which is what the readout reports as “the best possible”. In the one-column picture above, the green arrow is the stopping place of the slider.

    Quick checkWhich of these is NOT a way of saying that x^\hat x is a least squares solution of Ax=bAx = b?
    Beyond the course: for understanding· Does a least squares solution always exist?

    Yes. The orthogonal decomposition theorem of 2.9 writes b=p+eb = p + e with pp in the column space and ee perpendicular to it. Since pp is in the column space, p=Ax^p = A\hat x for some x^\hat x, and then b−Ax^=eb - A\hat x = e is perpendicular to every column, so (2) holds. When the columns of AA are independent, the next theorem gives x^\hat x by a formula and needs no other result.

    Worked example Spagnolie Lecture 1
    Spagnolie's three equations in two unknowns: find the best xx for 3x1+x2=13x_1 + x_2 = 1, 2x1−x2=02x_1 - x_2 = 0, 4x1+7x2=24x_1 + 7x_2 = 2.

    Solution.

    1. Write the system as Ax=bAx = b. A=[312−147]A = \begin{bmatrix} 3 & 1 \\ 2 & -1 \\ 4 & 7 \end{bmatrix} and b=(1,0,2)b = (1, 0, 2). We showed at the start of the chapter that no exact solution exists, so we look for the closest point of the column space instead.
    2. Build the normal equations. ATA=[29292951]A^{\mathsf T}A = \begin{bmatrix} 29 & 29 \\ 29 & 51 \end{bmatrix} and ATb=(11,15)A^{\mathsf T}b = (11, 15). Entry (i,j)(i, j) of ATAA^{\mathsf T}A is the dot product ai⋅aja_i \cdot a_j of two columns, and entry ii of ATbA^{\mathsf T}b is ai⋅ba_i \cdot b.
    3. Solve. Subtracting the first equation 29x1+29x2=1129x_1 + 29x_2 = 11 from the second gives 22x2=422x_2 = 4, so x^2=211\hat x_2 = \tfrac2{11} and x^1=1129−211=63319\hat x_1 = \tfrac{11}{29} - \tfrac2{11} = \tfrac{63}{319}. Two equations in two unknowns. The columns are independent (a2a_2 is not a multiple of a1a_1), so the solution is unique.
    4. Find the closest point and the residual. p=Ax^=1319(247,68,658)p = A\hat x = \tfrac1{319}(247, 68, 658) and r=b−p=1319(72,−68,−20)r = b - p = \tfrac1{319}(72, -68, -20). The residual is the leftover, data minus the closest point.
    5. Check that the residual is perpendicular to both columns. a1⋅r=216−136−80319=0a_1 \cdot r = \tfrac{216 - 136 - 80}{319} = 0 and a2⋅r=72+68−140319=0a_2 \cdot r = \tfrac{72 + 68 - 140}{319} = 0. This is the defining property of the answer, and it is checked by a route independent of the solving.
    6. Measure the miss. ∥r∥2=102083192=32319≈0.100\lVert r \rVert^2 = \tfrac{10208}{319^2} = \tfrac{32}{319} \approx 0.100. The first two equations alone give (0.2,0.4)(0.2, 0.4), which misses the third by 85\tfrac85 and has squared miss 2.562.56. The least squares answer is about 25 times better by this measure.

    The step-through below shows the same computation with every product written out.

    Answer. x^=(63/319, 2/11)≈(0.197,0.182)\hat x = (63/319,\ 2/11) \approx (0.197, 0.182), with closest point p=(247,68,658)/319p = (247, 68, 658)/319 and squared error 32/31932/319.

    Worked example
    Find the point of the plane spanned by (1,1,0)(1, 1, 0) and (0,1,1)(0, 1, 1) that is closest to b=(1,2,3)b = (1, 2, 3), and the distance from bb to the plane.

    Solution.

    1. Put the spanning vectors in the columns. A=[101101]A = \begin{bmatrix} 1 & 0 \\ 1 & 1 \\ 0 & 1 \end{bmatrix}. The plane is the column space of AA, so the closest point is Ax^A\hat x for the least squares solution x^\hat x.
    2. Form the normal equations. ATA=[2112]A^{\mathsf T}A = \begin{bmatrix} 2 & 1 \\ 1 & 2 \end{bmatrix} (the dot products 2,1,22, 1, 2 of the columns) and ATb=(1+2, 2+3)=(3,5)A^{\mathsf T}b = (1 + 2,\ 2 + 3) = (3, 5). The residual must be perpendicular to both columns, which is ATA x=ATbA^{\mathsf T}A\,x = A^{\mathsf T}b.
    3. Solve. 2x1+x2=32x_1 + x_2 = 3 gives x2=3−2x1x_2 = 3 - 2x_1. Then x1+2(3−2x1)=5x_1 + 2(3 - 2x_1) = 5, so −3x1=−1-3x_1 = -1 and x1=1/3x_1 = 1/3, x2=7/3x_2 = 7/3. The columns are independent, so there is exactly one solution.
    4. Compute the closest point. p=13(1,1,0)+73(0,1,1)=(1/3, 8/3, 7/3)p = \tfrac13(1, 1, 0) + \tfrac73(0, 1, 1) = (1/3,\ 8/3,\ 7/3). Ax^A\hat x is the combination of the columns with weights x^\hat x.
    5. Find the residual and check it. r=b−p=(2/3,−2/3,2/3)r = b - p = (2/3, -2/3, 2/3). Then r⋅(1,1,0)=0r \cdot (1, 1, 0) = 0 and r⋅(0,1,1)=0r \cdot (0, 1, 1) = 0. A residual that is perpendicular to both columns confirms the arithmetic by an independent route.
    6. Read off the distance. ∥r∥=3⋅49=2/3≈1.155\lVert r \rVert = \sqrt{3 \cdot \tfrac49} = 2/\sqrt3 \approx 1.155. The distance from bb to the plane is the length of the perpendicular error.

    Answer. Closest point (1/3,8/3,7/3)(1/3, 8/3, 7/3), distance 2/32/\sqrt3.

    Worked example Spagnolie HW4 (Piazza @38)
    Prove that if x^\hat x is a least squares solution of Ax=bAx = b, with p=Ax^p = A\hat x and r=b−pr = b - p, then ∥b∥2=∥p∥2+∥r∥2\lVert b \rVert^2 = \lVert p \rVert^2 + \lVert r \rVert^2. Then show that the squared error can be computed as ∥b∥2−x^⋅(ATb)\lVert b \rVert^2 - \hat x \cdot (A^{\mathsf T}b).

    Solution.

    1. Recall what the theorem gives. The residual rr is perpendicular to every column of AA, so r⋅(Ax)=0r \cdot (Ax) = 0 for every xx. This is condition (2) of the normal equations theorem, extended from the columns to all their combinations.
    2. Apply it to x=x^x = \hat x. r⋅p=r⋅(Ax^)=0r \cdot p = r \cdot (A\hat x) = 0. The closest point pp is one of the vectors AxAx.
    3. Split bb. b=p+rb = p + r. That is the definition of the residual.
    4. Expand the squared length. ∥b∥2=(p+r)⋅(p+r)=∥p∥2+2 p⋅r+∥r∥2\lVert b \rVert^2 = (p + r)\cdot(p + r) = \lVert p \rVert^2 + 2\,p \cdot r + \lVert r \rVert^2. The dot product distributes over sums and is symmetric.
    5. Use step 2. The middle term is 00, so ∥b∥2=∥p∥2+∥r∥2\lVert b \rVert^2 = \lVert p \rVert^2 + \lVert r \rVert^2. Pythagoras: pp and rr are the two perpendicular legs.
    6. Rewrite ∥p∥2\lVert p \rVert^2. ∥p∥2=(Ax^)⋅(Ax^)=x^TATAx^=x^TATb=x^⋅(ATb)\lVert p \rVert^2 = (A\hat x)\cdot(A\hat x) = \hat x^{\mathsf T}A^{\mathsf T}A\hat x = \hat x^{\mathsf T}A^{\mathsf T}b = \hat x \cdot (A^{\mathsf T}b). (Ax^)T=x^TAT(A\hat x)^{\mathsf T} = \hat x^{\mathsf T}A^{\mathsf T}, and the normal equations replace ATAx^A^{\mathsf T}A\hat x by ATbA^{\mathsf T}b.
    7. Substitute. ∥r∥2=∥b∥2−x^⋅(ATb)\lVert r \rVert^2 = \lVert b \rVert^2 - \hat x \cdot (A^{\mathsf T}b). Solve step 5 for ∥r∥2\lVert r \rVert^2 and use step 6. This needs only numbers we already computed when solving the normal equations.

    Answer. Proved. A useful consequence: ∥r∥2=∥b∥2−∥p∥2\lVert r \rVert^2 = \lVert b \rVert^2 - \lVert p \rVert^2. Check with the first example: ∥b∥2=5\lVert b \rVert^2 = 5 and ∥p∥2=498597/101761≈4.8997\lVert p \rVert^2 = 498597/101761 \approx 4.8997, and 5−4.8997≈0.1003=32/3195 - 4.8997 \approx 0.1003 = 32/319.

    Your answerFor some data, ∥b∥2=50\lVert b \rVert^2 = 50, and the least squares solution has x^⋅(ATb)=42\hat x \cdot (A^{\mathsf T}b) = 42. What is the sum of the squared residuals?

    When is the answer a single vector? The key is a small lemma.

    Lemma B Strang 4.2

    A and A-transpose A have the same null space

    For every real m×nm \times n matrix AA, the null space of ATAA^{\mathsf T}A equals the null space of AA. (We write N(M)N(M) for the null space of a matrix MM, the set of xx with Mx=OMx = O.)

    In one lineATAx=OA^{\mathsf T}Ax = O exactly when Ax=OAx = O.

    Why it is trueMultiplying by ATA^{\mathsf T} could lose information if it sent a non-zero vector to zero, and a squared length rules that out.

    ProofStrang 4.2
    The idea: One inclusion is free. For the other, dot the equation with x itself, so that it becomes a squared length.
    Ax=OAx = O gives ATAx=ATO=OA^{\mathsf T}Ax = A^{\mathsf T}O = O. So N(A)⊆N(ATA)N(A) \subseteq N(A^{\mathsf T}A).
    If Ax=OAx = O, multiply both sides by ATA^{\mathsf T}.
    xTATAx=xTO=0x^{\mathsf T}A^{\mathsf T}Ax = x^{\mathsf T}O = 0.
    Conversely, start with ATAx=OA^{\mathsf T}Ax = O and multiply on the left by the row vector xTx^{\mathsf T}.
    ∥Ax∥2=0\lVert Ax \rVert^2 = 0.
    (Ax)T=xTAT(Ax)^{\mathsf T} = x^{\mathsf T}A^{\mathsf T}, the rule for the transpose of a product. So the left side is (Ax)T(Ax)=(Ax)⋅(Ax)(Ax)^{\mathsf T}(Ax) = (Ax)\cdot(Ax).This is the trick of the whole chapter: a matrix times its own transpose produces a squared length.
    Ax=OAx = O. So N(ATA)⊆N(A)N(A^{\mathsf T}A) \subseteq N(A), and the two sets are equal.
    The only vector of length zero is OO.
    Theorem B Strang 4.3

    Independent columns give a unique least squares solution

    (a) The columns of AA are linearly independent if and only if ATAA^{\mathsf T}A (an n×nn \times n matrix) is invertible.

    (b) If they are, Ax=bAx = b has exactly one least squares solution, x^=(ATA)−1ATb\hat x = (A^{\mathsf T}A)^{-1}A^{\mathsf T}b.

    (c) In general, the fitted vector Ax^A\hat x is the same for every least squares solution x^\hat x. Different solutions differ by a vector in the null space of AA.

    In one lineThe columns of AA are independent exactly when ATAA^{\mathsf T}A is invertible. Then the unique least squares solution is x^=(ATA)−1ATb\hat x = (A^{\mathsf T}A)^{-1}A^{\mathsf T}b.

    Why it is trueIndependent columns mean each point of the column space comes from only one xx, so the closest point has only one name.

    ProofStrang 4.3
    The idea: Independence says the null space of A is trivial. The lemma moves that statement to A-transpose A. A square matrix with trivial null space is invertible, so the normal equations can be solved by multiplying by the inverse.
    The columns are independent iff N(A)={O}N(A) = \{O\}.
    By definition (2.2), a1,…,ana_1, \dots, a_n are independent exactly when x1a1+⋯+xnan=Ox_1 a_1 + \dots + x_n a_n = O only for x=Ox = O. That sum is AxAx.
    N(A)={O}N(A) = \{O\} iff N(ATA)={O}N(A^{\mathsf T}A) = \{O\}.
    The lemma proved above.
    A square matrix MM has N(M)={O}N(M) = \{O\} iff MM is invertible. This proves (a).
    For a square matrix, trivial null space means one-to-one, which by rank–nullity (2.3) means onto, hence invertible (2.4).This is the problem in 2.3: between spaces of the same finite dimension, one-to-one and onto are the same thing.
    So x^=(ATA)−1ATb\hat x = (A^{\mathsf T}A)^{-1}A^{\mathsf T}b is the only least squares solution. (It exists because we wrote it down.)
    Part (b). If ATAA^{\mathsf T}A is invertible, the normal equations ATAx=ATbA^{\mathsf T}Ax = A^{\mathsf T}b have exactly one solution, found by multiplying both sides by the inverse. By the previous theorem the solutions of the normal equations are exactly the least squares solutions.
    ∥b−Ax^′∥2=∥b−Ax^∥2+∥Ax^−Ax^′∥2\lVert b - A\hat x' \rVert^2 = \lVert b - A\hat x \rVert^2 + \lVert A\hat x - A\hat x' \rVert^2 and both sides’ first terms are equal, so Ax^=Ax^′A\hat x = A\hat x', that is x^−x^′∈N(A)\hat x - \hat x' \in N(A).
    Part (c). If x^\hat x and x^′\hat x' are both least squares solutions, apply the 'moreover' formula of the previous theorem with x=x^′x = \hat x'. Both have the same minimum value, so the extra term must be zero.
    Quick checkThe columns of AA are dependent and bb is arbitrary. Which statement is true?

    Remember part (c). The closest point is always unique, as a point of the plane. When the columns are dependent, several vectors xx give that same point, so the point has several NAMES as AxAx. The names are what can fail to be unique.

    Worked example the picture at the top
    Fit a line y=c+mty = c + mt to the points (−1,0),(0,1),(1,1),(2,3)(-1, 0), (0, 1), (1, 1), (2, 3) by least squares.

    Solution.

    1. Write one equation per point. c+mti=yic + mt_i = y_i gives c−m=0c - m = 0, c=1c = 1, c+m=1c + m = 1, c+2m=3c + 2m = 3. The line must pass through (ti,yi)(t_i, y_i). No line passes through all four, so these four equations are inconsistent, and we look for the closest.
    2. Put them in matrix form. A=[1−1101112]A = \begin{bmatrix} 1 & -1 \\ 1 & 0 \\ 1 & 1 \\ 1 & 2 \end{bmatrix}, x=(c,m)x = (c, m), b=(0,1,1,3)b = (0, 1, 1, 3). The first column multiplies cc (all ones) and the second multiplies mm (the tt values). The column space is the set of all heights some line produces.
    3. Build the normal equations. ATA=[4226]A^{\mathsf T}A = \begin{bmatrix} 4 & 2 \\ 2 & 6 \end{bmatrix} and ATb=(5,7)A^{\mathsf T}b = (5, 7). The entries are ∑1=4\sum 1 = 4, ∑ti=2\sum t_i = 2, ∑ti2=6\sum t_i^2 = 6, ∑yi=5\sum y_i = 5 and ∑tiyi=7\sum t_iy_i = 7.
    4. Solve. 4c+2m=54c + 2m = 5 and 2c+6m=72c + 6m = 7 give m=910m = \tfrac9{10} and c=45c = \tfrac45. From the first, c=(5−2m)/4c = (5 - 2m)/4. Substituting into the second: 5+10m=145 + 10m = 14.
    5. Find the residuals and check them. The fitted heights are (−0.1,0.8,1.7,2.6)(-0.1, 0.8, 1.7, 2.6) and the residuals are (0.1,0.2,−0.7,0.4)(0.1, 0.2, -0.7, 0.4). They sum to 00 and ∑tiri=−0.1+0−0.7+0.8=0\sum t_ir_i = -0.1 + 0 - 0.7 + 0.8 = 0. The residual must be perpendicular to both columns, the all-ones column and the tt column.
    6. Measure the error. ∥r∥2=0.01+0.04+0.49+0.16=0.70\lVert r \rVert^2 = 0.01 + 0.04 + 0.49 + 0.16 = 0.70. The line y=0.5+ty = 0.5 + t has residuals ±0.5\pm0.5 with sum of squares 1.001.00, which is worse.

    The step-through below shows the same computation with every product written out.

    Answer. y=0.8+0.9ty = 0.8 + 0.9t, with sum of squared residuals 0.700.70. The same recipe fits any model that is linear in its unknowns: to fit a parabola c+mt+qt2c + mt + qt^2, add a third column holding the values ti2t_i^2 and change nothing else.

    Quick checkWhat does the least squares line minimize?
    Your answerFit a line to the points (0,0),(1,1),(2,3)(0, 0), (1, 1), (2, 3). What is the slope mm?
    Your answerThe constant model y=cy = c is fitted to the data 2,4,92, 4, 9. The model's single column is (1,1,1)(1, 1, 1). What is the least squares value of cc?
    Worked example
    Fit a parabola y = c + mt + qt² to the points (0, 0), (1, 1), (2, 2), (3, 5) by least squares.

    Solution.

    1. Choose the columns. AA has columns 1\mathbf 1, tt and t2t^2, so the rows are (1,0,0),(1,1,1),(1,2,4),(1,3,9)(1, 0, 0), (1, 1, 1), (1, 2, 4), (1, 3, 9), and b=(0,1,2,5)b = (0, 1, 2, 5). The model is linear in the unknowns c,m,qc, m, q even though it is quadratic in tt. Each unknown multiplies one column.
    2. Collect the sums. ∑1=4\sum 1 = 4, ∑t=6\sum t = 6, ∑t2=14\sum t^2 = 14, ∑t3=36\sum t^3 = 36, ∑t4=98\sum t^4 = 98, and ∑y=8\sum y = 8, ∑ty=0+1+4+15=20\sum ty = 0 + 1 + 4 + 15 = 20, ∑t2y=0+1+8+45=54\sum t^2y = 0 + 1 + 8 + 45 = 54. Entry (i,j)(i, j) of ATAA^{\mathsf T}A is the dot product of columns ii and jj, which is a sum of a power of tt.
    3. Write the normal equations. [461461436143698][cmq]=[82054]\begin{bmatrix} 4 & 6 & 14 \\ 6 & 14 & 36 \\ 14 & 36 & 98 \end{bmatrix}\begin{bmatrix} c \\ m \\ q \end{bmatrix} = \begin{bmatrix} 8 \\ 20 \\ 54 \end{bmatrix}. ATA x=ATbA^{\mathsf T}A\,x = A^{\mathsf T}b, with the sums from step 2.
    4. Solve by elimination. (c,m,q)=(0.1,0.1,0.5)(c, m, q) = (0.1, 0.1, 0.5). The columns are independent (the points have four distinct tt values), so there is exactly one solution.
    5. Check in the equations. 4(0.1)+6(0.1)+14(0.5)=84(0.1) + 6(0.1) + 14(0.5) = 8, 6(0.1)+14(0.1)+36(0.5)=206(0.1) + 14(0.1) + 36(0.5) = 20 and 14(0.1)+36(0.1)+98(0.5)=5414(0.1) + 36(0.1) + 98(0.5) = 54. Substituting back catches elimination slips.
    6. Check the residual. The fitted heights are 0.1,0.7,2.3,4.90.1, 0.7, 2.3, 4.9, so the residual is (−0.1,0.3,−0.3,0.1)(-0.1, 0.3, -0.3, 0.1). It is perpendicular to all three columns. With 1\mathbf 1: −0.1+0.3−0.3+0.1=0-0.1 + 0.3 - 0.3 + 0.1 = 0. With tt: 0.3−0.6+0.3=00.3 - 0.6 + 0.3 = 0. With t2t^2: 0.3−1.2+0.9=00.3 - 1.2 + 0.9 = 0.

    Answer. y=0.1+0.1t+0.5t2y = 0.1 + 0.1t + 0.5t^2, with sum of squared residuals 0.01+0.09+0.09+0.01=0.200.01 + 0.09 + 0.09 + 0.01 = 0.20.

    Worked example
    Fit a line through the origin, y=mty = mt, to the points (1,1),(2,3),(4,3)(1, 1), (2, 3), (4, 3).

    Solution.

    1. Write the system. There is one unknown mm, so AA is the single column (1,2,4)(1, 2, 4) and b=(1,3,3)b = (1, 3, 3). The equations are m⋅ti=yim \cdot t_i = y_i. A line through the origin has no constant term, so there is no column of ones.
    2. Form the normal equation. ATA=1+4+16=21A^{\mathsf T}A = 1 + 4 + 16 = 21 and ATb=1+6+12=19A^{\mathsf T}b = 1 + 6 + 12 = 19. With one column, the matrices are 1×11 \times 1 numbers: (t⋅t) m=t⋅y(t \cdot t)\,m = t \cdot y.
    3. Solve. m=19/21≈0.905m = 19/21 \approx 0.905. Dividing by 2121 is allowed because the column is not zero, which is what independence means for one column.
    4. Compute the residuals. r=b−m (1,2,4)=(2/21, 25/21, −13/21)r = b - m\,(1, 2, 4) = (2/21,\ 25/21,\ -13/21). Data minus fitted values.
    5. Check perpendicularity. r⋅(1,2,4)=(2+50−52)/21=0r \cdot (1, 2, 4) = (2 + 50 - 52)/21 = 0. An independent check that the arithmetic and the theory agree.
    6. Size of the error. ∥r∥2=(4+625+169)/441=38/21\lVert r \rVert^2 = (4 + 625 + 169)/441 = 38/21. Check by the shortcut ∥b∥2−x^⋅ATb=19−1921⋅19=399−36121=3821\lVert b \rVert^2 - \hat x \cdot A^{\mathsf T}b = 19 - \tfrac{19}{21}\cdot 19 = \tfrac{399 - 361}{21} = \tfrac{38}{21}, which agrees.

    Answer. y=1921ty = \tfrac{19}{21}t, with squared error 38/2138/21. This is projection of bb onto the line through (1,2,4)(1, 2, 4), the situation in the first picture.

    Worked example
    Find all least squares solutions of Ax=bAx = b when AA is the 3×23 \times 2 matrix whose two columns are both (1,1,1)(1, 1, 1), and b=(1,2,3)b = (1, 2, 3).

    Solution.

    1. Form the normal equations. ATA=[3333]A^{\mathsf T}A = \begin{bmatrix} 3 & 3 \\ 3 & 3 \end{bmatrix} and ATb=(6,6)A^{\mathsf T}b = (6, 6). The theorem says least squares solutions are exactly the solutions of these equations, whether or not the columns are independent.
    2. Notice the formula fails. det⁡ATA=9−9=0\det A^{\mathsf T}A = 9 - 9 = 0, so (ATA)−1(A^{\mathsf T}A)^{-1} does not exist. The two columns are equal, so they are dependent, and the invertibility theorem says ATAA^{\mathsf T}A is singular.
    3. Solve the system anyway. Both equations say 3x1+3x2=63x_1 + 3x_2 = 6, that is x1+x2=2x_1 + x_2 = 2. So the solutions are x^=(2−s, s)\hat x = (2 - s,\ s) for any number ss. One equation in two unknowns leaves one free variable, as in chapter 2.6.
    4. Compare the fitted vectors. Ax^=(2−s+s)(1,1,1)=(2,2,2)A\hat x = (2 - s + s)(1, 1, 1) = (2, 2, 2) for every ss. Part (c) of the theorem: the closest point is unique, only its name as AxAx is not.
    5. Check the residual. r=(1,2,3)−(2,2,2)=(−1,0,1)r = (1, 2, 3) - (2, 2, 2) = (-1, 0, 1), and r⋅(1,1,1)=0r \cdot (1, 1, 1) = 0. It is perpendicular to the (only) direction in the column space.

    Answer. x^=(2−s,s)\hat x = (2 - s, s) for every real ss; the fitted vector is (2,2,2)(2, 2, 2), the average of the data in every entry. Two copies of one feature cannot be told apart, so only their sum is determined. The solutions differ by multiples of (1,−1)(1, -1), which is in the null space of AA.

    Worked example new (ridge regression)
    Let A be any real m by n matrix, with columns possibly dependent, and let λ be a positive number. Prove that AᵀA + λI is invertible.

    Solution.

    1. Aim at the null space. Suppose (ATA+λI)x=O(A^{\mathsf T}A + \lambda I)x = O. We show x=Ox = O. A square matrix with null space {O}\{O\} is invertible, by rank–nullity (2.3), as in the uniqueness proof above.
    2. Multiply on the left by xTx^{\mathsf T}. xTATAx+λxTx=0x^{\mathsf T}A^{\mathsf T}Ax + \lambda x^{\mathsf T}x = 0. The right side stays 00. This is the trick of the chapter again: a matrix times its own transpose makes a squared length.
    3. Recognise squared lengths. ∥Ax∥2+λ∥x∥2=0\lVert Ax \rVert^2 + \lambda\lVert x \rVert^2 = 0. xTATAx=(Ax)⋅(Ax)x^{\mathsf T}A^{\mathsf T}Ax = (Ax)\cdot(Ax) and xTx=x⋅xx^{\mathsf T}x = x\cdot x.
    4. Both terms are non-negative. Both ∥Ax∥2≥0\lVert Ax \rVert^2 \ge 0 and λ∥x∥2≥0\lambda\lVert x \rVert^2 \ge 0, and they add to 00, so each is 00. This is where λ>0\lambda > 0 is used. If λ\lambda were 00, the second term would vanish for free and we could not conclude anything about xx.
    5. Conclude. λ∥x∥2=0\lambda\lVert x \rVert^2 = 0 and λ>0\lambda > 0 give ∥x∥=0\lVert x \rVert = 0, so x=Ox = O. Only the zero vector has length zero.

    Answer. ATA+λIA^{\mathsf T}A + \lambda I is invertible for every λ>0\lambda > 0, so ridge regression (ATA+λI)x=ATb(A^{\mathsf T}A + \lambda I)x = A^{\mathsf T}b always has exactly one solution, even for dependent columns. For the two equal columns above, [3333]+λI\begin{bmatrix}3&3\\3&3\end{bmatrix} + \lambda I has determinant (3+λ)2−9=λ(6+λ)≠0(3 + \lambda)^2 - 9 = \lambda(6 + \lambda) \ne 0.

    Your answerA single column a=(1,2,2)a = (1, 2, 2) and b=(1,1,1)b = (1, 1, 1) are given. Solve the ridge equation (aTa+λ) x=aTb(a^{\mathsf T}a + \lambda)\,x = a^{\mathsf T}b with λ=1\lambda = 1. What is xx?
    Worked example
    Prove that the least squares line y=c+mty = c + mt through NN data points passes through the point (tˉ,yˉ)(\bar t, \bar y) of the averages.

    Solution.

    1. Name the pieces. AA has two columns: the all-ones vector 1=(1,…,1)\mathbf 1 = (1, \dots, 1) and the vector of the tit_i. The residual is ri=yi−c−mtir_i = y_i - c - mt_i. The residual of the best fit is data minus fitted line, point by point.
    2. Use perpendicularity to the first column. 1⋅r=0\mathbf 1 \cdot r = 0, so ∑iri=0\sum_i r_i = 0. By the normal equations theorem, rr is perpendicular to every column of AA, and this column is 1\mathbf 1.
    3. Substitute the formula for rir_i. 0=∑i(yi−c−mti)=∑iyi−Nc−m∑iti0 = \sum_i (y_i - c - mt_i) = \sum_i y_i - Nc - m\sum_i t_i. Sums split term by term, and ∑ic=Nc\sum_i c = Nc because cc does not depend on ii.
    4. Divide by NN. 0=yˉ−c−mtˉ0 = \bar y - c - m\bar t, that is yˉ=c+mtˉ\bar y = c + m\bar t. ∑iyi/N=yˉ\sum_i y_i / N = \bar y and ∑iti/N=tˉ\sum_i t_i / N = \bar t by the definition of an average.
    5. Read the result. The point (tˉ,yˉ)(\bar t, \bar y) satisfies the line’s equation. That is what “the line passes through the point” means.

    Answer. Proved. Check with the line fit above: tˉ=0.5\bar t = 0.5, yˉ=1.25\bar y = 1.25 and 0.8+0.9⋅0.5=1.250.8 + 0.9 \cdot 0.5 = 1.25. The same proof shows that the residuals sum to zero whenever the model has a constant term.

    The projection matrix

    Part (b) gives the closest point Ax^=A(ATA)−1ATbA\hat x = A(A^{\mathsf T}A)^{-1}A^{\mathsf T}b. Look at how it depends on bb: the vector bb is multiplied on the left by a fixed matrix that depends only on AA. That matrix is worth a name.

    Definition B

    Projection matrix

    If AA has independent columns, the projection matrix onto its column space is

    P=A (ATA)−1AT.P = A\,(A^{\mathsf T}A)^{-1}A^{\mathsf T}.

    It is m×mm \times m. In statistics it is called the hat matrix, because it puts a hat on yy: the fitted values are y^=Py\hat y = Py.

    In one lineThe matrix P=A(ATA)−1ATP = A(A^{\mathsf T}A)^{-1}A^{\mathsf T} that sends every bb to the closest point of the column space of AA.

    Why it existsIt does the whole job at once: feed it any bb and it returns the fitted values, without solving a new system.

    Theorem B Strang 4.2; Axler 6C

    The projection matrix projects

    Let AA have independent columns and P=A(ATA)−1ATP = A(A^{\mathsf T}A)^{-1}A^{\mathsf T}. Then:

    1. Pb=Ax^Pb = A\hat x, the projection of bb onto the column space of AA;
    2. Pv=vPv = v for every vv in the column space;
    3. P2=PP^2 = P;
    4. PT=PP^{\mathsf T} = P;
    5. (I−P)b=b−Pb(I - P)b = b - Pb is the residual, perpendicular to every column, so AT(I−P)=OA^{\mathsf T}(I - P) = O.

    In one linePbPb is the closest point of the column space to bb, P2=PP^2 = P and PT=PP^{\mathsf T} = P.

    Why it is trueProjecting a second time must change nothing, because the first projection already landed on the plane.

    ProofStrang 4.2
    The idea: Everything is algebra on the one expression A(A-transpose A)^{-1}A-transpose, plus the fact that the middle factor cancels against A-transpose A when it meets it.
    (1) Pb=A(ATA)−1ATb=Ax^Pb = A(A^{\mathsf T}A)^{-1}A^{\mathsf T}b = A\hat x.
    Substitute the formula x^=(ATA)−1ATb\hat x = (A^{\mathsf T}A)^{-1}A^{\mathsf T}b from the previous theorem.
    (2) Pv=A(ATA)−1ATAx=A I x=Ax=vPv = A(A^{\mathsf T}A)^{-1}A^{\mathsf T}Ax = A\,I\,x = Ax = v.
    A vector in the column space is v=Axv = Ax for some xx. Then the middle factors cancel: (ATA)−1ATA=I(A^{\mathsf T}A)^{-1}A^{\mathsf T}A = I.
    (3) P2b=P(Pb)=PbP^2 b = P(Pb) = Pb for every bb, so P2=PP^2 = P.
    PbPb is in the column space by (1), so apply (2) to the vector PbPb. This is also the geometric reason: a point already on the plane is its own shadow.
    (4) PT=(AT)T((ATA)−1)TAT=A (ATA)−1AT=PP^{\mathsf T} = (A^{\mathsf T})^{\mathsf T}\big((A^{\mathsf T}A)^{-1}\big)^{\mathsf T}A^{\mathsf T} = A\,(A^{\mathsf T}A)^{-1}A^{\mathsf T} = P, since ATAA^{\mathsf T}A is its own transpose.
    Transpose reverses the order of a product: (XYZ)T=ZTYTXT(XYZ)^{\mathsf T} = Z^{\mathsf T}Y^{\mathsf T}X^{\mathsf T}. The transpose of an inverse is the inverse of the transpose. And (ATA)T=ATA(A^{\mathsf T}A)^{\mathsf T} = A^{\mathsf T}A.
    (5) AT(I−P)=AT−ATA(ATA)−1AT=AT−AT=OA^{\mathsf T}(I - P) = A^{\mathsf T} - A^{\mathsf T}A(A^{\mathsf T}A)^{-1}A^{\mathsf T} = A^{\mathsf T} - A^{\mathsf T} = O.
    Multiply out, using the cancellation ATA(ATA)−1=IA^{\mathsf T}A(A^{\mathsf T}A)^{-1} = I.
    Quick checkPP is the 5×55 \times 5 projection matrix onto a 2-dimensional column space. Is PP invertible?

    A matrix with P2=PP^2 = P is called idempotent, and one with PT=PP^{\mathsf T} = P is symmetric. Properties 3 and 4 together (idempotent and symmetric) characterize orthogonal projections. A problem below proves the converse.

    Why· The picture behind the proof

    Look at the first picture of the chapter, the line through uu. The shadow pp is PvPv. Property 2 and property 3 say: if you take the shadow of a point that is already on the line (the green arrow), it stays where it is, so projecting twice is the same as once. Property 5 is the red dashed arrow: whatever the shadow leaves behind, v−pv - p, meets the line at a right angle, and AT(I−P)=OA^{\mathsf T}(I - P) = O says exactly that.

    The projection matrix for the line-fit data. For the AA of the line-fit example,

    P=110[741−243211234−2147].P = \frac{1}{10}\begin{bmatrix} 7 & 4 & 1 & -2 \\ 4 & 3 & 2 & 1 \\ 1 & 2 & 3 & 4 \\ -2 & 1 & 4 & 7 \end{bmatrix}.

    Applying it to b=(0,1,1,3)b = (0, 1, 1, 3) gives Pb=(−0.1,0.8,1.7,2.6)Pb = (-0.1, 0.8, 1.7, 2.6), the fitted heights, in one step. Its diagonal is 0.7,0.3,0.3,0.70.7, 0.3, 0.3, 0.7, which sums to 22, the number of columns. (That sum of the diagonal entries is the trace. It is no accident: the trace of PP always equals the number of independent columns. The proof uses tr⁡(XY)=tr⁡(YX)\operatorname{tr}(XY) = \operatorname{tr}(YX), which holds because both equal ∑i,jXijYji\sum_{i,j} X_{ij}Y_{ji}. Then tr⁡P=tr⁡((ATA)−1ATA)=tr⁡In=n\operatorname{tr}P = \operatorname{tr}\big((A^{\mathsf T}A)^{-1}A^{\mathsf T}A\big) = \operatorname{tr}I_n = n.) The big diagonal entries at the two end points say those points have the most pull on the line, their “leverage”. Move one of them and the line follows.

    Worked example
    Let PP be a projection matrix (so P2=PP^2 = P and PT=PP^{\mathsf T} = P). Prove that I−PI - P is also symmetric and idempotent, that (I−P)P=O(I - P)P = O, and that every diagonal entry of PP satisfies 0≤Pii≤10 \le P_{ii} \le 1.

    Solution.

    1. Symmetry of I−PI - P. (I−P)T=IT−PT=I−P(I - P)^{\mathsf T} = I^{\mathsf T} - P^{\mathsf T} = I - P. The transpose of a difference is the difference of transposes, and II and PP are both symmetric.
    2. Idempotence of I−PI - P. (I−P)2=I−2P+P2=I−2P+P=I−P(I - P)^2 = I - 2P + P^2 = I - 2P + P = I - P. Multiply out (matrices commute with II and with themselves), then use P2=PP^2 = P.
    3. Killing what PP keeps. (I−P)P=P−P2=P−P=O(I - P)P = P - P^2 = P - P = O. PP lands in the plane and I−PI - P removes exactly the plane’s part, so applying I−PI - P after PP leaves nothing.
    4. A formula for the diagonal. P=P2=PTPP = P^2 = P^{\mathsf T}P, so PiiP_{ii} is the dot product of column ii of PP with itself: Pii=∑kPki2P_{ii} = \sum_k P_{ki}^2. Entry (i,i)(i, i) of PTPP^{\mathsf T}P multiplies row ii of PTP^{\mathsf T}, which is column ii of PP, by column ii of PP.
    5. Non-negativity. A sum of squares is at least 00, so Pii≥0P_{ii} \ge 0. Squares of real numbers are never negative.
    6. The upper bound. The term k=ik = i of the sum is Pii2P_{ii}^2 and the other terms are at least 00, so Pii≥Pii2P_{ii} \ge P_{ii}^2. If Pii>0P_{ii} > 0, dividing by it gives 1≥Pii1 \ge P_{ii}. If Pii=0P_{ii} = 0 the bound holds already. Dropping non-negative terms can only make a sum smaller.

    Answer. Proved. Check with the line-fit PP: P11=0.49+0.16+0.01+0.04=0.70P_{11} = 0.49 + 0.16 + 0.01 + 0.04 = 0.70, the sum of the squares of column 1, and 0≤0.7≤10 \le 0.7 \le 1.

    Your answerAA is a 10×310 \times 3 matrix with independent columns and PP is its projection matrix. What is the trace of PP (the sum of its diagonal entries)?
    Worked example Axler 6C
    A is a 5 by 2 matrix with independent columns and P is its projection matrix. Give the sizes of AᵀA, Aᵀb and P, the rank of P, and say whether P is invertible. Then prove that for any symmetric idempotent matrix P, b − Pb is perpendicular to the range of P.

    Solution.

    1. Sizes. ATAA^{\mathsf T}A is 2×22 \times 2, ATbA^{\mathsf T}b is a vector in R2\mathbb R^2 and P=A(ATA)−1ATP = A(A^{\mathsf T}A)^{-1}A^{\mathsf T} is 5×55 \times 5. The product of sizes (5×2)(2×2)(2×5)(5 \times 2)(2 \times 2)(2 \times 5) is 5×55 \times 5. The normal equations always have as many unknowns as columns.
    2. Rank. Every output PbPb lies in the column space of AA, and every vector of the column space is fixed by PP, so it is an output. The range of PP is the column space, of dimension 22, so rank⁡P=2\operatorname{rank}P = 2. Property (2) of the projection matrix theorem says Pv=vPv = v for vv in the column space.
    3. Invertibility. PP is 5×55 \times 5 of rank 22, so it is not invertible. An invertible 5×55 \times 5 matrix has rank 55 (2.4). The part of bb perpendicular to the plane is lost and cannot be recovered.
    4. The proof: pick a vector in the range. Any vector in the range of PP is PzPz for some zz. That is what “range” means.
    5. Compute the two inner products. (Pb)⋅(Pz)=bTPTPz=bTP2z=bTPz(Pb)\cdot(Pz) = b^{\mathsf T}P^{\mathsf T}Pz = b^{\mathsf T}P^2z = b^{\mathsf T}Pz, and b⋅(Pz)=bTPzb\cdot(Pz) = b^{\mathsf T}Pz. First PT=PP^{\mathsf T} = P, then P2=PP^2 = P.
    6. Subtract. (b−Pb)⋅(Pz)=bTPz−bTPz=0(b - Pb)\cdot(Pz) = b^{\mathsf T}Pz - b^{\mathsf T}Pz = 0. Both inner products from step 5 are the same number.
    7. Conclude. By the first theorem of the chapter, with WW the range of PP and p=Pbp = Pb (which lies in WW), PbPb is the closest point of WW to bb. Perpendicular error means closest point.

    Answer. Sizes 2×22 \times 2, R2\mathbb R^2 and 5×55 \times 5; rank 22; not invertible. And any symmetric idempotent matrix is the orthogonal projection onto its range.

    QR: how computers do it (B)

    The formula x^=(ATA)−1ATb\hat x = (A^{\mathsf T}A)^{-1}A^{\mathsf T}b is perfect on paper and risky in a computer. Forming ATAA^{\mathsf T}A squares the “difficulty” of the problem. The condition number of a matrix measures how much a tiny error in the input can be magnified in the output. For the standard condition number (the biggest stretching the matrix does divided by the smallest), cond⁡(ATA)=cond⁡(A)2\operatorname{cond}(A^{\mathsf T}A) = \operatorname{cond}(A)^2 when the columns of AA are independent. We state this fact without proof. A concrete failure shows the damage.

    Take ε=10−8\varepsilon = 10^{-8} and A=[11ε00ε]A = \begin{bmatrix} 1 & 1 \\ \varepsilon & 0 \\ 0 & \varepsilon \end{bmatrix}. Its columns are independent. In exact arithmetic,

    ATA=[1+ε2111+ε2].A^{\mathsf T}A = \begin{bmatrix} 1 + \varepsilon^2 & 1 \\ 1 & 1 + \varepsilon^2 \end{bmatrix}.

    But ε2=10−16\varepsilon^2 = 10^{-16} is below the rounding resolution of double-precision numbers, so the computer stores 1+10−161 + 10^{-16} as exactly 11. The stored matrix is [1111]\begin{bmatrix} 1 & 1 \\ 1 & 1 \end{bmatrix}, which is singular. The normal equations cannot be solved, although the original problem is perfectly fine. (Numerical analysts call this the Läuchli example. Running numpy’s solve on A.T @ A reports a singular matrix here, while numpy.linalg.lstsq(A, b) and the QR method below give the right answer.)

    The fix is to use the Gram–Schmidt process from 2.9 on the columns of AA and never form ATAA^{\mathsf T}A.

    Theorem B Strang 4.4

    QR from Gram–Schmidt

    Let AA be m×nm \times n with independent columns a1,…,ana_1, \dots, a_n. Gram–Schmidt produces orthonormal vectors q1,…,qnq_1, \dots, q_n with span⁡(q1,…,qj)=span⁡(a1,…,aj)\operatorname{span}(q_1, \dots, q_j) = \operatorname{span}(a_1, \dots, a_j) for each jj. Let QQ be the m×nm \times n matrix with columns qjq_j. Then there is an upper triangular n×nn \times n matrix RR with nonzero diagonal entries such that A=QRA = QR. Consequently QTQ=IQ^{\mathsf T}Q = I, ATA=RTRA^{\mathsf T}A = R^{\mathsf T}R, the least squares solution satisfies Rx^=QTbR\hat x = Q^{\mathsf T}b, and the projection matrix is P=QQTP = QQ^{\mathsf T}.

    In one lineA matrix AA with independent columns factors as A=QRA = QR: QQ has orthonormal columns and RR is square, upper triangular and invertible. Then x^\hat x solves Rx^=QTbR\hat x = Q^{\mathsf T}b and P=QQTP = QQ^{\mathsf T}.

    Why it is trueGram–Schmidt rewrites each column as a combination of earlier orthonormal vectors. Writing that down column by column is a matrix product, and orthonormal columns make the normal equations collapse.

    ProofStrang 4.4
    The idea: Column j of A lies in the span of the first j of the q's, so it is a combination of only those. The coefficients are dot products. Stack them into R.
    aj=R1jq1+R2jq2+⋯+Rjjqja_j = R_{1j}q_1 + R_{2j}q_2 + \dots + R_{jj}q_j for some numbers RijR_{ij}.
    Gram–Schmidt (2.9) gives span⁡(q1,…,qj)=span⁡(a1,…,aj)\operatorname{span}(q_1, \dots, q_j) = \operatorname{span}(a_1, \dots, a_j), so aja_j is in the span of q1,…,qjq_1, \dots, q_j.
    Rij=qi⋅ajR_{ij} = q_i \cdot a_j for i≤ji \le j. Put Rij=0R_{ij} = 0 for i>ji > j.
    Dot both sides with qiq_i for i≤ji \le j. The qq's are orthonormal, so qi⋅qkq_i \cdot q_k is 11 if i=ki = k and 00 otherwise, and every term but one vanishes.This is the Lecture 6 formula: coefficients along an orthonormal set are dot products.
    So A=QRA = QR, and RR is upper triangular.
    Column jj of the product QRQR is ∑iRijqi\sum_i R_{ij}q_i, the combination written in step 1.
    Every Rjj≠0R_{jj} \ne 0. A triangular matrix has determinant equal to the product of its diagonal (2.7), which is non-zero, so RR is invertible.
    If Rjj=0R_{jj} = 0, then aja_j would be in span⁡(q1,…,qj−1)=span⁡(a1,…,aj−1)\operatorname{span}(q_1, \dots, q_{j-1}) = \operatorname{span}(a_1, \dots, a_{j-1}), contradicting independence.
    QTQ=IQ^{\mathsf T}Q = I.
    Entry (i,k)(i, k) of QTQQ^{\mathsf T}Q is qi⋅qkq_i \cdot q_k.
    The normal equations read RTR x^=RTQTbR^{\mathsf T}R\,\hat x = R^{\mathsf T}Q^{\mathsf T}b.
    AT=RTQTA^{\mathsf T} = R^{\mathsf T}Q^{\mathsf T}, so ATA=RTQTQR=RTRA^{\mathsf T}A = R^{\mathsf T}Q^{\mathsf T}QR = R^{\mathsf T}R and ATb=RTQTbA^{\mathsf T}b = R^{\mathsf T}Q^{\mathsf T}b. The normal equations become RTRx^=RTQTbR^{\mathsf T}R\hat x = R^{\mathsf T}Q^{\mathsf T}b.
    Rx^=QTbR\hat x = Q^{\mathsf T}b.
    RTR^{\mathsf T} is invertible because RR is. Multiply both sides by (RT)−1(R^{\mathsf T})^{-1}. Since RR is triangular, solving this is back-substitution: the last equation has one unknown, and so on upward.
    P=QR (RTR)−1RTQT=QR R−1(RT)−1RTQT=QQTP = QR\,(R^{\mathsf T}R)^{-1}R^{\mathsf T}Q^{\mathsf T} = QR\,R^{-1}(R^{\mathsf T})^{-1}R^{\mathsf T}Q^{\mathsf T} = QQ^{\mathsf T}.
    Substitute A=QRA = QR and ATA=RTRA^{\mathsf T}A = R^{\mathsf T}R into the formula for PP. Then RR−1=IR R^{-1} = I and (RT)−1RT=I(R^{\mathsf T})^{-1}R^{\mathsf T} = I.

    The last line is Lecture 6’s formula in matrix form: Pb=QQTb=∑i(qi⋅b) qiPb = QQ^{\mathsf T}b = \sum_i (q_i \cdot b)\,q_i. The projection onto a subspace with an orthonormal basis is the sum of the shadows on each basis vector. In the picture: each (qi⋅b) qi(q_i \cdot b)\,q_i is a shadow like the green arrow in the projection visualizer, and because the qiq_i are perpendicular to each other, the shadows do not interfere and add up. Real libraries compute the factorization with Householder reflections, which are more stable than Gram–Schmidt, and numpy.linalg.lstsq uses the SVD. The idea is the same: work with orthonormal columns so the problem never gets worse.

    Python labFit a line to noisy data with the normal equations
    import numpy as np
    import matplotlib.pyplot as plt
    
    rng = np.random.default_rng(0)
    x = np.linspace(0, 10, 25)
    y = 2.0 + 0.7 * x + rng.normal(0, 1.0, x.size)    # a true line plus noise
    
    A = np.column_stack([np.ones_like(x), x])          # columns: 1 and x
    c = np.linalg.solve(A.T @ A, A.T @ y)              # the normal equations
    print("intercept, slope:", np.round(c, 4))
    print("numpy's lstsq agrees:", np.round(np.linalg.lstsq(A, y, rcond=None)[0], 4))
    
    r = y - A @ c                                      # the residual (error) vector
    print("A^T r =", np.round(A.T @ r, 10))
    
    plt.figure(figsize=(6, 3.5))
    plt.scatter(x, y, s=14, label="data")
    plt.plot(x, A @ c, color="C3", label="least squares line")
    plt.legend(); plt.title("Line of best fit")

    Try this. The last line printed is ATrA^{\mathsf T}r, the residual dotted with each column: it is zero, which is the perpendicularity the whole chapter rests on. Now fit a parabola: add the column x**2 to A (and change the plot to a smooth curve), or change the noise from 1.0 to 5.0 and watch the fitted slope drift from the true 0.70.7.

    Examples and non-examples

    The worked examples sit beside the ideas they practise, above. Here are three more checks.

    Check with a formula from statistics. The slope should equal ∑(ti−tˉ)(yi−yˉ)∑(ti−tˉ)2\dfrac{\sum (t_i - \bar t)(y_i - \bar y)}{\sum (t_i - \bar t)^2} where tˉ=0.5\bar t = 0.5 and yˉ=1.25\bar y = 1.25 are the averages. The top is ∑tiyi−4tˉyˉ=7−2.5=4.5\sum t_iy_i - 4\bar t \bar y = 7 - 2.5 = 4.5 and the bottom is ∑ti2−4tˉ2=6−1=5\sum t_i^2 - 4\bar t^2 = 6 - 1 = 5, so the slope is 0.90.9. This is “covariance over variance”, and it agrees with the normal equations.

    The same line by QR, with no ATAA^{\mathsf T}A.

    An exact fit. If bb happens to be in the column space, the closest point is bb itself and the residual is OO. For example, the points (−1,1),(0,0),(1,1)(-1, 1), (0, 0), (1, 1) lie exactly on y=t2y = t^2. Fitting c+mt+qt2c + mt + qt^2 gives (c,m,q)=(0,0,1)(c, m, q) = (0, 0, 1) and zero residual. Real data with noise almost never fits a small model exactly. A model with as many columns as data points (with distinct tt values) always fits exactly, which is the danger of fitting too much.

    Where it is used

    Used inside maths· Inside maths: approximating a function, and Fourier

    The argument of this chapter never used the fact that the vectors are lists of numbers. It only needs an inner product, so it works for functions too. Spagnolie’s HW4 problem asks for the best linear approximation a+bxa + bx to exe^x on [−1,1][-1, 1] with ⟨f,g⟩=∫−11fg dx\langle f, g \rangle = \int_{-1}^{1} fg\,dx. The columns are now the functions 11 and xx, and the normal equations have entries that are integrals: ⟨1,1⟩=2\langle 1, 1 \rangle = 2, ⟨1,x⟩=0\langle 1, x \rangle = 0, ⟨x,x⟩=2/3\langle x, x \rangle = 2/3, ⟨ex,1⟩=e−1/e\langle e^x, 1 \rangle = e - 1/e and ⟨ex,x⟩=2/e\langle e^x, x \rangle = 2/e. Because ⟨1,x⟩=0\langle 1, x \rangle = 0, the two equations separate: 2a=e−1/e2a = e - 1/e and 23b=2/e\tfrac23 b = 2/e. So a=(e−1/e)/2≈1.175a = (e - 1/e)/2 \approx 1.175 and b=3/e≈1.104b = 3/e \approx 1.104. The course reached the same answer by projection and by calculus, and the calculus equations are exactly these normal equations.

    When the columns are orthonormal (the QQ of the QR section), ATA=IA^{\mathsf T}A = I and the normal equations solve themselves: x^=QTb\hat x = Q^{\mathsf T}b. For ⟨f,g⟩=∫fg\langle f, g \rangle = \int fg and the cosines and sines of Lecture 6, this is the Fourier series: each coefficient is one inner product, and the partial sums are the closest trigonometric polynomials to ff.

    Used in the real world· Linear regression in ML and statistics (CS 532)

    Predicting a house price from its area and number of bedrooms with a linear model is this chapter. Each of the mm houses is a row of AA: a 1 (for the intercept), the area, the bedrooms. The prices are bb. The weight vector x^\hat x solves ATA x^=ATbA^{\mathsf T}A\,\hat x = A^{\mathsf T}b, and the predictions are y^=Ax^=Pb\hat y = A\hat x = Pb. The matrix ATAA^{\mathsf T}A has only 3 rows and columns, even for a million houses, which is the reason the normal equations were practical long before computers were large. “Polynomial regression” adds columns for t2,t3,…t^2, t^3, \dots. The model is nonlinear in tt and still linear in the unknowns, which is all this chapter needs, and the exact-fit example with y=t2y = t^2 was one. Libraries such as scikit-learn’s LinearRegression solve it with a least squares routine (not the normal equations) for the stability reason shown above.

    When two features are nearly copies of each other (area in square feet and area in square metres), the columns are almost dependent, ATAA^{\mathsf T}A is nearly singular and the weights become huge and unstable. The standard cure is ridge regression: solve (ATA+λI)x=ATb(A^{\mathsf T}A + \lambda I)x = A^{\mathsf T}b for a small λ>0\lambda > 0. A problem below proves the matrix is always invertible. Training a neural network’s last layer with a squared-error loss, and most “closed form” fitting in the first weeks of an ML course, use exactly these equations.

    Used in the real world· GPS: a position fix from more satellites than unknowns

    A GPS receiver measures, for each visible satellite, the travel time of a radio signal. Multiplied by the speed of light, that is a distance (a “pseudorange”). There are four unknowns: the receiver’s position (x,y,z)(x, y, z) and its clock error. The clock error matters because light travels about 300 metres in one microsecond, and a cheap quartz clock in a phone is off by much more than a microsecond. Four unknowns need four satellites. A receiver in open sky often sees eight or more, so it has more equations than unknowns, and the measurements disagree slightly because of noise. Least squares settles it.

    The distance equations are not linear, so the receiver linearizes them around a guess. A two-dimensional toy version with the same mathematics: four beacons at (0,0),(10,0),(0,10),(10,10)(0,0), (10,0), (0,10), (10,10); the receiver is truly at (3,4)(3, 4) and measures distances with small errors, getting 5.10,7.86,6.86,9.175.10, 7.86, 6.86, 9.17. Guess x0=(4,4)x_0 = (4, 4). The distances from the guess to the beacons are 5.657,7.211,7.211,8.4855.657, 7.211, 7.211, 8.485. Near the guess, the distance to beacon ii changes with the position correction Δ\Delta as ui⋅Δu_i \cdot \Delta, where uiu_i is the unit vector pointing from beacon ii to the guess. That gives four equations UΔ=measured−predictedU\Delta = \text{measured} - \text{predicted} with rows uiu_i:

    [0.7070.707−0.8320.5550.555−0.832−0.707−0.707]Δ=[−0.5570.649−0.3510.685].\begin{bmatrix} 0.707 & 0.707 \\ -0.832 & 0.555 \\ 0.555 & -0.832 \\ -0.707 & -0.707 \end{bmatrix}\Delta = \begin{bmatrix} -0.557 \\ 0.649 \\ -0.351 \\ 0.685 \end{bmatrix}.

    The normal equations UTUΔ=UT(right side)U^{\mathsf T}U\Delta = U^{\mathsf T}(\text{right side}) give Δ=(−0.803,−0.082)\Delta = (-0.803, -0.082), so the new guess is (3.197,3.918)(3.197, 3.918). Repeating the step (with the unit vectors recomputed at the new guess) settles at (3.186,3.928)(3.186, 3.928), which is about 0.2 from the true (3,4)(3, 4), even though each measured distance was off by up to 0.2. (This is Gauss–Newton iteration: a least squares problem solved at every step.) A real receiver does this with a fourth column of ones for the clock error and four or more satellites.

    Used in the real world· Calibrating a sensor

    A temperature sensor outputs a number of ADC counts. To turn counts into degrees you measure it at known temperatures and fit a line. Suppose the readings at 0,25,50,100 ∘C0, 25, 50, 100\,^\circ\text{C} are 102,205,310,515102, 205, 310, 515 counts. We fit T=c+m⋅countsT = c + m \cdot \text{counts}, with the all-ones column and the counts column. The normal equations give T≈−24.73+0.2420⋅countsT \approx -24.73 + 0.2420 \cdot \text{counts}. The residuals are 0.05,0.12,−0.28,0.110.05, 0.12, -0.28, 0.11 degrees, so no calibration point is off by more than a third of a degree, and any later reading is converted with the line. Using four points for two unknowns means a single bad reading shows up as a large residual instead of silently ruining the calibration.

    Used in the real world· Hooke's law from noisy spring data

    Hooke’s law says the force of a spring is F=ksF = ks for an extension ss, with no constant term. (We call the extension ss, because xx is already our name for the unknowns.) Hang weights on a spring and measure the extensions s=0.02,0.04,0.06,0.08,0.10s = 0.02, 0.04, 0.06, 0.08, 0.10 metres against forces F=0.21,0.38,0.62,0.79,1.02F = 0.21, 0.38, 0.62, 0.79, 1.02 newtons. There is one unknown kk, so AA is the single column ss and the system ksi=Fiks_i = F_i has five equations. The normal equation is (s⋅s) k=s⋅F(s \cdot s)\,k = s \cdot F, with s⋅s=0.0220s \cdot s = 0.0220 and s⋅F=0.2218s \cdot F = 0.2218, so

    k^=0.22180.0220≈10.08 N/m.\hat k = \frac{0.2218}{0.0220} \approx 10.08\ \text{N/m}.

    This is projection onto a line, the first picture in this chapter. The residuals are 0.008,−0.023,0.015,−0.017,0.0120.008, -0.023, 0.015, -0.017, 0.012 newtons. They are perpendicular to ss (their dot product with ss is zero up to rounding), and the spring constant is close to 1010. If you also allowed an offset (fitting F=F0+ksF = F_0 + ks) you would get k≈10.15k \approx 10.15 and F0≈−0.005F_0 \approx -0.005. The offset is tiny, which supports Hooke’s law with no constant term.

    Traps

    Watch out· The line minimizes VERTICAL misses, not distance to the line

    Least squares measures the error in yy only, along the vertical segments of the picture. The perpendicular distance from a point to the line is a different quantity, and minimizing it is a different problem (total least squares). The perpendicular in our theorem is in Rm\mathbb R^m, between the whole data vector bb and the column space, not in the data plane.

    Watch out· Dependent columns: A-transpose A is singular

    The formula (ATA)−1ATb(A^{\mathsf T}A)^{-1}A^{\mathsf T}b needs independent columns. Duplicate features, a column that is the sum of others, or fewer data points than columns all break it. The fitted values are still unique (part (c)). The weights are not. In statistics this is called collinearity, and the “dummy variable trap” is one case.

    Watch out· Do not invert A-transpose A on a computer

    The formula is for understanding. The Läuchli example above has independent columns, and the computer still reports a singular matrix after forming ATAA^{\mathsf T}A. Use QR or a library least squares routine. Also, never build the m×mm \times m matrix PP for large mm: a million data points would need a million by a million matrix. Compute PbPb as Q(QTb)Q(Q^{\mathsf T}b).

    Watch out· Squaring lets one wild point steer the line

    The residuals are squared, so a point ten units off counts a hundred times as much as a point one unit off. Add a single outlier (3,10)(3, 10) to our four points and the best line changes from y=0.8+0.9ty = 0.8 + 0.9t to y=0.8+2.2ty = 0.8 + 2.2t, so the slope more than doubles. When data may contain wild values, robust methods (minimizing absolute values, for example) are used instead.

    Watch out· P squared equals P does not mean P is the identity

    A projection matrix is NOT invertible unless the column space is everything. PP throws away the part of bb perpendicular to the plane, and that information cannot be recovered. P2=PP^2 = P only says that doing it twice is the same as once.

    Watch out· Computing the size of the error (the HW4 mistake)

    In MATH 375 HW4, several problems asked for ∥f−g∥2\lVert f - g \rVert^2 where gg is the best approximation, and the long way is to square out and integrate. The short way is Pythagoras: since r⊥pr \perp p, ∥b∥2=∥p∥2+∥r∥2\lVert b \rVert^2 = \lVert p \rVert^2 + \lVert r \rVert^2, so ∥r∥2=∥b∥2−∥p∥2\lVert r \rVert^2 = \lVert b \rVert^2 - \lVert p \rVert^2. Check with the line fit: ∥b∥2=0+1+1+9=11\lVert b \rVert^2 = 0 + 1 + 1 + 9 = 11 and ∥p∥2=0.01+0.64+2.89+6.76=10.30\lVert p \rVert^2 = 0.01 + 0.64 + 2.89 + 6.76 = 10.30, and 11−10.30=0.7011 - 10.30 = 0.70, as before.

    Problems

    checkStrang 4.3, adapted

    Find the least squares solution of Ax=bAx = b for A=[101112]A = \begin{bmatrix} 1 & 0 \\ 1 & 1 \\ 1 & 2 \end{bmatrix}, b=(6,0,0)b = (6, 0, 0). Also find the closest point and the residual, and check that the residual is perpendicular to the columns.

    Solution

    ATA=[3335]A^{\mathsf T}A = \begin{bmatrix} 3 & 3 \\ 3 & 5 \end{bmatrix} and ATb=(6,0)A^{\mathsf T}b = (6, 0). The equations 3c+3m=63c + 3m = 6 and 3c+5m=03c + 5m = 0 subtract to 2m=−62m = -6, so m=−3m = -3 and c=5c = 5. The closest point is Ax^=(5,2,−1)A\hat x = (5, 2, -1) and the residual is r=(1,−2,1)r = (1, -2, 1). Check: (1,1,1)⋅r=0(1, 1, 1) \cdot r = 0 and (0,1,2)⋅r=−2+2=0(0, 1, 2) \cdot r = -2 + 2 = 0.

    check

    AA is a 5×25 \times 2 matrix with independent columns. State the sizes of ATAA^{\mathsf T}A, of ATbA^{\mathsf T}b and of PP. What is the rank of PP?

    Solution

    ATAA^{\mathsf T}A is 2×22 \times 2, ATbA^{\mathsf T}b is in R2\mathbb R^2, and PP is 5×55 \times 5. Every output PbPb is in the column space, and every vector of the column space is an output (it is fixed by PP), so the range of PP is the column space of AA, which has dimension 22. So the rank of PP is 22.

    check

    Why can the formula (ATA)−1ATb(A^{\mathsf T}A)^{-1}A^{\mathsf T}b not be used for A=[122436]A = \begin{bmatrix} 1 & 2 \\ 2 & 4 \\ 3 & 6 \end{bmatrix}?

    Solution

    The second column is twice the first, so the columns are dependent. Then ATA=[14282856]A^{\mathsf T}A = \begin{bmatrix} 14 & 28 \\ 28 & 56 \end{bmatrix} has determinant 14⋅56−28⋅28=014 \cdot 56 - 28 \cdot 28 = 0 and is not invertible, as the theorem says.

    use

    Fit a line y=c+mty = c + mt to (1,1),(2,3),(3,4)(1, 1), (2, 3), (3, 4) by least squares. What is the sum of the squared residuals?

    Solution

    A=[111213]A = \begin{bmatrix} 1 & 1 \\ 1 & 2 \\ 1 & 3 \end{bmatrix}, b=(1,3,4)b = (1, 3, 4). Then ATA=[36614]A^{\mathsf T}A = \begin{bmatrix} 3 & 6 \\ 6 & 14 \end{bmatrix} and ATb=(8,19)A^{\mathsf T}b = (8, 19). The determinant is 42−36=642 - 36 = 6. Solve 3c+6m=83c + 6m = 8 and 6c+14m=196c + 14m = 19: doubling the first gives 6c+12m=166c + 12m = 16, so 2m=32m = 3 and m=3/2m = 3/2; then c=(8−9)/3=−1/3c = (8 - 9)/3 = -1/3. The line is y=−13+32ty = -\tfrac13 + \tfrac32 t. The fitted values are 7/6,8/3,25/67/6, 8/3, 25/6, the residuals are −1/6,1/3,−1/6-1/6, 1/3, -1/6 (they sum to 00 and ∑tiri=−1/6+2/3−1/2=0\sum t_ir_i = -1/6 + 2/3 - 1/2 = 0), and the sum of squares is 136+19+136=16\tfrac1{36} + \tfrac19 + \tfrac1{36} = \tfrac16.

    use

    Fit a line through the origin, y=mty = mt, to (1,2),(2,3),(3,7)(1, 2), (2, 3), (3, 7).

    Solution

    AA is the single column (1,2,3)(1, 2, 3) and b=(2,3,7)b = (2, 3, 7). The normal equation is 14m=2+6+21=2914m = 2 + 6 + 21 = 29, so m=29/14m = 29/14. The fitted values are 29/14,29/7,87/1429/14, 29/7, 87/14, the residuals are −1/14,−8/7,11/14-1/14, -8/7, 11/14 and their dot product with (1,2,3)(1, 2, 3) is −1/14−16/7+33/14=0-1/14 - 16/7 + 33/14 = 0. The sum of squares is (1+256+121)/196=378/196=27/14(1 + 256 + 121)/196 = 378/196 = 27/14.

    use

    Find the point of the plane spanned by u=(1,0,1)u = (1, 0, 1) and v=(0,1,1)v = (0, 1, 1) that is closest to b=(1,1,1)b = (1, 1, 1), and the distance.

    Solution

    Take AA with columns u,vu, v. Then ATA=[2112]A^{\mathsf T}A = \begin{bmatrix} 2 & 1 \\ 1 & 2 \end{bmatrix} and ATb=(2,2)A^{\mathsf T}b = (2, 2). The equations 2x1+x2=22x_1 + x_2 = 2 and x1+2x2=2x_1 + 2x_2 = 2 give x1=x2=2/3x_1 = x_2 = 2/3. The closest point is 23u+23v=(2/3,2/3,4/3)\tfrac23 u + \tfrac23 v = (2/3, 2/3, 4/3), the residual is (1/3,1/3,−1/3)(1/3, 1/3, -1/3) (perpendicular to uu and vv: 1/3−1/3=01/3 - 1/3 = 0 for each), and the distance is 1/9+1/9+1/9=1/3\sqrt{1/9 + 1/9 + 1/9} = 1/\sqrt3.

    use

    Fit a parabola y=c+mt+qt2y = c + mt + qt^2 to (−1,1),(0,0),(1,2),(2,5)(-1, 1), (0, 0), (1, 2), (2, 5).

    Solution

    The columns of AA are 11, tt, t2t^2 at t=−1,0,1,2t = -1, 0, 1, 2. The sums needed are ∑1=4\sum 1 = 4, ∑t=2\sum t = 2, ∑t2=6\sum t^2 = 6, ∑t3=8\sum t^3 = 8, ∑t4=18\sum t^4 = 18, ∑y=8\sum y = 8, ∑ty=−1+0+2+10=11\sum ty = -1 + 0 + 2 + 10 = 11, ∑t2y=1+0+2+20=23\sum t^2y = 1 + 0 + 2 + 20 = 23. The normal equations are

    [4262686818][cmq]=[81123].\begin{bmatrix} 4 & 2 & 6 \\ 2 & 6 & 8 \\ 6 & 8 & 18 \end{bmatrix}\begin{bmatrix} c \\ m \\ q \end{bmatrix} = \begin{bmatrix} 8 \\ 11 \\ 23 \end{bmatrix}.

    Eliminating gives (c,m,q)=(0.3,0.4,1)(c, m, q) = (0.3, 0.4, 1). Check: 4(0.3)+2(0.4)+6=84(0.3) + 2(0.4) + 6 = 8, 2(0.3)+6(0.4)+8=112(0.3) + 6(0.4) + 8 = 11, 6(0.3)+8(0.4)+18=236(0.3) + 8(0.4) + 18 = 23. The parabola is y=0.3+0.4t+t2y = 0.3 + 0.4t + t^2, with fitted values 0.9,0.3,1.7,5.10.9, 0.3, 1.7, 5.1 and residuals 0.1,−0.3,0.3,−0.10.1, -0.3, 0.3, -0.1.

    proveHW4 shortcut

    Let x^\hat x be a least squares solution of Ax=bAx = b. Prove that ∥Ax^∥2=x^⋅(ATb)\lVert A\hat x \rVert^2 = \hat x \cdot (A^{\mathsf T}b), and hence that the sum of squared residuals is ∥b∥2−x^⋅(ATb)\lVert b \rVert^2 - \hat x \cdot (A^{\mathsf T}b).

    Solution

    Write p=Ax^p = A\hat x. Then ∥p∥2=(Ax^)⋅(Ax^)=x^TATAx^\lVert p \rVert^2 = (A\hat x)\cdot(A\hat x) = \hat x^{\mathsf T}A^{\mathsf T}A\hat x. By the normal equations ATAx^=ATbA^{\mathsf T}A\hat x = A^{\mathsf T}b, so ∥p∥2=x^TATb=x^⋅(ATb)\lVert p \rVert^2 = \hat x^{\mathsf T}A^{\mathsf T}b = \hat x \cdot (A^{\mathsf T}b). The worked example on Pythagoras gave ∥r∥2=∥b∥2−∥p∥2\lVert r \rVert^2 = \lVert b \rVert^2 - \lVert p \rVert^2, so ∥r∥2=∥b∥2−x^⋅(ATb)\lVert r \rVert^2 = \lVert b \rVert^2 - \hat x \cdot (A^{\mathsf T}b). Check with the line fit: ∥b∥2=11\lVert b \rVert^2 = 11 and x^⋅ATb=0.8⋅5+0.9⋅7=10.3\hat x \cdot A^{\mathsf T}b = 0.8 \cdot 5 + 0.9 \cdot 7 = 10.3, and 11−10.3=0.711 - 10.3 = 0.7.

    proveAxler 6C

    Let PP be an m×mm \times m matrix with P2=PP^2 = P and PT=PP^{\mathsf T} = P. Prove that for every bb, the vector b−Pbb - Pb is perpendicular to every vector in the range of PP. (So PbPb is the projection of bb onto the range of PP.)

    Solution

    A vector in the range of PP has the form PzPz. Then (Pb)⋅(Pz)=bTPTPz=bTP2z=bTPz(Pb)\cdot(Pz) = b^{\mathsf T}P^{\mathsf T}Pz = b^{\mathsf T}P^2z = b^{\mathsf T}Pz, using PT=PP^{\mathsf T} = P and then P2=PP^2 = P. And b⋅(Pz)=bTPzb \cdot (Pz) = b^{\mathsf T}Pz. So (b−Pb)⋅(Pz)=bTPz−bTPz=0(b - Pb)\cdot(Pz) = b^{\mathsf T}Pz - b^{\mathsf T}Pz = 0. By the first theorem of the chapter (with WW the range of PP and p=Pbp = Pb, which is in WW), PbPb is the closest point of WW to bb.

    prove

    You fit a plane y=c+m1t+m2sy = c + m_1 t + m_2 s to NN data points (ti,si,yi)(t_i, s_i, y_i) by least squares. Prove that the average of the fitted values equals the average of the data, and that the plane passes through the point of averages (tˉ,sˉ,yˉ)(\bar t, \bar s, \bar y).

    Solution

    The first column of AA is the all-ones vector 1\mathbf 1, and the residual r=y−Ax^r = y - A\hat x is perpendicular to it, so ∑iri=0\sum_i r_i = 0. Since ri=yi−y^ir_i = y_i - \hat y_i with y^i=c+m1ti+m2si\hat y_i = c + m_1t_i + m_2s_i, this says ∑iy^i=∑iyi\sum_i \hat y_i = \sum_i y_i, and dividing by NN gives equal averages. Also 1N∑iy^i=c+m1tˉ+m2sˉ\frac1N\sum_i \hat y_i = c + m_1\bar t + m_2\bar s (average each term), so yˉ=c+m1tˉ+m2sˉ\bar y = c + m_1\bar t + m_2\bar s, which says the plane passes through (tˉ,sˉ,yˉ)(\bar t, \bar s, \bar y).

    prove

    Let AA be any real m×nm \times n matrix (the columns may be dependent) and let λ>0\lambda > 0. Prove that ATA+λIA^{\mathsf T}A + \lambda I is invertible.

    Solution

    Suppose (ATA+λI)x=O(A^{\mathsf T}A + \lambda I)x = O. Multiply on the left by xTx^{\mathsf T}: xTATAx+λxTx=0x^{\mathsf T}A^{\mathsf T}Ax + \lambda x^{\mathsf T}x = 0, that is ∥Ax∥2+λ∥x∥2=0\lVert Ax \rVert^2 + \lambda\lVert x \rVert^2 = 0. Both terms are non-negative and λ>0\lambda > 0, so both are zero, and ∥x∥=0\lVert x \rVert = 0 gives x=Ox = O. So the null space of this square matrix is {O}\{O\}, and by the argument in the uniqueness theorem it is invertible.

    stretch

    Let P1P_1 and P2P_2 be m×mm \times m matrices that are both symmetric and idempotent and have the same range WW. Prove P1=P2P_1 = P_2. (So the orthogonal projection onto a subspace is a single, well-defined matrix.)

    Solution

    Fix bb. By the prove-problem on symmetric idempotent matrices, b−P1bb - P_1b is perpendicular to every vector of WW, and P1bP_1b is in WW because WW is the range of P1P_1. The same holds for P2P_2. By the theorem ‘Perpendicular error means closest point’, each of P1bP_1b and P2bP_2b is the unique closest point of WW to bb. A unique closest point is one point, so P1b=P2bP_1b = P_2b. This holds for every bb, so P1=P2P_1 = P_2.

    stretch

    Add one more column aa to AA, giving A′=[A∣a]A' = [A \mid a]. Prove that the smallest possible sum of squared residuals for A′A' is at most the smallest possible for AA. (More features can never raise the training error, which is why training error is a poor judge of a model.)

    Solution

    Let x^\hat x be a least squares solution for AA with minimum squared error E=∥b−Ax^∥2E = \lVert b - A\hat x \rVert^2. The vector x′=(x^,0)x' = (\hat x, 0) gives A′x′=Ax^+0⋅a=Ax^A'x' = A\hat x + 0 \cdot a = A\hat x, so it has the same squared error EE. The least squares solution for A′A' minimizes over all vectors, including this one, so its minimum is at most EE. The inequality can be strict: adding a column enlarges the column space, so there are more points to be close to.

    Summary

    • When Ax=bAx = b has no solution, ask for the xx whose AxAx is closest to bb. The set of all AxAx is the column space, so this is projection onto the column space (2.9).
    • The closest point is the one whose error r=b−Ax^r = b - A\hat x is perpendicular to the column space. Proof: Pythagoras on the triangle formed by bb, the closest point and any other point.
    • “Perpendicular to every column” is ATr=OA^{\mathsf T}r = O, which is the normal equations ATA x^=ATbA^{\mathsf T}A\,\hat x = A^{\mathsf T}b. They are equivalent to being a least squares solution.
    • ATAA^{\mathsf T}A has the same null space as AA (because xTATAx=∥Ax∥2x^{\mathsf T}A^{\mathsf T}Ax = \lVert Ax \rVert^2). So it is invertible exactly when the columns are independent, and then x^=(ATA)−1ATb\hat x = (A^{\mathsf T}A)^{-1}A^{\mathsf T}b is unique.
    • The projection matrix P=A(ATA)−1ATP = A(A^{\mathsf T}A)^{-1}A^{\mathsf T} satisfies P2=PP^2 = P, PT=PP^{\mathsf T} = P and tr⁡P=n\operatorname{tr}P = n. It sends bb to the fitted values.
    • Computers use QR, A=QRA = QR: solve Rx^=QTbR\hat x = Q^{\mathsf T}b and P=QQTP = QQ^{\mathsf T}. Forming ATAA^{\mathsf T}A squares the condition number and can destroy the problem.
    • The sum of squared errors of the best fit is ∥b∥2−∥p∥2\lVert b \rVert^2 - \lVert p \rVert^2.
    • Regression, ridge regression, GPS fixes, sensor calibration and Hooke’s law are all this one picture: a data vector, a subspace, and a perpendicular.

    Watch and read

    The same ideas explained by someone else. Use these when an explanation here does not land.

    Where this sits

    Comes from
    2.6 Systems of equations and elimination
    2.9 Inner products, orthogonality, Gram–Schmidt, projection
    Leads to
    2.11 Markov chains and PageRank
    Same idea elsewhere
    CS 532: Linear regression, ridge regression, polynomial features and the hat matrix are all this chapter. Later in CS 532 the SVD gives the most reliable way to compute the same answer and also tells you what to do when the columns are nearly dependent.
    MATH 431: If you meet covariance in 431, the slope of the regression line is the covariance of x and y divided by the variance of x. The worked example below checks that formula against the normal equations. The deeper link is that E[Y given X] is the projection of Y onto the functions of X, with E[UV] as the inner product.
    MATH 376: Fitting a model to measured data is the same problem as an overdetermined linear system. When you fit y = a cos t + b sin t to noisy readings you are solving normal equations.