Skip to content
AriadneTechnology

The Inner Ring · Chamber 7 of 9

Orthogonality and Least Squares

Projections, orthonormal bases and the normal equations: linear regression, derived with geometry.

45 min 60 XP + 12 questions + 1 challengeMathVideoPapersProofsCodeLab

In this chamber you will

  • Project a vector onto a line and onto a subspace
  • Derive the normal equations AᵀA x̂ = Aᵀb
  • Build an orthonormal basis with Gram–Schmidt
  • Fit linear regression as a projection
DiscoverLearnRead beyondPapers & lecturesYour turn

Discover: eight equations, two unknowns

Meet eight researchers, surveyed for two numbers each: cups of coffee per day (xx) and lines of code written per day, in tens (yy). 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 y^=wx+b\hat{y} = wx + b 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 ww and bb. Stack them, as Chamber 5 taught you, into a single matrix equation Xθ=yX\boldsymbol{\theta} = \mathbf{y}:

[0.511.512.01⋮⋮6.51]⏟X[wb]⏟θ=[4.45.29.6⋮21.1]⏟y\underbrace{\begin{bmatrix} 0.5 & 1 \\ 1.5 & 1 \\ 2.0 & 1 \\ \vdots & \vdots \\ 6.5 & 1 \end{bmatrix}}_{X} \underbrace{\begin{bmatrix} w \\ b \end{bmatrix}}_{\boldsymbol{\theta}} = \underbrace{\begin{bmatrix} 4.4 \\ 5.2 \\ 9.6 \\ \vdots \\ 21.1 \end{bmatrix}}_{\mathbf{y}}

The first column of XX holds the xx values, and the column of ones multiplies bb. Row ii says wxi+b=yiw x_i + b = y_i. The data is noisy, so no line hits all eight points, and this system has no solution. Elimination would grind to a contradiction like 0=1.30 = 1.3.

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

