linearly

Lecture 11

Projections

When the target is out of reach, the best you can do is its shadow. The projection formula, the projection matrix, and why the miss is always perpendicular.

73 slides / MIT 18.06, Lecture 15 / Strang §4.2

Slide 1 of 73
1 / 73

The idea in one sentence

When a target is out of reach, the closest thing you can reach is its shadow, and you can find that shadow because the miss it leaves behind stands at a right angle to everything reachable.

A target with no answer

Five rows of data, two knobs to turn, and no setting of the knobs that works. That is the measurements table from Lecture 8: each row carries a weight ww and a height hh, and each row wants a target number built from them with the same two coefficients u1u_1 and u2u_2:

u1[53214]+u2[24857]=[38792].u_1 \begin{bmatrix} 5 \\ 3 \\ 2 \\ 1 \\ 4 \end{bmatrix} + u_2 \begin{bmatrix} 2 \\ 4 \\ 8 \\ 5 \\ 7 \end{bmatrix} = \begin{bmatrix} 3 \\ 8 \\ 7 \\ 9 \\ 2 \end{bmatrix}.

Two knobs, five demands. Take the first two rows on their own and they pin the knobs down: 5u1+2u2=35u_1 + 2u_2 = 3 and 3u1+4u2=83u_1 + 4u_2 = 8 give u1=2/7u_1 = -2/7 and u2=31/14u_2 = 31/14. Now look at row three. It wants 2u1+8u2=72u_1 + 8u_2 = 7, and those knob settings deliver 120/7120/7, which is about 17.117.1. The first two rows and the third row want different things, and no setting of two knobs can satisfy all five.

Write the two columns side by side as a matrix AA, and the target as bb. The reachable outputs are the combinations AxAx, which is the column space C(A)C(A): a flat two-dimensional plane sitting inside five-dimensional space. The target bb is not on that plane. The code at the end of this chapter checks it in one line: AA has rank 2, and AA with bb glued on as a third column has rank 3, so bb adds a direction the columns never had.

That is the ordinary situation. Real data almost never lands in the column space. Lecture 10 showed which directions are perpendicular to which. This chapter uses that to answer the question the failure raises: if you cannot reach bb, what is the closest point you can reach?

Start with one column

Shrink the problem until it cannot get smaller. One column aa, one target bb. Every reachable point is a multiple xaxa, so the reachable set is the line through aa. Which multiple sits closest to bb?

You already know the answer as a picture. Drop a perpendicular from bb onto the line, and the foot of that perpendicular is the nearest point. Every other point on the line is the far corner of a right triangle whose short side is that perpendicular, so it has to be farther away.

a = (5, 1)b = (2, 3)p = (2.5, 0.5)e = b − pthe line through a
Fig. 1 

The closest point on the line to bb is the foot of the perpendicular, and the arrow ee that is left over meets the line at a right angle.

Now turn the picture into algebra. Call the closest point pp and write it as p=x^ap = \hat{x}a, where x^\hat{x} is the multiple you are looking for. Call the miss e=bpe = b - p. The picture says ee is perpendicular to aa, and perpendicular means the dot product is zero:

aT(bx^a)=0aTb=x^aTax^=aTbaTa,p=aaTbaTa.a\T (b - \hat{x} a) = 0 \quad\Longrightarrow\quad a\T b = \hat{x}\, a\T a \quad\Longrightarrow\quad \hat{x} = \frac{a\T b}{a\T a}, \qquad p = a\,\frac{a\T b}{a\T a}.

That is the whole derivation. Two numbers go in, aTba\T b and aTaa\T a, and the closest point comes out. With the numbers in the figure, a=(5,1)a = (5, 1) and b=(2,3)b = (2, 3), so aTb=13a\T b = 13 and aTa=26a\T a = 26, giving x^=1/2\hat{x} = 1/2 and p=(2.5,0.5)p = (2.5, 0.5). The miss is e=(0.5,2.5)e = (-0.5, 2.5), and aTe=2.5+2.5=0a\T e = -2.5 + 2.5 = 0, exactly as promised.

