Orthogonality, projection and least squares
Which point on a line is closest to a given point? The one you reach by dropping straight onto the line at a right angle. The same idea finds the line that fits a set of points best. Drag the points and see.
Short answer. Projection finds the point on a line (or a plane) that is closest to a given point. The segment to that point meets the line at a right angle. Least squares is how you pick an answer when no exact answer exists: you take the one where "how wrong each point is, squared and added up" is as small as possible. Inside, it is the same thing as projection.
a = ( , )
b = ( , )
q = × a
Drag the tips of green a and blue b, or the purple q, or change the numbers. The light green line is the line set by a, and q only moves along it. The orange dashed line goes from b down to the line at a right angle. Where it lands is p.
Definitions
The text below uses arrows in the plane and a few points, but the definitions are the same in ℝⁿ.
- orthogonal
- Two vectors u, v in ℝⁿ are called orthogonal if their dot product is 0. The length (norm) of a vector v is the square root of its dot product with itself.
- orthogonal projection
- Let W be a subspace of ℝⁿ and b a vector. The vector p that lies in W and makes b − p orthogonal to every vector in W is called the orthogonal projection of b onto W. If W is the line spanned by one non-zero vector a, it is the formula below.
- Gram-Schmidt process
- Starting from linearly independent vectors v₁, …, vₖ, this process builds u₁, …, uₖ one at a time as below. The vectors u₁, …, uₖ are orthogonal to each other and span the same space as v₁, …, vₖ. Dividing each one by its length gives an orthonormal basis of that space.
- column space
- For an m×n matrix A, the column space is the subspace of ℝᵐ made of all linear combinations of the columns of A. In other words, it is the set of all vectors of the form Ax.
- least squares solution, residual
- Let A be an m×n matrix and b ∈ ℝᵐ. The vector b − Ax is called the residual (residual vector). A vector x̂ is called a least squares solution of Ax = b if the inequality below holds for every x ∈ ℝⁿ. So it is an x that makes the residual as short as possible.
- normal equations
- The equation below is called the normal equations of Ax = b. x̂ is a least squares solution of Ax = b exactly when x̂ solves the normal equations. If the columns of A are linearly independent, AᵀA has an inverse, and the least squares solution is unique.
1. Orthogonal: a dot product of 0 means a right angle
When two arrows meet at a right angle, we say they are orthogonal. You can check this with numbers, no picture needed. If the dot product is 0, they are at a right angle. The dot product multiplies across by across and up by up, then adds the two (see the dot product page).
Two directions at a right angle do not mix. However far you go along one, you do not move at all along the other. So you can count "how much this way" and "how much that way" separately. The rest of this page uses this again and again.
The length of an arrow v is written ‖v‖. The length squared is the arrow's dot product with itself: ‖v‖² = v·v.
2. Projection: drop onto the line at a right angle
There is a line through the origin. The arrow a shows its direction. A point b sits off the line. Draw a segment from b to the line so that it meets the line at a right angle. The point where it lands, p, is the projection of b. It is like the shadow a stick casts on the ground when the sun is straight overhead.
The part in brackets is a single number. It says how many times a you need to reach p. The bottom, a·a, is the length of a squared. If a is (0, 0), then a·a is 0 and you cannot divide. With no direction there is no line, so there is no projection.
It works the same way if you drop onto a plane or a bigger space instead of a line. You find the closest point in it, and the difference is at a right angle to it (section 7).
Where the formula comes from: see "How the formula is built" below, one picture at a time.
Work it out by hand
Take a = (2, 1) and b = (3, 4). The lab above starts with these.
- a·b = 2×3 + 1×4 = 10
- a·a = 2×2 + 1×1 = 5
- How many times a: 10 ÷ 5 = 2
- p = 2 × (2, 1) = (4, 2)
- Check: b − p = (3 − 4, 4 − 2) = (−1, 2). (b − p)·a = (−1)×2 + 2×1 = 0. It is a right angle.
- Distance from b to p = length of (−1, 2) = √(1 + 4) = √5 ≈ 2.24
Written as equations, the same solution looks like this.
In equations, (2, 1) is written standing up, as a column. It is the same arrow.
Try this. ① Drag q anywhere along the line. The distance from b to q never drops below 2.24. It only reaches 2.24 when q sits on p (q = 2 × a). ② Change a to (4, 2) or (−2, −1). p stays at (4, 2). Same line, same p. ③ Move b to (−1, 2). p becomes (0, 0). b is at a right angle to a, so there is no shadow.
How the formula is built: the projection formula
Let's build p = (a·b ÷ a·a) × a one step at a time. The data is the same as in the hand example: a = (2, 1), b = (3, 4). Press "Next" and a piece is added to the formula on top (the orange background marks the new piece), the picture changes to match, and the reason appears below.
Green a, blue b. The purple point is the point t × a on the line. Orange marks the right angle and the finished p. You can move the t slider in steps ① to ④. From step ⑤ on, t stays at the solved value, 2.
Written only as equations, the steps above look like this.
Why the graph is a parabola. Multiply out the distance squared and you get ‖b − t × a‖² = a·a × t² − 2 × a·b × t + b·b, a quadratic in t. Here it is 5t² − 20t + 25. If a is not (0, 0), the number in front of t², a·a, is above 0, so the parabola opens upward and has one bottom. The vertex formula for a quadratic (t = −(the number in front of t) ÷ (2 × the number in front of t²)) gives t = 2 × a·b ÷ (2 × a·a) = a·b ÷ a·a, the same answer.
The slope of a fitted line has the same shape. The least squares line passes through the mean point (x̄, ȳ) (section 6). So once you subtract the averages from x and y, you only need to fit y − ȳ ≈ m × (x − x̄), with no height k. That is a projection, with the y − ȳ values in the place of b and the x − x̄ values in the place of a (with four points, in 4 dimensions). So m = a·b ÷ a·a = Σ(x − x̄)(y − ȳ) ÷ Σ(x − x̄)². For the hand example in section 6, a = (−1.5, −0.5, 0.5, 1.5), b = (−1.5, 0.5, −0.5, 1.5), a·b = 4, a·a = 5, and m = 4 ÷ 5 = 0.8.
3. Why the right-angle point is the closest
Pick any other point q on the line. b, p and q make a right triangle. The right angle is at p, and the side from b to q is the long side. The Pythagorean theorem says:
The last part, ‖p − q‖², can never be less than 0. So ‖b − q‖ is always at least ‖b − p‖. They are equal only when q is p. In other words, the point you reach at a right angle is the closest point. It also works the other way: if you found the closest point, the difference is at a right angle to the line.
Check it with the lab's starting picture. q = 1.5 × a = (3, 1.5). ‖b − q‖² = 0² + 2.5² = 6.25, ‖b − p‖² = 5, ‖p − q‖² = 1² + 0.5² = 1.25. 5 + 1.25 = 6.25. It matches.
4. Making right-angle base arrows: Gram-Schmidt
Math is easier when the two base arrows of the plane are at a right angle. Then, for any point, "how much along this base arrow, how much along that one" takes just one projection each (see the basis page). Gram-Schmidt turns two arrows a and b that are not at a right angle into a pair that is.
- Keep a as it is.
- From b, take away the part that goes along a, which is p.
u = b − p. - u is at a right angle to a. a and u are the new base arrows.
- If you need to, divide each one by its own length so both have length 1.
Example: a = (2, 1), b = (3, 4). We found p = (4, 2) above, so u = (3, 4) − (4, 2) = (−1, 2). Check: a·u = 2×(−1) + 1×2 = 0. Both lengths are √5, so with length 1 they become (2, 1) ÷ √5 and (−1, 2) ÷ √5.
With three or more arrows, repeat the same step. From the third one, take away its parts along every base arrow you already made.
Try this. ① Press "Make a right angle" in the lab. The orange dashed b − p slides over to the origin and becomes the black arrow u = (−1, 2). A right-angle mark appears between a and u. ② Then move b to (4, 2). u becomes (0, 0). When b is on the same line as a, no new direction comes out.
5. Least squares: when there is no exact answer
You want a line through several points. Two points with different x have exactly one line through them. With three or more points that are not on one line, no line goes through all of them. So you pick the line that is "least wrong."
Write the line as y = m·x + k. m is the slope, and k is the height at x = 0. For each point, actual y − the line's y is how wrong the line is there. This is called the residual. The least squares line is the line where the residuals, squared and added up, are as small as possible.
Σ means "add them all up," and i is the point number (point 1, point 2, and so on). In the lab below, the area of each light orange square is that point's residual squared. You are looking for the line that makes the total area of the squares as small as possible.
( , )
Drag the blue points, or pick a point and change its numbers. "Remove a point" removes the selected point (the black ring). You can have 3 to 12 points. In "Least squares answer," the black dot "mean" is where the average of the x values meets the average of the y values.
Try this. ① For the first 6 points, the least squares line is y = 0.56x + 0.06 and the sum of squares is 2.22. ② Press "Fit it yourself." The starting line is y = 0x + 0, with a sum of squares of 15.12. Move the sliders to bring it down. However you try, it never goes below 2.22. Press "Show the answer" and the sliders move to the answer. ③ In "Least squares answer," drag point 6 from (3.6, 2.6) down to (3.6, −4). The line becomes y = −0.06x − 1.18. One point turns an uphill line into a downhill one. This is what "weak against outliers" means (section 8).
6. The line-fit formula, worked by hand
The least squares line comes straight out of a formula. x̄ ("x bar") is the average of the x values, and ȳ ("y bar") is the average of the y values.
The second formula says the line passes through the mean point (x̄, ȳ). If the bottom, Σ(x − x̄)², is 0, which means all the x values are the same, the slope cannot be found. This formula is the normal equations from section 7, written out for a line. The end of "How the formula is built" shows that the slope has the same shape as the projection formula a·b ÷ a·a.
Work it out by hand
Four points: (1, 1), (2, 3), (3, 2), (4, 4).
| x | y | x − x̄ | y − ȳ | (x − x̄)(y − ȳ) | (x − x̄)² |
|---|---|---|---|---|---|
| 1 | 1 | −1.5 | −1.5 | 2.25 | 2.25 |
| 2 | 3 | −0.5 | 0.5 | −0.25 | 0.25 |
| 3 | 2 | 0.5 | −0.5 | −0.25 | 0.25 |
| 4 | 4 | 1.5 | 1.5 | 2.25 | 2.25 |
| Total | 4 | 5 | |||
- Averages: x̄ = (1 + 2 + 3 + 4) ÷ 4 = 2.5, ȳ = (1 + 3 + 2 + 4) ÷ 4 = 2.5
- Table totals: Σ(x − x̄)(y − ȳ) = 4, Σ(x − x̄)² = 5
- Slope: m = 4 ÷ 5 = 0.8
- Height: k = 2.5 − 0.8 × 2.5 = 0.5
- Line: y = 0.8x + 0.5
- Residuals: 1 − 1.3 = −0.3, 3 − 2.1 = 0.9, 2 − 2.9 = −0.9, 4 − 3.7 = 0.3. Sum of squares = 0.09 + 0.81 + 0.81 + 0.09 = 1.8
Written as equations, the same solution looks like this.
By eye, y = x looks like a better fit. But its residuals are 0, 1, −1, 0, so its sum of squares is 2. That is more than 1.8.
7. Least squares is a projection: Ax ≈ b
Write the line fit with a matrix, and you can see it is the same thing as a projection. Put the four points above into the line y = m·x + k, and each point gives one equation.
There are two unknowns, m and k, but four equations. No m and k satisfy all four. We write this as Ax = b.
A = [[1, 1], [2, 1], [3, 1], [4, 1]]. Each row is [the point's x, 1]. The first column holds the x values. The second column is all 1s.x = (m, k). Here x means the bundle of unknowns. It uses the same letter as the points' x values, so be careful. Textbooks write it this way too.b = (1, 3, 2, 4). These are the points' y values.
Ax is the first column of A times m, plus the second column times k. However you change m and k, Ax can only move around inside "what you can make by mixing the columns of A." This set is called the column space of A (see the rank page). b is not inside it, so there is no exact answer. That is why we write Ax ≈ b (almost equal).
So pick the point in the column space that is closest to b. That is a projection. With four points, b is an arrow with four numbers (4 dimensions), so you cannot draw it. But what happens is the same as the picture in section 2. As section 3 showed, at the closest point the difference b − Ax is at a right angle to the column space. That means its dot product with every column of A is 0. Written in one line, these are the normal equations.
Aᵀ is A with its rows and columns swapped (the transpose). Multiplying an arrow by Aᵀ gives you the dot product of that arrow with each column of A. Try it on the example.
AᵀA = [[30, 10], [10, 4]]. 30 = 1² + 2² + 3² + 4², 10 = 1 + 2 + 3 + 4, 4 = the number of points.Aᵀb = (29, 10). 29 = 1×1 + 2×3 + 3×2 + 4×4, 10 = 1 + 3 + 2 + 4.- Two equations:
30m + 10k = 29and10m + 4k = 10. The second gives k = 2.5 − 2.5m. Put that into the first: 30m + 25 − 25m = 29, so 5m = 4, m = 0.8 and k = 0.5.
Same answer as the formula. Check the residuals (−0.3, 0.9, −0.9, 0.3) too. Their dot product with the x column (1, 2, 3, 4) is −0.3 + 1.8 − 2.7 + 1.2 = 0, and with the column of 1s it is −0.3 + 0.9 − 0.9 + 0.3 = 0. The residuals are at a right angle to both columns.
This is not just for lines. A curve y = c₂·x² + c₁·x + c₀, or a formula with several inputs, is solved the same way: just add columns to A. If no column of A can be made by mixing the other columns (the columns are linearly independent), there is exactly one answer. For a line, that means "the x values are not all the same."
8. Why squares and not absolute values?
You could add up the absolute values of the errors instead. Squares are used more for two reasons.
- The math is clean. Think of the sum of squares as a height that depends on m and k. It is a smooth bowl, and unless all the x values are the same, it has exactly one bottom. The formula above (the normal equations) gives that bottom in one step. The sum of absolute values has sharp corners, so no single formula like this solves it.
- Big errors count more. An error of 1 counts as 1, and an error of 3 counts as 9. One big error is avoided more than several small ones.
The cost: it is weak against outliers. If one badly measured point sits far away, its square gets huge and pulls the line toward it. That is "Try this ③" in the lab above. If outliers worry you, filter them out first, or use a method that weighs big errors less (the sum of absolute values, or Huber loss).
9. Properties worth knowing
| Property | What it means | Where to see it |
|---|---|---|
| Closest point ⇔ difference at a right angle | If p is the point on the line closest to b, then b − p is at a right angle to the line. The reverse is also true | Drag q in the first lab |
| Only the direction matters | Multiplying a by any number (even a negative one) leaves p the same. Only 0 does not work | Change a to (4, 2) or (−2, −1) |
| Doing it twice changes nothing | Projecting p onto the same line again gives p, because it is already on the line | Put b on the line and p = b |
| The least squares line passes through the mean point | The average point (x̄, ȳ) is always on the line | The black dot "mean" in the second lab |
| Residuals add up to 0, and their dot product with x is 0 | These are exactly the two rows of the normal equations (when the line has a height k) | The hand example's (−0.3, 0.9, −0.9, 0.3) |
Where is it used?
- Linear regression. The most basic model for estimating sales from ad spend, or house prices from floor area. With several inputs, add columns to A and solve the same normal equations.
- Trend lines. Excel's linear trendline and the LINEST function find the least squares line.
- GPS and sensor calibration. A GPS receiver has four unknowns: three for position (x, y, z) and one for its clock error. When it sees five or more satellites, there are more equations than unknowns, and every distance has some error, so there is no exact answer. A common approach is to pick the most likely position with least squares. To calibrate a sensor, compare its readings with known values several times and fit a line. The slope and height give the scale and zero-point corrections.
- Mean squared error (MSE) in AI training. MSE, a common loss for regression models, is the sum of squares divided by the number of points. If the model is a straight-line kind of model, the normal equations solve it in one step. When there is no direct formula (as with neural networks) or the data is too large, you shrink the loss a little at a time instead. That is gradient descent.
- Sliding along walls in games. When a character runs into a wall, the game takes the movement arrow and removes the part at a right angle to the wall (a projection), so the character slides along the wall.
# Solve the hand example in Python (numpy)
import numpy as np
x = np.array([1, 2, 3, 4]); y = np.array([1, 3, 2, 4])
A = np.column_stack([x, np.ones(4)]) # columns: the x values, 1
(m, k), *_ = np.linalg.lstsq(A, y, rcond=None) # m ≈ 0.8, k ≈ 0.5
Common questions
What is a projection?
It is the point you reach when you drop a segment from a point onto a line or plane at a right angle. It is also the point on that line (or plane) closest to the original point. For a line through the origin, p = (a·b ÷ a·a) × a.
Is orthogonal the same as perpendicular?
Almost. Orthogonal means the dot product of two arrows is 0, and the word is also used in 4 or more dimensions, where you cannot draw a picture. An arrow of length 0 is orthogonal to every arrow.
Why does least squares use squares and not absolute values?
The math is clean, so one formula gives the answer, and big errors count more. The cost is that one far-off point can pull the line a lot.
Are least squares and linear regression the same thing?
Linear regression is a model that estimates an output by multiplying inputs by numbers and adding them up. Least squares is the most common way to pick those numbers. That is why people often use the two words to mean the same thing.
Does real code solve AᵀA x = Aᵀb directly?
For small problems that is fine. Libraries usually use a QR decomposition or a singular value decomposition (SVD) instead, because forming AᵀA can make rounding errors bigger. In Python, use numpy.linalg.lstsq.
Words
| Word used here | Word used in textbooks |
|---|---|
| at a right angle (dot product 0) | orthogonal, perpendicular |
| the point you reach at a right angle, the shadow | orthogonal projection |
| making right-angle base arrows | Gram-Schmidt process |
| base arrows at right angles, each of length 1 | orthonormal basis |
| how wrong a point is (actual y − the line's y) | residual |
| sum of squares | residual sum of squares (RSS) |
| best-fit line | least squares line, regression line |
| height k | intercept, y-intercept |
| what you can make by mixing the columns | column space |
| swapping rows and columns | transpose. Written Aᵀ |
AᵀA x = Aᵀb | normal equations |
| a far-off point | outlier |
| sum of squares ÷ number of points | mean squared error (MSE) |
Sources
- Gilbert Strang, Introduction to Linear Algebra, chapter 4, Orthogonality (projections, least squares, Gram-Schmidt).
- MIT OCW 18.06 Linear Algebra, lectures 15 to 17 (projections, least squares, Gram-Schmidt).
- numpy.linalg.lstsq documentation.
← Orthogonal matrices and inner product spacesSingular value decomposition →