β^=(X′X)−1 X′Y\hat{\boldsymbol{\beta}} = (\mathbf{X}'\mathbf{X})^{-1}\,\mathbf{X}'\mathbf{Y}
Hoerl & Kennard (1970), “Ridge Regression: Biased Estimation for Nonorthogonal Problems”, Eq. (1.1)

Their β^\hat{\boldsymbol{\beta}} (read “beta hat”) is our θ\boldsymbol{\theta}, their Y\mathbf{Y} is our y\mathbf{y}, and the prime ′' is an older way to write the transpose ⊤^\top. 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 X′X\mathbf{X}'\mathbf{X} appears in it. The same paper then changes one symbol in it to invent ridge regression, which you'll decode near the end.

Quick check +20 XP

A line y^=wx+b\hat{y} = wx + b passes through all eight points only if Xθ=yX\boldsymbol{\theta} = \mathbf{y} has a solution, where XX is the 8×28 \times 2 matrix with columns x\mathbf{x} and 1\mathbf{1}, and θ=(w,b)\boldsymbol{\theta} = (w, b). When does a solution exist?

DiscoverLearnRead beyondPapers & lecturesYour turn

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

u⊥v⟺u⊤v=0,\mathbf{u} \perp \mathbf{v} \quad\Longleftrightarrow\quad \mathbf{u}^\top\mathbf{v} = 0,

and read ⊥\perp as “is perpendicular to” or “is orthogonal to”. For example (1,2)⊥(2,−1)(1, 2) \perp (2, -1), because 2−2=02 - 2 = 0.

The idea scales up from vectors to whole subspaces. Two subspaces VV and WW are orthogonal when every vector in VV is perpendicular to every vector in WW. The floor of a room and the line of a vertical pole standing on it are orthogonal subspaces of R3\mathbb{R}^3. The orthogonal complement V⊥V^\perp (read “V perp”) is everything perpendicular to VV. The complement of the floor is the vertical line, and the complement of the vertical line is the floor.

Orthogonality notation
  • u⊥v\mathbf{u} \perp \mathbf{v}“u is perpendicular to v”
    The vectors are orthogonal: their dot product is zero, u⊤v=0\mathbf{u}^\top\mathbf{v} = 0. Also read “u is orthogonal to v”.
    (1,2)⊥(2,−1)(1, 2) \perp (2, -1)
  • V⊥V^\perp“V perp”
    The orthogonal complement of a subspace VV: every vector that is perpendicular to all of VV. It is a subspace too.
    N(A)=C(A⊤)⊥N(A) = C(A^\top)^\perp
  • qi⊤qj=δij\mathbf{q}_i^\top\mathbf{q}_j = \delta_{ij}“q i transpose q j equals delta i j”
    The vectors q1,…,qn\mathbf{q}_1, \ldots, \mathbf{q}_n are orthonormal: each has length 1 (when i=ji = j, δij=1\delta_{ij} = 1) and every pair is perpendicular (when i≠ji \ne j, δij=0\delta_{ij} = 0). δij\delta_{ij} is the Kronecker delta.
  • Q⊤Q=IQ^\top Q = I“Q transpose Q equals I”
    The columns of QQ are orthonormal. When QQ is square it is called an orthogonal matrix, and Q−1=Q⊤Q^{-1} = Q^\top.
    Q=15[3−443]Q = \tfrac{1}{5}\begin{bmatrix} 3 & -4 \\ 4 & 3 \end{bmatrix}

Chamber 6 introduced four subspaces of a matrix AA. 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 y\mathbf{y} satisfies A⊤y=0A^\top\mathbf{y} = \mathbf{0} exactly when y\mathbf{y} is perpendicular to every column of AA.

The reason is short enough to see in one line. Row jj of A⊤A^\top is column jj of AA, call it aj\mathbf{a}_j, so the jj-th entry of A⊤yA^\top\mathbf{y} is aj⊤y\mathbf{a}_j^\top\mathbf{y}. The whole vector A⊤yA^\top\mathbf{y} is zero exactly when every one of these dot products is zero, that is, when y⊥aj\mathbf{y} \perp \mathbf{a}_j for every column. And a vector perpendicular to each column is perpendicular to every combination of columns: (c1a1+c2a2)⊤y=c1a1⊤y+c2a2⊤y=0(c_1\mathbf{a}_1 + c_2\mathbf{a}_2)^\top\mathbf{y} = c_1\mathbf{a}_1^\top\mathbf{y} + c_2\mathbf{a}_2^\top\mathbf{y} = 0. So N(A⊤)=C(A)⊥N(A^\top) = C(A)^\perp, where C(A)C(A) is the column space and N(A⊤)N(A^\top) the left null space. The same argument with rows shows that the null space N(A)N(A) is perpendicular to the row space.

Keep “A⊤y=0A^\top\mathbf{y} = \mathbf{0} means y\mathbf{y} 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 q1,…,qn\mathbf{q}_1, \ldots, \mathbf{q}_n 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:

qi⊤qj=δij={1if i=j,0if i≠j.\mathbf{q}_i^\top\mathbf{q}_j = \delta_{ij} = \begin{cases} 1 & \text{if } i = j, \\ 0 & \text{if } i \ne j. \end{cases}

Stack the vectors as the columns of a matrix QQ. Entry (i,j)(i, j) of Q⊤QQ^\top Q is row ii of Q⊤Q^\top times column jj of QQ, which is exactly qi⊤qj\mathbf{q}_i^\top\mathbf{q}_j. So the whole table of dot products collapses into one statement:

Q⊤Q=I.Q^\top Q = I.

Why is this so pleasant? Coordinates become dot products. To write x=c1q1+⋯+cnqn\mathbf{x} = c_1\mathbf{q}_1 + \cdots + c_n\mathbf{q}_n, dot both sides with qi\mathbf{q}_i. Every term but one vanishes, and ci=qi⊤xc_i = \mathbf{q}_i^\top\mathbf{x}. No elimination, no inverse. For example, q1=(35,45)\mathbf{q}_1 = (\tfrac{3}{5}, \tfrac{4}{5}) and q2=(−45,35)\mathbf{q}_2 = (-\tfrac{4}{5}, \tfrac{3}{5}) are orthonormal, and x=(2,1)\mathbf{x} = (2, 1) has coordinates c1=65+45=2c_1 = \tfrac{6}{5} + \tfrac{4}{5} = 2 and c2=−85+35=−1c_2 = -\tfrac{8}{5} + \tfrac{3}{5} = -1. Check: 2q1−q2=(65+45,85−35)=(2,1)2\mathbf{q}_1 - \mathbf{q}_2 = (\tfrac{6}{5} + \tfrac{4}{5}, \tfrac{8}{5} - \tfrac{3}{5}) = (2, 1).

When QQ is square it is called an orthogonal matrix (the standard, slightly unlucky name: its columns are orthonormal). Then Q⊤Q=IQ^\top Q = I says that Q⊤Q^\top is the inverse of QQ. 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 Q⊤Q=IQ^\top Q = I, then ∥Qx∥=∥x∥\|Q\mathbf{x}\| = \|\mathbf{x}\| for every vector x\mathbf{x}.

Proof. Squared lengths are dot products, and the transpose of a product reverses the order, (Qx)⊤=x⊤Q⊤(Q\mathbf{x})^\top = \mathbf{x}^\top Q^\top. So

∥Qx∥2=(Qx)⊤(Qx)=x⊤Q⊤Q x=x⊤I x=∥x∥2.\|Q\mathbf{x}\|^2 = (Q\mathbf{x})^\top(Q\mathbf{x}) = \mathbf{x}^\top Q^\top Q\,\mathbf{x} = \mathbf{x}^\top I\,\mathbf{x} = \|\mathbf{x}\|^2.

Both lengths are non-negative, so taking square roots gives ∥Qx∥=∥x∥\|Q\mathbf{x}\| = \|\mathbf{x}\|. ■\blacksquare

The same computation with two different vectors shows (Qx)⊤(Qy)=x⊤y(Q\mathbf{x})^\top(Q\mathbf{y}) = \mathbf{x}^\top\mathbf{y}: dot products, and therefore angles, survive too.

Quick check +20 XP

QQ is a square matrix whose columns are orthonormal, so Q⊤Q=IQ^\top Q = I. What is Q−1Q^{-1}?

Learn: projecting onto a line

Now the central picture. Take a line through the origin in the direction a\mathbf{a}, and a vector b\mathbf{b} that is not on it. Which point of the line is closest to b\mathbf{b}?

Think of the myth's shaft of light. The shadow of b\mathbf{b} falls straight onto the line, at the foot of the perpendicular. Call that point p\mathbf{p}, the projection of b\mathbf{b} onto a\mathbf{a}, sometimes written proj⁡a(b)\operatorname{proj}_{\mathbf{a}}(\mathbf{b}) (“the projection of b onto a”). The gap e=b−p\mathbf{e} = \mathbf{b} - \mathbf{p} 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. 1

    Name the unknown

    The point p\mathbf{p} lies on the line, so it is some multiple of a\mathbf{a}: p=x^ a\mathbf{p} = \hat{x}\,\mathbf{a} (read “x hat times a”). We need the number x^\hat{x}.

  2. 2

    Write down the right angle

    The error e=b−x^ a\mathbf{e} = \mathbf{b} - \hat{x}\,\mathbf{a} must be perpendicular to a\mathbf{a}:   a⊤(b−x^ a)=0\;\mathbf{a}^\top(\mathbf{b} - \hat{x}\,\mathbf{a}) = 0.

  3. 3

    Expand and solve

    Distributing gives a⊤b−x^ a⊤a=0\mathbf{a}^\top\mathbf{b} - \hat{x}\,\mathbf{a}^\top\mathbf{a} = 0, so x^=a⊤ba⊤a\hat{x} = \dfrac{\mathbf{a}^\top\mathbf{b}}{\mathbf{a}^\top\mathbf{a}}. This is allowed because a⊤a=∥a∥2\mathbf{a}^\top\mathbf{a} = \|\mathbf{a}\|^2 is not zero.

  4. 4

    Assemble the projection

    p=x^ a=a a⊤ba⊤a\mathbf{p} = \hat{x}\,\mathbf{a} = \mathbf{a}\,\dfrac{\mathbf{a}^\top\mathbf{b}}{\mathbf{a}^\top\mathbf{a}}. Moving the scalar around, p=aa⊤a⊤a b=Pb\mathbf{p} = \dfrac{\mathbf{a}\mathbf{a}^\top}{\mathbf{a}^\top\mathbf{a}}\,\mathbf{b} = P\mathbf{b}, with the projection matrix P=aa⊤a⊤aP = \dfrac{\mathbf{a}\mathbf{a}^\top}{\mathbf{a}^\top\mathbf{a}}.

A worked example. Let a=(1,2)\mathbf{a} = (1, 2) and b=(3,1)\mathbf{b} = (3, 1). Then a⊤b=3+2=5\mathbf{a}^\top\mathbf{b} = 3 + 2 = 5 and a⊤a=5\mathbf{a}^\top\mathbf{a} = 5, so x^=1\hat{x} = 1 and p=(1,2)\mathbf{p} = (1, 2). The error is e=(2,−1)\mathbf{e} = (2, -1), and indeed a⊤e=2−2=0\mathbf{a}^\top\mathbf{e} = 2 - 2 = 0. The matrix is

P=15[1224].P = \frac{1}{5}\begin{bmatrix} 1 & 2 \\ 2 & 4 \end{bmatrix}.

Notice three things. PP is the outer product aa⊤\mathbf{a}\mathbf{a}^\top scaled down, so it has rank 1, just like the uv⊤\mathbf{u}\mathbf{v}^\top matrices of Chamber 6: everything lands on one line. PP is symmetric. And P2=PP^2 = P (read “P squared equals P”): once a vector is on the line, projecting it again leaves it where it is. Try multiplying PP by itself to see it happen.

Quick check +20 XP

Project b=(3,4)\mathbf{b} = (3, 4) onto the line through a=(2,1)\mathbf{a} = (2, 1). The projection is p=(p1,p2)\mathbf{p} = (p_1, p_2). What is p1p_1?

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 SS be a subspace, b\mathbf{b} any vector, and p\mathbf{p} a point of SS whose error b−p\mathbf{b} - \mathbf{p} is perpendicular to every vector in SS. Then p\mathbf{p} is the closest point of SS to b\mathbf{b}: ∥b−q∥≥∥b−p∥\|\mathbf{b} - \mathbf{q}\| \ge \|\mathbf{b} - \mathbf{p}\| for every q\mathbf{q} in SS, with equality only when q=p\mathbf{q} = \mathbf{p}.

Proof. Let q\mathbf{q} be any point of SS. Split the path from q\mathbf{q} to b\mathbf{b} at p\mathbf{p}:

b−q=(b−p)+(p−q).\mathbf{b} - \mathbf{q} = (\mathbf{b} - \mathbf{p}) + (\mathbf{p} - \mathbf{q}).

Both p\mathbf{p} and q\mathbf{q} lie in the subspace SS, so their difference p−q\mathbf{p} - \mathbf{q} does too. By assumption b−p\mathbf{b} - \mathbf{p} is perpendicular to everything in SS, so the two pieces are perpendicular: (b−p)⊤(p−q)=0(\mathbf{b} - \mathbf{p})^\top(\mathbf{p} - \mathbf{q}) = 0. Expanding the squared length, the cross terms are exactly this dot product (twice), so they vanish:

∥b−q∥2=∥b−p∥2+2(b−p)⊤(p−q)+∥p−q∥2=∥b−p∥2+∥p−q∥2.\|\mathbf{b} - \mathbf{q}\|^2 = \|\mathbf{b} - \mathbf{p}\|^2 + 2(\mathbf{b} - \mathbf{p})^\top(\mathbf{p} - \mathbf{q}) + \|\mathbf{p} - \mathbf{q}\|^2 = \|\mathbf{b} - \mathbf{p}\|^2 + \|\mathbf{p} - \mathbf{q}\|^2.

The last term is a squared length, so it is never negative. Therefore ∥b−q∥2≥∥b−p∥2\|\mathbf{b} - \mathbf{q}\|^2 \ge \|\mathbf{b} - \mathbf{p}\|^2, and equality forces ∥p−q∥=0\|\mathbf{p} - \mathbf{q}\| = 0, that is, q=p\mathbf{q} = \mathbf{p}. ■\blacksquare

Read the anatomy. The claim has a hypothesis (the error is perpendicular to SS) and a conclusion (closest point). The one idea is to split b−q\mathbf{b} - \mathbf{q} into a perpendicular piece and a piece inside SS. Then Pythagoras does the rest: the right triangle with corners b\mathbf{b}, p\mathbf{p} and q\mathbf{q} has hypotenuse b−q\mathbf{b} - \mathbf{q}, 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 AA be m×nm \times n with independent columns a1,…,an\mathbf{a}_1, \ldots, \mathbf{a}_n, and let b\mathbf{b} be a vector in Rm\mathbb{R}^m. The closest point of C(A)C(A) to b\mathbf{b} is some combination of the columns, p=Ax^\mathbf{p} = A\hat{\mathbf{x}}. 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. 1

    Name the unknowns

    p=Ax^\mathbf{p} = A\hat{\mathbf{x}} for an unknown vector of weights x^∈Rn\hat{\mathbf{x}} \in \mathbb{R}^n (read “x hat”). The error is e=b−Ax^\mathbf{e} = \mathbf{b} - A\hat{\mathbf{x}}.

  2. 2

    Write down the right angles

    e\mathbf{e} must be perpendicular to every column: a1⊤e=0,…,an⊤e=0\mathbf{a}_1^\top\mathbf{e} = 0, \ldots, \mathbf{a}_n^\top\mathbf{e} = 0. These nn dot products are the entries of A⊤eA^\top\mathbf{e}, so all of them at once read A⊤(b−Ax^)=0A^\top(\mathbf{b} - A\hat{\mathbf{x}}) = \mathbf{0}.

  3. 3

    Rearrange: the normal equations

    Distribute and move one term across: A⊤A x^=A⊤bA^\top A\,\hat{\mathbf{x}} = A^\top\mathbf{b}. These are the normal equations (“normal” is an old word for perpendicular). They are nn equations in nn unknowns, a square system.

  4. 4

    Solve

    When the columns of AA are independent, the square matrix A⊤AA^\top A is invertible (you'll assemble the proof in Your turn). So x^=(A⊤A)−1A⊤b\hat{\mathbf{x}} = (A^\top A)^{-1}A^\top\mathbf{b}.

  5. 5

    Project

    p=Ax^=A(A⊤A)−1A⊤b=Pb\mathbf{p} = A\hat{\mathbf{x}} = A(A^\top A)^{-1}A^\top\mathbf{b} = P\mathbf{b}, with the projection matrix P=A(A⊤A)−1A⊤P = A(A^\top A)^{-1}A^\top.

That is the formula from the Discover section, with A=XA = \mathbf{X}, b=Y\mathbf{b} = \mathbf{Y} and x^=β^\hat{\mathbf{x}} = \hat{\boldsymbol{\beta}}. It came from one idea: the error is perpendicular to the columns. With a single column a\mathbf{a}, the matrix A⊤AA^\top A is the number a⊤a\mathbf{a}^\top\mathbf{a} and everything reduces to the line case.

Projection and least-squares notation
  • proj⁡a(b)\operatorname{proj}_{\mathbf{a}}(\mathbf{b})“the projection of b onto a”
    The point on the line through a\mathbf{a} that is closest to b\mathbf{b}: the shadow of b\mathbf{b} on that line.
    proj⁡a(b)=a⊤ba⊤a a\operatorname{proj}_{\mathbf{a}}(\mathbf{b}) = \frac{\mathbf{a}^\top\mathbf{b}}{\mathbf{a}^\top\mathbf{a}}\,\mathbf{a}
  • P=A(A⊤A)−1A⊤P = A(A^\top A)^{-1}A^\top“P equals A, times A transpose A inverse, times A transpose”
    The projection matrix onto the column space of AA (whose columns are independent): PbP\mathbf{b} is the closest point to b\mathbf{b} in C(A)C(A).
  • P2=PP^2 = P“P squared equals P”
    Projecting twice changes nothing. Matrices with this property are called idempotent.
  • x^\hat{\mathbf{x}}“x hat”
    The least-squares solution of Ax≈bA\mathbf{x} \approx \mathbf{b}: the best compromise when no exact solution exists. As always, the hat marks an estimate.
    x^=(A⊤A)−1A⊤b\hat{\mathbf{x}} = (A^\top A)^{-1}A^\top\mathbf{b}
  • e=b−Ax^\mathbf{e} = \mathbf{b} - A\hat{\mathbf{x}}“e equals b minus A x hat”
    The error (or residual) vector: the part of b\mathbf{b} the best fit can't reach. Statistics usually calls it r\mathbf{r}.
  • A⊤Ax^=A⊤bA^\top A\hat{\mathbf{x}} = A^\top\mathbf{b}“A transpose A x hat equals A transpose b”
    The normal equations. They say the error is perpendicular (“normal”) to every column of AA.
  • min⁡x ∥b−Ax∥2\min_{\mathbf{x}}\, \|\mathbf{b} - A\mathbf{x}\|^2“the minimum over x of the squared length of b minus A x”
    The least-squares problem: choose x\mathbf{x} to make the sum of squared errors as small as possible.

Like the line version, PP is symmetric and satisfies P2=PP^2 = P. You'll prove both in Your turn.

Quick check +20 XP

Which equation says “the error e=b−Ax^\mathbf{e} = \mathbf{b} - A\hat{\mathbf{x}} is perpendicular to every column of AA”?

Learn: least squares is a projection

Back to the eight researchers. For a candidate line θ=(w,b)\boldsymbol{\theta} = (w, b), the vector of predictions is XθX\boldsymbol{\theta}, and the sum of squared errors is

∑i=18(yi−(wxi+b))2=∥y−Xθ∥2.\sum_{i=1}^{8} \big(y_i - (w x_i + b)\big)^2 = \|\mathbf{y} - X\boldsymbol{\theta}\|^2.

That is the squared distance in R8\mathbb{R}^8 between the data y\mathbf{y} and the point XθX\boldsymbol{\theta}. As θ\boldsymbol{\theta} varies, XθX\boldsymbol{\theta} sweeps out the column space C(X)C(X), a plane in R8\mathbb{R}^8. So the best line is the closest point of that plane to y\mathbf{y}, which is the projection. Linear regression is a projection, and its coefficients solve the normal equations X⊤Xθ^=X⊤yX^\top X\hat{\boldsymbol{\theta}} = X^\top\mathbf{y}. Statistics writes the same thing as Xβ≈Y\mathbf{X}\boldsymbol{\beta} \approx \mathbf{Y} and linear algebra as Ax≈bA\mathbf{x} \approx \mathbf{b}: one problem, three dialects.

Let's do a small one completely by hand, with three points (1,1)(1, 1), (2,2)(2, 2) and (3,2)(3, 2). It is the example Gilbert Strang works in the lecture recommended below.

X=[112131],X⊤X=[14663],X⊤y=[115].X = \begin{bmatrix} 1 & 1 \\ 2 & 1 \\ 3 & 1 \end{bmatrix}, \quad X^\top X = \begin{bmatrix} 14 & 6 \\ 6 & 3 \end{bmatrix}, \quad X^\top\mathbf{y} = \begin{bmatrix} 11 \\ 5 \end{bmatrix}.

The normal equations are 14w+6b=1114w + 6b = 11 and 6w+3b=56w + 3b = 5. Doubling the second gives 12w+6b=1012w + 6b = 10, and subtracting it from the first leaves 2w=12w = 1. So w=12w = \tfrac{1}{2} and b=23b = \tfrac{2}{3}: the best line is y^=12x+23\hat{y} = \tfrac{1}{2}x + \tfrac{2}{3}. Its predictions are (76,53,136)(\tfrac{7}{6}, \tfrac{5}{3}, \tfrac{13}{6}) and the residuals are

r=y−Xθ^=(−16,  13,  −16).\mathbf{r} = \mathbf{y} - X\hat{\boldsymbol{\theta}} = \left(-\tfrac{1}{6},\; \tfrac{1}{3},\; -\tfrac{1}{6}\right).

Check the right angles. Against the column of ones: −16+13−16=0-\tfrac{1}{6} + \tfrac{1}{3} - \tfrac{1}{6} = 0. Against the xx column: −16+23−12=0-\tfrac{1}{6} + \tfrac{2}{3} - \tfrac{1}{2} = 0. 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

Eight researchers again: x is cups of coffee per day, y is lines of code (in tens). Drag the two handles on the line, or use the sliders, to make the sum of squared errors ‖y − Xθ‖² as small as you can. Get within 1% of the least-squares minimum, then look at the residual.
051015202501234567cups of coffee per day (x)lines of code, tens (y)

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.

Challenge: Least squares by handGet within 1% of the least-squares error, then confirm the residual is orthogonal.+40 XP

In the lab you saw a line whose error was almost minimal but whose residual was not orthogonal to the columns: X⊤rX^\top\mathbf{r} 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 C(X)C(X), the least-squares residuals of any line with an intercept sum to zero, and the fitted line always passes through the mean point (xˉ,yˉ)(\bar{x}, \bar{y}).

Learn: Gram–Schmidt and QR

Projections are easiest of all when the columns are orthonormal. If A=QA = Q with Q⊤Q=IQ^\top Q = I, the normal equations Q⊤Q x^=Q⊤bQ^\top Q\,\hat{\mathbf{x}} = Q^\top\mathbf{b} collapse to x^=Q⊤b\hat{\mathbf{x}} = Q^\top\mathbf{b}, and the projection matrix becomes P=QQ⊤P = QQ^\top. 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.

Gram–Schmidt and QR
  • vk=ak−∑j<k(qj⊤ak) qj\mathbf{v}_k = \mathbf{a}_k - \sum_{j<k} (\mathbf{q}_j^\top\mathbf{a}_k)\,\mathbf{q}_j“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 ak\mathbf{a}_k its projections onto the earlier directions, then normalise, qk=vk/∥vk∥\mathbf{q}_k = \mathbf{v}_k / \|\mathbf{v}_k\|.
  • A=QRA = QR“A equals Q R”
    The QR factorisation: QQ has orthonormal columns (from Gram–Schmidt) and R=Q⊤AR = Q^\top A is upper triangular.

Here it is on a1=(1,1,0)\mathbf{a}_1 = (1, 1, 0) and a2=(1,0,1)\mathbf{a}_2 = (1, 0, 1).

  1. 1

    First direction: just normalise

    ∥a1∥=2\|\mathbf{a}_1\| = \sqrt{2}, so q1=12(1,1,0)\mathbf{q}_1 = \tfrac{1}{\sqrt{2}}(1, 1, 0).

  2. 2

    Second direction: remove the shadow on the first

    q1⊤a2=12\mathbf{q}_1^\top\mathbf{a}_2 = \tfrac{1}{\sqrt{2}}, so v2=a2−12 q1=(1,0,1)−(12,12,0)=(12,−12,1)\mathbf{v}_2 = \mathbf{a}_2 - \tfrac{1}{\sqrt{2}}\,\mathbf{q}_1 = (1, 0, 1) - (\tfrac{1}{2}, \tfrac{1}{2}, 0) = (\tfrac{1}{2}, -\tfrac{1}{2}, 1). Check: q1⊤v2∝12−12+0=0\mathbf{q}_1^\top\mathbf{v}_2 \propto \tfrac{1}{2} - \tfrac{1}{2} + 0 = 0.

  3. 3

    Normalise

    ∥v2∥=14+14+1=32\|\mathbf{v}_2\| = \sqrt{\tfrac{1}{4} + \tfrac{1}{4} + 1} = \sqrt{\tfrac{3}{2}}, so q2=16(1,−1,2)\mathbf{q}_2 = \tfrac{1}{\sqrt{6}}(1, -1, 2).

q1\mathbf{q}_1 and q2\mathbf{q}_2 span the same plane as a1\mathbf{a}_1 and a2\mathbf{a}_2, but now they meet at a right angle and have unit length.

Record the bookkeeping and you get a factorisation. Each ak\mathbf{a}_k is a combination of q1,…,qk\mathbf{q}_1, \ldots, \mathbf{q}_k only, never of later ones, so

A=QR,R=Q⊤A upper triangular.A = QR, \qquad R = Q^\top A \text{ upper triangular}.

This QR factorisation is how careful software does least squares. Substituting A=QRA = QR into the normal equations and cancelling (both R⊤R^\top and RR are invertible here) leaves Rx^=Q⊤bR\hat{\mathbf{x}} = Q^\top\mathbf{b}: a triangular system you solve by back substitution, as in Chamber 5.

Python
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
DiscoverLearnRead beyondPapers & lecturesYour turn

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 Squares

Stephen 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 Learning

Marc 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 Notes

Andrew 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-Schmidt

Gilbert 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.

DiscoverLearnRead beyondPapers & lecturesYour 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 ∥y−Xθ^∥2\|\mathbf{y} - X\hat{\boldsymbol{\theta}}\|^2. 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), 1970

Adds a small positive number to the diagonal of X′X\mathbf{X}'\mathbf{X} 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, 2013

The 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 Problems

Arthur E. Hoerl, Robert W. Kennard · Technometrics 12(1), 1970

+30 XP
β^∗=[X′X+kI]−1X′Y;k≥0\hat{\boldsymbol{\beta}}^* = [\mathbf{X}'\mathbf{X} + k\mathbf{I}]^{-1}\mathbf{X}'\mathbf{Y}; \quad k \ge 0

The ridge estimator, as Hoerl and Kennard print it. Set k=0k = 0 and it becomes their Eq. (1.1), β^=(X′X)−1X′Y\hat{\boldsymbol{\beta}} = (\mathbf{X}'\mathbf{X})^{-1}\mathbf{X}'\mathbf{Y}: exactly the normal-equations solution from this chamber. Match each piece to its meaning.

β^∗\hat{\boldsymbol{\beta}}^*
X′\mathbf{X}'
X′X\mathbf{X}'\mathbf{X}
kk
I\mathbf{I}
Y\mathbf{Y}
[ ⋅ ]−1[\,\cdot\,]^{-1}

Options

Watch

15. Projections onto SubspacesMIT OpenCourseWare · 49 min
16. Projection Matrices and Least SquaresMIT OpenCourseWare · 48 min

Gilbert Strang's classic 18.06 lectures. In the first, watch him derive A⊤(b−Ax^)=0A^\top(\mathbf{b} - A\hat{\mathbf{x}}) = \mathbf{0} from the same right angle you used here. In the second, he fits the line through (1,1)(1, 1), (2,2)(2, 2) and (3,2)(3, 2) and draws both pictures at once: the points and line in the plane, and the projection in R3\mathbb{R}^3. Pause each time before he writes a formula and try to say it first.

DiscoverLearnRead beyondPapers & lecturesYour turn

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

+25 XP

Match each piece of notation to what it says in words.

u⊤v=0\mathbf{u}^\top\mathbf{v} = 0
Q⊤Q=IQ^\top Q = I
P2=PP^2 = P
aa⊤a⊤a\frac{\mathbf{a}\mathbf{a}^\top}{\mathbf{a}^\top\mathbf{a}}
A⊤(b−Ax^)=0A^\top(\mathbf{b} - A\hat{\mathbf{x}}) = \mathbf{0}
min⁡x∥b−Ax∥2\min_{\mathbf{x}} \|\mathbf{b} - A\mathbf{x}\|^2
A=QRA = QR

Options

Match · Maths ↔ NumPy

From symbols to NumPy

+25 XP

Match each formula to the NumPy that computes it. Here @ is matrix multiplication and .T is the transpose.

A⊤Ax^=A⊤bA^\top A\hat{\mathbf{x}} = A^\top\mathbf{b}, solved for x^\hat{\mathbf{x}}
x^\hat{\mathbf{x}}, computed the numerically careful way
A=QRA = QR
Q⊤QQ^\top Q
aa⊤a⊤a\frac{\mathbf{a}\mathbf{a}^\top}{\mathbf{a}^\top\mathbf{a}}
A⊤(b−Ax^)A^\top(\mathbf{b} - A\hat{\mathbf{x}})
∥b−Ax∥2\|\mathbf{b} - A\mathbf{x}\|^2

Options

Proofs

The puzzle proves the fact the normal equations rely on: independent columns make A⊤AA^\top A invertible. Then prove the two properties of PP yourself.

Proof puzzle

Independent columns make AᵀA invertible

+25 XP

Claim

If the columns of an m×nm \times n matrix AA are linearly independent, then the n×nn \times n matrix A⊤AA^\top A 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

  1. Pick the first line below.

Available lines

Prove it yourself

The projection matrix is idempotent and symmetric

+40 XP

Claim

Let AA be an m×nm \times n matrix with independent columns, and let P=A(A⊤A)−1A⊤P = A(A^\top A)^{-1}A^\top. Prove that P2=PP^2 = P and P⊤=PP^\top = P.

Preview

Your typeset proof appears here.

Code it up

Problem 19·Warm-up

A line through the origin

+20 XP

Some models have no intercept: y^=w x\hat{y} = w\,x. Fitting ww by least squares is a projection onto a line. Stack the inputs into x∈Rn\mathbf{x} \in \mathbb{R}^n and the targets into y∈Rn\mathbf{y} \in \mathbb{R}^n. The best ww is the projection coefficient

w^=x⊤yx⊤x,\hat{w} = \frac{\mathbf{x}^\top\mathbf{y}}{\mathbf{x}^\top\mathbf{x}},

and the smallest possible sum of squared errors is ∥y−w^x∥2\|\mathbf{y} - \hat{w}\mathbf{x}\|^2: the squared distance from y\mathbf{y} to the line through x\mathbf{x}.

Take n=12n = 12 points with xi=ix_i = i and yi=7i mod 13y_i = 7i \bmod 13 for i=1,2,…,12i = 1, 2, \ldots, 12 (so y1=7y_1 = 7, y2=1y_2 = 1, y3=8y_3 = 8, …). What is the minimum sum of squared errors

∑i=112(yi−w^ xi)2?\sum_{i=1}^{12} \big(y_i - \hat{w}\,x_i\big)^2 ?

Give it as a fraction in lowest terms, like 7/12.

An exact integer (or a fraction like 7/12)

Problem 20·Standard

Gram's orthogonal polynomials

+35 XP

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 t=0,1,2,…,10t = 0, 1, 2, \ldots, 10 and build four vectors in R11\mathbb{R}^{11} from the powers of tt: ak=(0k,1k,2k,…,10k)\mathbf{a}_k = (0^k, 1^k, 2^k, \ldots, 10^k) for k=0,1,2,3k = 0, 1, 2, 3. So a0\mathbf{a}_0 is all ones (take 00=10^0 = 1) and a2=(0,1,4,9,…,100)\mathbf{a}_2 = (0, 1, 4, 9, \ldots, 100).

Run Gram–Schmidt without normalising:

vk=ak−∑j<kvj⊤akvj⊤vj vj,k=0,1,2,3,\mathbf{v}_k = \mathbf{a}_k - \sum_{j<k} \frac{\mathbf{v}_j^\top\mathbf{a}_k}{\mathbf{v}_j^\top\mathbf{v}_j}\,\mathbf{v}_j, \qquad k = 0, 1, 2, 3,

where the sum is empty for k=0k = 0, so v0=a0\mathbf{v}_0 = \mathbf{a}_0. What is ∥v3∥2\|\mathbf{v}_3\|^2? Give it as a fraction in lowest terms.

An exact integer (or a fraction like 7/12)

Problem 21·Challenge

Walking the ridge trace

+50 XP

Hoerl and Kennard (1970) warn that when the columns of XX 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

β^∗(k)=[X⊤X+kI]−1X⊤y,k≥0,\hat{\boldsymbol{\beta}}^*(k) = [X^\top X + kI]^{-1}X^\top\mathbf{y}, \qquad k \ge 0,

and their ridge trace follows each coefficient as kk grows from 00. (The paper first rescales the predictors so that X⊤XX^\top X is a correlation matrix. We skip that step to keep the numbers simple.)

Twelve observations have two predictors and no intercept. For i=1,2,…,12i = 1, 2, \ldots, 12:

xi1=i,xi2=i+(7i mod 3)−1,yi=i+(3i mod 11)−5.x_{i1} = i, \qquad x_{i2} = i + (7i \bmod 3) - 1, \qquad y_i = i + (3i \bmod 11) - 5.

Row ii of XX is (xi1,xi2)(x_{i1}, x_{i2}). The two columns are almost identical, and at k=0k = 0 (ordinary least squares) the second coefficient β^2∗\hat{\beta}^*_2 comes out negative, even though yy rises with both predictors. What is the smallest integer k≥0k \ge 0 for which β^2∗(k)>0\hat{\beta}^*_2(k) > 0?

An exact integer (or a fraction like 7/12)

Key takeaways

  • Orthogonal means a zero dot product, and A⊤y=0A^\top\mathbf{y} = \mathbf{0} says y\mathbf{y} is perpendicular to every column of AA: N(A⊤)=C(A)⊥N(A^\top) = C(A)^\perp.
  • Orthonormal columns satisfy Q⊤Q=IQ^\top Q = I. Coordinates become dot products, a square QQ is inverted by transposing, and lengths and angles are preserved.
  • The closest point is the foot of the perpendicular. Projection onto a line is a⊤ba⊤aa\frac{\mathbf{a}^\top\mathbf{b}}{\mathbf{a}^\top\mathbf{a}}\mathbf{a}; onto a column space it is PbP\mathbf{b} with P=A(A⊤A)−1A⊤P = A(A^\top A)^{-1}A^\top, and P2=P=P⊤P^2 = P = P^\top.
  • Least squares is a projection. Requiring the error to be perpendicular to the columns gives the normal equations A⊤Ax^=A⊤bA^\top A\hat{\mathbf{x}} = A^\top\mathbf{b}, the same equations as setting the gradient of the squared error to zero.
  • Gram–Schmidt builds an orthonormal basis by subtracting projections, giving A=QRA = QR, the stable way to solve least squares in practice. Ridge regression adds kIkI to A⊤AA^\top A 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.

0/8
Question 1 of 8 +20 XP

Which pair of vectors is orthogonal?

Question 2 of 8 +20 XP

q1=(35,45)\mathbf{q}_1 = (\tfrac{3}{5}, \tfrac{4}{5}) and q2=(−45,35)\mathbf{q}_2 = (-\tfrac{4}{5}, \tfrac{3}{5}) form an orthonormal basis of R2\mathbb{R}^2. Writing x=(5,10)\mathbf{x} = (5, 10) as c1q1+c2q2c_1\mathbf{q}_1 + c_2\mathbf{q}_2, what is c1c_1?

Question 3 of 8 +20 XP

Fit y^=wx+b\hat{y} = wx + b by least squares to the four points (0,1)(0, 1), (1,3)(1, 3), (2,4)(2, 4) and (3,4)(3, 4). What is the intercept bb?

Question 4 of 8 +20 XP

When a least-squares line has an intercept bb, its residuals always sum to exactly zero. Why?

Question 5 of 8 +20 XP

PP is the matrix that projects onto a plane through the origin in R3\mathbb{R}^3. Which statement is true?

Question 6 of 8 +20 XP

Gram–Schmidt starts from a1=(1,0,1)\mathbf{a}_1 = (1, 0, 1) and a2=(2,1,0)\mathbf{a}_2 = (2, 1, 0). The second, unnormalised, vector is v2=a2−a1⊤a2a1⊤a1 a1\mathbf{v}_2 = \mathbf{a}_2 - \frac{\mathbf{a}_1^\top\mathbf{a}_2}{\mathbf{a}_1^\top\mathbf{a}_1}\,\mathbf{a}_1. What is v2\mathbf{v}_2?

Question 7 of 8 +20 XP

Hoerl and Kennard's ridge regression replaces X⊤XX^\top X with X⊤X+kIX^\top X + kI for some k>0k > 0. What does the extra kIkI do?

Question 8 of 8 +20 XP

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

+60 XPOrthonormal BasisProjectionLeast SquaresGram–Schmidt