Discover: eight equations, two unknowns
Meet eight researchers, surveyed for two numbers each: cups of coffee per day () and lines of code written per day, in tens (). You'll meet them again in Neural Networks from First Principles, where gradient descent takes about two thousand small steps to find the best straight line through their data. Here you'll find the same line in one move, and you'll see why it's the best one.
Ask for a line through all eight points and you are asking for eight equations to hold at once, one per researcher, in only two unknowns and . Stack them, as Chamber 5 taught you, into a single matrix equation :
The first column of holds the values, and the column of ones multiplies . Row says . The data is noisy, so no line hits all eight points, and this system has no solution. Elimination would grind to a contradiction like .
So the real question is: what is the best wrong answer? Statisticians settled it long ago, and they write the answer like this:
Spotted in the wild
Their (read “beta hat”) is our , their is our , and the prime is an older way to write the transpose . By the end of this chamber you'll derive this formula from a single picture, a right angle, and you'll know why the matrix appears in it. The same paper then changes one symbol in it to invent ridge regression, which you'll decode near the end.
A line passes through all eight points only if has a solution, where is the matrix with columns and , and . When does a solution exist?
Learn: orthogonal vectors and orthogonal subspaces
Chamber 2 gave you the test for a right angle: two vectors are orthogonal when their dot product is zero. We write
and read as “is perpendicular to” or “is orthogonal to”. For example , because .
The idea scales up from vectors to whole subspaces. Two subspaces and are orthogonal when every vector in is perpendicular to every vector in . The floor of a room and the line of a vertical pole standing on it are orthogonal subspaces of . The orthogonal complement (read “V perp”) is everything perpendicular to . The complement of the floor is the vertical line, and the complement of the vertical line is the floor.
- “u is perpendicular to v”The vectors are orthogonal: their dot product is zero, . Also read “u is orthogonal to v”.
- “V perp”The orthogonal complement of a subspace : every vector that is perpendicular to all of . It is a subspace too.
- “q i transpose q j equals delta i j”The vectors are orthonormal: each has length 1 (when , ) and every pair is perpendicular (when , ). is the Kronecker delta.
- “Q transpose Q equals I”The columns of are orthonormal. When is square it is called an orthogonal matrix, and .
| Symbol | Say it | Meaning | LaTeX |
|---|---|---|---|
| “u is perpendicular to v” | The vectors are orthogonal: their dot product is zero, . Also read “u is orthogonal to v”. | ||
| “V perp” | The orthogonal complement of a subspace : every vector that is perpendicular to all of . It is a subspace too. | ||
| “q i transpose q j equals delta i j” | The vectors are orthonormal: each has length 1 (when , ) and every pair is perpendicular (when , ). is the Kronecker delta. | ||
| “Q transpose Q equals I” | The columns of are orthonormal. When is square it is called an orthogonal matrix, and . |
Chamber 6 introduced four subspaces of a matrix . Orthogonality is the thread that ties them into pairs, and one pairing drives this whole chamber:
The left null space is perpendicular to the column space. A vector satisfies exactly when is perpendicular to every column of .
The reason is short enough to see in one line. Row of is column of , call it , so the -th entry of is . The whole vector is zero exactly when every one of these dot products is zero, that is, when for every column. And a vector perpendicular to each column is perpendicular to every combination of columns: . So , where is the column space and the left null space. The same argument with rows shows that the null space is perpendicular to the row space.
Keep “ means is perpendicular to the columns” in your pocket. It is the whole secret of least squares.
Learn: orthonormal bases
Some bases are much nicer than others. A set of vectors is orthonormal when each has length 1 and each pair is perpendicular. The Kronecker delta from Mathematics for Machine Learning says it in one line:
Stack the vectors as the columns of a matrix . Entry of is row of times column of , which is exactly . So the whole table of dot products collapses into one statement:
Why is this so pleasant? Coordinates become dot products. To write , dot both sides with . Every term but one vanishes, and . No elimination, no inverse. For example, and are orthonormal, and has coordinates and . Check: .
When is square it is called an orthogonal matrix (the standard, slightly unlucky name: its columns are orthonormal). Then says that is the inverse of . Rotations, reflections and permutation matrices are all orthogonal matrices, and inverting any of them costs nothing but a transpose.
Orthogonal matrices never distort anything. Here is the proof that they preserve length.
Claim. If , then for every vector .
Proof. Squared lengths are dot products, and the transpose of a product reverses the order, . So
Both lengths are non-negative, so taking square roots gives .
The same computation with two different vectors shows : dot products, and therefore angles, survive too.
is a square matrix whose columns are orthonormal, so . What is ?
Learn: projecting onto a line
Now the central picture. Take a line through the origin in the direction , and a vector that is not on it. Which point of the line is closest to ?
Think of the myth's shaft of light. The shadow of falls straight onto the line, at the foot of the perpendicular. Call that point , the projection of onto , sometimes written (“the projection of b onto a”). The gap is the error, and the picture says it meets the line at a right angle. Chamber 2 previewed the answer. Here is the derivation in full.
- 1
Name the unknown
The point lies on the line, so it is some multiple of : (read “x hat times a”). We need the number .
- 2
Write down the right angle
The error must be perpendicular to : .
- 3
Expand and solve
Distributing gives , so . This is allowed because is not zero.
- 4
Assemble the projection
. Moving the scalar around, , with the projection matrix .
A worked example. Let and . Then and , so and . The error is , and indeed . The matrix is
Notice three things. is the outer product scaled down, so it has rank 1, just like the matrices of Chamber 6: everything lands on one line. is symmetric. And (read “P squared equals P”): once a vector is on the line, projecting it again leaves it where it is. Try multiplying by itself to see it happen.
Project onto the line through . The projection is . What is ?
Learn: why the perpendicular is the shortest way
The picture makes it believable that the foot of the perpendicular is the closest point. Mathematics wants “always”, so here is the proof. It works for a line, a plane, or any subspace, and it uses nothing but Pythagoras.
Claim. Let be a subspace, any vector, and a point of whose error is perpendicular to every vector in . Then is the closest point of to : for every in , with equality only when .
Proof. Let be any point of . Split the path from to at :
Both and lie in the subspace , so their difference does too. By assumption is perpendicular to everything in , so the two pieces are perpendicular: . Expanding the squared length, the cross terms are exactly this dot product (twice), so they vanish:
The last term is a squared length, so it is never negative. Therefore , and equality forces , that is, .
Read the anatomy. The claim has a hypothesis (the error is perpendicular to ) and a conclusion (closest point). The one idea is to split into a perpendicular piece and a piece inside . Then Pythagoras does the rest: the right triangle with corners , and has hypotenuse , and a hypotenuse is never shorter than a leg.
Learn: projecting onto a subspace
Now replace the line by the column space of a matrix. Let be with independent columns , and let be a vector in . The closest point of to is some combination of the columns, . By the proof above, it's the point whose error is perpendicular to the whole column space. The derivation follows the line case step for step.
- 1
Name the unknowns
for an unknown vector of weights (read “x hat”). The error is .
- 2
Write down the right angles
must be perpendicular to every column: . These dot products are the entries of , so all of them at once read .
- 3
Rearrange: the normal equations
Distribute and move one term across: . These are the normal equations (“normal” is an old word for perpendicular). They are equations in unknowns, a square system.
- 4
Solve
When the columns of are independent, the square matrix is invertible (you'll assemble the proof in Your turn). So .
- 5
Project
, with the projection matrix .
That is the formula from the Discover section, with , and . It came from one idea: the error is perpendicular to the columns. With a single column , the matrix is the number and everything reduces to the line case.
- “the projection of b onto a”The point on the line through that is closest to : the shadow of on that line.
- “P equals A, times A transpose A inverse, times A transpose”The projection matrix onto the column space of (whose columns are independent): is the closest point to in .
- “P squared equals P”Projecting twice changes nothing. Matrices with this property are called idempotent.
- “x hat”The least-squares solution of : the best compromise when no exact solution exists. As always, the hat marks an estimate.
- “e equals b minus A x hat”The error (or residual) vector: the part of the best fit can't reach. Statistics usually calls it .
- “A transpose A x hat equals A transpose b”The normal equations. They say the error is perpendicular (“normal”) to every column of .
- “the minimum over x of the squared length of b minus A x”The least-squares problem: choose to make the sum of squared errors as small as possible.
| Symbol | Say it | Meaning | LaTeX |
|---|---|---|---|
| “the projection of b onto a” | The point on the line through that is closest to : the shadow of on that line. | ||
| “P equals A, times A transpose A inverse, times A transpose” | The projection matrix onto the column space of (whose columns are independent): is the closest point to in . | ||
| “P squared equals P” | Projecting twice changes nothing. Matrices with this property are called idempotent. | ||
| “x hat” | The least-squares solution of : the best compromise when no exact solution exists. As always, the hat marks an estimate. | ||
| “e equals b minus A x hat” | The error (or residual) vector: the part of the best fit can't reach. Statistics usually calls it . | ||
| “A transpose A x hat equals A transpose b” | The normal equations. They say the error is perpendicular (“normal”) to every column of . | ||
| “the minimum over x of the squared length of b minus A x” | The least-squares problem: choose to make the sum of squared errors as small as possible. |
Like the line version, is symmetric and satisfies . You'll prove both in Your turn.
Which equation says “the error is perpendicular to every column of ”?
Learn: least squares is a projection
Back to the eight researchers. For a candidate line , the vector of predictions is , and the sum of squared errors is
That is the squared distance in between the data and the point . As varies, sweeps out the column space , a plane in . So the best line is the closest point of that plane to , which is the projection. Linear regression is a projection, and its coefficients solve the normal equations . Statistics writes the same thing as and linear algebra as : one problem, three dialects.
Let's do a small one completely by hand, with three points , and . It is the example Gilbert Strang works in the lecture recommended below.
The normal equations are and . Doubling the second gives , and subtracting it from the first leaves . So and : the best line is . Its predictions are and the residuals are
Check the right angles. Against the column of ones: . Against the column: . The residual is perpendicular to the column space, as promised.
Now it's your turn to be the projection. Tune the line by hand until you're within 1% of the least-squares error, then look at the residual.
Interactive lab
Least squares by hand, then by projection
Gold handles: drag, or focus one and use the arrow keys (hold Shift for bigger steps). Dashed red segments are the residuals: each point's y minus your line's prediction.
Sum of squared errors
113.29
Least-squares minimum 9.796
You are 1056.5% above it. Goal: under 1%.
Your line
ŷ = 1x + 9
Step 2 unlocks when your error is within 1% of the minimum.
In the lab you saw a line whose error was almost minimal but whose residual was not orthogonal to the columns: was small, not zero. The right angle is what singles out the exact optimum. You also met a consequence worth remembering. Because the column of ones is in , the least-squares residuals of any line with an intercept sum to zero, and the fitted line always passes through the mean point .
Learn: Gram–Schmidt and QR
Projections are easiest of all when the columns are orthonormal. If with , the normal equations collapse to , and the projection matrix becomes . No inverse anywhere. So it is worth knowing how to make an orthonormal basis out of any independent vectors. The recipe is the Gram–Schmidt process, and it uses nothing but projections onto lines.
The idea: take the vectors one at a time. From each new vector, subtract its projections onto the directions you've already built. What's left is perpendicular to all of them. Then scale it to length 1.
- “v k equals a k minus the sum over j less than k of q j transpose a k, times q j”One Gram–Schmidt step: strip from its projections onto the earlier directions, then normalise, .
- “A equals Q R”The QR factorisation: has orthonormal columns (from Gram–Schmidt) and is upper triangular.
| Symbol | Say it | Meaning | LaTeX |
|---|---|---|---|
| “v k equals a k minus the sum over j less than k of q j transpose a k, times q j” | One Gram–Schmidt step: strip from its projections onto the earlier directions, then normalise, . | ||
| “A equals Q R” | The QR factorisation: has orthonormal columns (from Gram–Schmidt) and is upper triangular. |
Here it is on and .
- 1
First direction: just normalise
, so .
- 2
Second direction: remove the shadow on the first
, so . Check: .
- 3
Normalise
, so .
and span the same plane as and , but now they meet at a right angle and have unit length.
Record the bookkeeping and you get a factorisation. Each is a combination of only, never of later ones, so
This QR factorisation is how careful software does least squares. Substituting into the normal equations and cancelling (both and are invertible here) leaves : a triangular system you solve by back substitution, as in Chamber 5.
import numpy as np
def gram_schmidt(A):
"""Orthonormalise the columns of A (assumed independent)."""
Q = np.zeros(A.shape)
for k in range(A.shape[1]):
v = A[:, k].astype(float)
for j in range(k):
v = v - (Q[:, j] @ A[:, k]) * Q[:, j] # remove the shadow on q_j
Q[:, k] = v / np.linalg.norm(v)
return Q
A = np.array([[1, 1], [1, 0], [0, 1]])
Q = gram_schmidt(A)
print(np.round(Q.T @ Q, 10)) # the identity: orthonormal columns
Read beyond the course
Each of these picks up exactly where this chamber stops. All are free.
Book · free online · ~60 min
Introduction to Applied Linear Algebra: Vectors, Matrices, and Least SquaresStephen Boyd & Lieven Vandenberghe · Chapter 12 (Least squares) and Section 13.1; Section 5.4 for Gram–Schmidt
A whole book built around least squares, written for engineers and data scientists rather than mathematicians. Chapter 12 derives the normal equations the way you just did, and Section 13.1 fits models to real data. Read it now while the projection picture is fresh.
Book · free online · ~50 min
Mathematics for Machine LearningMarc Peter Deisenroth, A. Aldo Faisal & Cheng Soon Ong · Sections 3.4–3.8 (orthogonality to orthogonal projections), then Section 9.4
Section 3.8 derives projections onto lines and subspaces with the same steps as this chamber, and includes Gram–Schmidt (Section 3.8.3). Section 9.4 then shows that the maximum-likelihood solution of linear regression is an orthogonal projection, tying this chamber to probability.
Lecture notes · free online · ~20 min
CS229 Lecture NotesAndrew Ng & Tengyu Ma (Stanford) · Part I, Section 1.2: The normal equations
The machine-learning derivation of the same equations, by matrix calculus: differentiate the loss and set it to zero. Reading it side by side with this chamber's geometric derivation is the best way to see that the two routes meet.
Lecture notes · free online · ~40 min
Orthogonal Matrices and Gram-SchmidtGilbert Strang, MIT OpenCourseWare 18.06SC · Lecture summary, recitation video and problem set
The session that follows the two lectures below: a short lecture summary, a worked recitation on Gram–Schmidt, and problems with full solutions. Good practice before the proofs in Your turn.
Papers and lectures
Hoerl and Kennard's 1970 paper is thirteen pages long, and you can read the important parts today. It is on the publisher's website, where you may need library access (most universities provide it). Start with the abstract and Section 0, one page of plain English about why least squares misbehaves when predictors are correlated. In Section 1, read Eq. (1.1), which you now know how to derive, and Eq. (1.2), the residual sum of squares, which is your . Then read Section 2 up to Eq. (2.8): the ridge estimator and the fact that it is shorter than the least-squares one. Skip Sections 4 and 5, which need expectations and eigenvalues (Chamber 8 covers the eigenvalues). Finish with the bullet list in Section 7 and the conclusions in Section 8.
Ridge Regression: Biased Estimation for Nonorthogonal ProblemsArthur E. Hoerl, Robert W. Kennard · Technometrics 12(1), 1970Adds a small positive number to the diagonal of and shows the resulting biased estimates can have smaller error. The same idea is L2 regularisation in machine learning.
Exact solutions to the nonlinear dynamics of learning in deep linear neural networksAndrew M. Saxe, James L. McClelland, Surya Ganguli · arXiv; ICLR 2014, 2013The paper behind orthogonal initialisation. Read the abstract and the introduction now; the analysis uses the SVD from Chamber 9.
Decode the paper · Eq. (2.1), Section 2
Ridge Regression: Biased Estimation for Nonorthogonal ProblemsArthur E. Hoerl, Robert W. Kennard · Technometrics 12(1), 1970
The ridge estimator, as Hoerl and Kennard print it. Set and it becomes their Eq. (1.1), : exactly the normal-equations solution from this chamber. Match each piece to its meaning.
Options
Watch
Gilbert Strang's classic 18.06 lectures. In the first, watch him derive from the same right angle you used here. In the second, he fits the line through , and and draws both pictures at once: the points and line in the plane, and the projection in . Pause each time before he writes a formula and try to say it first.
Your turn
Match the notation to its meaning and to its code, assemble one proof and write another, then solve three problems. The last one applies Hoerl and Kennard's estimator to a dataset built to fool least squares.
Match · Maths ↔ In words
Say what it means
Match each piece of notation to what it says in words.
Options
Match · Maths ↔ NumPy
From symbols to NumPy
Match each formula to the NumPy that computes it. Here @ is matrix multiplication and .T is the transpose.
Options
Proofs
The puzzle proves the fact the normal equations rely on: independent columns make invertible. Then prove the two properties of yourself.
Proof puzzle
Independent columns make AᵀA invertible
Claim
If the columns of an matrix are linearly independent, then the matrix is invertible. (This is what guarantees that the normal equations have exactly one solution.)
Tap lines in the order they should appear. Not every line belongs. Tap a line in your proof to send it back.
Your proof
- Pick the first line below.
Available lines
Prove it yourself
The projection matrix is idempotent and symmetric
Claim
Let be an matrix with independent columns, and let . Prove that and .
Your typeset proof appears here.
Code it up
Problem 19·Warm-up
A line through the origin
Some models have no intercept: . Fitting by least squares is a projection onto a line. Stack the inputs into and the targets into . The best is the projection coefficient
and the smallest possible sum of squared errors is : the squared distance from to the line through .
Take points with and for (so , , , …). What is the minimum sum of squared errors
Give it as a fraction in lowest terms, like 7/12.
Problem 20·Standard
Gram's orthogonal polynomials
Jørgen Pedersen Gram published the Gram–Schmidt process in 1883, in a paper on fitting functions by least squares (Laplace had used a version of it decades earlier). Here is a version of Gram's problem.
Sample the eleven points and build four vectors in from the powers of : for . So is all ones (take ) and .
Run Gram–Schmidt without normalising:
where the sum is empty for , so . What is ? Give it as a fraction in lowest terms.
Problem 21·Challenge
Walking the ridge trace
Hoerl and Kennard (1970) warn that when the columns of are nearly dependent, least squares can return coefficients that are too large and even have the wrong sign. Their remedy, Eq. (2.1) of the paper, is the ridge estimate
and their ridge trace follows each coefficient as grows from . (The paper first rescales the predictors so that is a correlation matrix. We skip that step to keep the numbers simple.)
Twelve observations have two predictors and no intercept. For :
Row of is . The two columns are almost identical, and at (ordinary least squares) the second coefficient comes out negative, even though rises with both predictors. What is the smallest integer for which ?
Key takeaways
- Orthogonal means a zero dot product, and says is perpendicular to every column of : .
- Orthonormal columns satisfy . Coordinates become dot products, a square is inverted by transposing, and lengths and angles are preserved.
- The closest point is the foot of the perpendicular. Projection onto a line is ; onto a column space it is with , and .
- Least squares is a projection. Requiring the error to be perpendicular to the columns gives the normal equations , the same equations as setting the gradient of the squared error to zero.
- Gram–Schmidt builds an orthonormal basis by subtracting projections, giving , the stable way to solve least squares in practice. Ridge regression adds to to tame nearly dependent columns.
Checkpoint
Prove it to the labyrinth
Answer every question to clear this chamber. First-try answers earn the most XP.
Which pair of vectors is orthogonal?
and form an orthonormal basis of . Writing as , what is ?
Fit by least squares to the four points , , and . What is the intercept ?
When a least-squares line has an intercept , its residuals always sum to exactly zero. Why?
is the matrix that projects onto a plane through the origin in . Which statement is true?
Gram–Schmidt starts from and . The second, unnormalised, vector is . What is ?
Hoerl and Kennard's ridge regression replaces with for some . What does the extra do?
Numerical libraries solve least squares with orthogonal factorisations (a QR factorisation, or the SVD that np.linalg.lstsq uses) rather than computing inv(X.T @ X) @ X.T @ y. Why?
End of the chamber
Clear this chamber
- Questions in this chamber (0/12 solved)Next unsolved
- Bonus: Least squares by hand (+40 XP)
- Bonus: Problem 19: A line through the origin (+20 XP)
- Bonus: Problem 20: Gram's orthogonal polynomials (+35 XP)
- Bonus: Problem 21: Walking the ridge trace (+50 XP)
- Bonus: Proof: Independent columns make AᵀA invertible (+25 XP)
- Bonus: Proof: The projection matrix is idempotent and symmetric (+40 XP)
- Bonus: Decode the paper (+30 XP)
- Bonus: Match: Say what it means (+25 XP)
- Bonus: Match: From symbols to NumPy (+25 XP)