One question is still open. The picture asserted that the foot of the perpendicular is the closest point, and the algebra only ever used the right angle. Take any other point qq on the line. Then bb, pp, and qq sit at the corners of a right triangle whose right angle is at pp, so bq2=bp2+pq2\norm{b - q}^2 = \norm{b - p}^2 + \norm{p - q}^2. The last term is never negative, and it is zero only when qq is pp. No other point on the line can tie.

bpqq′every dashed join is a hypotenuse
Fig. 2 

Three points on the line, three joins from bb. Only the join to pp arrives at a right angle, so each of the others is the hypotenuse of a right triangle and has to be longer.

Two cases you can check in your head

A formula you cannot sanity check is a formula you do not own. There are two cases where you already know the answer.

b lies along ab is perpendicular to ab = a, so p = bab = (−1, 5)p = 0x̂ = 1x̂ = 0
Fig. 3 

Two cases the formula has to get right. On the left x^=1\hat{x} = 1 and the shadow is bb itself. On the right x^=0\hat{x} = 0 and the shadow collapses to the origin.

If bb lies along aa, say b=ab = a, then aTb=aTaa\T b = a\T a and x^=1\hat{x} = 1, so p=bp = b. The shadow of something already on the line is itself. If bb is perpendicular to aa, then aTb=0a\T b = 0 and x^=0\hat{x} = 0, so p=0p = 0. Nothing of bb lies along the line, so the closest reachable point is the origin.

Look at the second picture again next to the first. The vector (1,5)(-1, 5) is perpendicular to (5,1)(5, 1), and the miss computed a moment ago was e=(0.5,2.5)e = (-0.5, 2.5), which is exactly half of (1,5)(-1, 5). So b=(2,3)b = (2, 3) splits as 12(5,1)+12(1,5)\tfrac12 (5,1) + \tfrac12 (-1,5): the part the line can see, and the part it is blind to. Projection is that split.

Try it. Drag the target, watch the shadow
abp

a = (2.00, 0.00)
b = (2.00, 1.40)
x̂ = 1.00
length of p = 2.00
length of e = 1.40

P = [1.00 0.00;0.00 0.00]

Drag anywhere in the picture to move b. Warm is the target you chose, green is the shadow the line can reach, blue is what is left over. The right-angle mark never breaks, and the two diagonal entries of P always add to 1.

The matrix that casts the shadow

The formula for pp hides a matrix. In p=a(aTb/aTa)p = a \left( a\T b / a\T a \right) the quantity aTba\T b is a single number, so it can be moved around freely. Slide it to the right of aa and group differently:

p  =  aaTbaTa  =  (aaTaTa)b  =  Pb,P=aaTaTa.p \;=\; \frac{a\,a\T b}{a\T a} \;=\; \left( \frac{a a\T}{a\T a} \right) b \;=\; P b, \qquad P = \frac{a a\T}{a\T a}.

Read the two products carefully, because they look alike and are nothing alike. A row times a column, aTaa\T a, is one number. A column times a row, aaTa a\T, is a full square matrix.

5151=25551aaᵀaaᵀrow 1 = 5 × (5  1)row 2 = 1 × (5  1)every row is a multiple of the same row, so the rank is one
Fig. 4 

A column times a row. Both rows of aaTa a\T are multiples of (5,1)(5, 1), which is what rank one looks like. The projection matrix PP is this matrix divided by 26.

For a=(5,1)a = (5, 1) the outer product aaTa a\T is the matrix with rows (25,5)(25, 5) and (5,1)(5, 1), and PP is that matrix divided by 26. Every row of aaTa a\T is a multiple of the same row (5,1)(5, 1), so all rows sit on one line and the rank is 1. That has to be true: PP maps everything onto a one-dimensional line, so its column space is that line.

Three properties fall out.

PP is symmetric, since (aaT)T=aaT(a a\T)\T = a a\T.

PP applied twice is PP applied once:

