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.
Quick checkA is a 3×2 matrix and x is in R2. Where does Ax live?
Ax=x1a1+x2a2 is a combination of the two columns, and each column has 3 entries. So Ax is in R3, inside the column space of A.Review: matrices as maps
Quick checkTwo vectors u,v satisfy u⋅v=0. What does that say?
The dot product is ∥u∥∥v∥cosθ, which is 0 exactly when the angle is 90∘ (or one vector is O). Parallel vectors have a dot product of largest size, not zero.Review: inner products and orthogonality
Quick checkThe columns of A are linearly independent. What is the null space of A?
Ax=x1a1+⋯+xnan, and independence says this is O only when every xi=0. So the only vector sent to O is O itself.Review: null space
The picture
Four data points sit in the plane. A line y=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,…,y4 as ONE vector b in R4. The heights that ANY line could produce at those four t values also form vectors in R4, and they fill out a plane (a 2-dimensional subspace). So fitting a line means finding the point of that plane closest to b. 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:
The first two equations force x1=1/5 and x2=2/5. The third then reads 4/5+14/5=18/5, not 2. So no x works.
Chapter 2.6 told us why: Ax=x1a1+x2a2, where a1=(3,2,4) and a2=(1,−1,7) are the columns of A. So Ax=b has a solution exactly when b is in the column space of A, the set of all combinations of the columns. Here the column space is a plane in R3, and b=(1,0,2) is not on it.
If we cannot hit b, we can at least get as close as possible. Every vector Ax lies in the plane, so we want the x for which Ax is nearest to b. The leftover b−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.
Geometry. The closest point of a plane to b is the foot of the perpendicular dropped from b. Lecture 6 proved this with Pythagoras. Pythagoras speaks in squares, so squares are the natural way to measure.
Calculus. The squared length ∥Ax−b∥2 is a smooth function of x whose gradient is 2AT(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”.
Statistics (B). If each measurement is the true value plus independent Gaussian noise, the most likely x 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 ATAx=ATb; (3) find when that equation has exactly one solution; (4) package the answer as a matrix P that drops any b onto the plane; (5) see how computers do it without ever forming ATA.
Definitions and theorems
Throughout, A is an m×n matrix of real numbers with columns a1,…,an, b is in Rm, and ∥v∥=v⋅v. Two facts about A are used all the time.
Ax=x1a1+⋯+xnan, so the column space of A is exactly {Ax:x∈Rn}.
The j-th entry of ATr is aj⋅r: row j of AT is column j of A. So ATr=O says that r is perpendicular to every column of A.
Definition B
Least squares solution
A vector x^∈Rn is a least squares solution of Ax=b if
∥b−Ax^∥≤∥b−Ax∥for every x∈Rn.
The vector r=b−Ax^ is the residual. Its squared length ∥r∥2=r12+⋯+rm2 is the sum of the squared residuals. If Ax=b has an exact solution, it is a least squares solution with residual O.
In one lineA vector x^ that makes ∥b−Ax^∥ as small as possible, even when Ax=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 TSpagnolie Lecture 6; Apostol Thm 1.16
Perpendicular error means closest point
Let W be a subspace of Rm, let b∈Rm, and let p∈W with (b−p)⋅w=0 for every w∈W. Then for every w∈W,
∥b−w∥2=∥b−p∥2+∥p−w∥2.
So ∥b−w∥≥∥b−p∥, with equality only when w=p.
In one lineIf p is in a subspace W and b−p is perpendicular to all of W, then p is the closest point of W to b, and no other point of W is as close.
Why it is trueAny other point w of W forms a right triangle with b and p, 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).
Add and subtract p. This is the move from Lecture 6: the vector from w up to b is the vector from w to p followed by the vector from p to b.
p−w∈W.
W is a subspace, so it is closed under subtraction. Both p and w are in W.
(b−p)⋅(p−w)=0.
The hypothesis: b−p is perpendicular to every vector of W, and p−w is one of them.
∥b−w∥2=∥b−p∥2+∥p−w∥2.
Expand ∥u+v∥2=(u+v)⋅(u+v)=∥u∥2+2u⋅v+∥v∥2 with u=b−p and v=p−w. The middle term is the zero from the line above. This is Pythagoras.
So ∥b−w∥2≥∥b−p∥2, with equality only when w=p.
A square is never negative, and ∥p−w∥2=0 only when p−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.
b−w=(b−p)+(p−w)
p−w∈W
(b−p)⋅(p−w)=0
∥b−w∥2=∥b−p∥2+2(b−p)⋅(p−w)+∥p−w∥2=∥b−p∥2+∥p−w∥2
∥b−w∥2≥∥b−p∥2, with equality only if w=p
Why· The picture behind the proof
Here is the proof as a picture, with W the line through u. Think of the arrow v as our b and drag it anywhere. The green arrow is p, and the red dashed segment is b−p, at a right angle to the line. The orange point is some other point w of the line; slide it with the slider. The orange dashed segment is b−w, the hypotenuse of a right triangle whose legs are the red segment (b−p) and the stretch of the line between p and w (p−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 p of a subspace W is the closest point of W to b?
That is the hypothesis of the theorem, and Pythagoras does the rest. The length of p says nothing about its distance to b: a vector of the right length can still point the wrong way.Review: the theorem above
The theorem is about points of a subspace W. Our subspace is the column space of A, and the points of it are the vectors Ax. Now we translate “the error is perpendicular to the column space” into a matrix equation.
Definition B
Normal equations
The normal equations for Ax=b are
ATAx=ATb.
Here ATA is n×n and ATb is in Rn. (‘Normal’ is the old word for perpendicular.)
In one lineThe square system ATAx=ATb. Its solutions are exactly the least squares solutions of Ax=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 BStrang 4.3; Axler 6C
Least squares solutions solve the normal equations
For x^∈Rn and r=b−Ax^, the following are equivalent:
x^ is a least squares solution of Ax=b;
ATr=O, that is, aj⋅r=0 for every column aj;
ATAx^=ATb.
Moreover, for every x, ∥b−Ax∥2=∥r∥2+∥Ax^−Ax∥2 whenever (2) holds.
In one linex^ is a least squares solution of Ax=b exactly when ATAx^=ATb, which says the residual is perpendicular to every column of A.
Why it is trueMoving 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^. This is zero exactly when (3) holds.
Then r⋅(Ax)=∑jxj(aj⋅r)=0 for every x: the residual is perpendicular to the whole column space.
Suppose (2). Any vector in the column space is Ax=∑xjaj, and dot products distribute over sums.
So ∥b−Ax∥2=∥r∥2+∥Ax^−Ax∥2≥∥r∥2 for every x. This proves (2) implies (1), and the ‘moreover’ formula.
Apply the previous theorem with W the column space, p=Ax^ (which is in W), and w=Ax. Here b−p=r.
Fix j with aj⋅r=0. For a number t, the residual at x^+tej is r−taj.
Now suppose (1) holds but (2) fails. Then some column has aj⋅r=0. We will move x^ along that column. The new vector x^+tej (with ej the j-th standard basis vector) has residual b−Ax^−taj=r−taj.
∥r−taj∥2=∥r∥2−2t(aj⋅r)+t2∥aj∥2.
Expand the square as in the previous proof. The cross term is linear in t and the last term is quadratic in t.
Take t=∥aj∥2aj⋅r. Then ∥r−taj∥2=∥r∥2−∥aj∥2(aj⋅r)2<∥r∥2.
Choose t to make the right side as small as possible. Because aj⋅r=0 we have aj=O, so we may divide by ∥aj∥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=0 for every j, which is (2). All three are equivalent.
This contradicts (1): x^+tej would do strictly better than 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.
We argue by contradiction: assume the residual is not perpendicular to a column and find a better x.
Moving x^ by t in the j-th coordinate changes Ax^ by taj.
You need the residual r and the column aj to be named before you can say how the residual changes.
Expand the squared length of a difference.
This expands the new residual, which the previous line has to introduce first.
This is the bottom of the parabola in t. It is allowed because aj=O, since aj⋅r=0.
The choice of t is made by looking at the formula for the squared length, so that formula comes first.
Substitute t. The subtracted fraction is positive because aj⋅r=0.
You can only substitute t after it has been chosen.
A strictly smaller residual than the minimum is impossible.
The contradiction needs the strict inequality from the line above.
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 c and m move x^ along the two columns of A: c moves along the all-ones column and m along the t 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^ is a least squares solution of Ax=b?
Ax^=b is a stronger statement: it holds only when b is in the column space, and then the residual is zero. A least squares solution exists even when Ax=b has no solution at all, which is the reason for the whole chapter.Review: the normal equations theorem
Beyond the course: for understanding· Does a least squares solution always exist?
Yes. The orthogonal decomposition theorem of 2.9 writes b=p+e with p in the column space and e perpendicular to it. Since p is in the column space, p=Ax^ for some x^, and then b−Ax^=e is perpendicular to every column, so (2) holds. When the columns of A are independent, the next theorem gives x^ by a formula and needs no other result.
Worked example Spagnolie Lecture 1
Spagnolie's three equations in two unknowns: find the best x for 3x1+x2=1, 2x1−x2=0, 4x1+7x2=2.
Solution.
Write the system as Ax=b.A=3241−17 and 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.
Build the normal equations.ATA=[29292951] and ATb=(11,15). Entry (i,j) of ATA is the dot product ai⋅aj of two columns, and entry i of ATb is ai⋅b.
Solve. Subtracting the first equation 29x1+29x2=11 from the second gives 22x2=4, so x^2=112 and x^1=2911−112=31963. Two equations in two unknowns. The columns are independent (a2 is not a multiple of a1), so the solution is unique.
Find the closest point and the residual.p=Ax^=3191(247,68,658) and r=b−p=3191(72,−68,−20). The residual is the leftover, data minus the closest point.
Check that the residual is perpendicular to both columns.a1⋅r=319216−136−80=0 and a2⋅r=31972+68−140=0. This is the defining property of the answer, and it is checked by a route independent of the solving.
Measure the miss.∥r∥2=319210208=31932≈0.100. The first two equations alone give (0.2,0.4), which misses the third by 58 and has squared miss 2.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), with closest point p=(247,68,658)/319 and squared error 32/319.
Worked example
Find the point of the plane spanned by (1,1,0) and (0,1,1) that is closest to b=(1,2,3), and the distance from b to the plane.
Solution.
Put the spanning vectors in the columns.A=110011. The plane is the column space of A, so the closest point is Ax^ for the least squares solution x^.
Form the normal equations.ATA=[2112] (the dot products 2,1,2 of the columns) and ATb=(1+2,2+3)=(3,5). The residual must be perpendicular to both columns, which is ATAx=ATb.
Solve.2x1+x2=3 gives x2=3−2x1. Then x1+2(3−2x1)=5, so −3x1=−1 and x1=1/3, x2=7/3. The columns are independent, so there is exactly one solution.
Compute the closest point.p=31(1,1,0)+37(0,1,1)=(1/3,8/3,7/3). Ax^ is the combination of the columns with weights x^.
Find the residual and check it.r=b−p=(2/3,−2/3,2/3). Then r⋅(1,1,0)=0 and r⋅(0,1,1)=0. A residual that is perpendicular to both columns confirms the arithmetic by an independent route.
Read off the distance.∥r∥=3⋅94=2/3≈1.155. The distance from b to the plane is the length of the perpendicular error.
Answer. Closest point (1/3,8/3,7/3), distance 2/3.
Worked example Spagnolie HW4 (Piazza @38)
Prove that if x^ is a least squares solution of Ax=b, with p=Ax^ and r=b−p, then ∥b∥2=∥p∥2+∥r∥2. Then show that the squared error can be computed as ∥b∥2−x^⋅(ATb).
Solution.
Recall what the theorem gives. The residual r is perpendicular to every column of A, so r⋅(Ax)=0 for every x. This is condition (2) of the normal equations theorem, extended from the columns to all their combinations.
Apply it to x=x^.r⋅p=r⋅(Ax^)=0. The closest point p is one of the vectors Ax.
Split b.b=p+r. That is the definition of the residual.
Expand the squared length.∥b∥2=(p+r)⋅(p+r)=∥p∥2+2p⋅r+∥r∥2. The dot product distributes over sums and is symmetric.
Use step 2. The middle term is 0, so ∥b∥2=∥p∥2+∥r∥2. Pythagoras: p and r are the two perpendicular legs.
Rewrite ∥p∥2.∥p∥2=(Ax^)⋅(Ax^)=x^TATAx^=x^TATb=x^⋅(ATb). (Ax^)T=x^TAT, and the normal equations replace ATAx^ by ATb.
Substitute.∥r∥2=∥b∥2−x^⋅(ATb). Solve step 5 for ∥r∥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. Check with the first example: ∥b∥2=5 and ∥p∥2=498597/101761≈4.8997, and 5−4.8997≈0.1003=32/319.
Your answerFor some data, ∥b∥2=50, and the least squares solution has x^⋅(ATb)=42. What is the sum of the squared residuals?
The fitted vector and the residual are perpendicular legs of a right triangle with hypotenuse b.
By the shortcut, ∥r∥2=∥b∥2−x^⋅(ATb)=50−42=8. The quantity 42 is ∥p∥2, the squared length of the fitted vector.
When is the answer a single vector? The key is a small lemma.
Lemma BStrang 4.2
A and A-transpose A have the same null space
For every real m×n matrix A, the null space of ATA equals the null space of A. (We write N(M) for the null space of a matrix M, the set of x with Mx=O.)
In one lineATAx=O exactly when Ax=O.
Why it is trueMultiplying by AT 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=O gives ATAx=ATO=O. So N(A)⊆N(ATA).
If Ax=O, multiply both sides by AT.
xTATAx=xTO=0.
Conversely, start with ATAx=O and multiply on the left by the row vector xT.
∥Ax∥2=0.
(Ax)T=xTAT, the rule for the transpose of a product. So the left side is (Ax)T(Ax)=(Ax)⋅(Ax).This is the trick of the whole chapter: a matrix times its own transpose produces a squared length.
Ax=O. So N(ATA)⊆N(A), and the two sets are equal.
The only vector of length zero is O.
Theorem BStrang 4.3
Independent columns give a unique least squares solution
(a) The columns of A are linearly independent if and only if ATA (an n×n matrix) is invertible.
(b) If they are, Ax=b has exactly one least squares solution, x^=(ATA)−1ATb.
(c) In general, the fitted vector Ax^ is the same for every least squares solution x^. Different solutions differ by a vector in the null space of A.
In one lineThe columns of A are independent exactly when ATA is invertible. Then the unique least squares solution is x^=(ATA)−1ATb.
Why it is trueIndependent columns mean each point of the column space comes from only one x, 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}.
By definition (2.2), a1,…,an are independent exactly when x1a1+⋯+xnan=O only for x=O. That sum is Ax.
N(A)={O} iff N(ATA)={O}.
The lemma proved above.
A square matrix M has N(M)={O} iff M 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 is the only least squares solution. (It exists because we wrote it down.)
Part (b). If ATA is invertible, the normal equations ATAx=ATb 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 and both sides’ first terms are equal, so Ax^=Ax^′, that is x^−x^′∈N(A).
Part (c). If x^ and x^′ are both least squares solutions, apply the 'moreover' formula of the previous theorem with x=x^′. Both have the same minimum value, so the extra term must be zero.
Quick checkThe columns of A are dependent and b is arbitrary. Which statement is true?
A closest point to b always exists, and it is unique as a point. Dependent columns mean several vectors x name that same point as Ax, so the solution is not unique. The fitted vector is unique. (Part (c).)Review: the uniqueness theorem
Remember part (c). The closest point is always unique, as a point of the plane. When the columns are dependent, several vectors x give that same point, so the point has several NAMES as Ax. The names are what can fail to be unique.
Worked example the picture at the top
Fit a line y=c+mt to the points (−1,0),(0,1),(1,1),(2,3) by least squares.
Solution.
Write one equation per point.c+mti=yi gives c−m=0, c=1, c+m=1, c+2m=3. The line must pass through (ti,yi). No line passes through all four, so these four equations are inconsistent, and we look for the closest.
Put them in matrix form.A=1111−1012, x=(c,m), b=(0,1,1,3). The first column multiplies c (all ones) and the second multiplies m (the t values). The column space is the set of all heights some line produces.
Build the normal equations.ATA=[4226] and ATb=(5,7). The entries are ∑1=4, ∑ti=2, ∑ti2=6, ∑yi=5 and ∑tiyi=7.
Solve.4c+2m=5 and 2c+6m=7 give m=109 and c=54. From the first, c=(5−2m)/4. Substituting into the second: 5+10m=14.
Find the residuals and check them. The fitted heights are (−0.1,0.8,1.7,2.6) and the residuals are (0.1,0.2,−0.7,0.4). They sum to 0 and ∑tiri=−0.1+0−0.7+0.8=0. The residual must be perpendicular to both columns, the all-ones column and the t column.
Measure the error.∥r∥2=0.01+0.04+0.49+0.16=0.70. The line y=0.5+t has residuals ±0.5 with sum of squares 1.00, which is worse.
The step-through below shows the same computation with every product written out.
Answer.y=0.8+0.9t, with sum of squared residuals 0.70. The same recipe fits any model that is linear in its unknowns: to fit a parabola c+mt+qt2, add a third column holding the values ti2 and change nothing else.
Quick checkWhat does the least squares line minimize?
The error vector lives in the space of heights, so each miss is measured straight up or down. The perpendicular distance to the line is a different problem (total least squares). The largest miss is a different problem again. And the plain sum of misses can be zero for a terrible line, because positive and negative misses cancel, which is why we square.
Your answerFit a line to the points (0,0),(1,1),(2,3). What is the slope m?
Build A with a column of ones and a column (0,1,2), then solve the 2×2 normal equations.
ATA=[3335] and ATb=(4,7). Subtracting the equations 3c+3m=4 and 3c+5m=7 gives 2m=3, so m=23 and c=−61. Check by the average rule: the line passes through (tˉ,yˉ)=(1,34), and −61+23=34.
Your answerThe constant model y=c is fitted to the data 2,4,9. The model's single column is (1,1,1). What is the least squares value of c?
With one column, the normal equation is (a⋅a)c=a⋅b.
ATA=3 and ATb=2+4+9=15, so c=15/3=5. Projection onto the all-ones column gives the average of the data.
Worked example
Fit a parabola y = c + mt + qt² to the points (0, 0), (1, 1), (2, 2), (3, 5) by least squares.
Solution.
Choose the columns.A has columns 1, t and t2, so the rows are (1,0,0),(1,1,1),(1,2,4),(1,3,9), and b=(0,1,2,5). The model is linear in the unknowns c,m,q even though it is quadratic in t. Each unknown multiplies one column.
Collect the sums.∑1=4, ∑t=6, ∑t2=14, ∑t3=36, ∑t4=98, and ∑y=8, ∑ty=0+1+4+15=20, ∑t2y=0+1+8+45=54. Entry (i,j) of ATA is the dot product of columns i and j, which is a sum of a power of t.
Write the normal equations.461461436143698cmq=82054. ATAx=ATb, with the sums from step 2.
Solve by elimination.(c,m,q)=(0.1,0.1,0.5). The columns are independent (the points have four distinct t values), so there is exactly one solution.
Check in the equations.4(0.1)+6(0.1)+14(0.5)=8, 6(0.1)+14(0.1)+36(0.5)=20 and 14(0.1)+36(0.1)+98(0.5)=54. Substituting back catches elimination slips.
Check the residual. The fitted heights are 0.1,0.7,2.3,4.9, so the residual is (−0.1,0.3,−0.3,0.1). It is perpendicular to all three columns. With 1: −0.1+0.3−0.3+0.1=0. With t: 0.3−0.6+0.3=0. With t2: 0.3−1.2+0.9=0.
Answer.y=0.1+0.1t+0.5t2, with sum of squared residuals 0.01+0.09+0.09+0.01=0.20.
Worked example
Fit a line through the origin, y=mt, to the points (1,1),(2,3),(4,3).
Solution.
Write the system. There is one unknown m, so A is the single column (1,2,4) and b=(1,3,3). The equations are m⋅ti=yi. A line through the origin has no constant term, so there is no column of ones.
Form the normal equation.ATA=1+4+16=21 and ATb=1+6+12=19. With one column, the matrices are 1×1 numbers: (t⋅t)m=t⋅y.
Solve.m=19/21≈0.905. Dividing by 21 is allowed because the column is not zero, which is what independence means for one column.
Compute the residuals.r=b−m(1,2,4)=(2/21,25/21,−13/21). Data minus fitted values.
Check perpendicularity.r⋅(1,2,4)=(2+50−52)/21=0. An independent check that the arithmetic and the theory agree.
Size of the error.∥r∥2=(4+625+169)/441=38/21. Check by the shortcut ∥b∥2−x^⋅ATb=19−2119⋅19=21399−361=2138, which agrees.
Answer.y=2119t, with squared error 38/21. This is projection of b onto the line through (1,2,4), the situation in the first picture.
Worked example
Find all least squares solutions of Ax=b when A is the 3×2 matrix whose two columns are both (1,1,1), and b=(1,2,3).
Solution.
Form the normal equations.ATA=[3333] and ATb=(6,6). The theorem says least squares solutions are exactly the solutions of these equations, whether or not the columns are independent.
Notice the formula fails.detATA=9−9=0, so (ATA)−1 does not exist. The two columns are equal, so they are dependent, and the invertibility theorem says ATA is singular.
Solve the system anyway. Both equations say 3x1+3x2=6, that is x1+x2=2. So the solutions are x^=(2−s,s) for any number s. One equation in two unknowns leaves one free variable, as in chapter 2.6.
Compare the fitted vectors.Ax^=(2−s+s)(1,1,1)=(2,2,2) for every s. Part (c) of the theorem: the closest point is unique, only its name as Ax is not.
Check the residual.r=(1,2,3)−(2,2,2)=(−1,0,1), and r⋅(1,1,1)=0. It is perpendicular to the (only) direction in the column space.
Answer.x^=(2−s,s) for every real s; the fitted vector is (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), which is in the null space of A.
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.
Aim at the null space. Suppose (ATA+λI)x=O. We show x=O. A square matrix with null space {O} is invertible, by rank–nullity (2.3), as in the uniqueness proof above.
Multiply on the left by xT.xTATAx+λxTx=0. The right side stays 0. This is the trick of the chapter again: a matrix times its own transpose makes a squared length.
Recognise squared lengths.∥Ax∥2+λ∥x∥2=0. xTATAx=(Ax)⋅(Ax) and xTx=x⋅x.
Both terms are non-negative. Both ∥Ax∥2≥0 and λ∥x∥2≥0, and they add to 0, so each is 0. This is where λ>0 is used. If λ were 0, the second term would vanish for free and we could not conclude anything about x.
Conclude.λ∥x∥2=0 and λ>0 give ∥x∥=0, so x=O. Only the zero vector has length zero.
Answer.ATA+λI is invertible for every λ>0, so ridge regression (ATA+λI)x=ATb always has exactly one solution, even for dependent columns. For the two equal columns above, [3333]+λI has determinant (3+λ)2−9=λ(6+λ)=0.
Your answerA single column a=(1,2,2) and b=(1,1,1) are given. Solve the ridge equation (aTa+λ)x=aTb with λ=1. What is x?
Both matrices are 1×1 numbers here. Add λ to aTa before dividing.
aTa=1+4+4=9 and aTb=1+2+2=5. So (9+1)x=5 and x=21. The ordinary least squares answer would be 95. Ridge shrinks the weight toward 0.
Worked example
Prove that the least squares line y=c+mt through N data points passes through the point (tˉ,yˉ) of the averages.
Solution.
Name the pieces.A has two columns: the all-ones vector 1=(1,…,1) and the vector of the ti. The residual is ri=yi−c−mti. The residual of the best fit is data minus fitted line, point by point.
Use perpendicularity to the first column.1⋅r=0, so ∑iri=0. By the normal equations theorem, r is perpendicular to every column of A, and this column is 1.
Substitute the formula for ri.0=∑i(yi−c−mti)=∑iyi−Nc−m∑iti. Sums split term by term, and ∑ic=Nc because c does not depend on i.
Divide by N.0=yˉ−c−mtˉ, that is yˉ=c+mtˉ. ∑iyi/N=yˉ and ∑iti/N=tˉ by the definition of an average.
Read the result. The point (tˉ,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, yˉ=1.25 and 0.8+0.9⋅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)−1ATb. Look at how it depends on b: the vector b is multiplied on the left by a fixed matrix that depends only on A. That matrix is worth a name.
Definition B
Projection matrix
If A has independent columns, the projection matrix onto its column space is
P=A(ATA)−1AT.
It is m×m. In statistics it is called the hat matrix, because it puts a hat on y: the fitted values are y^=Py.
In one lineThe matrix P=A(ATA)−1AT that sends every b to the closest point of the column space of A.
Why it existsIt does the whole job at once: feed it any b and it returns the fitted values, without solving a new system.
Theorem BStrang 4.2; Axler 6C
The projection matrix projects
Let A have independent columns and P=A(ATA)−1AT. Then:
Pb=Ax^, the projection of b onto the column space of A;
Pv=v for every v in the column space;
P2=P;
PT=P;
(I−P)b=b−Pb is the residual, perpendicular to every column, so AT(I−P)=O.
In one linePb is the closest point of the column space to b, P2=P and PT=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^.
Substitute the formula x^=(ATA)−1ATb from the previous theorem.
(2) Pv=A(ATA)−1ATAx=AIx=Ax=v.
A vector in the column space is v=Ax for some x. Then the middle factors cancel: (ATA)−1ATA=I.
(3) P2b=P(Pb)=Pb for every b, so P2=P.
Pb is in the column space by (1), so apply (2) to the vector Pb. 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=P, since ATA is its own transpose.
Transpose reverses the order of a product: (XYZ)T=ZTYTXT. The transpose of an inverse is the inverse of the transpose. And (ATA)T=ATA.
(5) AT(I−P)=AT−ATA(ATA)−1AT=AT−AT=O.
Multiply out, using the cancellation ATA(ATA)−1=I.
Quick checkP is the 5×5 projection matrix onto a 2-dimensional column space. Is P invertible?
If P were invertible, multiplying P2=P by P−1 would give P=I, which projects nothing. A projection onto a plane inside R5 has rank 2, so it cannot be invertible. Symmetry has nothing to do with invertibility.Review: the projection matrix theorem
A matrix with P2=P is called idempotent, and one with PT=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 u. The shadow p is Pv. 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−p, meets the line at a right angle, and AT(I−P)=O says exactly that.
The projection matrix for the line-fit data. For the A of the line-fit example,
P=101741−243211234−2147.
Applying it to b=(0,1,1,3) gives 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.7, which sums to 2, the number of columns. (That sum of the diagonal entries is the trace. It is no accident: the trace of P always equals the number of independent columns. The proof uses tr(XY)=tr(YX), which holds because both equal ∑i,jXijYji. Then trP=tr((ATA)−1ATA)=trIn=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 P be a projection matrix (so P2=P and PT=P). Prove that I−P is also symmetric and idempotent, that (I−P)P=O, and that every diagonal entry of P satisfies 0≤Pii≤1.
Solution.
Symmetry of I−P.(I−P)T=IT−PT=I−P. The transpose of a difference is the difference of transposes, and I and P are both symmetric.
Idempotence of I−P.(I−P)2=I−2P+P2=I−2P+P=I−P. Multiply out (matrices commute with I and with themselves), then use P2=P.
Killing what P keeps.(I−P)P=P−P2=P−P=O. P lands in the plane and I−P removes exactly the plane’s part, so applying I−P after P leaves nothing.
A formula for the diagonal.P=P2=PTP, so Pii is the dot product of column i of P with itself: Pii=∑kPki2. Entry (i,i) of PTP multiplies row i of PT, which is column i of P, by column i of P.
Non-negativity. A sum of squares is at least 0, so Pii≥0. Squares of real numbers are never negative.
The upper bound. The term k=i of the sum is Pii2 and the other terms are at least 0, so Pii≥Pii2. If Pii>0, dividing by it gives 1≥Pii. If Pii=0 the bound holds already. Dropping non-negative terms can only make a sum smaller.
Answer. Proved. Check with the line-fit P: P11=0.49+0.16+0.01+0.04=0.70, the sum of the squares of column 1, and 0≤0.7≤1.
Your answerA is a 10×3 matrix with independent columns and P is its projection matrix. What is the trace of P (the sum of its diagonal entries)?
The trace of P equals its rank, which is the dimension of the column space.
The trace of P equals the number of independent columns: trP=tr((ATA)−1ATA)=trI3=3. The size 10 of P does not matter.
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.
Sizes.ATA is 2×2, ATb is a vector in R2 and P=A(ATA)−1AT is 5×5. The product of sizes (5×2)(2×2)(2×5) is 5×5. The normal equations always have as many unknowns as columns.
Rank. Every output Pb lies in the column space of A, and every vector of the column space is fixed by P, so it is an output. The range of P is the column space, of dimension 2, so rankP=2. Property (2) of the projection matrix theorem says Pv=v for v in the column space.
Invertibility.P is 5×5 of rank 2, so it is not invertible. An invertible 5×5 matrix has rank 5 (2.4). The part of b perpendicular to the plane is lost and cannot be recovered.
The proof: pick a vector in the range. Any vector in the range of P is Pz for some z. That is what “range” means.
Compute the two inner products.(Pb)⋅(Pz)=bTPTPz=bTP2z=bTPz, and b⋅(Pz)=bTPz. First PT=P, then P2=P.
Subtract.(b−Pb)⋅(Pz)=bTPz−bTPz=0. Both inner products from step 5 are the same number.
Conclude. By the first theorem of the chapter, with W the range of P and p=Pb (which lies in W), Pb is the closest point of W to b. Perpendicular error means closest point.
Answer. Sizes 2×2, R2 and 5×5; rank 2; 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 is perfect on paper and risky in a computer. Forming ATA 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 when the columns of A are independent. We state this fact without proof. A concrete failure shows the damage.
Take ε=10−8 and A=1ε010ε. Its columns are independent. In exact arithmetic,
ATA=[1+ε2111+ε2].
But ε2=10−16 is below the rounding resolution of double-precision numbers, so the computer stores 1+10−16 as exactly 1. The stored matrix is [1111], 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 A and never form ATA.
Theorem BStrang 4.4
QR from Gram–Schmidt
Let A be m×n with independent columns a1,…,an. Gram–Schmidt produces orthonormal vectors q1,…,qn with span(q1,…,qj)=span(a1,…,aj) for each j. Let Q be the m×n matrix with columns qj. Then there is an upper triangular n×n matrix R with nonzero diagonal entries such that A=QR. Consequently QTQ=I, ATA=RTR, the least squares solution satisfies Rx^=QTb, and the projection matrix is P=QQT.
In one lineA matrix A with independent columns factors as A=QR: Q has orthonormal columns and R is square, upper triangular and invertible. Then x^ solves Rx^=QTb and P=QQT.
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+⋯+Rjjqj for some numbers Rij.
Gram–Schmidt (2.9) gives span(q1,…,qj)=span(a1,…,aj), so aj is in the span of q1,…,qj.
Rij=qi⋅aj for i≤j. Put Rij=0 for i>j.
Dot both sides with qi for i≤j. The q's are orthonormal, so qi⋅qk is 1 if i=k and 0 otherwise, and every term but one vanishes.This is the Lecture 6 formula: coefficients along an orthonormal set are dot products.
So A=QR, and R is upper triangular.
Column j of the product QR is ∑iRijqi, the combination written in step 1.
Every Rjj=0. A triangular matrix has determinant equal to the product of its diagonal (2.7), which is non-zero, so R is invertible.
If Rjj=0, then aj would be in span(q1,…,qj−1)=span(a1,…,aj−1), contradicting independence.
QTQ=I.
Entry (i,k) of QTQ is qi⋅qk.
The normal equations read RTRx^=RTQTb.
AT=RTQT, so ATA=RTQTQR=RTR and ATb=RTQTb. The normal equations become RTRx^=RTQTb.
Rx^=QTb.
RT is invertible because R is. Multiply both sides by (RT)−1. Since R is triangular, solving this is back-substitution: the last equation has one unknown, and so on upward.
P=QR(RTR)−1RTQT=QRR−1(RT)−1RTQT=QQT.
Substitute A=QR and ATA=RTR into the formula for P. Then RR−1=I and (RT)−1RT=I.
The last line is Lecture 6’s formula in matrix form: Pb=QQTb=∑i(qi⋅b)qi. 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 is a shadow like the green arrow in the projection visualizer, and because the qi 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 npimport matplotlib.pyplot as pltrng = 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 noiseA = np.column_stack([np.ones_like(x), x]) # columns: 1 and xc = np.linalg.solve(A.T @ A, A.T @ y) # the normal equationsprint("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) vectorprint("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 ATr, 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.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ˉ)2∑(ti−tˉ)(yi−yˉ) where tˉ=0.5 and yˉ=1.25 are the averages. The top is ∑tiyi−4tˉyˉ=7−2.5=4.5 and the bottom is ∑ti2−4tˉ2=6−1=5, so the slope is 0.9. This is “covariance over variance”, and it agrees with the normal equations.
The same line by QR, with no ATA.
An exact fit. If b happens to be in the column space, the closest point is b itself and the residual is O. For example, the points (−1,1),(0,0),(1,1) lie exactly on y=t2. Fitting c+mt+qt2 gives (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 t 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+bx to ex on [−1,1] with ⟨f,g⟩=∫−11fgdx. The columns are now the functions 1 and x, and the normal equations have entries that are integrals: ⟨1,1⟩=2, ⟨1,x⟩=0, ⟨x,x⟩=2/3, ⟨ex,1⟩=e−1/e and ⟨ex,x⟩=2/e. Because ⟨1,x⟩=0, the two equations separate: 2a=e−1/e and 32b=2/e. So a=(e−1/e)/2≈1.175 and b=3/e≈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 Q of the QR section), ATA=I and the normal equations solve themselves: x^=QTb. For ⟨f,g⟩=∫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 f.
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 m houses is a row of A: a 1 (for the intercept), the area, the bedrooms. The prices are b. The weight vector x^ solves ATAx^=ATb, and the predictions are y^=Ax^=Pb. The matrix ATA 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,…. The model is nonlinear in t and still linear in the unknowns, which is all this chapter needs, and the exact-fit example with y=t2 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, ATA is nearly singular and the weights become huge and unstable. The standard cure is ridge regression: solve (ATA+λI)x=ATb for a small λ>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) 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); the receiver is truly at (3,4) and measures distances with small errors, getting 5.10,7.86,6.86,9.17. Guess x0=(4,4). The distances from the guess to the beacons are 5.657,7.211,7.211,8.485. Near the guess, the distance to beacon i changes with the position correction Δ as ui⋅Δ, where ui is the unit vector pointing from beacon i to the guess. That gives four equations UΔ=measured−predicted with rows ui:
The normal equations UTUΔ=UT(right side) give Δ=(−0.803,−0.082), so the new guess is (3.197,3.918). Repeating the step (with the unit vectors recomputed at the new guess) settles at (3.186,3.928), which is about 0.2 from the true (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∘C are 102,205,310,515 counts. We fit T=c+m⋅counts, with the all-ones column and the counts column. The normal equations give T≈−24.73+0.2420⋅counts. The residuals are 0.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=ks for an extension s, with no constant term. (We call the extension s, because x 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.10 metres against forces F=0.21,0.38,0.62,0.79,1.02 newtons. There is one unknown k, so A is the single column s and the system ksi=Fi has five equations. The normal equation is (s⋅s)k=s⋅F, with s⋅s=0.0220 and s⋅F=0.2218, so
k^=0.02200.2218≈10.08N/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.012 newtons. They are perpendicular to s (their dot product with s is zero up to rounding), and the spring constant is close to 10. If you also allowed an offset (fitting F=F0+ks) you would get k≈10.15 and F0≈−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 y 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, between the whole data vector b and the column space, not in the data plane.
Watch out· Dependent columns: A-transpose A is singular
The formula (ATA)−1ATb 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 ATA. Use QR or a library least squares routine. Also, never build the m×m matrix P for large m: a million data points would need a million by a million matrix. Compute Pb as Q(QTb).
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) to our four points and the best line changes from y=0.8+0.9t to y=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. P throws away the part of b perpendicular to the plane, and that information cannot be recovered. P2=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 where g is the best approximation, and the long way is to square out and integrate. The short way is Pythagoras: since r⊥p, ∥b∥2=∥p∥2+∥r∥2, so ∥r∥2=∥b∥2−∥p∥2. Check with the line fit: ∥b∥2=0+1+1+9=11 and ∥p∥2=0.01+0.64+2.89+6.76=10.30, and 11−10.30=0.70, as before.
Problems
checkStrang 4.3, adapted
Find the least squares solution of Ax=b for A=111012, 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] and ATb=(6,0). The equations 3c+3m=6 and 3c+5m=0 subtract to 2m=−6, so m=−3 and c=5. The closest point is Ax^=(5,2,−1) and the residual is r=(1,−2,1). Check: (1,1,1)⋅r=0 and (0,1,2)⋅r=−2+2=0.
check
A is a 5×2 matrix with independent columns. State the sizes of ATA, of ATb and of P. What is the rank of P?
Solution
ATA is 2×2, ATb is in R2, and P is 5×5. Every output Pb is in the column space, and every vector of the column space is an output (it is fixed by P), so the range of P is the column space of A, which has dimension 2. So the rank of P is 2.
check
Why can the formula (ATA)−1ATb not be used for A=123246?
Solution
The second column is twice the first, so the columns are dependent. Then ATA=[14282856] has determinant 14⋅56−28⋅28=0 and is not invertible, as the theorem says.
use
Fit a line y=c+mt to (1,1),(2,3),(3,4) by least squares. What is the sum of the squared residuals?
Solution
A=111123, b=(1,3,4). Then ATA=[36614] and ATb=(8,19). The determinant is 42−36=6. Solve 3c+6m=8 and 6c+14m=19: doubling the first gives 6c+12m=16, so 2m=3 and m=3/2; then c=(8−9)/3=−1/3. The line is y=−31+23t. The fitted values are 7/6,8/3,25/6, the residuals are −1/6,1/3,−1/6 (they sum to 0 and ∑tiri=−1/6+2/3−1/2=0), and the sum of squares is 361+91+361=61.
use
Fit a line through the origin, y=mt, to (1,2),(2,3),(3,7).
Solution
A is the single column (1,2,3) and b=(2,3,7). The normal equation is 14m=2+6+21=29, so m=29/14. The fitted values are 29/14,29/7,87/14, the residuals are −1/14,−8/7,11/14 and their dot product with (1,2,3) is −1/14−16/7+33/14=0. The sum of squares is (1+256+121)/196=378/196=27/14.
use
Find the point of the plane spanned by u=(1,0,1) and v=(0,1,1) that is closest to b=(1,1,1), and the distance.
Solution
Take A with columns u,v. Then ATA=[2112] and ATb=(2,2). The equations 2x1+x2=2 and x1+2x2=2 give x1=x2=2/3. The closest point is 32u+32v=(2/3,2/3,4/3), the residual is (1/3,1/3,−1/3) (perpendicular to u and v: 1/3−1/3=0 for each), and the distance is 1/9+1/9+1/9=1/3.
use
Fit a parabola y=c+mt+qt2 to (−1,1),(0,0),(1,2),(2,5).
Solution
The columns of A are 1, t, t2 at t=−1,0,1,2. The sums needed are ∑1=4, ∑t=2, ∑t2=6, ∑t3=8, ∑t4=18, ∑y=8, ∑ty=−1+0+2+10=11, ∑t2y=1+0+2+20=23. The normal equations are
4262686818cmq=81123.
Eliminating gives (c,m,q)=(0.3,0.4,1). Check: 4(0.3)+2(0.4)+6=8, 2(0.3)+6(0.4)+8=11, 6(0.3)+8(0.4)+18=23. The parabola is y=0.3+0.4t+t2, with fitted values 0.9,0.3,1.7,5.1 and residuals 0.1,−0.3,0.3,−0.1.
proveHW4 shortcut
Let x^ be a least squares solution of Ax=b. Prove that ∥Ax^∥2=x^⋅(ATb), and hence that the sum of squared residuals is ∥b∥2−x^⋅(ATb).
Solution
Write p=Ax^. Then ∥p∥2=(Ax^)⋅(Ax^)=x^TATAx^. By the normal equations ATAx^=ATb, so ∥p∥2=x^TATb=x^⋅(ATb). The worked example on Pythagoras gave ∥r∥2=∥b∥2−∥p∥2, so ∥r∥2=∥b∥2−x^⋅(ATb). Check with the line fit: ∥b∥2=11 and x^⋅ATb=0.8⋅5+0.9⋅7=10.3, and 11−10.3=0.7.
proveAxler 6C
Let P be an m×m matrix with P2=P and PT=P. Prove that for every b, the vector b−Pb is perpendicular to every vector in the range of P. (So Pb is the projection of b onto the range of P.)
Solution
A vector in the range of P has the form Pz. Then (Pb)⋅(Pz)=bTPTPz=bTP2z=bTPz, using PT=P and then P2=P. And b⋅(Pz)=bTPz. So (b−Pb)⋅(Pz)=bTPz−bTPz=0. By the first theorem of the chapter (with W the range of P and p=Pb, which is in W), Pb is the closest point of W to b.
prove
You fit a plane y=c+m1t+m2s to N data points (ti,si,yi) 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ˉ).
Solution
The first column of A is the all-ones vector 1, and the residual r=y−Ax^ is perpendicular to it, so ∑iri=0. Since ri=yi−y^i with y^i=c+m1ti+m2si, this says ∑iy^i=∑iyi, and dividing by N gives equal averages. Also N1∑iy^i=c+m1tˉ+m2sˉ (average each term), so yˉ=c+m1tˉ+m2sˉ, which says the plane passes through (tˉ,sˉ,yˉ).
prove
Let A be any real m×n matrix (the columns may be dependent) and let λ>0. Prove that ATA+λI is invertible.
Solution
Suppose (ATA+λI)x=O. Multiply on the left by xT: xTATAx+λxTx=0, that is ∥Ax∥2+λ∥x∥2=0. Both terms are non-negative and λ>0, so both are zero, and ∥x∥=0 gives x=O. So the null space of this square matrix is {O}, and by the argument in the uniqueness theorem it is invertible.
stretch
Let P1 and P2 be m×m matrices that are both symmetric and idempotent and have the same range W. Prove P1=P2. (So the orthogonal projection onto a subspace is a single, well-defined matrix.)
Solution
Fix b. By the prove-problem on symmetric idempotent matrices, b−P1b is perpendicular to every vector of W, and P1b is in W because W is the range of P1. The same holds for P2. By the theorem ‘Perpendicular error means closest point’, each of P1b and P2b is the unique closest point of W to b. A unique closest point is one point, so P1b=P2b. This holds for every b, so P1=P2.
stretch
Add one more column a to A, giving A′=[A∣a]. Prove that the smallest possible sum of squared residuals for A′ is at most the smallest possible for A. (More features can never raise the training error, which is why training error is a poor judge of a model.)
Solution
Let x^ be a least squares solution for A with minimum squared error E=∥b−Ax^∥2. The vector x′=(x^,0) gives A′x′=Ax^+0⋅a=Ax^, so it has the same squared error E. The least squares solution for A′ minimizes over all vectors, including this one, so its minimum is at most E. The inequality can be strict: adding a column enlarges the column space, so there are more points to be close to.
Summary
When Ax=b has no solution, ask for the x whose Ax is closest to b. The set of all Ax 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^ is perpendicular to the column space. Proof: Pythagoras on the triangle formed by b, the closest point and any other point.
“Perpendicular to every column” is ATr=O, which is the normal equationsATAx^=ATb. They are equivalent to being a least squares solution.
ATA has the same null space as A (because xTATAx=∥Ax∥2). So it is invertible exactly when the columns are independent, and then x^=(ATA)−1ATb is unique.
The projection matrixP=A(ATA)−1AT satisfies P2=P, PT=P and trP=n. It sends b to the fitted values.
Computers use QR, A=QR: solve Rx^=QTb and P=QQT. Forming ATA squares the condition number and can destroy the problem.
The sum of squared errors of the best fit is ∥b∥2−∥p∥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.
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.