Lesson 8 of 117 min
Projection
Drop a vector onto a line at a right angle: with the line's arrow shrunk to length 1, the dot product says how far along it lands, and what is left is the error.
After this lesson you can drop a vector onto a direction and read what is left as the error.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
One line, with no shrink
The video shrank the road's arrow to length 1 first. Real code often skips that: it divides the dot product by road @ road, the arrow's length twice, once for the dot product and once for the arrow you walk along. You get 0.6 of the arrow [4, 3]: the same bus stop.
import numpy as np
position = np.array([3, 1])
road = np.array([4, 3])
share = (position @ road) / (road @ road)
print(share)
print(share * road)0.6 [2.4 1.8]
A onto B is not B onto A
A projection always lies along the line you drop onto. So dropping your position onto the road gives a point on the road, and dropping the road's arrow onto your position gives a point on your position's line. The two answers are different arrows.
def project(v, d):
return (v @ d) / (d @ d) * d
print(project(position, road))
print(project(road, position))[2.4 1.8] [4.5 1.5]
Drop it twice and nothing moves
A drop onto a line can be written as a matrix, np.outer(unit, unit). Multiply by it and you land on the road. Multiply again and you stay where you are: a point already on the road is its own nearest point. That is how you can tell a real projection.
unit = road / np.linalg.norm(road)
P = np.outer(unit, unit)
once = P @ position
print(once)
print(P @ once)[2.4 1.8] [2.4 1.8]
`q_proj` is another kind of projection
In a language model's code you will see layers named q_proj, k_proj, v_proj and o_proj. In Llama's code in Hugging Face Transformers, each is an nn.Linear: a learned matrix that turns numbers into other numbers. The name means any such layer, not this drop. Run one twice and it moves the numbers again. Your numbers may differ.
import torch
torch.manual_seed(0)
q_proj = torch.nn.Linear(2, 2, bias=False)
x = torch.tensor([3.0, 1.0])
with torch.no_grad():
once = q_proj(x)
print(once)
print(q_proj(once))tensor([ 0.3634, -2.2663]) tensor([-0.8616, 0.9679])
Fitting a line is a projection too
A line fitted by least squares measures each miss straight up or down, so it is not the drop of the video. It is a projection in another picture: the four y values are one arrow, dropped onto the columns of X. The misses are what is left, and their dot product with each column is 0.
x = np.array([1, 2, 3, 4])
y = np.array([1, 3, 2, 4])
X = np.column_stack([x, np.ones(4)])
coef = np.linalg.lstsq(X, y)[0]
fitted = X @ coef
print(coef.round(2))
print(fitted.round(2))
print((X.T @ (y - fitted)).round(10) + 0)[0.8 0.5] [1.3 2.1 2.9 3.7] [0. 0.]
Put the numbers on one scale first
The video measured flippers in centimeters and weight in kilograms, so both numbers were about the same size. In millimeters and grams, the weight's numbers are far bigger, and the road that follows the cloud is almost only weight. Give each column the same spread first, and both count.
import pandas as pd
from sklearn.decomposition import PCA
url = "https://raw.githubusercontent.com/allisonhorst/palmerpenguins/main/inst/extdata/penguins.csv"
df = pd.read_csv(url).dropna(subset=["flipper_length_mm", "body_mass_g"])
raw = df[["flipper_length_mm", "body_mass_g"]].to_numpy()
print(PCA(1).fit(raw).components_.round(3))
same = (raw - raw.mean(axis=0)) / raw.std(axis=0)
print(PCA(1).fit(same).components_.round(3))[[0.015 1. ]] [[0.707 0.707]]
Run on Python 3.13, NumPy 2.5.5, pandas 3.1.1, scikit-learn 1.9.1 and PyTorch 2.15.0. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: The dot product
You rate two movies [1, 2]. A friend rates them [2, -2]. What is your dot product?
2 of 3
A road leans along the arrow [4, 3]. Your position is [3, 1], and its dot product with [4, 3] is 15. Is your projection 15 along the road?
3 of 3
A road runs along [0.6, 0.8], an arrow of length 1. Your position is [5, 0]. How far is your position from the road?
The ideas in this lesson
- Projection
- Drop a vector onto a line at a right angle: the arrow along the line to where it lands.
- How far along
- With the line's arrow shrunk to length 1, the dot product says how far along the line a vector lands.
- The error
- A vector minus its projection: it meets the line at a right angle, and its length is the vector's distance from the line.
It leans on
- PCA
Transcript
What the video says, part by part. Press a time to watch from there.
The bet
Here's a bet. On your phone's map, a dot shows your position. It's often a little off the road. The phone never knows exactly where you are. Say you know you're on this straight road. Which is nearest: the school, the bus stop, or the bridge?
The nearest point
Let's measure the three gaps from your position. The school is about one and two-thirds away. The bridge, one and a quarter. And the bus stop... just one. The bus stop is the nearest. Look where its gap meets the road. At a right angle. If you picked the bridge, straight up from your position, you're not alone. But the road leans, so straight up is not the shortest way onto it. Any other point is farther away. Its gap is the long side of a triangle, with the right angle at the bus stop. So the nearest point on a straight line is where the gap meets it at a right angle.
The projection
So what does that look like with arrows?
The road passes through the start, where everything is measured from. Draw your position as an arrow from the start: three, one. That's three east and one north.
Now draw an arrow from the start to the bus stop. It lies along the road. That arrow is the... projection of your position onto the road. It's like a shadow on the road. So the projection is the point on the road nearest to your position, drawn as an arrow.
The road east
The projection is the point on a road nearest to your position, as an arrow. So how do you find it without drawing? Start with a road that runs east. Its arrow is one, zero. Take the dot product of your position, three, one, with that arrow. Three times one, plus one times zero... three. It keeps the first number of your position: how far east you are. On this road, that's how far along. Walk three steps along the road's arrow, and you're at three, zero. That's the projection, right below your position.
A road that leans
That was the easy road. When the road runs east, the dot product says how far along. So does it still work when the road leans?
Fifteen
This road leans four east for every three north. Its arrow is four, three. The dot product with your position: three times four, plus one times three.
Fifteen. So you're fifteen along the road? Look where fifteen lands.
Far past your position. You're only about three from the start.
Here's why. The road's arrow has a length of five: four squared plus three squared is twenty-five, and its square root is five.
And a dot product grows with an arrow's length.
Make an arrow twice as long, and its dot product doubles. So with an arrow of length five, the number comes out five times too big.
Shrink it to length one
So how do you fix it?
The arrow of the road east, one, zero, has a length of one. That's why it worked. So give this arrow a length of one too: divide both its numbers by five. Zero point eight, zero point six.
Now take the dot product again. Can you work it out?
Three times zero point eight, plus one times zero point six... three.
Walk three steps along that arrow, and you're at two point four, one point eight.
The projection, right at the bus stop. So once the road's arrow has a length of one... the dot product tells you how far along.
The error
Your position is three, one. Its projection on the road is two point four, one point eight. So what's left between them? Take your position minus its projection. You get the arrow zero point six... and minus zero point eight. What's left... is called the error. Its length is one: how far your position is from the road. And its dot product with the road's arrow, four, three? Make a guess.
Zero point six times four, minus zero point eight times three.
Zero. And a dot product of zero means a right angle, as the picture showed.
Add the projection and the error, and you're back at your position.
In NumPy
So what is this for?
Here are the penguins from Python for AI, in NumPy. Flipper length goes across, and weight goes up, each measured from the average penguin. The cloud follows a road, about two across for one up.
Say you want one number for each penguin, not two: drop every penguin onto the road.
In NumPy, once the road's arrow has length one, that's one line: the at sign takes each row's dot product with the road's arrow. Each penguin's error is what that one number leaves out.
On average, how far is a penguin from the road?
A bit more than a quarter. Small, compared to a cloud about six across. If the road follows flipper length alone, the average error is more than twice as big. So the road that follows the cloud leaves the smallest errors. Finding that road is what PCA does... and here, PCA's road is nearly the same as ours.
All of it together
So when you drop an arrow onto a line, the gap meets the line at a right angle. Where it lands is the projection. Give the line's arrow a length of one, and the dot product tells you how far along. And what's left over... is the error.
Drop it at a right angle
So a projection is the nearest point on a line. Now try it on this lesson's page, and take the quiz. Make the projection exactly as long as the error.
You use this lesson in Lab 3: The penguins' best road, after Eigenvectors and eigenvalues.
Facts last checked on .