P2=aaTaTaaaTaTa=a(aTa)aT(aTa)2=aaTaTa=P.P^2 = \frac{a a\T}{a\T a}\cdot\frac{a a\T}{a\T a} = \frac{a\,(a\T a)\,a\T}{(a\T a)^2} = \frac{a a\T}{a\T a} = P .

The middle step is the whole trick: the two inner factors aTa\T and aa meet and collapse into the number aTaa\T a, which then cancels one copy from the denominator. The geometry says the same thing. PbPb already sits on the line, and the shadow of a point on the line is itself, so pressing the button again changes nothing.

bp = PbPP again, and p does not move:P(Pb) = Pb
Fig. 5 

One press of PP carries bb to pp. A second press does nothing, because pp is already on the line, and that is P2=PP^2 = P with no algebra in sight.

And the trace of PP is aTa/aTa=1a\T a / a\T a = 1, which matches the rank. For projections that is a rule: the trace counts how many dimensions survive.

The simplest projection matrix in the world

Here is a projection you have used without calling it one. Take a picture six pixels wide, two rows of three, and stack the pixels into a vector in R6\R^6. Now redact the middle column by multiplying with a diagonal matrix of ones and zeros.

771202993444805336101101the picturePwhat is leftevery entry off the diagonal is 0redact the redacted picture and nothing more happens
Fig. 6 

Six pixels and one diagonal matrix of ones and zeros. It keeps four coordinates and destroys two, and running it a second time does no more damage than the first.

That diagonal matrix PP is symmetric because diagonal matrices are. It satisfies P2=PP^2 = P because 12=11^2 = 1 and 02=00^2 = 0, and because redacting an already redacted picture does nothing new. Its rank is 4, its trace is 4, and its column space is the four-dimensional set of pictures whose middle column is blank. It is a projection onto that subspace, and it is not rank one.

So rank one came from projecting onto a line, and the real definition of a projection matrix is the pair of properties: P2=PP^2 = P and P=PTP = P\T. The matrix IPI - P is a projection too, the one that keeps exactly what PP throws away. In this picture IPI - P keeps the middle column and blanks the rest.

Many columns at once

Back to the real problem. Now AA has nn independent columns instead of one, so the reachable set grows from a single line to the whole column space. Everything else survives the upgrade.

Write the closest reachable point as p=Ax^p = A\hat{x}, where x^\hat{x} now holds one coefficient per column, and write the miss as e=bAx^e = b - A\hat{x}. Closest still means the miss is perpendicular to everything reachable, and everything reachable is built from the columns, so it is enough for ee to be perpendicular to each column separately. Stacking those conditions is exactly what ATA\T does, since the rows of ATA\T are the columns of AA:

AT(bAx^)=0.A\T (b - A\hat{x}) = 0 .
bpea₁a₂C(A): every point the two columns can reach
Fig. 7 

Projection onto a plane, with a1=(1,1,0)a_1 = (1, 1, 0), a2=(0,1,1)a_2 = (0, 1, 1), and b=(2,3,4)b = (2, 3, 4). The shadow is p=(1,4,3)p = (1, 4, 3) and the miss is e=(1,1,1)e = (1, -1, 1), which leans on neither column. That single sentence is the equation AT(bAx^)=0A\T(b - A\hat{x}) = 0.

One rearrangement finishes it:

ATAx^=ATbx^=(ATA)1ATb.A\T A\, \hat{x} = A\T b \quad\Longrightarrow\quad \hat{x} = (A\T A)^{-1} A\T b . p=A(ATA)1ATb,P=A(ATA)1AT.p = A (A\T A)^{-1} A\T b, \qquad P = A (A\T A)^{-1} A\T .

The picture uses columns a1=(1,1,0)a_1 = (1, 1, 0) and a2=(0,1,1)a_2 = (0, 1, 1) and target b=(2,3,4)b = (2, 3, 4). Then ATAA\T A has rows (2,1)(2, 1) and (1,2)(1, 2), and ATb=(5,7)A\T b = (5, 7), so x^=(1,3)\hat{x} = (1, 3) and p=1a1+3a2=(1,4,3)p = 1 a_1 + 3 a_2 = (1, 4, 3). The miss is e=(1,1,1)e = (1, -1, 1), and it dots to zero against both columns: 11+0=01 - 1 + 0 = 0 and 01+1=00 - 1 + 1 = 0.

Two checks tell you the formula is the right one.

Set n=1n = 1, so AA is the single column aa. Then ATAA\T A is the number aTaa\T a, its inverse is division, and P=a(aTa)1aT=aaT/aTaP = a (a\T a)^{-1} a\T = a a\T / a\T a. The subspace formula contains the line formula.

Now let AA be square and invertible. Then every bb is reachable and the projection should do nothing, and indeed P=AA1(AT)1AT=IP = A A^{-1} (A\T)^{-1} A\T = I.

Why you are allowed to invert that

The formula leans on (ATA)1(A\T A)^{-1}, so it owes you a reason. Here it is, in two directions.

If Ax=0Ax = 0 then ATAx=AT0=0A\T A x = A\T 0 = 0. That direction is free.

Going back, suppose ATAx=0A\T A x = 0. Multiply on the left by xTx\T:

xTATAx=0(Ax)T(Ax)=0Ax2=0.x\T A\T A x = 0 \quad\Longrightarrow\quad (Ax)\T (Ax) = 0 \quad\Longrightarrow\quad \norm{Ax}^2 = 0 .

A squared length is zero only for the zero vector, so Ax=0Ax = 0. The two null spaces are the same set: N(ATA)=N(A)N(A\T A) = N(A).

Now the conclusion writes itself. If the columns of AA are independent, then N(A)N(A) holds only the zero vector, so N(ATA)N(A\T A) holds only the zero vector, and ATAA\T A is a square matrix whose null space is trivial. That is exactly what invertible means. Independent columns are the only condition the projection formula ever needs.

One vector, two pieces

Put the pieces together. Any bb splits as b=p+eb = p + e, where p=Pbp = Pb lives in C(A)C(A) and ee satisfies ATe=0A\T e = 0, which is the definition of the left null space N(AT)N(A\T). Lecture 10 proved those two subspaces are perpendicular complements inside Rm\R^m, so every bb splits this way, and only this way.

C(A)N(Aᵀ)bp = Pb, length √26e = (I − P)b, length √3b has length √29, and 26 + 3 = 29
Fig. 8 

The column space and the left null space meet at a right angle, so every bb splits exactly one way. PP keeps the reachable piece, IPI - P keeps the leftover, and the two lengths obey Pythagoras.

Since pp and ee meet at a right angle, the lengths obey Pythagoras: b2=p2+e2\norm{b}^2 = \norm{p}^2 + \norm{e}^2. For the plane above that reads 29=26+329 = 26 + 3.

The two machines are PP and IPI - P. For that same plane, IPI - P turns out to be the matrix nnT/nTnn n\T / n\T n with n=(1,1,1)n = (1, -1, 1), the direction perpendicular to the plane. That is the rank-one formula from the start of the chapter, doing the complementary job. Projecting onto a plane in R3\R^3 and projecting onto the line perpendicular to it are the same calculation seen from two sides.

python
import numpy as np

a = np.array([5., 1.])
b = np.array([2., 3.])

x_hat = (a @ b) / (a @ a)
p = x_hat * a
e = b - p
print(x_hat)                   # 0.5
print(p)                       # [2.5 0.5]
print(e)                       # [-0.5  2.5]
print(a @ e)                   # 0.0        the miss is perpendicular to a
print(b @ b, p @ p + e @ e)    # 13.0 13.0  Pythagoras

P = np.outer(a, a) / (a @ a)   # a column times a row, over a number
print(bool(abs(P @ b - p).max() < 1e-6))    # True   P finds the same shadow
print(bool(abs(P @ P - P).max() < 1e-6))    # True   P applied twice is P
print(bool(abs(P - P.T).max() < 1e-6))      # True   P is symmetric
print(round(float(np.trace(P)), 6))     # 1.0    the trace counts what is kept
print(int(np.linalg.matrix_rank(P)))        # 1
print(bool(abs(P @ a - a).max() < 1e-6))    # True   a projects to itself
print(bool(abs(P @ np.array([-1., 5.])).max() < 1e-6))  # True

The second block moves up to a subspace. It confirms that the measurements table really is unreachable, then projects onto a plane and checks every claim this chapter made about PP.

python
import numpy as np

w = np.array([5., 3., 2., 1., 4.])
h = np.array([2., 4., 8., 5., 7.])
target = np.array([3., 8., 7., 9., 2.])
A = np.column_stack([w, h])
print(int(np.linalg.matrix_rank(A)))                              # 2
print(int(np.linalg.matrix_rank(np.column_stack([A, target]))))   # 3

B = np.array([[1., 0.], [1., 1.], [0., 1.]])   # columns (1,1,0) and (0,1,1)
b = np.array([2., 3., 4.])
print(B.T @ B)                      # [[2. 1.] [1. 2.]]
x_hat = np.linalg.solve(B.T @ B, B.T @ b)
print(x_hat)                        # [1. 3.]
p = B @ x_hat
e = b - p
print(p)                            # [1. 4. 3.]
print(e)                            # [ 1. -1.  1.]
print(B.T @ e)                      # [0. 0.]  perpendicular to both columns
print(b @ b, p @ p + e @ e)         # 29.0 29.0  Pythagoras again

P = B @ np.linalg.inv(B.T @ B) @ B.T
print(bool(abs(P @ b - p).max() < 1e-6))    # True
print(bool(abs(P @ P - P).max() < 1e-6))    # True   still idempotent
print(bool(abs(P - P.T).max() < 1e-6))      # True   still symmetric
print(round(float(np.trace(P)), 6))     # 2.0    two dimensions kept this time
n = np.array([1., -1., 1.])         # the direction perpendicular to the plane
print(bool(abs(np.eye(3) - P - np.outer(n, n) / (n @ n)).max() < 1e-6))

Deleting a direction on purpose

The redaction matrix threw away coordinates. A direction a model has learned is almost never one of your coordinates, and you can throw it away anyway.

Take the word embeddings inside a language model and train a small linear classifier to read some property off them. The classifier’s weight vector is a direction aa in embedding space, and how much of the property a word carries is how far that word reaches along aa. To remove the property, project every embedding onto the perpendicular complement of aa. That is IPI - P with P=aaT/aTaP = a a\T / a\T a, the same rank-one matrix from the start of this chapter, now used for what it destroys instead of what it keeps.

a246the line that survivesreceptionist 6.26nurse 4.92plumber 3.13engineer 1.79the number is how far the word reaches along aafter the projection every one of them is exactly 0
Fig. 9 

Four embeddings drawn in a frame where the learned direction aa runs along the horizontal, so the projection is a slide straight onto the line that survives. The readings along aa start at 6.26, 4.92, 3.13 and 1.79 and all four land on 0. The words stay apart vertically, so one direction is gone and the rest of the space is untouched.

The readings are not shrunk. They are exactly zero, because aT(IP)=aTaT=0a\T(I - P) = a\T - a\T = 0, and a classifier whose weight vector is aa now reads the same number off every word in the language. What the words keep is everything perpendicular to aa, which in a real model is all but one of several hundred directions.

One pass rarely finishes the job. Train a fresh classifier on what survived and it often finds another direction that still carries the property, so the method is run in a loop: learn a direction, project it away, learn the next one. Each pass subtracts one more rank-one PP, and each pass costs the model one more direction of the space it had to work in.

Where this is going

You now have the closest reachable point and the matrix that finds it. What you have not been told is what the coefficients x^\hat{x} mean. For the measurements table they are the numbers a model would learn, and the miss ee is the error it has to live with. Naming that properly, and fitting a line to real data with it, is the next chapter: least squares.

One warning to carry forward. The formula P=A(ATA)1ATP = A(A\T A)^{-1}A\T is how you think about projection. A good program computes it another way, because forming ATAA\T A squares how badly conditioned the problem is. Lecture 13 replaces the inverse with orthonormal columns and turns the whole calculation into back substitution.