Math for ML / Linear Algebra II
0 / 12
Module 5

Linear Algebra II

Module 1 gave you the pictures: vectors, transformations, determinants, eigenvectors. This module turns them into the tools that machine learning uses every day. You'll see why perpendicular directions make everything easy, how least squares is just dropping a perpendicular, why every matrix is secretly rotate, stretch, rotate (A=UΣV⊤A=U\Sigma V^\top), how that one fact gives you image compression, PCA and the pseudoinverse, why some problems turn tiny noise into huge errors, and how to keep tensor shapes straight in NumPy and PyTorch. It ends with the low-rank factorizations behind recommender systems and LoRA fine-tuning.

How to use this module

  • Watch, then play. Chapters link to the best videos on each idea. Watch, then come back and drag the figure until it feels obvious.
  • Questions get harder as you go: Warm-up Practice Think Challenge. Pick one answer, press Check answer, and the worked solution opens.
  • Code it: Python runs in your browser and is graded by test cases. The first run downloads Python (internet needed once).
  • Your progress is saved in this browser. Tick "mark as done" at the end of each chapter.
Chapter 1

Orthogonality and orthonormal bases

Watch: Orthogonal vectors and subspaces (MIT OCW, Gilbert Strang) Rewatch: Dot products and duality (3Blue1Brown)

Two vectors are orthogonal when their dot product is zero. A basis of mutually perpendicular unit vectors is the best basis there is: coordinates become dot products, lengths obey Pythagoras, and the matrix that holds the basis is inverted just by transposing it.

In Module 1, chapter 9 you met the dot product: v⋅w=v1w1+v2w2+…\mathbf v\cdot\mathbf w = v_1w_1+v_2w_2+\dots, which equals ∣v∣ ∣w∣cos⁡θ|\mathbf v|\,|\mathbf w|\cos\theta. The cosine is zero exactly at 90°, so

v⊥w⟺v⋅w=0.\mathbf v \perp \mathbf w \quad\Longleftrightarrow\quad \mathbf v\cdot\mathbf w = 0.

That's the whole definition of orthogonal (a fancier word for perpendicular that also works in 50 dimensions, where you can't see any angles). For example (2, −1) and (1, 2) are orthogonal because 2 − 2 = 0.

Why perpendicular is special. If v⊥w\mathbf v\perp\mathbf w then Pythagoras holds: ∣v+w∣2=∣v∣2+2 v⋅w+∣w∣2=∣v∣2+∣w∣2|\mathbf v+\mathbf w|^2 = |\mathbf v|^2+2\,\mathbf v\cdot\mathbf w+|\mathbf w|^2 = |\mathbf v|^2+|\mathbf w|^2. The cross term vanishes. Perpendicular pieces don't interfere with each other: you can measure, add and remove them separately. Almost every trick in this module comes from that one fact.

Orthonormal bases: coordinates for free

A set of vectors q1,…,qn\mathbf q_1,\dots,\mathbf q_n is orthonormal if each has length 1 and each pair is orthogonal:

qi⋅qj={1i=j0i≠j.\mathbf q_i\cdot\mathbf q_j = \begin{cases}1 & i=j\\ 0 & i\neq j.\end{cases}

Orthonormal vectors are automatically independent, so nn of them in nn dimensions form a basis. Now the payoff. In a general basis, finding the coordinates of x\mathbf x means solving a system of equations (change of basis). In an orthonormal basis, write x=c1q1+⋯+cnqn\mathbf x = c_1\mathbf q_1+\dots+c_n\mathbf q_n and dot both sides with q1\mathbf q_1. Every term except the first dies, because q1⋅qj=0\mathbf q_1\cdot\mathbf q_j=0, and q1⋅q1=1\mathbf q_1\cdot\mathbf q_1=1, so

ci=qi⋅x.c_i = \mathbf q_i\cdot\mathbf x.

Each coordinate is just "how far does x\mathbf x reach along qi\mathbf q_i?" No system to solve. And because the pieces are perpendicular, Pythagoras gives ∣x∣2=c12+⋯+cn2|\mathbf x|^2 = c_1^2+\dots+c_n^2.

Drag the teal tip to turn the orthonormal basis q1,q2\mathbf q_1,\mathbf q_2 (q2\mathbf q_2 always stays perpendicular), and drag the gold vector x\mathbf x. The dashed drops show the two coordinates c1=q1⋅xc_1=\mathbf q_1\cdot\mathbf x and c2=q2⋅xc_2=\mathbf q_2\cdot\mathbf x. Notice that c12+c22c_1^2+c_2^2 always equals ∣x∣2|\mathbf x|^2, however you turn the basis.

Orthogonal matrices

Put orthonormal vectors in the columns of a matrix QQ. The entries of Q⊤QQ^\top Q are exactly the dot products qi⋅qj\mathbf q_i\cdot\mathbf q_j, so

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

When QQ is square this means Q−1=Q⊤Q^{-1}=Q^\top: inverting is free. Such a QQ is called an orthogonal matrix (the name is a historical accident; "orthonormal matrix" would be better). Geometrically it's a rotation, a reflection, or a mix. It keeps every length and angle, because (Qx)⋅(Qy)=x⊤Q⊤Q y=x⋅y(Q\mathbf x)\cdot(Q\mathbf y) = \mathbf x^\top Q^\top Q\,\mathbf y = \mathbf x\cdot\mathbf y. Its determinant is +1+1 (rotation) or −1-1 (includes a flip), since det⁡(Q)2=det⁡(Q⊤Q)=1\det(Q)^2=\det(Q^\top Q)=1.

The coordinate formula ci=qi⋅xc_i=\mathbf q_i\cdot\mathbf x for all ii at once is c=Q⊤x\mathbf c = Q^\top\mathbf x, and rebuilding is x=Qc\mathbf x = Q\mathbf c.

Careful with tall ones. If QQ is 5×2 with orthonormal columns, Q⊤Q=I2Q^\top Q = I_2 still holds, but QQ⊤QQ^\top is a 5×5 matrix that is not the identity: it can't be, since it has rank 2. It turns out to be the projection onto the plane of the two columns. That's the next chapter.

Orthogonal subspaces

Whole subspaces can be perpendicular too: every vector in one is orthogonal to every vector in the other. The most important example hides inside every matrix. If Ax=0A\mathbf x=\mathbf 0, then each row of AA dotted with x\mathbf x gives 0. So the null space is perpendicular to every row, and hence to the row space (the span of the rows). In Rn\mathbb R^n these two fill everything between them: their dimensions add up to nn. They are orthogonal complements. Likewise the column space is perpendicular to the null space of A⊤A^\top.

Worked exampleCoordinates in a tilted orthonormal basis

Take q1=(0.6, 0.8)\mathbf q_1 = (0.6,\ 0.8) and q2=(−0.8, 0.6)\mathbf q_2=(-0.8,\ 0.6). Check: ∣q1∣2=0.36+0.64=1|\mathbf q_1|^2 = 0.36+0.64=1, ∣q2∣2=1|\mathbf q_2|^2=1, and q1⋅q2=−0.48+0.48=0\mathbf q_1\cdot\mathbf q_2 = -0.48+0.48=0. Orthonormal ✓.

Find the coordinates of x=(2,1)\mathbf x = (2, 1):

  • c1=q1⋅x=1.2+0.8=2c_1 = \mathbf q_1\cdot\mathbf x = 1.2+0.8 = 2
  • c2=q2⋅x=−1.6+0.6=−1c_2 = \mathbf q_2\cdot\mathbf x = -1.6+0.6 = -1

Check by rebuilding: 2q1−q2=(1.2+0.8, 1.6−0.6)=(2,1)2\mathbf q_1 - \mathbf q_2 = (1.2+0.8,\ 1.6-0.6) = (2, 1) ✓. And Pythagoras: c12+c22=4+1=5=∣x∣2c_1^2+c_2^2 = 4+1 = 5 = |\mathbf x|^2 ✓.

As a matrix: Q=[0.6−0.80.80.6]Q=\begin{bmatrix}0.6&-0.8\\0.8&0.6\end{bmatrix} is a rotation by about 53°, det⁡Q=0.36+0.64=1\det Q = 0.36+0.64=1, and c=Q⊤x\mathbf c = Q^\top\mathbf x.

Watch outCommon misconceptions

  • "Orthogonal columns make an orthogonal matrix." The columns also need length 1. [11−11]\begin{bmatrix}1&1\\-1&1\end{bmatrix} has perpendicular columns, but Q⊤Q=2IQ^\top Q = 2I, not II.
  • "Q⊤Q=IQ^\top Q=I means QQ⊤=IQQ^\top=I." Only for square QQ. For a tall QQ, QQ⊤QQ^\top is a projection.
  • "Orthogonal means independent, and independent means orthogonal." Nonzero orthogonal vectors are always independent, but (1, 0) and (1, 1) are independent and not orthogonal.
  • "Uncorrelated features are orthogonal vectors." Only after you subtract each feature's mean. Correlation is the cosine between centred columns.

In ML & deep learningWhere this shows up

Orthogonal initialisation: starting a deep or recurrent network's weight matrices as random orthogonal matrices keeps signals from blowing up or dying as they pass through many layers, because QQ preserves length. Rotary position embeddings (RoPE) in modern transformers rotate query and key vectors by position-dependent 2D rotations, which are orthogonal, so attention scores depend only on relative position. Cosine similarity between embeddings is the dot product of unit vectors: 0 means "unrelated directions". And PCA (chapter 8) hands you an orthonormal basis in which features are uncorrelated.

Practice (pick one answer per question)

Are (2, −1) and (1, 2) orthogonal?

  1. Yes, their dot product is 0
  2. No, their dot product is 4
  3. No, they have different lengths
  4. Yes, because both have length √5

2⋅1+(−1)⋅2=02\cdot1+(-1)\cdot2=0, so yes. Lengths don't matter for orthogonality (they happen to be equal here, but that isn't the reason).

For which kk is (1,k,2)(1, k, 2) orthogonal to (3,1,−1)(3, 1, -1)?

  1. k=−1k=-1
  2. k=1k=1
  3. k=−5k=-5
  4. k=0k=0

3+k−2=03 + k - 2 = 0, so k=−1k=-1.

With q1=12(1,1)\mathbf q_1=\tfrac1{\sqrt2}(1,1) and q2=12(1,−1)\mathbf q_2=\tfrac1{\sqrt2}(1,-1), what are the coordinates of x=(4,2)\mathbf x=(4,2)?

  1. (32, 2)(3\sqrt2,\ \sqrt2)
  2. (6, 2)(6,\ 2)
  3. (3, 1)(3,\ 1)
  4. (2, 32)(\sqrt2,\ 3\sqrt2)

c1=q1⋅x=6/2=32c_1=\mathbf q_1\cdot\mathbf x = 6/\sqrt2 = 3\sqrt2 and c2=2/2=2c_2 = 2/\sqrt2=\sqrt2. Check with Pythagoras: 18+2=20=∣x∣218+2=20=|\mathbf x|^2 ✓. Forgetting the 1/21/\sqrt2 gives (6, 2), whose squares add to 40, not 20.

QQ is a 3×3 orthogonal matrix and ∣x∣=5|\mathbf x|=5. What is ∣Qx∣|Q\mathbf x|?

  1. 5
  2. It depends on QQ
  3. 25
  4. 535\sqrt3

∣Qx∣2=x⊤Q⊤Qx=x⊤x=25|Q\mathbf x|^2 = \mathbf x^\top Q^\top Q\mathbf x = \mathbf x^\top\mathbf x = 25. Rotations and reflections never change length.

Which of these matrices is orthogonal?

  1. [0.6−0.80.80.6]\begin{bmatrix}0.6&-0.8\\0.8&0.6\end{bmatrix}
  2. [11−11]\begin{bmatrix}1&1\\-1&1\end{bmatrix}
  3. [0.60.80.80.6]\begin{bmatrix}0.6&0.8\\0.8&0.6\end{bmatrix}
  4. [1011]\begin{bmatrix}1&0\\1&1\end{bmatrix}

The first has unit columns with dot product −0.48+0.48=0-0.48+0.48=0. The second has perpendicular columns of length 2\sqrt2 (not unit). The third has unit columns but their dot product is 0.96≠00.96\neq0. The fourth is a shear.

QQ is 5×2 with orthonormal columns. Which statement is true?

  1. Q⊤Q=I2Q^\top Q = I_2
  2. QQ⊤=I5QQ^\top = I_5
  3. QQ is invertible
  4. det⁡Q=±1\det Q=\pm1

Q⊤QQ^\top Q holds the dot products of the columns, so it's I2I_2. QQ⊤QQ^\top is 5×5 with rank 2, so it can't be I5I_5. A non-square matrix has no inverse and no determinant.

If Ax=0A\mathbf x=\mathbf 0, then x\mathbf x is guaranteed to be orthogonal to…

  1. every row of AA
  2. every column of AA
  3. the column space of AA
  4. only the first row of AA

Entry ii of AxA\mathbf x is (row ii)·x\mathbf x. All of them are 0, so x\mathbf x is perpendicular to every row and to the whole row space. Columns live in a different space when AA isn't square, so "orthogonal to the columns" doesn't even make sense in general.

Q1Q_1 and Q2Q_2 are orthogonal n×nn\times n matrices. Is the product Q1Q2Q_1Q_2 orthogonal?

  1. Always: (Q1Q2)⊤(Q1Q2)=Q2⊤Q1⊤Q1Q2=I(Q_1Q_2)^\top(Q_1Q_2)=Q_2^\top Q_1^\top Q_1Q_2 = I
  2. Only if Q1Q2=Q2Q1Q_1Q_2=Q_2Q_1
  3. Only if both are rotations
  4. Never, because the columns get mixed

(Q1Q2)⊤=Q2⊤Q1⊤(Q_1Q_2)^\top = Q_2^\top Q_1^\top, and the middle Q1⊤Q1Q_1^\top Q_1 collapses to II. Geometrically: doing one length-preserving map after another preserves length. (Two reflections make a rotation, which is still orthogonal.)

Code it (optional: real Python runs in your browser and is graded by test cases)

Chapter 2

Projections onto subspaces and least squares

Watch: Projections onto subspaces (MIT OCW, Gilbert Strang) Watch: Projection matrices and least squares (MIT OCW, Gilbert Strang)

The closest point to b\mathbf b in a subspace is the one where the leftover error is perpendicular to the subspace. Writing "error ⟂ every column of AA" as an equation gives the normal equations A⊤Ax^=A⊤bA^\top A\hat{\mathbf x}=A^\top\mathbf b, and that is least-squares regression.

Projecting onto a line

You have a vector b\mathbf b and a line through the origin in direction a\mathbf a. Which point p\mathbf p on the line is closest to b\mathbf b? Picture dropping a perpendicular from the tip of b\mathbf b to the line. The foot of that perpendicular is p\mathbf p, and the error e=b−p\mathbf e=\mathbf b-\mathbf p meets the line at a right angle. Any other point on the line is farther away: by Pythagoras its distance² is ∣e∣2|\mathbf e|^2 plus something positive.

To find p=x^ a\mathbf p = \hat x\,\mathbf a, just demand perpendicularity: a⋅(b−x^a)=0\mathbf a\cdot(\mathbf b - \hat x\mathbf a)=0. Solve for x^\hat x:

x^=a⋅ba⋅a,p=a⋅ba⋅a a=aa⊤a⊤a⏟P b.\hat x = \frac{\mathbf a\cdot\mathbf b}{\mathbf a\cdot\mathbf a},\qquad \mathbf p = \frac{\mathbf a\cdot\mathbf b}{\mathbf a\cdot\mathbf a}\,\mathbf a = \underbrace{\frac{\mathbf a\mathbf a^\top}{\mathbf a^\top\mathbf a}}_{P}\,\mathbf b.

The matrix PP is the projection matrix. If a\mathbf a is a unit vector the formula is just P=aa⊤P=\mathbf a\mathbf a^\top, and x^=a⋅b\hat x = \mathbf a\cdot\mathbf b, the coordinate from chapter 1.

Drag b\mathbf b (gold) and the direction a\mathbf a (blue). The green arrow is the projection p\mathbf p; the red dashed arrow is the error e=b−p\mathbf e=\mathbf b-\mathbf p, always at a right angle to the line. The faint circle centred at b\mathbf b through p\mathbf p touches the line only at p\mathbf p: nothing on the line is closer.

Projecting onto a subspace

Now replace the line by the column space of a tall matrix AA (say n×kn\times k, with independent columns). Points in it look like AxA\mathbf x. We want the x^\hat{\mathbf x} making e=b−Ax^\mathbf e = \mathbf b - A\hat{\mathbf x} perpendicular to the whole subspace, which means perpendicular to every column of AA. Stack those kk dot products into one equation:

A⊤(b−Ax^)=0⟹A⊤A x^=A⊤bA^\top(\mathbf b - A\hat{\mathbf x}) = \mathbf 0 \quad\Longrightarrow\quad \boxed{A^\top A\,\hat{\mathbf x} = A^\top\mathbf b}

These are the normal equations ("normal" as in perpendicular). A⊤AA^\top A is a small k×kk\times k matrix, invertible exactly when the columns of AA are independent. Then

p=Ax^=A(A⊤A)−1A⊤⏟P b.\mathbf p = A\hat{\mathbf x} = \underbrace{A(A^\top A)^{-1}A^\top}_{P}\,\mathbf b.

Every projection matrix has two signature properties. P2=PP^2=P: projecting something that's already in the subspace does nothing. And P⊤=PP^\top = P: it's symmetric. If the columns are orthonormal (call the matrix QQ), then Q⊤Q=IQ^\top Q=I and everything simplifies to P=QQ⊤P = QQ^\top, which is the tall QQ⊤QQ^\top from chapter 1.

Least squares: solving the unsolvable

Fit a line y=c+mty = c + m t through data points (ti,yi)(t_i, y_i). Each point gives one equation c+mti=yic + m t_i = y_i. With more points than unknowns the system Ax=bA\mathbf x = \mathbf b,

[1t11t2⋮⋮1tn]⏟A[cm]=[y1y2⋮yn]⏟b,\underbrace{\begin{bmatrix}1&t_1\\1&t_2\\ \vdots&\vdots\\1&t_n\end{bmatrix}}_{A}\begin{bmatrix}c\\m\end{bmatrix} = \underbrace{\begin{bmatrix}y_1\\y_2\\ \vdots\\y_n\end{bmatrix}}_{\mathbf b},

usually has no solution: b\mathbf b is not in the column space. So settle for the x^\hat{\mathbf x} that makes the total squared error ∣Ax−b∣2=∑i(c+mti−yi)2|A\mathbf x-\mathbf b|^2 = \sum_i (c+mt_i-y_i)^2 as small as possible. The closest point Ax^A\hat{\mathbf x} to b\mathbf b in the column space is the projection, so the answer is the normal equations again. Least squares is projection, just in nn-dimensional "data space" where each axis is one data point.

Calculus agrees: the gradient of ∣Ax−b∣2|A\mathbf x-\mathbf b|^2 is 2A⊤(Ax−b)2A^\top(A\mathbf x-\mathbf b), and setting it to zero gives the same equations.

Drag the data points. The teal line is the least-squares fit, and the red segments are the residuals yi−(c+mti)y_i - (c+mt_i). Untick best fit and use the sliders to try your own line: you can never get the sum of squared residuals below the best fit's. Notice that the residuals of the best fit always add up to 0 (that's "error ⟂ the column of ones").

Worked exampleFit a line through (0, 6), (1, 0), (2, 0)

Here A=[101112]A=\begin{bmatrix}1&0\\1&1\\1&2\end{bmatrix}, b=(6,0,0)\mathbf b=(6,0,0).

  • A⊤A=[3335]A^\top A = \begin{bmatrix}3&3\\3&5\end{bmatrix} (the count of points, ∑t\sum t, ∑t2\sum t^2) and A⊤b=(6, 0)A^\top\mathbf b = (6,\ 0) (∑y\sum y, ∑ty\sum ty).
  • Solve 3c+3m=63c+3m=6, 3c+5m=03c+5m=0. Subtracting: 2m=−62m=-6, so m=−3m=-3, then c=5c=5. Best line: y=5−3ty = 5-3t.
  • Predictions p=(5,2,−1)\mathbf p = (5, 2, -1), residuals e=b−p=(1,−2,1)\mathbf e = \mathbf b-\mathbf p = (1, -2, 1), squared error 1+4+1=61+4+1=6.
  • Check perpendicularity: A⊤e=(1−2+1, 0−2+2)=(0,0)A^\top\mathbf e = (1-2+1,\ 0-2+2) = (0, 0) ✓.

Watch outCommon misconceptions

  • "Least squares minimises the perpendicular distance to the line." In regression the residuals are vertical (errors in yy only). The perpendicular is in the nn-dimensional data space, not in the scatter plot. Minimising perpendicular distances in the picture is a different problem: that's PCA (chapter 8).
  • "Compute (A⊤A)−1(A^\top A)^{-1} and multiply." Mathematically fine, numerically poor. Solve the system (np.linalg.solve), or better use QR or np.linalg.lstsq; chapters 3 and 10 explain why.
  • "P=A(A⊤A)−1A⊤P = A(A^\top A)^{-1}A^\top simplifies to AA−1(A⊤)−1A⊤=IAA^{-1}(A^\top)^{-1}A^\top = I." Only if AA is square and invertible, in which case the subspace is everything and projecting does nothing. A tall AA has no inverse.

In ML & deep learningWhere this shows up

Linear regression is exactly this chapter: features in the columns of AA (plus a column of ones for the bias), targets in b\mathbf b, and the fitted weights solve the normal equations. The mean-squared-error loss used to train neural networks is the same ∣Ax−b∣2|A\mathbf x-\mathbf b|^2, just with a nonlinear model so there's no closed form. The final linear layer of a frozen network can be fitted in one shot this way ("linear probing"). Projections also appear directly: removing a "bias direction" from word embeddings projects them onto the orthogonal complement of that direction, v−(u⋅v)u\mathbf v - (\mathbf u\cdot\mathbf v)\mathbf u.

Practice (pick one answer per question)

Project b=(4,3)\mathbf b=(4,3) onto the x-axis.

  1. (4, 0)
  2. (0, 3)
  3. (4, 3)
  4. (5, 0)

With a=(1,0)\mathbf a=(1,0): x^=4/1\hat x = 4/1, p=(4,0)\mathbf p=(4,0). The error (0, 3) is vertical, perpendicular to the axis. (5, 0) rotates b down instead of dropping a perpendicular.

Project b=(3,1)\mathbf b=(3,1) onto the line through a=(1,2)\mathbf a=(1,2).

  1. (1, 2)
  2. (5, 10)
  3. (3, 6)
  4. (1.5, 0.5)

a⋅b=5\mathbf a\cdot\mathbf b = 5, a⋅a=5\mathbf a\cdot\mathbf a=5, so x^=1\hat x=1 and p=(1,2)\mathbf p=(1,2). Check: e=(2,−1)\mathbf e = (2,-1) and e⋅a=2−2=0\mathbf e\cdot\mathbf a = 2-2=0 ✓. (5, 10) forgets to divide by a⋅a\mathbf a\cdot\mathbf a.

What is the projection matrix onto the line through a=(1,1)\mathbf a=(1,1)?

  1. [0.50.50.50.5]\begin{bmatrix}0.5&0.5\\0.5&0.5\end{bmatrix}
  2. [1111]\begin{bmatrix}1&1\\1&1\end{bmatrix}
  3. [0.5000.5]\begin{bmatrix}0.5&0\\0&0.5\end{bmatrix}
  4. [1001]\begin{bmatrix}1&0\\0&1\end{bmatrix}

P=aa⊤/a⊤a=12[1111]P=\mathbf a\mathbf a^\top/\mathbf a^\top\mathbf a = \tfrac12\begin{bmatrix}1&1\\1&1\end{bmatrix}. Check P2P^2: each entry is 0.25+0.25=0.50.25+0.25=0.5, so P2=PP^2=P ✓. The all-ones matrix forgets to divide by 2; it doubles vectors on the line.

For any projection matrix PP, P2P^2 equals…

  1. PP
  2. II
  3. 00
  4. 2P2P

After one projection you're in the subspace; projecting again changes nothing. (A reflection would give II.)

In least squares, the residual e=b−Ax^\mathbf e=\mathbf b-A\hat{\mathbf x} is orthogonal to…

  1. every column of AA
  2. every row of AA
  3. b\mathbf b
  4. x^\hat{\mathbf x}

That's exactly what A⊤e=0A^\top\mathbf e=\mathbf 0 says: each column of AA dotted with e\mathbf e is zero. e\mathbf e lives in data space (length nn), the same space as the columns. It is usually not perpendicular to b\mathbf b.

Fit y=c+mty=c+mt by least squares to the points (0, 1), (1, 3), (2, 4).

  1. m=1.5, c=7/6m=1.5,\ c=7/6
  2. m=1.5, c=1m=1.5,\ c=1
  3. m=2, c=1m=2,\ c=1
  4. m=1.5, c=4/3m=1.5,\ c=4/3

A⊤A=[3335]A^\top A=\begin{bmatrix}3&3\\3&5\end{bmatrix}, A⊤b=(8, 11)A^\top\mathbf b = (8,\ 11). Then 3c+3m=83c+3m=8 and 3c+5m=113c+5m=11 give 2m=32m=3, m=1.5m=1.5, c=8/3−1.5=7/6c = 8/3-1.5 = 7/6. Check: residuals 1−7/6=−1/61-7/6=-1/6, 3−8/3=1/33-8/3=1/3, 4−25/6=−1/64-25/6=-1/6 sum to 0 ✓. The line through the first two points (m=2,c=1m=2, c=1) ignores the third.

If b\mathbf b already lies in the column space of AA (independent columns), least squares returns…

  1. the exact solution of Ax=bA\mathbf x=\mathbf b, with zero residual
  2. x^=0\hat{\mathbf x}=\mathbf 0
  3. an approximate solution with a small positive error
  4. no answer, because A⊤AA^\top A becomes singular

Then b\mathbf b is its own closest point: p=b\mathbf p=\mathbf b, e=0\mathbf e=\mathbf 0, and x^\hat{\mathbf x} solves Ax=bA\mathbf x=\mathbf b exactly. A⊤AA^\top A depends only on AA, not on b\mathbf b, so it stays invertible.

PP projects R10\mathbb R^{10} onto a 3-dimensional subspace. What is the trace of PP (the sum of its diagonal entries)?

  1. 3
  2. 10
  3. 7
  4. 1

Vectors in the subspace are kept (Pv=vP\mathbf v=\mathbf v: eigenvalue 1, three independent directions) and vectors perpendicular to it are killed (eigenvalue 0, seven directions). The trace is the sum of eigenvalues: 1+1+1=31+1+1 = 3. Equivalently, with an orthonormal basis QQ, tr⁡(QQ⊤)=tr⁡(Q⊤Q)=tr⁡(I3)=3\operatorname{tr}(QQ^\top)=\operatorname{tr}(Q^\top Q)=\operatorname{tr}(I_3)=3.

Code it (optional: real Python runs in your browser and is graded by test cases)

Chapter 3

Gram–Schmidt and the QR decomposition

Watch: Orthogonal matrices and Gram–Schmidt (MIT OCW, Gilbert Strang)

Gram–Schmidt turns any independent vectors into an orthonormal basis for the same space: take each vector, subtract its projections onto the ones already done, and normalise. Keeping track of what you subtracted gives A=QRA=QR, with QQ orthonormal and RR upper triangular.

Chapter 1 showed that orthonormal bases make life easy. But real data rarely hands you one: the columns of a data matrix point wherever they like. Gram–Schmidt is the recipe that straightens them out.

The recipe

Start with independent vectors a1,a2,a3,…\mathbf a_1,\mathbf a_2,\mathbf a_3,\dots

  1. First vector: just normalise it. q1=a1/∣a1∣\mathbf q_1 = \mathbf a_1/|\mathbf a_1|.
  2. Second vector: remove the part of a2\mathbf a_2 that points along q1\mathbf q_1 (that's its projection, chapter 2), then normalise what's left: v2=a2−(q1⋅a2) q1,q2=v2/∣v2∣.\mathbf v_2 = \mathbf a_2 - (\mathbf q_1\cdot\mathbf a_2)\,\mathbf q_1,\qquad \mathbf q_2 = \mathbf v_2/|\mathbf v_2|. v2\mathbf v_2 is the error vector of projecting a2\mathbf a_2 onto the line of q1\mathbf q_1, so it's perpendicular to q1\mathbf q_1 by construction.
  3. Third vector: remove its components along both earlier directions: v3=a3−(q1⋅a3) q1−(q2⋅a3) q2,q3=v3/∣v3∣.\mathbf v_3 = \mathbf a_3 - (\mathbf q_1\cdot\mathbf a_3)\,\mathbf q_1 - (\mathbf q_2\cdot\mathbf a_3)\,\mathbf q_2,\qquad \mathbf q_3=\mathbf v_3/|\mathbf v_3|.
  4. And so on: each new vector loses its shadow on everything before it.

Because the q\mathbf q's are orthonormal, removing the projection onto their span is just a sum of separate one-dimensional projections (no normal equations needed). At every step, q1,…,qj\mathbf q_1,\dots,\mathbf q_j span exactly the same space as a1,…,aj\mathbf a_1,\dots,\mathbf a_j. If some vj\mathbf v_j comes out as zero, then aj\mathbf a_j was already in the span of the earlier vectors: the columns weren't independent.

Drag a1\mathbf a_1 (green) and a2\mathbf a_2 (red), then press Next step. Step 1 shrinks a1\mathbf a_1 to the unit vector q1\mathbf q_1. Step 2 shows the shadow (q1⋅a2)q1(\mathbf q_1\cdot\mathbf a_2)\mathbf q_1 being subtracted. Step 3 normalises the leftover v2\mathbf v_2 into q2\mathbf q_2. The readout builds the matrix RR as you go.

QR: Gram–Schmidt written as a matrix

Read the recipe backwards. Each original vector is a combination of the q\mathbf q's that came before or with it:

a1=r11q1,a2=r12q1+r22q2,a3=r13q1+r23q2+r33q3,\mathbf a_1 = r_{11}\mathbf q_1,\qquad \mathbf a_2 = r_{12}\mathbf q_1 + r_{22}\mathbf q_2,\qquad \mathbf a_3 = r_{13}\mathbf q_1+r_{23}\mathbf q_2+r_{33}\mathbf q_3,

where rij=qi⋅ajr_{ij} = \mathbf q_i\cdot\mathbf a_j (the amounts we subtracted) and rjj=∣vj∣r_{jj} = |\mathbf v_j| (the lengths we divided by). In matrix form, with the a\mathbf a's as the columns of AA:

[∣∣∣a1a2a3∣∣∣]⏟A=[∣∣∣q1q2q3∣∣∣]⏟Q[r11r12r130r22r2300r33]⏟R.\underbrace{\begin{bmatrix}|&|&|\\ \mathbf a_1&\mathbf a_2&\mathbf a_3\\ |&|&|\end{bmatrix}}_{A} = \underbrace{\begin{bmatrix}|&|&|\\ \mathbf q_1&\mathbf q_2&\mathbf q_3\\ |&|&|\end{bmatrix}}_{Q}\underbrace{\begin{bmatrix}r_{11}&r_{12}&r_{13}\\0&r_{22}&r_{23}\\0&0&r_{33}\end{bmatrix}}_{R}.

RR is upper triangular because aj\mathbf a_j never needs a later q\mathbf q. Its diagonal is positive. And since Q⊤Q=IQ^\top Q=I, you can always recover it as R=Q⊤AR=Q^\top A.

Why QR is the grown-up way to do least squares

Put A=QRA=QR into the normal equations A⊤Ax^=A⊤bA^\top A\hat{\mathbf x}=A^\top\mathbf b: R⊤Q⊤QRx^=R⊤Q⊤bR^\top Q^\top Q R\hat{\mathbf x} = R^\top Q^\top\mathbf b, and Q⊤Q=IQ^\top Q=I and the invertible R⊤R^\top cancel, leaving

R x^=Q⊤b.R\,\hat{\mathbf x} = Q^\top\mathbf b.

Triangular systems are solved by back-substitution: the last equation has one unknown, the one above it has two, and so on. More importantly, you never form A⊤AA^\top A, which squares the sensitivity of the problem to rounding errors (chapter 10). This is what serious least-squares solvers do.

In practice nobody runs the textbook version. Modified Gram–Schmidt subtracts each projection from the running vector one at a time (v←v−(qi⋅v)qi\mathbf v \leftarrow \mathbf v - (\mathbf q_i\cdot\mathbf v)\mathbf q_i), which is far less sensitive to rounding. Libraries like np.linalg.qr use Householder reflections, which are more stable still. The answer is the same QQ and RR (up to signs).

Worked exampleGram–Schmidt on two vectors in 3D

a1=(1,1,0)\mathbf a_1 = (1, 1, 0), a2=(1,0,1)\mathbf a_2=(1,0,1).

  • ∣a1∣=2|\mathbf a_1| = \sqrt2, so q1=12(1,1,0)\mathbf q_1 = \tfrac{1}{\sqrt2}(1,1,0) and r11=2r_{11}=\sqrt2.
  • r12=q1⋅a2=12r_{12}=\mathbf q_1\cdot\mathbf a_2 = \tfrac1{\sqrt2}. Subtract: v2=(1,0,1)−12⋅12(1,1,0)=(12,−12,1)\mathbf v_2 = (1,0,1) - \tfrac1{\sqrt2}\cdot\tfrac1{\sqrt2}(1,1,0) = (\tfrac12, -\tfrac12, 1).
  • Check: v2⋅a1=12−12+0=0\mathbf v_2\cdot\mathbf a_1 = \tfrac12-\tfrac12+0 = 0 ✓.
  • r22=∣v2∣=14+14+1=1.5≈1.225r_{22}=|\mathbf v_2| = \sqrt{\tfrac14+\tfrac14+1}=\sqrt{1.5}\approx1.225, so q2=(1,−1,2)/6\mathbf q_2 = (1,-1,2)/\sqrt6.

So R=[21/201.5]≈[1.4140.70701.225]R = \begin{bmatrix}\sqrt2 & 1/\sqrt2\\ 0 & \sqrt{1.5}\end{bmatrix}\approx\begin{bmatrix}1.414&0.707\\0&1.225\end{bmatrix}. Check the second column: 12q1+1.5 q2=(12,12,0)+12(1,−1,2)=(1,0,1)=a2\tfrac1{\sqrt2}\mathbf q_1 + \sqrt{1.5}\,\mathbf q_2 = (\tfrac12,\tfrac12,0)+\tfrac12(1,-1,2) = (1,0,1)=\mathbf a_2 ✓.

Watch outCommon misconceptions

  • "Gram–Schmidt only normalises the vectors." Normalising makes them unit length; the subtraction is what makes them perpendicular. Both are needed.
  • "The order doesn't matter." q1\mathbf q_1 always points along a1\mathbf a_1. Reorder the inputs and you get a different orthonormal basis (for the same overall span).
  • "Subtract the projection onto a1\mathbf a_1, not q1\mathbf q_1: same thing." It is the same projection, but if you use a1\mathbf a_1 you must divide by a1⋅a1\mathbf a_1\cdot\mathbf a_1. Forgetting that is the classic bug.
  • "RR is just bookkeeping." It carries real information: ∣det⁡A∣=r11r22⋯rnn|\det A| = r_{11}r_{22}\cdots r_{nn} for square AA, and a tiny rjjr_{jj} warns that column jj is nearly dependent on the earlier ones.

In ML & deep learningWhere this shows up

Orthogonal initialisation in PyTorch (torch.nn.init.orthogonal_) takes a random Gaussian matrix and runs QR on it, keeping QQ. Least-squares solvers (np.linalg.lstsq, statsmodels, R's lm) use QR or SVD rather than the normal equations. Gram–Schmidt-style orthogonalisation appears in optimisers that keep weight matrices orthogonal, in Krylov methods (Lanczos, Arnoldi) that compute a few eigenvectors of huge matrices like Hessians, and in the QR algorithm, the standard way computers find all eigenvalues of a matrix.

Practice (pick one answer per question)

The first Gram–Schmidt step on a1=(3,4)\mathbf a_1=(3,4) gives q1=\mathbf q_1=

  1. (0.6, 0.8)
  2. (3, 4)
  3. (0.75, 1)
  4. (0.8, 0.6)

Divide by the length 5: (0.6,0.8)(0.6, 0.8).

Continue with a2=(1,0)\mathbf a_2=(1,0). What is q2\mathbf q_2?

  1. (0.8, −0.6)
  2. (−0.8, 0.6)
  3. (0.64, −0.48)
  4. (1, 0)

q1⋅a2=0.6\mathbf q_1\cdot\mathbf a_2=0.6. v2=(1,0)−0.6(0.6,0.8)=(0.64,−0.48)\mathbf v_2 = (1,0)-0.6(0.6,0.8) = (0.64,-0.48), with length 0.4096+0.2304=0.8\sqrt{0.4096+0.2304}=0.8. So q2=(0.8,−0.6)\mathbf q_2=(0.8,-0.6). The opposite vector (−0.8, 0.6) is also perpendicular to q1\mathbf q_1, but Gram–Schmidt keeps the direction of v2\mathbf v_2 (so r22>0r_{22}>0). (0.64, −0.48) is v2\mathbf v_2 before normalising.

In A=QRA=QR from Gram–Schmidt, RR is…

  1. upper triangular with a positive diagonal
  2. diagonal
  3. lower triangular
  4. orthogonal

Column jj of AA only uses q1…qj\mathbf q_1\dots\mathbf q_j, so entries below the diagonal are 0. The diagonal entries are the lengths ∣vj∣>0|\mathbf v_j|>0.

The entry r12r_{12} of RR equals…

  1. q1⋅a2\mathbf q_1\cdot\mathbf a_2
  2. a1⋅a2\mathbf a_1\cdot\mathbf a_2
  3. q2⋅a1\mathbf q_2\cdot\mathbf a_1
  4. ∣a2∣|\mathbf a_2|

Row ii, column jj of R=Q⊤AR=Q^\top A is qi⋅aj\mathbf q_i\cdot\mathbf a_j: how much of a2\mathbf a_2 lies along q1\mathbf q_1. q2⋅a1\mathbf q_2\cdot\mathbf a_1 is r21r_{21}, which is 0.

Running Gram–Schmidt, you get v3=0\mathbf v_3=\mathbf 0. What does that tell you?

  1. a3\mathbf a_3 is a combination of a1\mathbf a_1 and a2\mathbf a_2
  2. a3=0\mathbf a_3=\mathbf 0
  3. a3\mathbf a_3 is perpendicular to a1\mathbf a_1 and a2\mathbf a_2
  4. you made an arithmetic mistake, since v3\mathbf v_3 can never be zero

v3\mathbf v_3 is what's left of a3\mathbf a_3 after removing its projection onto span(a1,a2)(\mathbf a_1,\mathbf a_2). Nothing left means a3\mathbf a_3 was entirely inside that span: the columns are dependent. If a3\mathbf a_3 were perpendicular, nothing would be removed and v3=a3\mathbf v_3=\mathbf a_3.

With A=QRA=QR (tall AA, independent columns), the least-squares solution of Ax≈bA\mathbf x\approx\mathbf b comes from…

  1. solving Rx^=Q⊤bR\hat{\mathbf x}=Q^\top\mathbf b by back-substitution
  2. x^=Q⊤R b\hat{\mathbf x}=Q^\top R\,\mathbf b
  3. solving Qx^=R⊤bQ\hat{\mathbf x}=R^\top\mathbf b
  4. x^=R⊤Q b\hat{\mathbf x}=R^\top Q\,\mathbf b

Substitute A=QRA=QR into A⊤Ax^=A⊤bA^\top A\hat{\mathbf x}=A^\top\mathbf b: R⊤Rx^=R⊤Q⊤bR^\top R\hat{\mathbf x} = R^\top Q^\top\mathbf b, and cancel R⊤R^\top. The other options don't even have matching shapes in general.

For A=[3140]A=\begin{bmatrix}3&1\\4&0\end{bmatrix} (the columns from the first two questions), what is RR, and what is ∣det⁡A∣|\det A|?

  1. R=[50.600.8]R=\begin{bmatrix}5&0.6\\0&0.8\end{bmatrix}, ∣det⁡A∣=4|\det A|=4
  2. R=[50.600.8]R=\begin{bmatrix}5&0.6\\0&0.8\end{bmatrix}, ∣det⁡A∣=5.6|\det A|=5.6
  3. R=[500.60.8]R=\begin{bmatrix}5&0\\0.6&0.8\end{bmatrix}, ∣det⁡A∣=4|\det A|=4
  4. R=[5101]R=\begin{bmatrix}5&1\\0&1\end{bmatrix}, ∣det⁡A∣=5|\det A|=5

r11=∣a1∣=5r_{11}=|\mathbf a_1|=5, r12=q1⋅a2=0.6r_{12}=\mathbf q_1\cdot\mathbf a_2=0.6, r22=∣v2∣=0.8r_{22}=|\mathbf v_2|=0.8. Since ∣det⁡Q∣=1|\det Q|=1, ∣det⁡A∣=det⁡R=5×0.8=4|\det A| = \det R = 5\times0.8=4. Directly: det⁡A=3⋅0−1⋅4=−4\det A = 3\cdot0-1\cdot4=-4 ✓.

Code it (optional: real Python runs in your browser and is graded by test cases)

Chapter 4

Symmetric matrices and the spectral theorem

Watch: Symmetric matrices and positive definiteness (MIT OCW, Gilbert Strang) Rewatch: Eigenvectors and eigenvalues (3Blue1Brown)

A symmetric matrix (S=S⊤S=S^\top) always has real eigenvalues and perpendicular eigenvectors. So it is just a stretch along some set of perpendicular axes: S=QΛQ⊤S=Q\Lambda Q^\top, "rotate to the axes, stretch, rotate back".

In Module 1, chapter 14, eigenvectors were the special directions a matrix only stretches. For a general matrix they can be a disappointment: a rotation has none (in real numbers), a shear has only one direction, and even when there are enough of them they meet at odd angles. Symmetric matrices are the happy case where everything works perfectly.

A matrix is symmetric when it equals its own transpose: the entry in row ii, column jj equals the one in row jj, column ii, so it's a mirror image across the diagonal. For example [5222]\begin{bmatrix}5&2\\2&2\end{bmatrix}.

The spectral theorem

Every real symmetric n×nn\times n matrix SS has

  1. real eigenvalues λ1,…,λn\lambda_1,\dots,\lambda_n (no complex numbers, ever), and
  2. a full set of orthonormal eigenvectors q1,…,qn\mathbf q_1,\dots,\mathbf q_n.

Put the eigenvectors in the columns of an orthogonal matrix QQ and the eigenvalues on the diagonal of Λ\Lambda. Then SQ=QΛSQ=Q\Lambda, and since Q−1=Q⊤Q^{-1}=Q^\top,

S=QΛQ⊤=λ1q1q1⊤+λ2q2q2⊤+⋯+λnqnqn⊤.S = Q\Lambda Q^\top = \lambda_1\mathbf q_1\mathbf q_1^\top + \lambda_2\mathbf q_2\mathbf q_2^\top+\dots+\lambda_n\mathbf q_n\mathbf q_n^\top.

Read it right to left, as in Module 1: Q⊤Q^\top takes the coordinates of x\mathbf x along the eigenvector axes (chapter 1: coordinates are dot products), Λ\Lambda stretches each coordinate by its eigenvalue, and QQ puts the result back in standard coordinates. The second form says SS is a weighted sum of projections onto its eigen-directions (each qiqi⊤\mathbf q_i\mathbf q_i^\top is a projection matrix from chapter 2).

Why are the eigenvectors perpendicular? Take Sx=λ1xS\mathbf x=\lambda_1\mathbf x and Sy=λ2yS\mathbf y=\lambda_2\mathbf y with λ1≠λ2\lambda_1\neq\lambda_2. Compute x⊤Sy\mathbf x^\top S\mathbf y two ways: it's λ2 x⋅y\lambda_2\,\mathbf x\cdot\mathbf y, and, using S⊤=SS^\top=S, it's also (Sx)⊤y=λ1 x⋅y(S\mathbf x)^\top\mathbf y=\lambda_1\,\mathbf x\cdot\mathbf y. Two different numbers times the same x⋅y\mathbf x\cdot\mathbf y are equal only if x⋅y=0\mathbf x\cdot\mathbf y = 0. (If an eigenvalue repeats, you get a whole plane of eigenvectors and can pick perpendicular ones inside it.)

The picture: circles become ellipses with eigenvector axes

Apply SS to every point of the unit circle. Along q1\mathbf q_1 points are stretched by λ1\lambda_1, along q2\mathbf q_2 by λ2\lambda_2, and those directions are perpendicular. So the circle becomes an ellipse whose axes point along the eigenvectors, with semi-axis lengths ∣λ1∣|\lambda_1| and ∣λ2∣|\lambda_2|. A negative eigenvalue flips that axis over but the ellipse looks the same.

Choose the entries of the symmetric matrix with the sliders (the off-diagonal bb is used twice, so the matrix stays symmetric). The unit circle (faint) becomes the filled ellipse; the green and red arrows are the eigenvectors scaled by their eigenvalues, always at right angles along the ellipse's axes. Drag the gold point around the circle and watch its image. Press Make it non-symmetric to see the perpendicularity break.

Where symmetric matrices come from

They are everywhere in ML, because anything built as "all pairwise dot products" is symmetric:

  • A⊤AA^\top A for any AA (it's the Gram matrix of the columns; (A⊤A)⊤=A⊤A(A^\top A)^\top = A^\top A).
  • Covariance matrices: entry (i,j)(i,j) is the covariance of features ii and jj.
  • Hessians: the matrix of second derivatives of a loss, because ∂2L/∂wi∂wj=∂2L/∂wj∂wi\partial^2 L/\partial w_i\partial w_j = \partial^2L/\partial w_j\partial w_i.
  • Kernel matrices Kij=k(xi,xj)K_{ij}=k(\mathbf x_i,\mathbf x_j), graph adjacency matrices and graph Laplacians.

Worked exampleDiagonalise S=[2112]S=\begin{bmatrix}2&1\\1&2\end{bmatrix} and compute S10S^{10}

Trace 4, determinant 3, so λ2−4λ+3=0\lambda^2-4\lambda+3=0: λ1=3\lambda_1=3, λ2=1\lambda_2=1. Eigenvectors: q1=12(1,1)\mathbf q_1=\tfrac1{\sqrt2}(1,1) (check: S(1,1)=(3,3)S(1,1)=(3,3)) and q2=12(1,−1)\mathbf q_2=\tfrac1{\sqrt2}(1,-1) (check: S(1,−1)=(1,−1)S(1,-1)=(1,-1)). They're perpendicular, as promised.

Spectral form: S=3⋅12[1111]+1⋅12[1−1−11]=[2112]S = 3\cdot\tfrac12\begin{bmatrix}1&1\\1&1\end{bmatrix} + 1\cdot\tfrac12\begin{bmatrix}1&-1\\-1&1\end{bmatrix} = \begin{bmatrix}2&1\\1&2\end{bmatrix} ✓.

Powers are now easy, because Sk=QΛkQ⊤S^k = Q\Lambda^kQ^\top (the inner Q⊤QQ^\top Q's cancel):

S10=310⋅12[1111]+110⋅12[1−1−11]=[29525295242952429525].S^{10} = 3^{10}\cdot\tfrac12\begin{bmatrix}1&1\\1&1\end{bmatrix} + 1^{10}\cdot\tfrac12\begin{bmatrix}1&-1\\-1&1\end{bmatrix} = \begin{bmatrix}29525&29524\\29524&29525\end{bmatrix}.

The same trick gives any function of SS: S\sqrt S, eSe^S, S−1S^{-1}: apply the function to the eigenvalues.

Watch outCommon misconceptions

  • "Every matrix has perpendicular eigenvectors." Only symmetric ones (more precisely, "normal" ones) are guaranteed to. [2101]\begin{bmatrix}2&1\\0&1\end{bmatrix} has eigenvectors (1, 0) and (1, −1), at 45°.
  • "Symmetric means invertible." No: [1111]\begin{bmatrix}1&1\\1&1\end{bmatrix} is symmetric with eigenvalue 0.
  • "Symmetric means positive eigenvalues." [0110]\begin{bmatrix}0&1\\1&0\end{bmatrix} has eigenvalues 1 and −1. Positivity is the next chapter's extra condition.
  • "Use np.linalg.eig." For symmetric matrices use np.linalg.eigh: it's faster, guarantees real output and orthonormal eigenvectors, and returns eigenvalues in ascending order.

In ML & deep learningWhere this shows up

PCA diagonalises the covariance matrix: its eigenvectors are the principal directions (chapter 8). The Hessian of a loss at a minimum is symmetric; its eigenvalues measure the curvature along perpendicular directions, which explains why gradient descent zig-zags when they differ wildly and is used to study "sharp" versus "flat" minima. Spectral clustering and graph neural networks are built on eigenvectors of graph Laplacians. Kernel methods (SVMs, Gaussian processes) rely on symmetric kernel matrices, and the "neural tangent kernel" describes very wide networks the same way.

Practice (pick one answer per question)

Which matrix is symmetric?

  1. [144−2]\begin{bmatrix}1&4\\4&-2\end{bmatrix}
  2. [14−41]\begin{bmatrix}1&4\\-4&1\end{bmatrix}
  3. [1414]\begin{bmatrix}1&4\\1&4\end{bmatrix}
  4. [1241]\begin{bmatrix}1&2\\4&1\end{bmatrix}

Symmetric means s12=s21s_{12}=s_{21}. Only the first has equal off-diagonal entries. The second is "skew-symmetric" (s21=−s12s_{21}=-s_{12}), a rotation-like matrix.

What are the eigenvalues of S=[5222]S=\begin{bmatrix}5&2\\2&2\end{bmatrix}?

  1. 6 and 1
  2. 5 and 2
  3. 7 and 6
  4. 3 and 4

Trace 7, determinant 10−4=610-4=6. Two numbers with sum 7 and product 6: 6 and 1. (5 and 2 are the diagonal entries; those are eigenvalues only for triangular matrices.)

(2, 1) is an eigenvector of that SS for λ=6\lambda=6. Which is an eigenvector for λ=1\lambda=1?

  1. (1, −2)
  2. (1, 2)
  3. (2, −1)
  4. (−2, −1)

Eigenvectors of a symmetric matrix for different eigenvalues are perpendicular, so we need a vector perpendicular to (2, 1): (1, −2). Check: S(1,−2)=(5−4, 2−4)=(1,−2)S(1,-2) = (5-4,\ 2-4) = (1,-2) ✓. (−2, −1) is just −1⋅(2,1)-1\cdot(2,1), the same eigen-direction for 6.

S=[5222]S=\begin{bmatrix}5&2\\2&2\end{bmatrix} maps the unit circle to an ellipse. What are its semi-axes?

  1. length 6 along (2, 1) and length 1 along (1, −2)
  2. length 5 along the x-axis and length 2 along the y-axis
  3. length 6 along (1, −2) and length 1 along (2, 1)
  4. length √6 along (2, 1) and length 1 along (1, −2)

The axes are the eigenvectors and each is stretched by its eigenvalue: 6 along (2, 1), 1 along (1, −2). (√6 would be the answer for S\sqrt S.)

Which property is not guaranteed for every real symmetric matrix SS?

  1. SS is invertible
  2. all eigenvalues of SS are real
  3. the eigenvectors can be chosen orthonormal
  4. S=QΛQ⊤S=Q\Lambda Q^\top with QQ orthogonal

The spectral theorem promises real eigenvalues and an orthonormal eigenbasis, which is exactly S=QΛQ⊤S=Q\Lambda Q^\top. Nothing stops an eigenvalue from being 0, e.g. [1111]\begin{bmatrix}1&1\\1&1\end{bmatrix}, so SS can be singular.

AA is a 3×2 matrix. What can you say about A⊤AA^\top A?

  1. It is 2×2 and symmetric
  2. It is 3×3 and symmetric
  3. It is 2×2 but symmetric only if AA is
  4. It is 3×2

(2×3)(3×2) = 2×2. Its (i,j)(i,j) entry is (column ii)·(column jj), which is the same as the (j,i)(j,i) entry. Formally (A⊤A)⊤=A⊤(A⊤)⊤=A⊤A(A^\top A)^\top = A^\top (A^\top)^\top = A^\top A.

S=[2112]S=\begin{bmatrix}2&1\\1&2\end{bmatrix}. What is the top-left entry of S10S^{10}?

  1. 29525
  2. 1024
  3. 59049
  4. 29524

S10=310q1q1⊤+110q2q2⊤S^{10}=3^{10}\mathbf q_1\mathbf q_1^\top + 1^{10}\mathbf q_2\mathbf q_2^\top, and both projections have top-left entry ½. So (59049+1)/2=29525(59049+1)/2 = 29525. (1024 is 2102^{10}, wrongly powering the entry; 29524 is the off-diagonal entry.)

Over all unit vectors x\mathbf x, what is the largest value of x⊤Sx\mathbf x^\top S\mathbf x for S=[5222]S=\begin{bmatrix}5&2\\2&2\end{bmatrix}?

  1. 6
  2. 5
  3. 7
  4. 9

In eigen-coordinates x⊤Sx=6c12+1c22\mathbf x^\top S\mathbf x = 6c_1^2 + 1c_2^2 with c12+c22=1c_1^2+c_2^2=1. That's a weighted average of 6 and 1, largest (6) at x=q1\mathbf x=\mathbf q_1. This ratio is the Rayleigh quotient; its max and min are the largest and smallest eigenvalues. (5 is the value at x=(1,0)\mathbf x=(1,0), not the max.)

Code it (optional: real Python runs in your browser and is graded by test cases)

Chapter 5

Positive-definite matrices and quadratic forms

Watch: Positive definite matrices and minima (MIT OCW, Gilbert Strang) Watch: Positive definite and semidefinite matrices (MIT 18.065, Gilbert Strang)

A symmetric matrix SS defines a "quadratic form" q(x)=x⊤Sxq(\mathbf x)=\mathbf x^\top S\mathbf x, a bowl, a saddle or a dome. SS is positive definite when the bowl points up in every direction: q(x)>0q(\mathbf x)>0 for all x≠0\mathbf x\neq\mathbf 0, which happens exactly when all eigenvalues are positive.

Quadratic forms

For S=[abbc]S=\begin{bmatrix}a&b\\b&c\end{bmatrix} and x=(x,y)\mathbf x=(x,y),

q(x)=x⊤S x=ax2+2bxy+cy2.q(\mathbf x)=\mathbf x^\top S\,\mathbf x = ax^2 + 2bxy + cy^2.

The diagonal entries give the squared terms; the off-diagonal entry (used twice) gives the cross term. Any expression with only degree-2 terms can be written this way, in any number of dimensions. The graph of qq is a surface over the plane, and it comes in a few shapes:

  • positive definite (PD): q>0q>0 except at the origin. A bowl; the origin is the unique minimum.
  • positive semidefinite (PSD): q≥0q\ge0. A bowl that may be flat along some direction (a trough).
  • indefinite: qq is positive in some directions and negative in others. A saddle.
  • negative definite: q<0q<0 except at the origin. A dome.

Eigenvalues tell you everything

Use the spectral theorem (chapter 4): S=QΛQ⊤S=Q\Lambda Q^\top. In the eigenvector coordinates c=Q⊤x\mathbf c=Q^\top\mathbf x, the cross terms disappear:

q(x)=x⊤QΛQ⊤x=c⊤Λc=λ1c12+λ2c22+⋯+λncn2.q(\mathbf x) = \mathbf x^\top Q\Lambda Q^\top\mathbf x = \mathbf c^\top\Lambda\mathbf c = \lambda_1c_1^2+\lambda_2c_2^2+\dots+\lambda_nc_n^2.

A sum of squares weighted by the eigenvalues. It's positive for every nonzero c\mathbf c exactly when every λi>0\lambda_i>0. One negative λ\lambda and you can walk downhill along its eigenvector: a saddle. A zero λ\lambda gives a flat direction. So:

S is PD  ⟺  all λi>0S is PSD  ⟺  all λi≥0.S \text{ is PD} \iff \text{all } \lambda_i > 0 \qquad\qquad S\text{ is PSD}\iff\text{all }\lambda_i\ge0.

The level curves q(x)=1q(\mathbf x)=1 of a PD matrix are ellipses with axes along the eigenvectors and semi-axis lengths 1/λi1/\sqrt{\lambda_i}: a big eigenvalue means a steep direction and a narrow ellipse.

The colour shows q(x)=x⊤Sxq(\mathbf x)=\mathbf x^\top S\mathbf x: blue where it's positive, red where it's negative, with stripes marking the level curves. Change aa, bb, cc with the sliders or try the presets. Drag the gold point to read off qq; the arrow is the gradient 2Sx2S\mathbf x, pointing uphill, perpendicular to the level curves. The dashed lines are the eigenvector axes.

Other tests that don't need eigenvalues

All of these are equivalent ways to say "SS is positive definite":

  1. Energy: x⊤Sx>0\mathbf x^\top S\mathbf x>0 for every x≠0\mathbf x\neq\mathbf 0.
  2. Eigenvalues: all λi>0\lambda_i>0.
  3. Leading minors (Sylvester's test): the top-left 1×1, 2×2, …, n×nn\times n determinants are all positive. For 2×2: a>0a>0 and ac−b2>0ac-b^2>0.
  4. Cholesky: S=LL⊤S=LL^\top with LL lower triangular with a positive diagonal. Computers test PD by just trying Cholesky: it fails exactly when SS isn't PD.
  5. Gram form: S=A⊤AS=A^\top A for some AA with independent columns. Indeed x⊤A⊤Ax=∣Ax∣2≥0\mathbf x^\top A^\top A\mathbf x = |A\mathbf x|^2\ge 0, and it's 0 only if Ax=0A\mathbf x=\mathbf 0.

That last one explains why A⊤AA^\top A and covariance matrices are always at least PSD: they are sums of squares in disguise.

Worked exampleIs S=[2−1−12]S=\begin{bmatrix}2&-1\\-1&2\end{bmatrix} positive definite?

  • Quadratic form: q=2x2−2xy+2y2=x2+y2+(x−y)2q = 2x^2-2xy+2y^2 = x^2 + y^2 + (x-y)^2, a sum of squares that is zero only at the origin. PD ✓.
  • Minors: a=2>0a=2>0 and det⁡S=4−1=3>0\det S = 4-1 = 3>0 ✓.
  • Eigenvalues: trace 4, det 3, so λ=3,1\lambda = 3, 1, both positive ✓. Eigenvectors (1,−1)(1,-1) for 3 and (1,1)(1,1) for 1, so the level curve q=1q=1 is an ellipse reaching 1/3≈0.5771/\sqrt3\approx0.577 along (1,−1)(1,-1) and 11 along (1,1)(1,1).
  • Cholesky: L=[20−1/23/2]L=\begin{bmatrix}\sqrt2&0\\-1/\sqrt2&\sqrt{3/2}\end{bmatrix}. Check LL⊤LL^\top: top-left 2, off-diagonal 2⋅(−1/2)=−1\sqrt2\cdot(-1/\sqrt2)=-1, bottom-right 12+32=2\tfrac12+\tfrac32=2 ✓.

Watch outCommon misconceptions

  • "Positive entries mean positive definite." [1331]\begin{bmatrix}1&3\\3&1\end{bmatrix} has all positive entries, but q(1,−1)=1−6+1=−4q(1,-1)=1-6+1=-4. Its eigenvalues are 4 and −2.
  • "A negative entry rules it out." [2−1−12]\begin{bmatrix}2&-1\\-1&2\end{bmatrix} above is PD. (Negative diagonal entries do rule it out: q(ei)=siiq(\mathbf e_i)=s_{ii}.)
  • "Checking a>0a>0 and c>0c>0 is enough." You need the determinant too: [1221]\begin{bmatrix}1&2\\2&1\end{bmatrix} has positive diagonal but det⁡=−3\det=-3.
  • "Positive determinant means PD." −I-I (2×2) has determinant +1+1 and is negative definite. Two negative eigenvalues multiply to a positive number.

In ML & deep learningWhere this shows up

Minima of a loss: near a critical point a loss looks like a quadratic form in the Hessian. A PD Hessian means a true local minimum; an indefinite one means a saddle point, and in high-dimensional deep nets most critical points are saddles. Convexity: a twice-differentiable function is convex exactly when its Hessian is PSD everywhere, which is why least squares (Hessian 2A⊤A2A^\top A) has no bad local minima. Covariance matrices must be PSD, and a multivariate Gaussian needs a PD covariance Σ\Sigma; sampling it uses the Cholesky factor (x=μ+Lz\mathbf x=\boldsymbol\mu+L\mathbf z). Mahalanobis distance (x−μ)⊤Σ−1(x−μ)\sqrt{(\mathbf x-\boldsymbol\mu)^\top\Sigma^{-1}(\mathbf x-\boldsymbol\mu)} and kernel matrices in SVMs and Gaussian processes are PD quadratic forms too. And the ratio λmax⁡/λmin⁡\lambda_{\max}/\lambda_{\min} of the Hessian decides how badly gradient descent zig-zags (chapter 10).

Practice (pick one answer per question)

Write x⊤Sx\mathbf x^\top S\mathbf x for S=[1225]S=\begin{bmatrix}1&2\\2&5\end{bmatrix} and x=(x,y)\mathbf x=(x,y).

  1. x2+4xy+5y2x^2+4xy+5y^2
  2. x2+2xy+5y2x^2+2xy+5y^2
  3. x2+4xy+5yx^2+4xy+5y
  4. x+4xy+5yx+4xy+5y

ax2+2bxy+cy2ax^2+2bxy+cy^2 with a=1,b=2,c=5a=1,b=2,c=5. The off-diagonal 2 appears twice, giving 4xy4xy.

Is S=[1225]S=\begin{bmatrix}1&2\\2&5\end{bmatrix} positive definite?

  1. Yes: a=1>0a=1>0 and det⁡S=1>0\det S=1>0
  2. No: the off-diagonal entry is bigger than aa
  3. No: det⁡S=9\det S = 9
  4. We can't tell without computing the eigenvectors

Leading minors: 1>01>0 and 5−4=1>05-4=1>0. In fact x2+4xy+5y2=(x+2y)2+y2x^2+4xy+5y^2=(x+2y)^2+y^2. The size of off-diagonal entries alone doesn't decide anything.

For which bb is [1bb4]\begin{bmatrix}1&b\\b&4\end{bmatrix} positive definite?

  1. −2<b<2-2<b<2
  2. b<4b<4
  3. −4<b<4-4<b<4
  4. b>0b>0

a=1>0a=1>0 always, and det⁡=4−b2>0  ⟺  ∣b∣<2\det = 4-b^2>0\iff |b|<2. At b=±2b=\pm2 it's only semidefinite.

For S=[1331]S=\begin{bmatrix}1&3\\3&1\end{bmatrix}, what is q(1,−1)q(1,-1), and what shape is the graph of qq?

  1. −4; a saddle
  2. 8; a bowl
  3. −4; a dome
  4. 2; a bowl

q=x2+6xy+y2q=x^2+6xy+y^2, so q(1,−1)=1−6+1=−4q(1,-1)=1-6+1=-4, while q(1,1)=8q(1,1)=8. Positive one way, negative another: indefinite, a saddle. Eigenvalues: 4 and −2.

The level curve 4x2+y2=14x^2+y^2=1 is an ellipse with semi-axes…

  1. ½ along x and 1 along y
  2. 4 along x and 1 along y
  3. 2 along x and 1 along y
  4. 1 along x and ½ along y

S=diag(4,1)S=\mathrm{diag}(4,1), semi-axes 1/λ1/\sqrt{\lambda}: 1/4=121/\sqrt4=\tfrac12 along x and 1 along y. Check: (12,0)(\tfrac12,0) gives 4⋅14=14\cdot\tfrac14=1 ✓. The steep direction (big λ) is the short axis.

For any matrix AA, the matrix A⊤AA^\top A is…

  1. always positive semidefinite, and positive definite exactly when AA has independent columns
  2. always positive definite
  3. positive definite exactly when AA is square
  4. indefinite unless AA is symmetric

x⊤A⊤Ax=∣Ax∣2≥0\mathbf x^\top A^\top A\mathbf x = |A\mathbf x|^2\ge0. It equals 0 for some x≠0\mathbf x\neq\mathbf 0 exactly when Ax=0A\mathbf x=\mathbf 0 has a nonzero solution, i.e. the columns are dependent.

A 2×2 PD matrix has eigenvalues 9 and 1. In its level curve x⊤Sx=1\mathbf x^\top S\mathbf x=1, what is the ratio of the longest axis to the shortest?

  1. 3
  2. 9
  3. 1/3
  4. 81

Semi-axes are 1/1=11/\sqrt1=1 and 1/9=131/\sqrt9=\tfrac13, so the ratio is 9/1=3\sqrt{9/1}=3. (The ratio of eigenvalues, 9, is the condition number; the axes' ratio is its square root.)

The gradient of q(x)=x⊤Sxq(\mathbf x)=\mathbf x^\top S\mathbf x is 2Sx2S\mathbf x. For S=[2−1−12]S=\begin{bmatrix}2&-1\\-1&2\end{bmatrix}, what is it at x=(1,1)\mathbf x=(1,1)?

  1. (2, 2)
  2. (1, 1)
  3. (4, 4)
  4. (2, −2)

S(1,1)=(2−1, −1+2)=(1,1)S(1,1) = (2-1,\ -1+2) = (1,1), so 2Sx=(2,2)2S\mathbf x=(2,2). Directly: q=2x2−2xy+2y2q=2x^2-2xy+2y^2, ∂q/∂x=4x−2y=2\partial q/\partial x = 4x-2y = 2 and ∂q/∂y=−2x+4y=2\partial q/\partial y=-2x+4y=2 ✓. (1, 1) forgets the factor 2.

Code it (optional: real Python runs in your browser and is graded by test cases)

Chapter 6

The singular value decomposition: rotate, stretch, rotate

Watch: SVD overview (Steve Brunton) Watch: SVD mathematical overview (Steve Brunton) Watch: Singular value decomposition (MIT OCW, Gilbert Strang) Watch: SVD visualized (Visual Kernel)

Every matrix, of any shape, is a rotation, then a stretch along the axes, then another rotation: A=UΣV⊤A=U\Sigma V^\top. The stretch factors σ1≥σ2≥⋯≥0\sigma_1\ge\sigma_2\ge\dots\ge0 are the singular values, and they tell you almost everything about the matrix.

The spectral theorem (chapter 4) was wonderful but picky: it only works for symmetric matrices. Most matrices in ML aren't symmetric, and most aren't even square: a weight matrix maps 768 numbers to 3072, a data matrix has 10,000 rows and 50 columns. The singular value decomposition is the version that works for every matrix.

The statement

Any m×nm\times n matrix AA can be written

A=U Σ V⊤,A = U\,\Sigma\,V^\top,
  • VV is an n×nn\times n orthogonal matrix. Its columns v1,…,vn\mathbf v_1,\dots,\mathbf v_n are the right singular vectors, an orthonormal basis of the input space.
  • Σ\Sigma is m×nm\times n and zero except on its diagonal, which holds the singular values σ1≥σ2≥⋯≥0\sigma_1\ge\sigma_2\ge\dots\ge0.
  • UU is an m×mm\times m orthogonal matrix. Its columns u1,…,um\mathbf u_1,\dots,\mathbf u_m are the left singular vectors, an orthonormal basis of the output space.

Column by column, AV=UΣAV=U\Sigma says

Avi=σi ui.A\mathbf v_i = \sigma_i\,\mathbf u_i.

That's the key sentence: there is a perpendicular set of input directions that AA maps to a perpendicular set of output directions, just stretched by σi\sigma_i. Eigenvectors asked for Av=λvA\mathbf v=\lambda\mathbf v, the same direction in and out, which often fails. The SVD lets the output basis differ from the input basis, and then it never fails.

The picture

Read Ax=UΣV⊤xA\mathbf x=U\Sigma V^\top\mathbf x right to left, like any product of transformations (Module 1, chapter 4):

  1. V⊤V^\top rotates (or reflects) the input so that the special directions vi\mathbf v_i line up with the coordinate axes.
  2. Σ\Sigma stretches along each axis by σi\sigma_i (and, if m≠nm\neq n, adds or drops dimensions).
  3. UU rotates (or reflects) the axes into the output directions ui\mathbf u_i.

So a unit circle always becomes an ellipse (in 2D) whose semi-axes are σ1u1\sigma_1\mathbf u_1 and σ2u2\sigma_2\mathbf u_2. Even a shear, which looks nothing like a stretch, is secretly rotate–stretch–rotate.

Type any 2×2 matrix (or pick a preset) and press Play. The unit circle and the two right singular vectors (green v1\mathbf v_1, red v2\mathbf v_2) are first rotated by V⊤V^\top onto the axes, then stretched by Σ\Sigma, then rotated by UU. The final ellipse is exactly the image of the circle under AA (the dashed outline), with semi-axes σ1u1\sigma_1\mathbf u_1 and σ2u2\sigma_2\mathbf u_2.

Where the pieces come from

Multiply AA by its transpose and the UU's cancel:

A⊤A=VΣ⊤U⊤UΣV⊤=V (Σ⊤Σ) V⊤.A^\top A = V\Sigma^\top U^\top U\Sigma V^\top = V\,(\Sigma^\top\Sigma)\,V^\top.

That's a spectral decomposition of the symmetric PSD matrix A⊤AA^\top A! So the vi\mathbf v_i are the eigenvectors of A⊤AA^\top A, and its eigenvalues are σi2\sigma_i^2. In the same way the ui\mathbf u_i are eigenvectors of AA⊤AA^\top. A practical recipe for small matrices: find the eigenvalues and eigenvectors of A⊤AA^\top A, take square roots, then get each ui=Avi/σi\mathbf u_i = A\mathbf v_i/\sigma_i. (Real libraries avoid forming A⊤AA^\top A, for the accuracy reasons in chapter 10.)

What the singular values tell you

  • Rank = the number of nonzero σi\sigma_i. The first rr columns of UU span the column space; the last n−rn-r columns of VV span the null space.
  • Biggest stretch: max⁡∣x∣=1∣Ax∣=σ1\max_{|\mathbf x|=1}|A\mathbf x| = \sigma_1, reached at x=v1\mathbf x=\mathbf v_1. This is the spectral norm ∥A∥2\|A\|_2.
  • Determinant (square AA): ∣det⁡A∣=σ1σ2⋯σn|\det A| = \sigma_1\sigma_2\cdots\sigma_n, since rotations don't change area.
  • Sum of rank-one pieces: A=σ1u1v1⊤+σ2u2v2⊤+⋯+σrurvr⊤A = \sigma_1\mathbf u_1\mathbf v_1^\top+\sigma_2\mathbf u_2\mathbf v_2^\top+\dots+\sigma_r\mathbf u_r\mathbf v_r^\top, ordered from most to least important. Chapter 7 is built on this.

The thin (economy) SVD keeps only the first rr or min⁡(m,n)\min(m,n) columns of UU and VV; np.linalg.svd(A, full_matrices=False) returns that. Note that numpy returns V⊤V^\top (called Vh), not VV, and the singular values as a 1-D array.

Worked exampleSVD of A=[3045]A=\begin{bmatrix}3&0\\4&5\end{bmatrix}

  • A⊤A=[3405][3045]=[25202025]A^\top A = \begin{bmatrix}3&4\\0&5\end{bmatrix}\begin{bmatrix}3&0\\4&5\end{bmatrix}=\begin{bmatrix}25&20\\20&25\end{bmatrix}. Eigenvalues: trace 50, determinant 625−400=225625-400=225, so 45 and 5.
  • Singular values σ1=45=35≈6.708\sigma_1=\sqrt{45}=3\sqrt5\approx6.708 and σ2=5≈2.236\sigma_2=\sqrt5\approx2.236. Check: σ1σ2=15=∣det⁡A∣\sigma_1\sigma_2=15=|\det A| ✓.
  • Eigenvectors of A⊤AA^\top A: v1=12(1,1)\mathbf v_1=\tfrac1{\sqrt2}(1,1), v2=12(1,−1)\mathbf v_2=\tfrac1{\sqrt2}(1,-1).
  • u1=Av1/σ1=12(3,9)/(35)=110(1,3)\mathbf u_1 = A\mathbf v_1/\sigma_1 = \tfrac1{\sqrt2}(3,9)/(3\sqrt5) = \tfrac1{\sqrt{10}}(1,3) and u2=Av2/σ2=12(3,−1)/5=110(3,−1)\mathbf u_2 = A\mathbf v_2/\sigma_2 = \tfrac1{\sqrt2}(3,-1)/\sqrt5=\tfrac1{\sqrt{10}}(3,-1). They're perpendicular: 3−3=03-3=0 ✓.

So the unit circle becomes an ellipse with its long axis (length 6.708) along (1, 3) and its short axis (2.236) along (3, −1). Note that AA's eigenvalues are 3 and 5 (it's triangular): not the singular values.

Watch outCommon misconceptions

  • "Singular values are the eigenvalues." Only for symmetric PSD matrices. In general σi=λi(A⊤A)\sigma_i=\sqrt{\lambda_i(A^\top A)}. [0200]\begin{bmatrix}0&2\\0&0\end{bmatrix} has eigenvalues 0, 0 but singular values 2, 0.
  • "Singular values can be negative." Never: signs are absorbed into UU or VV. A symmetric matrix with eigenvalues 4 and −3 has singular values 4 and 3.
  • "The SVD is unique." The singular values are. The vectors are only unique up to sign (flip ui\mathbf u_i and vi\mathbf v_i together), and less unique when singular values repeat. Two libraries can give different-looking but equally correct answers.
  • "np.linalg.svd returns V." It returns U, S, Vh where Vh is V⊤V^\top: the right singular vectors are its rows.

In ML & deep learningWhere this shows up

The SVD may be the single most useful matrix fact in data science. The next four chapters are all applications: low-rank compression (chapter 7), PCA (chapter 8), the pseudoinverse and least squares (chapter 9), and the condition number (chapter 10). In deep learning, σ1\sigma_1 of each weight matrix bounds how much a layer can amplify its input, which is why spectral normalisation (dividing WW by σ1\sigma_1) stabilises GAN training and why it appears in robustness and generalisation bounds. The singular-value spectrum of trained weight matrices is used to diagnose training, and it's typically dominated by a few large values, which is the observation that makes LoRA work (chapter 12). Latent semantic analysis, the ancestor of word embeddings, is an SVD of a word–document matrix.

Practice (pick one answer per question)

What are the singular values of [300−2]\begin{bmatrix}3&0\\0&-2\end{bmatrix}?

  1. 3 and 2
  2. 3 and −2
  3. 9 and 4
  4. √3 and √2

It stretches x by 3 and y by 2 (with a flip). The flip goes into UU; singular values are always ≥0\ge0. (9 and 4 are the eigenvalues of A⊤AA^\top A.)

For A=[3045]A=\begin{bmatrix}3&0\\4&5\end{bmatrix}, what is σ1σ2\sigma_1\sigma_2?

  1. 15
  2. 45
  3. 8
  4. 225

∣det⁡A∣=∣3⋅5−0⋅4∣=15|\det A|=|3\cdot5-0\cdot4|=15, and rotations don't change area, so the product of the stretches is 15. Check with the worked example: 35⋅5=153\sqrt5\cdot\sqrt5=15 ✓. (225 is det⁡(A⊤A)=(σ1σ2)2\det(A^\top A)=(\sigma_1\sigma_2)^2.)

The columns of VV (right singular vectors) are eigenvectors of…

  1. A⊤AA^\top A
  2. AA⊤AA^\top
  3. AA
  4. A+A⊤A+A^\top

A⊤A=VΣ⊤ΣV⊤A^\top A = V\Sigma^\top\Sigma V^\top, a spectral decomposition, so VV's columns are its eigenvectors. AA⊤AA^\top has the u\mathbf u's instead.

A matrix has singular values 7, 2 and 0. What is its rank?

  1. 2
  2. 3
  3. 9
  4. 1

Rank = number of nonzero singular values. One direction is squashed to 0.

AA is 5×3. What are the shapes in the full SVD A=UΣV⊤A=U\Sigma V^\top?

  1. UU: 5×5, Σ\Sigma: 5×3, VV: 3×3
  2. UU: 5×3, Σ\Sigma: 3×3, VV: 3×3
  3. UU: 3×3, Σ\Sigma: 3×5, VV: 5×5
  4. UU: 5×5, Σ\Sigma: 3×3, VV: 3×5

UU is a basis of the output space R5\mathbb R^5, VV of the input space R3\mathbb R^3, and Σ\Sigma has AA's shape. The second option is the thin SVD, which is also valid, but it isn't the full one.

A=[0200]A=\begin{bmatrix}0&2\\0&0\end{bmatrix} has eigenvalues 0 and 0. What are its singular values?

  1. 2 and 0
  2. 0 and 0
  3. 2 and 2
  4. 4 and 0

A⊤A=[0004]A^\top A=\begin{bmatrix}0&0\\0&4\end{bmatrix}, eigenvalues 4 and 0, so σ=2,0\sigma=2,0. AA sends (0, 1) to (2, 0): a real stretch by 2 that the eigenvalues completely miss.

What is the largest value of ∣Ax∣|A\mathbf x| over unit vectors x\mathbf x, for A=[3045]A=\begin{bmatrix}3&0\\4&5\end{bmatrix}?

  1. 35≈6.713\sqrt5\approx6.71
  2. 5
  3. 50≈7.07\sqrt{50}\approx7.07
  4. 45

It's σ1=45\sigma_1=\sqrt{45}, reached at v1=12(1,1)\mathbf v_1=\tfrac1{\sqrt2}(1,1): Av1=12(3,9)A\mathbf v_1=\tfrac1{\sqrt2}(3,9), length 90/2=45\sqrt{90/2}=\sqrt{45} ✓. 50\sqrt{50} is the Frobenius norm 9+16+25\sqrt{9+16+25}, which is bigger than any single stretch.

A symmetric matrix has eigenvalues 4 and −3. What are its singular values?

  1. 4 and 3
  2. 4 and −3
  3. 16 and 9
  4. 2 and √3

S=QΛQ⊤S=Q\Lambda Q^\top; move the sign of −3 into one column of the left factor: S=(QD) ∣Λ∣ Q⊤S = (QD)\,|\Lambda|\,Q^\top with D=diag(1,−1)D=\mathrm{diag}(1,-1). That's an SVD with Σ=∣Λ∣\Sigma=|\Lambda|. For symmetric matrices, σi=∣λi∣\sigma_i=|\lambda_i|.

Code it (optional: real Python runs in your browser and is graded by test cases)

Chapter 7

Low-rank approximation (Eckart–Young) and image compression

Watch: SVD matrix approximation (Steve Brunton) Watch: SVD image compression (Steve Brunton) Watch: Eckart–Young, the closest rank-k matrix (MIT 18.065, Gilbert Strang)

The SVD writes a matrix as a sum of rank-one layers, σ1u1v1⊤+σ2u2v2⊤+…\sigma_1\mathbf u_1\mathbf v_1^\top+\sigma_2\mathbf u_2\mathbf v_2^\top+\dots, sorted from most to least important. Keeping the first kk layers gives the best possible rank-kk approximation (the Eckart–Young theorem), and the error is exactly the singular values you threw away.

A matrix is a stack of rank-one layers

Multiply out UΣV⊤U\Sigma V^\top column-times-row and you get

A=σ1 u1v1⊤+σ2 u2v2⊤+⋯+σr urvr⊤.A = \sigma_1\,\mathbf u_1\mathbf v_1^\top + \sigma_2\,\mathbf u_2\mathbf v_2^\top + \dots + \sigma_r\,\mathbf u_r\mathbf v_r^\top.

Each uivi⊤\mathbf u_i\mathbf v_i^\top is an outer product: a whole m×nm\times n matrix built from one column and one row. Every row of it is a multiple of vi⊤\mathbf v_i^\top and every column a multiple of ui\mathbf u_i, so it has rank 1. If AA is a grayscale image, each layer is a "plaid" pattern: a fixed row profile, faded up and down by a column profile. The σ\sigma's say how loud each layer is, and they're sorted.

The rank-kk truncation keeps the first kk layers:

Ak=∑i=1kσiuivi⊤=UkΣkVk⊤,A_k = \sum_{i=1}^{k}\sigma_i\mathbf u_i\mathbf v_i^\top = U_k\Sigma_kV_k^\top,

where UkU_k and VkV_k are the first kk columns. Storing it takes kk columns of length mm, kk rows of length nn and kk numbers: k(m+n+1)k(m+n+1) numbers instead of mnmn.

Eckart–Young: you can't do better

The remarkable fact is that this greedy choice is optimal. Among all matrices BB of rank at most kk,

∥A−Ak∥2=σk+1,∥A−Ak∥F=σk+12+σk+22+⋯+σr2,\|A-A_k\|_2 = \sigma_{k+1},\qquad \|A-A_k\|_F=\sqrt{\sigma_{k+1}^2+\sigma_{k+2}^2+\dots+\sigma_r^2},

and no rank-kk BB has a smaller error in either norm. Here ∥⋅∥2\|\cdot\|_2 is the largest stretch (chapter 6) and ∥⋅∥F\|\cdot\|_F is the Frobenius norm, the square root of the sum of all squared entries, which also equals ∑σi2\sqrt{\sum\sigma_i^2}. So the error of the best rank-kk approximation is read straight off the discarded singular values, and

fraction of "energy" kept=σ12+⋯+σk2σ12+⋯+σr2.\text{fraction of "energy" kept} = \frac{\sigma_1^2+\dots+\sigma_k^2}{\sigma_1^2+\dots+\sigma_r^2}.

Real data usually has a fast-decaying spectrum: a few big singular values carrying the structure, then a long tail of small ones that is mostly noise or fine detail. That's why low-rank approximations work so well, and why truncating can even remove noise.

A 48×48 grayscale picture (left) and its rank-kk approximation (right), computed with an SVD right here in your browser. Slide kk and watch the picture build up layer by layer; the bar chart shows the singular values, with the kept ones highlighted. Show layer k only displays the single rank-one plaid σkukvk⊤\sigma_k\mathbf u_k\mathbf v_k^\top. Add noise shows that small kk keeps the shape and drops much of the noise.

Worked exampleHow much does truncation cost?

Suppose a 3×3 matrix has singular values 6, 3, 2.

  • Best rank-1 approximation: spectral error σ2=3\sigma_2=3, Frobenius error 32+22=13≈3.61\sqrt{3^2+2^2}=\sqrt{13}\approx3.61. Energy kept: 36/(36+9+4)=36/49≈73.5%36/(36+9+4)=36/49\approx73.5\%.
  • Best rank-2: spectral error 2, Frobenius error 2, energy kept 45/49≈91.8%45/49\approx91.8\%.

Now an image: a 512×512 grayscale picture with k=50k=50. Storage 50×(512+512+1)=51,25050\times(512+512+1)=51{,}250 numbers instead of 262,144262{,}144: about 19.6% of the original. For photos, k=50k=50 usually looks nearly perfect. (JPEG does better with a different transform, but the idea of keeping the big coefficients is the same.)

Watch outCommon misconceptions

  • "Rank-kk means keeping kk rows or kk columns of the picture." Every layer covers the whole matrix. A1A_1 is a blurry version of the entire image, not its first row.
  • "Low rank always saves space." Only when k(m+n+1)<mnk(m+n+1)<mn. For a 100×100 matrix, k=50k=50 already costs more than the original.
  • "The error is the first dropped singular value in every norm." In the spectral norm, yes. The Frobenius error is the root-sum-square of all the dropped ones.
  • "You could pick better layers by hand." Eckart–Young says no: for these norms no rank-kk matrix beats AkA_k.

In ML & deep learningWhere this shows up

Model compression: replace a dense weight matrix WW (m×nm\times n) by its truncated SVD, i.e. two thin layers UkΣkU_k\Sigma_k and Vk⊤V_k^\top, cutting parameters and compute from mnmn to k(m+n)k(m+n). LoRA (chapter 12) trains only a low-rank update. Recommender systems assume the user–item ratings matrix is approximately low-rank. Denoising and matrix completion rely on signals being low-rank while noise is spread over all singular values. Attention matrices, embedding tables and gradients are often approximately low-rank too, which methods like Linformer and GaLore exploit.

Practice (pick one answer per question)

How many numbers does a rank-10 SVD approximation of a 100×200 matrix need (UkU_k, VkV_k and the σ\sigma's)?

  1. 3,010
  2. 20,000
  3. 3,000
  4. 2,000

k(m+n+1)=10×301=3010k(m+n+1)=10\times301=3010, versus 20,000 for the full matrix. (3,000 forgets the 10 singular values; you could also fold them into UkU_k and store 3,000.)

AA has singular values 6, 3, 2. What is ∥A−A1∥2\|A-A_1\|_2, the spectral-norm error of the best rank-1 approximation?

  1. 3
  2. 6
  3. 13\sqrt{13}
  4. 5

Eckart–Young: σ2=3\sigma_2=3. The leftover 3u2v2⊤+2u3v3⊤3\mathbf u_2\mathbf v_2^\top+2\mathbf u_3\mathbf v_3^\top stretches by at most 3.

Same AA. What is the Frobenius error ∥A−A1∥F\|A-A_1\|_F?

  1. 13≈3.61\sqrt{13}\approx3.61
  2. 5
  3. 3
  4. 13

σ22+σ32=9+4\sqrt{\sigma_2^2+\sigma_3^2}=\sqrt{9+4}. Adding them (5) isn't how norms of perpendicular pieces combine; 13 forgets the square root.

Same AA. What fraction of the squared Frobenius norm ("energy") does A2A_2 keep?

  1. 45/49 ≈ 91.8%
  2. 9/11 ≈ 81.8%
  3. 36/49 ≈ 73.5%
  4. 2/3 ≈ 66.7%

(36+9)/(36+9+4)=45/49(36+9)/(36+9+4)=45/49. Using the unsquared σ\sigma's gives (6+3)/11, which isn't energy. 36/49 is what A1A_1 keeps.

What does the Eckart–Young theorem say?

  1. No matrix of rank ≤k\le k is closer to AA than AkA_k, in the spectral or Frobenius norm
  2. AkA_k equals AA whenever k≥1k\ge1
  3. Every matrix has rank at most kk
  4. The singular values of AkA_k are σk+1,…,σr\sigma_{k+1},\dots,\sigma_r

Truncating the SVD is the optimal rank-kk approximation. The singular values of AkA_k are the first kk; those of A−AkA-A_k are the rest.

For a 100×100 matrix, what is the smallest kk at which storing k(m+n+1)k(m+n+1) numbers no longer saves space?

  1. 50
  2. 100
  3. 49
  4. 10

Need 201k≥10,000201k\ge10{,}000, so k≥49.75k\ge49.75. At k=49k=49: 9,849 (still saves). At k=50k=50: 10,050 (more than the original).

What are the singular values of the rank-one matrix [3468]=[12][34]\begin{bmatrix}3&4\\6&8\end{bmatrix}=\begin{bmatrix}1\\2\end{bmatrix}\begin{bmatrix}3&4\end{bmatrix}?

  1. 55≈11.185\sqrt5\approx11.18 and 0
  2. 11 and 0
  3. 5 and 5\sqrt5
  4. 3 and 8

xy⊤=∣x∣∣y∣ x^y^⊤\mathbf x\mathbf y^\top = |\mathbf x||\mathbf y|\,\hat{\mathbf x}\hat{\mathbf y}^\top, so σ1=∣x∣∣y∣=5⋅5\sigma_1=|\mathbf x||\mathbf y|=\sqrt5\cdot5 and the other is 0. Check with Frobenius: 9+16+36+64=125=55\sqrt{9+16+36+64}=\sqrt{125}=5\sqrt5 ✓. (11 is the trace, which is the nonzero eigenvalue, not the singular value.)

You compress a photo with k=1k=1. What does the result look like?

  1. A "plaid" image: every row is a scaled copy of the same row pattern
  2. The first row of the photo, repeated
  3. A single-colour image of the average brightness
  4. The photo at a lower resolution, with square pixels

A1=σ1u1v1⊤A_1=\sigma_1\mathbf u_1\mathbf v_1^\top: row ii is σ1u1iv1⊤\sigma_1u_{1i}\mathbf v_1^\top, so all rows share the shape v1⊤\mathbf v_1^\top, just brighter or darker. It captures the dominant horizontal and vertical structure of the whole picture, not any single row.

Code it (optional: real Python runs in your browser and is graded by test cases)

Chapter 8

PCA through the SVD

Watch: Principal Component Analysis, step by step (StatQuest) Watch: Principal Component Analysis (Steve Brunton) Watch: Principal Component Analysis (Visually Explained)

PCA finds the orthonormal directions along which centred data varies the most. Take the SVD of the centred data matrix, Xc=UΣV⊤X_c=U\Sigma V^\top: the rows of V⊤V^\top are the principal directions, UΣU\Sigma gives each point's coordinates along them, and σi2/(n−1)\sigma_i^2/(n-1) is the variance each direction captures.

You have nn data points with dd features each, stored as the rows of an n×dn\times d matrix XX. Maybe d=784d=784 pixel values per digit image, or d=50d=50 measurements per patient. You'd like a few new axes, combinations of the features, that capture as much of the data's spread as possible, so you can plot it, compress it or denoise it. That's principal component analysis.

The recipe

  1. Centre the data: subtract each column's mean, Xc=X−1μ⊤X_c = X-\mathbf 1\boldsymbol\mu^\top. PCA is about spread around the centre, not the location of the cloud.
  2. Covariance: C=1n−1Xc⊤XcC = \frac1{n-1}X_c^\top X_c, a d×dd\times d symmetric PSD matrix. Entry (j,j)(j,j) is the variance of feature jj; entry (i,j)(i,j) is the covariance of features ii and jj.
  3. The variance of the data along a unit direction w\mathbf w is 1n−1∣Xcw∣2=w⊤C w\frac1{n-1}|X_c\mathbf w|^2 = \mathbf w^\top C\,\mathbf w, a quadratic form (chapter 5). It's maximised by the top eigenvector of CC (the Rayleigh quotient from chapter 4), and the maximum variance is the top eigenvalue. The next-best direction perpendicular to it is the second eigenvector, and so on.

So the principal directions are the eigenvectors of the covariance matrix: you saw this in Module 1's PCA-from-scratch problem. Now the SVD shortcut.

PCA is the SVD of the centred data

Take the SVD Xc=UΣV⊤X_c=U\Sigma V^\top. Then, as in chapter 6,

C=1n−1Xc⊤Xc=V Σ⊤Σn−1 V⊤.C=\frac{1}{n-1}X_c^\top X_c = V\,\frac{\Sigma^\top\Sigma}{n-1}\,V^\top.

That is the spectral decomposition of CC, handed to us for free. Reading it off:

  • Principal directions (also called components, or loadings) = the columns of VV = the rows of Vt.
  • Variance along direction ii = λi=σi2/(n−1)\lambda_i = \sigma_i^2/(n-1).
  • Scores (each point's coordinates along the principal axes) = XcV=UΣX_cV = U\Sigma.
  • Explained variance ratio of component ii = σi2/∑jσj2\sigma_i^2/\sum_j\sigma_j^2.

To reduce to kk dimensions keep the first kk scores, Z=XcVkZ = X_cV_k (an n×kn\times k matrix). To go back, X^=1μ⊤+ZVk⊤\hat X = \mathbf 1\boldsymbol\mu^\top + ZV_k^\top. By Eckart–Young (chapter 7), this reconstruction is the best rank-kk approximation of the centred data: PCA minimises the total squared perpendicular distance from the points to a kk-dimensional subspace.

Why go through the SVD rather than forming CC and calling eigh? Forming Xc⊤XcX_c^\top X_c squares the condition number (chapter 10), losing accuracy for the small components, and when dd is huge the d×dd\times d matrix may not even fit in memory. scikit-learn's PCA uses the SVD.

Drag any of the gold data points, or press New cloud. The green and red arrows are the principal directions from the SVD of the centred data, drawn from the mean with length 2λi2\sqrt{\lambda_i} (two standard deviations). Tick project onto PC1 to see each point's 1-D reconstruction: the residuals are perpendicular to PC1, and their total squared length is the variance PCA throws away.

Worked examplePCA of four points

Points (2, 1), (−2, −1), (1, 2), (−1, −2). The mean is already (0, 0), so Xc=XX_c=X.

  • Xc⊤Xc=[4+4+1+12+2+2+281+1+4+4]=[108810]X_c^\top X_c = \begin{bmatrix}4+4+1+1&2+2+2+2\\8&1+1+4+4\end{bmatrix}=\begin{bmatrix}10&8\\8&10\end{bmatrix}, with eigenvalues 18 and 2, so σ1=18\sigma_1=\sqrt{18}, σ2=2\sigma_2=\sqrt2.
  • Principal directions: v1=12(1,1)\mathbf v_1=\tfrac1{\sqrt2}(1,1), v2=12(1,−1)\mathbf v_2=\tfrac1{\sqrt2}(1,-1).
  • Variances (with n−1=3n-1=3): 18/3=618/3=6 along PC1, 2/32/3 along PC2. PC1 explains 18/20=90%18/20=90\%.
  • Scores on PC1: Xcv1=12(3,−3,3,−3)≈(2.12,−2.12,2.12,−2.12)X_c\mathbf v_1 = \tfrac{1}{\sqrt2}(3,-3,3,-3)\approx(2.12,-2.12,2.12,-2.12). Check: 4×4.5/3=64\times4.5/3=6 ✓.

Compressing to one number per point keeps 90% of the variance.

Watch outCommon misconceptions

  • "You can skip centring." Without it the first "component" mostly points at the mean of the data, not along its spread.
  • "PCA is the same as the regression line." Regression minimises vertical errors in yy (chapter 2); PCA minimises perpendicular distances and treats all features alike. They give different lines.
  • "Units don't matter." A feature measured in millimetres has a million times the variance of the same feature in kilometres and will dominate. Standardise (divide each feature by its standard deviation) when units differ; that's PCA on the correlation matrix.
  • "The sign of a component means something." v\mathbf v and −v-\mathbf v are equally valid; different libraries may flip them.
  • "PCA finds clusters or the most useful features for prediction." It finds directions of large variance. Those can be irrelevant to the label you care about.

In ML & deep learningWhere this shows up

Dimensionality reduction before training or clustering, and visualisation of embeddings (often PCA to 50 dimensions, then t-SNE or UMAP). Whitening: rotate onto the principal axes and divide by λi\sqrt{\lambda_i} so the features are uncorrelated with unit variance. Eigenfaces for face recognition. Analysing neural networks: PCA of hidden activations or of word embeddings reveals the main directions of variation, and probing work finds concepts lying along a few directions. A linear autoencoder trained with squared error learns exactly the PCA subspace.

Practice (pick one answer per question)

What is the first step of PCA?

  1. Subtract the mean of each feature (column)
  2. Normalise each data point (row) to length 1
  3. Sort the data points
  4. Compute the inverse of XX

Centre each column. PCA measures spread around the mean. Normalising rows changes the data's geometry, and a data matrix usually has no inverse.

If Xc=UΣV⊤X_c=U\Sigma V^\top (rows = data points), the principal directions are…

  1. the columns of VV (rows of V⊤V^\top)
  2. the columns of UU
  3. the rows of XcX_c
  4. the diagonal of Σ\Sigma

VV holds eigenvectors of Xc⊤Xc∝CX_c^\top X_c\propto C, which live in feature space (length dd). UU's columns have length nn: one entry per data point (they're the normalised scores).

A centred dataset with n=10n=10 points has singular values 6 and 3. What is the variance along PC1?

  1. 4
  2. 3.6
  3. 6
  4. 36

λ1=σ12/(n−1)=36/9=4\lambda_1=\sigma_1^2/(n-1)=36/9=4. Dividing by nn instead gives 3.6 (the biased version; numpy's np.cov uses n−1n-1).

Same data. What fraction of the variance does PC1 explain?

  1. 80%
  2. 66.7%
  3. 50%
  4. 90%

36/(36+9)=0.836/(36+9)=0.8. Using the unsquared σ\sigma's gives 6/9≈66.7%6/9\approx66.7\%, which is wrong: variance goes with σ2\sigma^2.

The PCA scores (each point's coordinates along the principal axes) are…

  1. XcV=UΣX_cV = U\Sigma
  2. V⊤XcV^\top X_c
  3. U⊤XcU^\top X_c
  4. ΣV⊤\Sigma V^\top

Coordinates in an orthonormal basis are dot products (chapter 1): row ii of XcVX_cV holds xi⋅vj\mathbf x_i\cdot\mathbf v_j. And XcV=UΣV⊤V=UΣX_cV=U\Sigma V^\top V=U\Sigma. V⊤XcV^\top X_c doesn't even have matching shapes unless n=dn=d.

You run PCA on height (in mm) and weight (in kg) without standardising. What happens?

  1. PC1 points almost entirely along height, just because its numbers are bigger
  2. Nothing; PCA is unit-free
  3. PC1 points along weight because kg is the SI unit
  4. PCA refuses to run on mixed units

Heights in mm have variances in the thousands, weights in kg in the tens to hundreds. Variance depends on units, so height dominates. Standardise first if the units are arbitrary.

For the points (2, 1), (−2, −1), (1, 2), (−1, −2), what fraction of the variance lies along PC1?

  1. 90%
  2. 50%
  3. 80%
  4. 100%

X⊤X=[108810]X^\top X=\begin{bmatrix}10&8\\8&10\end{bmatrix}, eigenvalues 18 and 2, so 18/20=90%18/20=90\%. (They don't all lie on a line, so it can't be 100%.)

A dataset has n=50n=50 points in d=1000d=1000 dimensions. After centring, at most how many principal components have nonzero variance?

  1. 49
  2. 50
  3. 1000
  4. 950

XcX_c is 50×1000, so its rank is at most 50. Centring makes the rows sum to zero, a dependency among them, so the rank drops to at most 49. At most 49 nonzero singular values, hence 49 components with positive variance.

Code it (optional: real Python runs in your browser and is graded by test cases)

Chapter 9

The pseudoinverse

Watch: Linear systems, least squares and the pseudoinverse (Steve Brunton) Watch: Left and right inverses; pseudoinverse (MIT OCW, Gilbert Strang)

Every matrix has a pseudoinverse A+=VΣ+U⊤A^+=V\Sigma^+U^\top: undo the rotations, and invert every stretch you can (the nonzero σ\sigma's) while leaving the squashed directions at zero. x+=A+b\mathbf x^+=A^+\mathbf b is the best answer to Ax=bA\mathbf x=\mathbf b there is: the least-squares solution, and the shortest one if there are many.

A−1A^{-1} exists only for square matrices that don't squash anything (Module 1, chapter 7). But we constantly want to "solve" systems that are too tall (more equations than unknowns, no exact solution), too wide (fewer equations than unknowns, infinitely many solutions), or squashed (rank-deficient, often both problems at once). The pseudoinverse handles all of them with one formula.

Building it from the SVD

A=UΣV⊤A=U\Sigma V^\top means: rotate by V⊤V^\top, stretch by σi\sigma_i, rotate by UU. To undo it, go backwards: rotate back by U⊤U^\top, un-stretch by 1/σi1/\sigma_i, rotate back by VV. The only problem is σi=0\sigma_i=0: that direction was crushed and can't be recovered, so we leave it at 0. Define Σ+\Sigma^+ (shape n×mn\times m) by putting 1/σi1/\sigma_i where σi≠0\sigma_i\neq0 and 0 elsewhere. Then

A+=V Σ+ U⊤=∑σi≠01σi viui⊤.A^+ = V\,\Sigma^+\,U^\top = \sum_{\sigma_i\neq0}\frac{1}{\sigma_i}\,\mathbf v_i\mathbf u_i^\top.

It maps each ui\mathbf u_i back to vi/σi\mathbf v_i/\sigma_i, and sends everything perpendicular to the column space to 0\mathbf 0.

What x+=A+b\mathbf x^+ = A^+\mathbf b means

Split the problem in two, using the orthonormal bases:

  • Output side: b\mathbf b might not be reachable. The part of b\mathbf b along the ui\mathbf u_i's (the column space) can be hit; the rest can't. So we aim at the projection p\mathbf p of b\mathbf b onto the column space: the least-squares choice (chapter 2). Indeed AA+AA^+ is exactly that projection.
  • Input side: if AA has a null space, adding any null-space vector to a solution gives another solution. A+A^+ only ever produces combinations of the vi\mathbf v_i with σi≠0\sigma_i\neq0, which span the row space, perpendicular to the null space. By Pythagoras, adding anything from the null space only makes the vector longer. So x+\mathbf x^+ is the minimum-norm solution. A+AA^+A is the projection onto the row space.

In short: x+\mathbf x^+ minimises ∣Ax−b∣|A\mathbf x-\mathbf b|, and among all minimisers it has the smallest ∣x∣|\mathbf x|.

Familiar special cases

  • Square and invertible: A+=A−1A^+=A^{-1}.
  • Tall, independent columns (regression): A+=(A⊤A)−1A⊤A^+=(A^\top A)^{-1}A^\top, the normal-equations solution from chapter 2. It's a left inverse: A+A=InA^+A=I_n, but AA+≠ImAA^+\neq I_m.
  • Wide, independent rows (underdetermined): A+=A⊤(AA⊤)−1A^+=A^\top(AA^\top)^{-1}, a right inverse: AA+=ImAA^+=I_m. It picks the shortest of infinitely many exact solutions.
  • Rank-deficient: neither formula works (the inverted matrix is singular), but the SVD formula still does.
The matrix starts out squashing the plane onto a line (rank 1). The blue line is its column space; drag the gold b\mathbf b off it. The green point p=AA+b\mathbf p=AA^+\mathbf b is the closest reachable output. Every x\mathbf x on the purple dashed line gives Ax=pA\mathbf x=\mathbf p; the pseudoinverse picks the teal x+\mathbf x^+, the one closest to the origin, which sits at a right angle to the null space (grey dashed). Edit the matrix to make it invertible and watch x+\mathbf x^+ become the ordinary A−1bA^{-1}\mathbf b.

Small singular values: the cutoff

In floating point, a singular value is rarely exactly 0; it's 10−1510^{-15} instead, and 1/σ1/\sigma would be a monstrous 101510^{15}. So np.linalg.pinv treats any σi\sigma_i below a cutoff (rcond times σ1\sigma_1) as zero. Raising the cutoff deliberately is a form of regularisation called truncated SVD: you give up fitting the weak directions to avoid amplifying noise. Chapter 10 explains why that matters.

Worked examplePseudoinverse of A=[1111]A=\begin{bmatrix}1&1\\1&1\end{bmatrix}

AA squashes the plane onto the line through (1, 1). Its SVD has σ1=2\sigma_1=2, u1=v1=12(1,1)\mathbf u_1=\mathbf v_1=\tfrac1{\sqrt2}(1,1), and σ2=0\sigma_2=0. So

A+=12v1u1⊤=12⋅12[1111]=[0.250.250.250.25].A^+ = \frac{1}{2}\mathbf v_1\mathbf u_1^\top = \frac12\cdot\frac12\begin{bmatrix}1&1\\1&1\end{bmatrix} = \begin{bmatrix}0.25&0.25\\0.25&0.25\end{bmatrix}.

Solve Ax≈b=(2,0)A\mathbf x\approx\mathbf b=(2, 0). Every output of AA has equal entries, so (2, 0) is unreachable; the closest reachable point is its projection onto (1, 1), which is (1, 1). Any x\mathbf x with x1+x2=1x_1+x_2=1 hits it: (1, 0), (0, 1), (2, −1), … The pseudoinverse gives A+b=(0.5,0.5)A^+\mathbf b=(0.5, 0.5), and it's the shortest of them, with length ≈0.707\approx0.707 versus 1 for (1, 0). It's also perpendicular to the null-space direction (1, −1) ✓.

Watch outCommon misconceptions

  • "A+A=IA^+A=I and AA+=IAA^+=I." Both are projections. They're identities only when AA is invertible; for a tall full-rank AA just the first one is.
  • "Pseudoinverse means 'approximately the inverse' of a nearly singular matrix." For an invertible matrix it is exactly the inverse, however badly conditioned. The cutoff is what changes things, and only for tiny σ\sigma's.
  • "(AB)+=B+A+(AB)^+ = B^+A^+, just like inverses." Not in general. It holds in special cases (e.g. AA with orthonormal columns), but don't rely on it.
  • "Use pinv to solve every regression." It works, but np.linalg.lstsq (which uses the SVD without forming A+A^+) is cheaper and is the standard tool.

In ML & deep learningWhere this shows up

Linear regression in closed form is w^=X+y\hat{\mathbf w}=X^+\mathbf y, and it still works when features are duplicated or collinear (the "dummy variable trap"). Over-parameterised models (more weights than data points) have infinitely many weight vectors that fit the training data perfectly. Gradient descent on linear least squares started from zero converges to exactly the minimum-norm one, X+yX^+\mathbf y: an example of the "implicit bias" of gradient descent, and a starting point for understanding double descent. Pseudoinverses also appear in ridge regression as λ→0\lambda\to0, in robotics (inverse kinematics) and in recovering linear layers or signals from measurements.

Practice (pick one answer per question)

What is the pseudoinverse of [2000]\begin{bmatrix}2&0\\0&0\end{bmatrix}?

  1. [0.5000]\begin{bmatrix}0.5&0\\0&0\end{bmatrix}
  2. It doesn't exist, because the matrix is singular
  3. [0.500∞]\begin{bmatrix}0.5&0\\0&\infty\end{bmatrix}
  4. [2000]\begin{bmatrix}2&0\\0&0\end{bmatrix}

Invert the nonzero stretch, leave the zero alone. Every matrix has a pseudoinverse; that's the point of it.

If AA is square and invertible, A+A^+ equals…

  1. A−1A^{-1}
  2. A⊤A^\top
  3. (A⊤A)−1(A^\top A)^{-1}
  4. AA

All σi>0\sigma_i>0, so Σ+=Σ−1\Sigma^+=\Sigma^{-1} and VΣ−1U⊤=(UΣV⊤)−1V\Sigma^{-1}U^\top=(U\Sigma V^\top)^{-1}. A⊤A^\top is the inverse only for orthogonal matrices.

One equation, two unknowns: x1+x2=2x_1+x_2=2. What is the minimum-norm solution A+bA^+\mathbf b?

  1. (1, 1)
  2. (2, 0)
  3. (0, 2)
  4. (0.5, 0.5)

A=[1  1]A=[1\ \ 1], A+=A⊤(AA⊤)−1=12(1,1)A^+=A^\top(AA^\top)^{-1}=\tfrac12(1,1), so x+=(1,1)\mathbf x^+=(1,1), length 2\sqrt2. (2, 0) also solves it but has length 2. (0.5, 0.5) doesn't solve it.

The matrix AA+AA^+ is…

  1. the projection onto the column space of AA
  2. always the identity
  3. the projection onto the null space of AA
  4. the zero matrix when AA is singular

AA+=UΣV⊤VΣ+U⊤=U(ΣΣ+)U⊤=∑σi≠0uiui⊤AA^+=U\Sigma V^\top V\Sigma^+U^\top=U(\Sigma\Sigma^+)U^\top=\sum_{\sigma_i\neq0}\mathbf u_i\mathbf u_i^\top, the projection onto the span of the ui\mathbf u_i with σi≠0\sigma_i\ne0: the column space.

AA is tall with independent columns. Which statement is true?

  1. A+=(A⊤A)−1A⊤A^+=(A^\top A)^{-1}A^\top and A+A=IA^+A=I, but AA+≠IAA^+\neq I
  2. A+=A⊤(AA⊤)−1A^+=A^\top(AA^\top)^{-1} and AA+=IAA^+=I
  3. A+=A−1A^+=A^{-1}
  4. A+AA^+A and AA+AA^+ are both II

A⊤AA^\top A is invertible (independent columns), giving the left inverse. AA⊤AA^\top is a singular m×mm\times m matrix, so the second formula fails, and AA+AA^+ is a projection onto an nn-dimensional subspace of Rm\mathbb R^m, not the identity.

AA is 3×5. What is the shape of A+A^+?

  1. 5×3
  2. 3×5
  3. 3×3
  4. 5×5

AA maps R5→R3\mathbb R^5\to\mathbb R^3; A+A^+ goes back, R3→R5\mathbb R^3\to\mathbb R^5. Same shape as A⊤A^\top.

For A=[1111]A=\begin{bmatrix}1&1\\1&1\end{bmatrix} and b=(4,2)\mathbf b=(4,2), what is x+=A+b\mathbf x^+=A^+\mathbf b?

  1. (1.5, 1.5)
  2. (3, 3)
  3. (2, 1)
  4. (4, 2)

A+=14[1111]A^+=\tfrac14\begin{bmatrix}1&1\\1&1\end{bmatrix}, so x+=14(6,6)=(1.5,1.5)\mathbf x^+=\tfrac14(6,6)=(1.5,1.5). Check: Ax+=(3,3)A\mathbf x^+=(3,3), the projection of (4, 2) onto the line through (1, 1) ✓. (3, 3) is that projection, the output, not the input.

Why does np.linalg.pinv zero out singular values below a small cutoff instead of inverting them?

  1. Inverting a tiny σ\sigma gives a huge 1/σ1/\sigma that blows up rounding errors and noise
  2. Small singular values are always exactly zero in theory
  3. To make the result symmetric
  4. To make A+A=IA^+A=I

A σ\sigma of 10−1510^{-15} is usually rounding error; multiplying by 101510^{15} would turn tiny noise in b\mathbf b along ui\mathbf u_i into an enormous component along vi\mathbf v_i. Cutting it off trades a little bias for a lot of stability (chapter 10).

Code it (optional: real Python runs in your browser and is graded by test cases)

Chapter 10

Norms and the condition number

Watch: Survey of difficulties with Ax = b (MIT 18.065, Gilbert Strang) Watch: SVD and optimal truncation (Steve Brunton)

Norms measure the size of vectors and matrices. The condition number κ(A)=σmax⁡/σmin⁡\kappa(A)=\sigma_{\max}/\sigma_{\min} measures how much solving Ax=bA\mathbf x=\mathbf b can magnify a small relative error in b\mathbf b. An ill-conditioned problem (huge κ\kappa) turns tiny noise into huge mistakes, no matter how good your algorithm is.

Vector norms: different ways to measure size

A norm ∥x∥\|\mathbf x\| is a length: zero only for 0\mathbf 0, scales as ∥cx∥=∣c∣ ∥x∥\|c\mathbf x\|=|c|\,\|\mathbf x\|, and obeys the triangle inequality ∥x+y∥≤∥x∥+∥y∥\|\mathbf x+\mathbf y\|\le\|\mathbf x\|+\|\mathbf y\|. Three are used constantly:

  • ∥x∥2=x12+⋯+xn2\|\mathbf x\|_2=\sqrt{x_1^2+\dots+x_n^2}, the ordinary Euclidean length. Its "unit ball" is a circle.
  • ∥x∥1=∣x1∣+⋯+∣xn∣\|\mathbf x\|_1 = |x_1|+\dots+|x_n|, the "taxicab" length. Unit ball: a diamond.
  • ∥x∥∞=max⁡i∣xi∣\|\mathbf x\|_\infty=\max_i|x_i|, the largest entry. Unit ball: a square.

For (3, −4): ∥⋅∥1=7\|\cdot\|_1=7, ∥⋅∥2=5\|\cdot\|_2=5, ∥⋅∥∞=4\|\cdot\|_\infty=4. In ML, the L2 penalty λ∥w∥22\lambda\|\mathbf w\|_2^2 (weight decay) shrinks all weights smoothly, while the L1 penalty λ∥w∥1\lambda\|\mathbf w\|_1 (lasso) pushes many weights to exactly zero: the corners of the diamond lie on the axes.

Matrix norms

  • Spectral norm ∥A∥2=max⁡x≠0∥Ax∥2/∥x∥2=σ1\|A\|_2=\max_{\mathbf x\neq0}\|A\mathbf x\|_2/\|\mathbf x\|_2=\sigma_1: the biggest stretch (chapter 6).
  • Frobenius norm ∥A∥F=∑ijaij2=σ12+⋯+σr2\|A\|_F=\sqrt{\sum_{ij}a_{ij}^2}=\sqrt{\sigma_1^2+\dots+\sigma_r^2}: treat the matrix as one long vector.

Both satisfy ∥AB∥≤∥A∥ ∥B∥\|AB\|\le\|A\|\,\|B\|, which is what lets you bound how errors grow through a chain of layers.

The condition number

Suppose Ax=bA\mathbf x=\mathbf b and the right-hand side is measured with a small error δb\delta\mathbf b. The solution moves by δx=A−1δb\delta\mathbf x=A^{-1}\delta\mathbf b. How bad can that be, relatively?

  • ∥δx∥≤∥A−1∥ ∥δb∥=∥δb∥/σmin⁡\|\delta\mathbf x\|\le\|A^{-1}\|\,\|\delta\mathbf b\|=\|\delta\mathbf b\|/\sigma_{\min}: an error along the weakest direction gets blown up by 1/σmin⁡1/\sigma_{\min}.
  • ∥b∥=∥Ax∥≤σmax⁡∥x∥\|\mathbf b\|=\|A\mathbf x\|\le\sigma_{\max}\|\mathbf x\|, so 1/∥x∥≤σmax⁡/∥b∥1/\|\mathbf x\|\le\sigma_{\max}/\|\mathbf b\|.

Multiply them:

∥δx∥∥x∥  ≤  σmax⁡σmin⁡⏟κ(A)  ∥δb∥∥b∥.\frac{\|\delta\mathbf x\|}{\|\mathbf x\|}\;\le\;\underbrace{\frac{\sigma_{\max}}{\sigma_{\min}}}_{\kappa(A)}\;\frac{\|\delta\mathbf b\|}{\|\mathbf b\|}.

The condition number κ(A)=∥A∥ ∥A−1∥=σmax⁡/σmin⁡\kappa(A)=\|A\|\,\|A^{-1}\|=\sigma_{\max}/\sigma_{\min} is the worst-case magnification of relative error, and the worst case really happens: when b\mathbf b lies along u1\mathbf u_1 and the error along un\mathbf u_n. κ≥1\kappa\ge1 always; κ=1\kappa=1 for orthogonal matrices (perfect); κ=∞\kappa=\infty for singular ones.

Rule of thumb: you lose about log⁡10κ\log_{10}\kappa significant digits. Double precision carries about 16, so κ=1010\kappa=10^{10} leaves you around 6 trustworthy digits, and at κ≈1016\kappa\approx10^{16} the answer can be pure noise.

Geometrically, in 2D: solving Ax=bA\mathbf x=\mathbf b means intersecting two lines. If the lines are nearly parallel, nudging one of them slides the intersection a long way. That's a large κ\kappa.

The two lines are the two equations of Ax=bA\mathbf x=\mathbf b; their crossing is the solution x\mathbf x (gold). Lower the angle between the lines with the slider. Each grey dot solves the system with b\mathbf b jiggled by a tiny random amount (the noise slider). With nearly parallel lines the cloud of solutions stretches into a long streak along the weak direction v2\mathbf v_2: that's κ\kappa at work.

Why the normal equations are risky, and what to do

A⊤AA^\top A has singular values σi2\sigma_i^2, so κ(A⊤A)=κ(A)2\kappa(A^\top A)=\kappa(A)^2. If κ(A)=105\kappa(A)=10^5, forming A⊤AA^\top A gives 101010^{10} and throws away 5 extra digits. That's why QR (chapter 3) and SVD-based solvers are preferred for least squares. Other remedies:

  • Rescale features so columns have similar sizes (a column in metres next to one in micrometres is a self-inflicted large κ\kappa).
  • Regularise: ridge regression solves (A⊤A+λI)w=A⊤b(A^\top A+\lambda I)\mathbf w=A^\top\mathbf b. Adding λ\lambda lifts every σi2\sigma_i^2 to σi2+λ\sigma_i^2+\lambda, so the condition number becomes (σ12+λ)/(σn2+λ)(\sigma_1^2+\lambda)/(\sigma_n^2+\lambda).
  • Truncate: drop tiny singular values (the pseudoinverse cutoff, chapter 9).
  • Precondition: solve an equivalent, better-conditioned system.

Worked exampleA tiny change, a huge jump

A=[1111.001]A=\begin{bmatrix}1&1\\1&1.001\end{bmatrix}, b=(2, 2.001)\mathbf b=(2,\ 2.001). The solution is x=(1,1)\mathbf x=(1,1).

Now change b\mathbf b to (2, 2.002)(2,\ 2.002), a relative change of 0.001/∣b∣≈0.035%0.001/|\mathbf b|\approx0.035\%. The new solution is (0, 2)(0,\ 2)! The relative change in x\mathbf x is ∣(−1,1)∣/∣(1,1)∣=100%|(-1,1)|/|(1,1)|=100\%: an amplification of about 2,800.

The bound explains it: σ1≈2.0005\sigma_1\approx2.0005, σ2≈0.0005\sigma_2\approx0.0005, so κ≈4002\kappa\approx4002. The two equations describe nearly the same line, so the data barely pins down where they cross.

Watch outCommon misconceptions

  • "A small determinant means ill-conditioned." 0.1 I0.1\,I (10×10) has determinant 10−1010^{-10} but κ=1\kappa=1: it's perfectly conditioned. Conditioning is about the ratio of stretches, not their product.
  • "A better algorithm fixes ill-conditioning." A stable algorithm avoids adding error (e.g. by not squaring κ\kappa), but the sensitivity is a property of the problem. If the data has noise, a large κ\kappa amplifies it whatever you do; only changing the problem (more data, regularisation) helps.
  • "κ\kappa only matters for solving equations." It also governs how fast gradient descent converges on a quadratic: the number of steps grows roughly like the condition number of the Hessian.

In ML & deep learningWhere this shows up

Optimisation: on a loss surface whose Hessian has condition number κ\kappa, gradient descent zig-zags across the narrow valley and needs roughly κ\kappa times more steps. Feature standardisation, batch normalisation and adaptive optimisers (Adam, RMSProp) all act partly as cheap preconditioners. Deep networks: the product of many weight matrices can have exploding or vanishing singular values; orthogonal initialisation and normalisation layers keep the spectrum near 1. Regression: collinear features (multicollinearity) give a huge κ\kappa and wildly unstable coefficients; ridge regression is the standard fix. Numerics: training in float16 or bfloat16 has only about 3 significant digits, so conditioning matters even more.

Practice (pick one answer per question)

What is ∥(3,−4)∥1\|(3,-4)\|_1?

  1. 7
  2. 5
  3. 4
  4. −1

Sum of absolute values: 3+4=73+4=7. (5 is the L2 norm, 4 the L∞ norm, and −1 forgets the absolute values.)

What is ∥(1,−6,2)∥∞\|(1,-6,2)\|_\infty?

  1. 6
  2. 2
  3. 9
  4. −6

The largest absolute entry: 6.

What is the condition number of diag(5, 0.1, 2)\mathrm{diag}(5,\ 0.1,\ 2)?

  1. 50
  2. 2.5
  3. 5
  4. 1

The singular values are 5, 2 and 0.1, so κ=5/0.1=50\kappa=5/0.1=50. (2.5 uses the wrong smallest value.)

What is the Frobenius norm of [1224]\begin{bmatrix}1&2\\2&4\end{bmatrix}?

  1. 5
  2. 9
  3. 25
  4. 5\sqrt{5}

1+4+4+16=25=5\sqrt{1+4+4+16}=\sqrt{25}=5. It's a rank-one matrix (1,2)(1,2)⊤(1,2)(1,2)^\top, so σ1=5\sigma_1=5 is its only nonzero singular value, and the two norms agree.

κ(A)=106\kappa(A)=10^6 and b\mathbf b is accurate to about 7 significant digits. Roughly how many digits of the solution can you trust in the worst case?

  1. about 1
  2. about 7
  3. about 13
  4. none at all

You lose about log⁡10κ=6\log_{10}\kappa=6 digits: 7−6=17-6=1. Adding the digits (13) gets the direction backwards.

κ(A)=1000\kappa(A)=1000. What is κ(A⊤A)\kappa(A^\top A)?

  1. 10610^6
  2. 1000
  3. 1000≈31.6\sqrt{1000}\approx31.6
  4. 2000

A⊤AA^\top A has singular values σi2\sigma_i^2, so the ratio is squared. That's why the normal equations are avoided for ill-conditioned least squares.

What is the condition number of any orthogonal matrix QQ?

  1. 1
  2. 0
  3. it depends on the size of QQ
  4. ∞\infty

All singular values of QQ are 1 (it preserves lengths), so κ=1/1=1\kappa=1/1=1, the best possible. Rotations never amplify relative errors.

AA has singular values 10 and 0.1. Ridge regression uses A⊤A+λIA^\top A+\lambda I with λ=1\lambda=1. What is its condition number (compared with 10410^4 for A⊤AA^\top A)?

  1. 100
  2. 10410^4
  3. 101
  4. 10

Eigenvalues of A⊤AA^\top A are 100 and 0.01; adding 1 gives 101 and 1.01, a ratio of exactly 100. Regularisation trades a little bias for a hundredfold improvement in conditioning here.

Code it (optional: real Python runs in your browser and is graded by test cases)

Chapter 11

Tensors, broadcasting and einsum

Watch: Broadcasting in Python (DeepLearning.AI, Andrew Ng) Watch: Einsum is all you need (Aladdin Persson)

Real ML code works with tensors: arrays with many axes, like a batch of sentences of token vectors, shape (B, T, D). Broadcasting stretches size-1 axes so arrays of different shapes can be combined, and einsum names every axis so you can say exactly which ones to multiply and which to sum. Most PyTorch bugs are shape bugs; these rules are how you avoid them.

Tensors are just arrays with more axes

A scalar has shape (), a vector (n,), a matrix (m, n). Keep going and you have a tensor (in ML, "tensor" just means an n-dimensional array). Typical shapes:

  • a batch of images: (B, C, H, W) in PyTorch (batch, colour channels, height, width), (B, H, W, C) in TensorFlow;
  • a batch of token embeddings in a transformer: (B, T, D) (batch, sequence length, model dimension);
  • attention scores: (B, heads, T, T).

Every operation says what it does to each axis. x.sum(axis=1) removes axis 1; keepdims=True keeps it with size 1, which (as we'll see) is often what you need to broadcast the result back. reshape regroups the same numbers in a new shape (order preserved); transpose / permute reorders axes. Mixing those two up silently scrambles your data.

Broadcasting: the rules

Element-wise operations (+ - * /, comparisons) need equal shapes, except that numpy and PyTorch will broadcast:

  1. Line the two shapes up from the right. If one has fewer axes, pad it on the left with 1s.
  2. For each axis, the sizes must be equal, or one of them must be 1.
  3. A size-1 axis is (virtually) copied to match the other; the result takes the larger size. No memory is actually copied.

So (B, T, D) + (D,) works: the bias vector is added to every token of every sequence. (4, 3) + (3,) → (4, 3). (5, 1) + (1, 6) → (5, 6), an "outer sum". But (2, 3) + (2,) fails: lined up from the right, 3 meets 2. To add a per-row value you need shape (2, 1), e.g. x - x.mean(axis=1, keepdims=True).

The silent killer: y of shape (n,) minus y_hat of shape (n, 1) broadcasts to (n, n). No error, just a wrong loss computed from n2n^2 meaningless differences. Check your shapes, or use .squeeze() / .reshape(-1) deliberately.

Matrix multiplication on tensors

A @ B treats the last two axes as matrices and broadcasts all the axes in front as a batch: (B, T, D) @ (D, E) → (B, T, E) (one linear layer applied to every token), and (B, h, T, d) @ (B, h, d, T) → (B, h, T, T).

einsum: name your axes

np.einsum (and torch.einsum) takes a little formula. Give every axis of every input a letter, then list the output's letters after ->. The rule: multiply matching entries; any letter that doesn't appear in the output is summed over.

einsummeaningmath
'i,i->'dot product∑ixiyi\sum_i x_iy_i
'i,j->ij'outer productxiyjx_iy_j
'ij,j->i'matrix × vector∑jAijxj\sum_j A_{ij}x_j
'ij,jk->ik'matrix × matrix∑jAijBjk\sum_j A_{ij}B_{jk}
'ij->ji'transposeAjiA_{ji}
'ii->'trace∑iAii\sum_i A_{ii}
'bij,bjk->bik'batched matmul∑jAbijBbjk\sum_j A_{bij}B_{bjk}
'bhqd,bhkd->bhqk'attention scores QK⊤QK^\top per batch and head∑dQbhqdKbhkd\sum_d Q_{bhqd}K_{bhkd}

Letters that share a name must have the same size. The cost is the product of the sizes of all distinct letters: for 'ij,jk->ik' that's i⋅j⋅ki\cdot j\cdot k multiply-adds, the familiar cost of a matrix product.

A shape playground. In Broadcast mode, type two shapes: they're lined up from the right, and each axis is coloured green (sizes match), blue (a 1 or a missing axis gets stretched) or red (incompatible). In einsum mode, type a formula and the input shapes: summed letters are purple, kept letters green, size clashes red, and you get the output shape and the number of multiply-adds. Try the presets, including the classic bugs.

Worked exampleShapes inside self-attention

A batch of B=2B=2 sentences, T=5T=5 tokens each, model dimension D=8D=8: X has shape (2, 5, 8). A query weight matrix WQW_Q is (8, 8).

  • Q = X @ W_Q: (2, 5, 8) @ (8, 8) → (2, 5, 8). The matmul acts on the last two axes and broadcasts over the batch.
  • Scores: np.einsum('btd,bsd->bts', Q, K) → (2, 5, 5): for each sentence, every query token dotted with every key token; dd is summed because it's missing from the output. Equivalent to Q @ K.transpose(0, 2, 1). Cost: 2⋅5⋅5⋅8=4002\cdot5\cdot5\cdot8=400 multiply-adds.
  • Scale and normalise: scores / np.sqrt(8) broadcasts a scalar; the softmax subtracts scores.max(axis=-1, keepdims=True), shape (2, 5, 1), which broadcasts back across the last axis. Without keepdims it would be (2, 5) and line up wrongly against (2, 5, 5): 5 meets 5, 2 meets 5, error (or worse, a silent bug if the sizes happened to match).

Watch outCommon misconceptions

  • "Shapes are aligned from the left." From the right. (3,) + (3, 4) fails (3 meets 4), even though the first axes match.
  • "(n,) and (n, 1) are the same vector." They broadcast completely differently. (n,) behaves like a row (1, n).
  • "reshape and transpose do the same thing." x.reshape(3, 2) of a 2×3 array keeps the reading order 1,2,3,4,5,6; x.T moves entries. Only one of them is a matrix transpose.
  • "* is matrix multiplication." In numpy and PyTorch * is element-wise (with broadcasting); @ is the matrix product.

In ML & deep learningWhere this shows up

Everywhere. Adding a bias, normalising features, layer norm (subtract the mean over the last axis with keepdims), softmax, masking attention with a (T, T) mask broadcast over batch and heads, pairwise distances for k-NN and contrastive losses (X[:, None, :] - Y[None, :, :], shape (n, m, d)), and every attention implementation are broadcasting and einsum. Libraries such as einops extend einsum's "name your axes" idea to reshapes and repeats, because named axes make shape bugs hard to write.

Practice (pick one answer per question)

What is the shape of A + b with A of shape (4, 3) and b of shape (3,)?

  1. (4, 3)
  2. error
  3. (3, 4)
  4. (4, 3, 3)

Pad b to (1, 3); then 3 meets 3 and 1 stretches to 4. The vector is added to every row.

Shape of (5, 1) + (1, 6)?

  1. (5, 6)
  2. error
  3. (5, 1)
  4. (6, 5)

Each axis has a 1 on one side, so both stretch: an "outer sum" table of shape (5, 6).

Shape of (2, 3) + (2,)?

  1. error
  2. (2, 3)
  3. (2, 2, 3)
  4. (3, 2)

Right-aligned, 3 meets 2: neither is 1, so it fails. Reshape the second to (2, 1) to add one number per row.

A is (3, 4) and x is (4,). What is np.einsum('ij,j->i', A, x)?

  1. the matrix–vector product AxA\mathbf x, shape (3,)
  2. the outer product, shape (3, 4)
  3. an error, because j appears twice
  4. the element-wise product, shape (3, 4)

j is in both inputs but not the output, so it's summed: ∑jAijxj\sum_jA_{ij}x_j. Repeating letters is the whole point of einsum.

y has shape (100,) and y_hat has shape (100, 1). What does ((y - y_hat)**2).mean() compute?

  1. a mean over a (100, 100) array of all pairwise differences: a silent bug
  2. the correct mean squared error
  3. an error about mismatched shapes
  4. a (100, 1) array

(100,) is treated as (1, 100); against (100, 1) both axes stretch, giving (100, 100). No error is raised. Fix with y_hat.reshape(-1) or y_hat[:, 0].

Q and K both have shape (2, 4, 10, 16) = (batch, heads, tokens, head dim). Shape of np.einsum('bhqd,bhkd->bhqk', Q, K)?

  1. (2, 4, 10, 10)
  2. (2, 4, 16, 16)
  3. (2, 4, 10, 16)
  4. (2, 4, 10)

Output letters b, h, q, k have sizes 2, 4, 10, 10. d (16) is summed away. One 10×10 score matrix per batch and head.

What does np.einsum('ii->', A) compute for a square A?

  1. the trace ∑iAii\sum_iA_{ii}
  2. the sum of all entries
  3. the diagonal as a vector
  4. the determinant

Using the same letter twice in one input picks the diagonal; leaving it out of the output sums it. 'ii->i' would return the diagonal itself, and 'ij->' the sum of all entries.

How many multiply-adds does np.einsum('bij,bjk->bik', A, B) take with b = 8, i = 32, j = 64, k = 16?

  1. 262,144
  2. 4,096
  3. 16,384
  4. 8,192

The product of all distinct letters' sizes: 8⋅32⋅64⋅16=262,1448\cdot32\cdot64\cdot16=262{,}144. (4,096 = 8·32·16 is the number of output entries; each needs 64 multiply-adds.)

Code it (optional: real Python runs in your browser and is graded by test cases)

Chapter 12

Matrix factorizations in ML: recommenders, LoRA and low-rank updates

Watch: How does Netflix recommend movies? Matrix factorization (Luis Serrano) Watch: LoRA explained visually, with PyTorch code (Umar Jamil)

A recurring trick in ML: approximate a big matrix by the product of two thin ones, M≈UV⊤M\approx UV^\top with only kk columns each. In recommender systems the thin factors are learned "taste" and "trait" vectors; in LoRA they're a tiny trainable update ΔW=BA\Delta W=BA added to a frozen giant weight matrix. Both work because the important structure is low-rank.

The pattern

An m×nm\times n matrix of rank kk can always be written as UV⊤UV^\top with UU of shape m×km\times k and VV of shape n×kn\times k (the truncated SVD of chapter 7 is one way, with U=UkΣkU=U_k\Sigma_k). Instead of mnmn numbers you store k(m+n)k(m+n). Entry (i,j)(i,j) becomes a dot product of two short vectors:

Mij≈ui⋅vj.M_{ij}\approx\mathbf u_i\cdot\mathbf v_j.

When the SVD isn't available (missing entries) or isn't what we want (we want to learn the factors by gradient descent), we optimise UU and VV directly. That is a matrix factorization model.

Recommender systems

Take a ratings matrix RR: one row per user, one column per movie, most entries missing (nobody has seen everything). Guess that tastes are driven by a few hidden factors (how much action, how much romance, …). Give every user ii a taste vector ui∈Rk\mathbf u_i\in\mathbb R^k and every movie jj a trait vector vj∈Rk\mathbf v_j\in\mathbb R^k, and predict r^ij=ui⋅vj\hat r_{ij}=\mathbf u_i\cdot\mathbf v_j: high when the user's tastes line up with the movie's traits (cosine-similarity intuition from chapter 1).

You can't just take the SVD of RR: the missing entries aren't zeros, and filling them with 0 would teach the model that unseen means hated. Instead, fit only the observed entries, with a penalty to keep the vectors small:

min⁡U,V ∑(i,j) observed(rij−ui⋅vj)2+λ(∑i∣ui∣2+∑j∣vj∣2).\min_{U,V}\ \sum_{(i,j)\ \text{observed}}\big(r_{ij}-\mathbf u_i\cdot\mathbf v_j\big)^2+\lambda\big(\textstyle\sum_i|\mathbf u_i|^2+\sum_j|\mathbf v_j|^2\big).

Alternating least squares (ALS) exploits a nice fact: if you freeze all the movie vectors, finding each user's vector is an ordinary small ridge regression (chapters 2 and 10): (Vi⊤Vi+λI)ui=Vi⊤ri(V_i^\top V_i+\lambda I)\mathbf u_i = V_i^\top\mathbf r_i, using the movies that user rated. Then freeze the users and solve for each movie the same way. Alternate until it settles. (Gradient descent on the same loss also works and is what deep-learning recommenders do, with the dot product replaced or joined by a neural network.)

Left: the 2-D "taste space". Grey dots are movies (their trait vectors); coloured arrows are users. Drag the gold arrow, You, to change your tastes. Right: the predicted ratings r^ij=ui⋅vj\hat r_{ij}=\mathbf u_i\cdot\mathbf v_j for every user and movie, a rank-2 matrix built from those vectors. Your row updates as you drag, and the readout names your top recommendation: the movie whose trait vector has the largest dot product with yours.

LoRA: fine-tuning with a low-rank update

A large language model has weight matrices like W0W_0 of shape 4096×4096: 16.8 million numbers each, and hundreds of them. Fine-tuning all of them for every new task is expensive, and storing a full copy per task is worse. LoRA (Low-Rank Adaptation) freezes W0W_0 and learns only a low-rank change:

W=W0+ΔW=W0+αr BA,B∈Rd×r, A∈Rr×k, r≪d,k.W = W_0 + \Delta W = W_0 + \frac{\alpha}{r}\,BA,\qquad B\in\mathbb R^{d\times r},\ A\in\mathbb R^{r\times k},\ r\ll d,k.
  • Parameters: r(d+k)r(d+k) instead of dkdk. With d=k=4096d=k=4096 and r=8r=8: 65,536 instead of 16,777,216, about 0.4%.
  • Forward pass: h=W0x+αrB(Ax)\mathbf h = W_0\mathbf x + \frac\alpha r B(A\mathbf x). Computing AxA\mathbf x first (shape rr) keeps it cheap; you never build the d×kd\times k matrix BABA during training.
  • Initialisation: AA random, B=0B=0, so ΔW=0\Delta W=0 and training starts exactly at the pretrained model.
  • Deployment: after training, merge W=W0+αrBAW=W_0+\frac\alpha rBA once. No extra cost at inference, and switching tasks means swapping tiny B,AB,A pairs.

Why should a rank-8 update be enough? Empirically, the change that fine-tuning makes to a pretrained weight matrix has most of its energy in a few singular directions (an "intrinsic low rank"), so by Eckart–Young a low-rank ΔW\Delta W captures most of it.

Choose the layer size dd (a square d×dd\times d layer) and the LoRA rank rr. Left: the frozen W0W_0 next to the trainable factors BB (d×rd\times r) and AA (r×dr\times d), drawn to scale (thin factors are widened to stay visible). Right: a random rank-rr update ΔW=BA\Delta W=BA on a small 24×24 grid, so you can see the "few patterns, combined" structure; at r=1r=1 every row is a multiple of one row.

The same idea, elsewhere

  • Compressing layers: replace a trained WW by its rank-kk SVD, i.e. two thin layers (chapter 7).
  • Embeddings: word2vec and GloVe can be read as implicitly factorising a matrix of word co-occurrence statistics; the word vectors are the rows of one factor.
  • Attention: the score matrix QK⊤=XWQWK⊤X⊤QK^\top=XW_QW_K^\top X^\top has rank at most the head dimension, because it's a product through a thin bottleneck.
  • Non-negative matrix factorization (U,V≥0U,V\ge0) gives parts-based, interpretable factors for topics and images.

Worked exampleA prediction and a parameter budget

Recommender: with factors (action, romance), a user with u=(2, 0.5)\mathbf u=(2,\ 0.5) and a movie with v=(1.5, 0.2)\mathbf v=(1.5,\ 0.2) get r^=2⋅1.5+0.5⋅0.2=3+0.1=3.1\hat r = 2\cdot1.5+0.5\cdot0.2 = 3+0.1=3.1. For a romance with v=(0.1, 2)\mathbf v=(0.1,\ 2): 0.2+1=1.20.2+1=1.2. Recommend the first.

LoRA: a model with 32 layers, each with four 4096×4096 attention matrices, has 32⋅4⋅16,777,216≈2.1532\cdot4\cdot16{,}777{,}216\approx2.15 billion weights in those matrices. LoRA with r=8r=8 on all of them trains 32⋅4⋅65,536=8,388,60832\cdot4\cdot65{,}536=8{,}388{,}608 numbers: 0.39%. With the Adam optimiser storing two extra numbers per trainable weight, the memory saving is even larger.

Watch outCommon misconceptions

  • "Missing ratings can be treated as zeros." Then the model learns that people dislike everything they haven't seen. Fit only the observed entries.
  • "LoRA makes the model itself low-rank." Only the update ΔW\Delta W is low-rank. W0+ΔWW_0+\Delta W is still full-rank.
  • "The factors are unique and interpretable." UV⊤=(UG)(VG−⊤)⊤UV^\top=(UG)(VG^{-\top})^\top for any invertible GG: you can rotate or rescale the latent space without changing a single prediction. "Action" and "romance" axes are a story we tell, not something the math guarantees.
  • "Larger kk or rr is always better." More factors fit the training data better but overfit the sparse observations; kk and λ\lambda are tuned on held-out data.

In ML & deep learningWhere this shows up

This whole chapter is the ML box. Matrix factorization won the Netflix Prize era of recommenders and still powers candidate retrieval in large systems (two-tower models compute user and item embeddings and rank by dot product). LoRA and its variants (QLoRA, which also quantises W0W_0 to 4 bits; DoRA) are the default way to fine-tune large language and image models on a single GPU. Low-rank structure is also exploited to compress gradients during training (GaLore) and to speed up attention (Linformer).

Practice (pick one answer per question)

A user's taste vector is (1, 2) and a movie's trait vector is (3, 1). What rating does the model predict?

  1. 5
  2. (3, 2)
  3. 7
  4. 4

1⋅3+2⋅1=51\cdot3+2\cdot1=5. The prediction is a dot product: a single number. (3, 2) is the element-wise product before summing.

How many trainable parameters does LoRA add to a 1024×1024 weight matrix with rank r=4r=4?

  1. 8,192
  2. 4,096
  3. 1,048,576
  4. 16,384

BB is 1024×4 and AA is 4×1024: 4⋅(1024+1024)=81924\cdot(1024+1024)=8192, versus 1,048,576 for the full matrix (0.78%).

BB is 1000×8 and AA is 8×1000. What is the largest possible rank of the 1000×1000 matrix BABA?

  1. 8
  2. 1000
  3. 16
  4. 992

Every column of BABA is a combination of the 8 columns of BB, so the column space has dimension at most 8.

Why not just take the SVD of the ratings matrix with missing entries set to 0?

  1. The zeros would be treated as real ratings, teaching the model that unseen movies are disliked
  2. The SVD only works on square matrices
  3. The SVD can't handle more than 2 factors
  4. Ratings matrices are always full rank

Missing isn't the same as zero. The SVD works for any shape and rank; the problem is that it fits every entry, including the made-up zeros. So we fit only observed entries (ALS or gradient descent).

LoRA initialises B=0B=0 (and AA randomly). What is the effect?

  1. ΔW=0\Delta W=0 at the start, so fine-tuning begins exactly at the pretrained model
  2. Training can't start, because the gradient with respect to AA is zero forever
  3. It forces ΔW\Delta W to stay rank 0
  4. It makes W0W_0 trainable

BA=0BA=0 initially, so the model's outputs are unchanged. The gradient with respect to BB is not zero (it involves AxA\mathbf x), so BB starts moving immediately, and then AA gets gradients too.

In alternating least squares, with every movie vector fixed, finding one user's vector ui\mathbf u_i is…

  1. a small (ridge) least-squares problem using the movies that user rated
  2. an eigenvalue problem for the whole ratings matrix
  3. impossible without the other users' vectors
  4. a full SVD of RR

The predictions ui⋅vj\mathbf u_i\cdot\mathbf v_j are linear in ui\mathbf u_i once the vj\mathbf v_j are fixed, so minimising squared error plus λ∣ui∣2\lambda|\mathbf u_i|^2 is ridge regression: (Vi⊤Vi+λI)ui=Vi⊤ri(V_i^\top V_i+\lambda I)\mathbf u_i=V_i^\top\mathbf r_i. Each user is independent of the others in this step.

You replace a 4096×4096 dense layer by a rank-256 factorization UU (4096×256) times V⊤V^\top (256×4096). What fraction of the original parameters remains?

  1. 1/8
  2. 1/16
  3. 1/4
  4. 1/256

2⋅4096⋅256=2,097,1522\cdot4096\cdot256 = 2{,}097{,}152 versus 40962=16,777,2164096^2=16{,}777{,}216: exactly 2⋅256/4096=1/82\cdot256/4096=1/8. (1/16 forgets that there are two factors.)

For a 4096×4096 matrix, LoRA with r=8r=8 trains what fraction of the parameters a full fine-tune would?

  1. about 0.39%
  2. about 0.2%
  3. about 3.9%
  4. about 25%

8⋅8192/40962=65,536/16,777,216=1/256≈0.39%8\cdot8192/4096^2 = 65{,}536/16{,}777{,}216 = 1/256 \approx 0.39\%. (0.2% counts only one of the two factors.)

Code it (optional: real Python runs in your browser and is graded by test cases)

Final tests

3 full-length tests covering the whole module, with single-concept and multi-concept questions and Python problems graded by test cases. You get a score, a chapter-by-chapter breakdown and the worked answer to every question. Your best score is saved in this browser.

One-page cheat sheet

The whole module, compressed. On paper, it prints on its own (figures hidden).

Orthogonality (ch 1)

v⊥w  ⟺  v⋅w=0\mathbf v\perp\mathbf w\iff\mathbf v\cdot\mathbf w=0; then ∣v+w∣2=∣v∣2+∣w∣2|\mathbf v+\mathbf w|^2=|\mathbf v|^2+|\mathbf w|^2.

Orthonormal basis: coordinates ci=qi⋅xc_i=\mathbf q_i\cdot\mathbf x, i.e. c=Q⊤x\mathbf c=Q^\top\mathbf x.

Orthogonal QQ: Q⊤Q=IQ^\top Q=I, Q−1=Q⊤Q^{-1}=Q^\top, keeps lengths and angles, det⁡Q=±1\det Q=\pm1.

Null space ⟂ row space; column space ⟂ null space of A⊤A^\top.

Projections & least squares (ch 2)

Onto a line: p=a⋅ba⋅aa\mathbf p=\frac{\mathbf a\cdot\mathbf b}{\mathbf a\cdot\mathbf a}\mathbf a, P=aa⊤a⊤aP=\frac{\mathbf a\mathbf a^\top}{\mathbf a^\top\mathbf a}.

Normal equations: A⊤Ax^=A⊤bA^\top A\hat{\mathbf x}=A^\top\mathbf b; P=A(A⊤A)−1A⊤P=A(A^\top A)^{-1}A^\top; with orthonormal QQ: P=QQ⊤P=QQ^\top.

P2=P=P⊤P^2=P=P^\top; residual e⊥\mathbf e\perp every column: A⊤e=0A^\top\mathbf e=\mathbf 0.

Gram–Schmidt & QR (ch 3)

vj=aj−∑i<j(qi⋅aj)qi\mathbf v_j=\mathbf a_j-\sum_{i<j}(\mathbf q_i\cdot\mathbf a_j)\mathbf q_i, qj=vj/∣vj∣\mathbf q_j=\mathbf v_j/|\mathbf v_j|.

A=QRA=QR: rij=qi⋅ajr_{ij}=\mathbf q_i\cdot\mathbf a_j, rjj=∣vj∣r_{jj}=|\mathbf v_j|, RR upper triangular.

Least squares: solve Rx^=Q⊤bR\hat{\mathbf x}=Q^\top\mathbf b (no A⊤AA^\top A).

Symmetric matrices (ch 4)

S=S⊤⇒S=S^\top\Rightarrow real λ\lambda's, orthonormal eigenvectors.

S=QΛQ⊤=∑λiqiqi⊤S=Q\Lambda Q^\top=\sum\lambda_i\mathbf q_i\mathbf q_i^\top; f(S)=Qf(Λ)Q⊤f(S)=Qf(\Lambda)Q^\top.

Unit circle → ellipse with axes ∣λi∣|\lambda_i| along qi\mathbf q_i. Use np.linalg.eigh (ascending).

Positive definite (ch 5)

q(x)=x⊤Sx=∑λici2q(\mathbf x)=\mathbf x^\top S\mathbf x=\sum\lambda_ic_i^2.

PD   ⟺  \iff all λ>0\lambda>0   ⟺  \iff leading minors >0>0   ⟺  \iff Cholesky S=LL⊤S=LL^\top   ⟺  \iff S=A⊤AS=A^\top A, independent columns.

2×2: a>0a>0 and ac−b2>0ac-b^2>0. Saddle = indefinite. ∇q=2Sx\nabla q=2S\mathbf x.

SVD (ch 6)

A=UΣV⊤A=U\Sigma V^\top: rotate, stretch by σ1≥σ2≥⋯≥0\sigma_1\ge\sigma_2\ge\dots\ge0, rotate.

Avi=σiuiA\mathbf v_i=\sigma_i\mathbf u_i; σi2\sigma_i^2 = eigenvalues of A⊤AA^\top A.

rank = # nonzero σ\sigma; ∥A∥2=σ1\|A\|_2=\sigma_1; ∣det⁡A∣=∏σi|\det A|=\prod\sigma_i. numpy returns U, s, Vh with Vh = V⊤V^\top.

Low rank (ch 7)

A=∑σiuivi⊤A=\sum\sigma_i\mathbf u_i\mathbf v_i^\top; AkA_k = first kk terms, stored in k(m+n+1)k(m+n+1) numbers.

Eckart–Young: ∥A−Ak∥2=σk+1\|A-A_k\|_2=\sigma_{k+1}, ∥A−Ak∥F=∑i>kσi2\|A-A_k\|_F=\sqrt{\sum_{i>k}\sigma_i^2}, and nothing of rank kk does better.

Energy kept =∑i≤kσi2/∑σi2=\sum_{i\le k}\sigma_i^2/\sum\sigma_i^2.

PCA (ch 8)

Centre: Xc=X−μX_c=X-\boldsymbol\mu. SVD Xc=UΣV⊤X_c=U\Sigma V^\top.

Directions = rows of V⊤V^\top; variances σi2/(n−1)\sigma_i^2/(n-1); scores XcV=UΣX_cV=U\Sigma; ratio σi2/∑σj2\sigma_i^2/\sum\sigma_j^2.

Standardise if units differ.

Pseudoinverse (ch 9)

A+=VΣ+U⊤=∑σi≠01σiviui⊤A^+=V\Sigma^+U^\top=\sum_{\sigma_i\ne0}\frac1{\sigma_i}\mathbf v_i\mathbf u_i^\top.

A+bA^+\mathbf b = least-squares solution of smallest norm. AA+AA^+ projects onto the column space, A+AA^+A onto the row space.

Tall: (A⊤A)−1A⊤(A^\top A)^{-1}A^\top. Wide: A⊤(AA⊤)−1A^\top(AA^\top)^{-1}. Invertible: A−1A^{-1}.

Norms & conditioning (ch 10)

∥x∥1=∑∣xi∣\|\mathbf x\|_1=\sum|x_i|, ∥x∥2=∑xi2\|\mathbf x\|_2=\sqrt{\sum x_i^2}, ∥x∥∞=max⁡∣xi∣\|\mathbf x\|_\infty=\max|x_i|.

κ=σmax⁡/σmin⁡\kappa=\sigma_{\max}/\sigma_{\min}; ∥δx∥∥x∥≤κ∥δb∥∥b∥\frac{\|\delta\mathbf x\|}{\|\mathbf x\|}\le\kappa\frac{\|\delta\mathbf b\|}{\|\mathbf b\|}; lose ≈log⁡10κ\approx\log_{10}\kappa digits.

κ(A⊤A)=κ(A)2\kappa(A^\top A)=\kappa(A)^2. Ridge: (σ12+λ)/(σn2+λ)(\sigma_1^2+\lambda)/(\sigma_n^2+\lambda).

Tensors (ch 11)

Broadcasting: align shapes from the right; sizes equal or one is 1; result takes the max.

(n,) vs (n,1) → (n,n): silent bug. Use keepdims=True.

einsum: letters missing from the output are summed. 'ij,jk->ik' matmul, 'ii->' trace, 'bhqd,bhkd->bhqk' attention.

Factorizations in ML (ch 12)

M≈UV⊤M\approx UV^\top, r^ij=ui⋅vj\hat r_{ij}=\mathbf u_i\cdot\mathbf v_j; fit observed entries only (ALS = alternating ridge regressions).

LoRA: W=W0+αrBAW=W_0+\frac\alpha rBA, params r(d+k)r(d+k) vs dkdk; B=0B=0 at start; merge after training.

Glossary

Alternating least squares (ALS)
Fitting a factorization UV⊤UV^\top by freezing one factor, solving a least-squares problem for the other, and alternating. (Ch 12)
Broadcasting
Combining arrays of different shapes by aligning them from the right and stretching size-1 axes. (Ch 11)
Cholesky factorization
S=LL⊤S=LL^\top with LL lower triangular; exists exactly when SS is positive definite. (Ch 5)
Condition number κ\kappa
σmax⁡/σmin⁡\sigma_{\max}/\sigma_{\min}: the worst-case factor by which solving Ax=bA\mathbf x=\mathbf b magnifies relative errors. (Ch 10)
Covariance matrix
C=Xc⊤Xc/(n−1)C=X_c^\top X_c/(n-1) for centred data; symmetric and positive semidefinite. (Ch 8)
Eckart–Young theorem
The truncated SVD AkA_k is the closest rank-kk matrix to AA in the spectral and Frobenius norms. (Ch 7)
einsum
Einstein-summation notation for tensor operations: name each axis with a letter; letters absent from the output are summed. (Ch 11)
Explained variance ratio
The fraction of total variance captured by a principal component: σi2/∑jσj2\sigma_i^2/\sum_j\sigma_j^2. (Ch 8)
Frobenius norm
∥A∥F=∑aij2=∑σi2\|A\|_F=\sqrt{\sum a_{ij}^2}=\sqrt{\sum\sigma_i^2}. (Ch 7, 10)
Gram–Schmidt
Turning independent vectors into an orthonormal basis of the same span by subtracting projections and normalising. (Ch 3)
Least squares
Choosing x^\hat{\mathbf x} to minimise ∣Ax−b∣2|A\mathbf x-\mathbf b|^2; solved by the normal equations, QR or the SVD. (Ch 2)
LoRA
Low-Rank Adaptation: fine-tuning a frozen weight W0W_0 by learning a low-rank update BABA. (Ch 12)
Low-rank approximation
Replacing a matrix by one of small rank, usually the truncated SVD. (Ch 7)
Matrix factorization
Writing a matrix as a product of simpler or thinner matrices, e.g. QRQR, UΣV⊤U\Sigma V^\top, UV⊤UV^\top. (Ch 3, 6, 12)
Normal equations
A⊤Ax^=A⊤bA^\top A\hat{\mathbf x}=A^\top\mathbf b: the condition that the residual is perpendicular to every column of AA. (Ch 2)
Orthogonal complement
All vectors perpendicular to a subspace; e.g. the null space is the orthogonal complement of the row space. (Ch 1)
Orthogonal matrix
A square matrix with orthonormal columns: Q⊤Q=IQ^\top Q=I, so Q−1=Q⊤Q^{-1}=Q^\top. A rotation, reflection or both. (Ch 1)
Orthonormal
Unit length and mutually perpendicular. (Ch 1)
Outer product
uv⊤\mathbf u\mathbf v^\top: a rank-one matrix whose rows are all multiples of v⊤\mathbf v^\top. (Ch 7)
PCA (principal component analysis)
Finding orthonormal directions of maximum variance in centred data; computed from the SVD of the data matrix. (Ch 8)
Positive definite / semidefinite
A symmetric SS with x⊤Sx>0\mathbf x^\top S\mathbf x>0 (resp. ≥0\ge0) for all x≠0\mathbf x\neq\mathbf 0; equivalently all eigenvalues >0>0 (resp. ≥0\ge0). (Ch 5)
Projection matrix
PP with P2=P=P⊤P^2=P=P^\top; maps every vector to its closest point in a subspace. (Ch 2)
Pseudoinverse A+A^+
VΣ+U⊤V\Sigma^+U^\top; A+bA^+\mathbf b is the minimum-norm least-squares solution. (Ch 9)
QR decomposition
A=QRA=QR with orthonormal columns in QQ and upper-triangular RR. (Ch 3)
Quadratic form
x⊤Sx\mathbf x^\top S\mathbf x, a function made only of degree-2 terms. (Ch 5)
Rayleigh quotient
x⊤Sx/x⊤x\mathbf x^\top S\mathbf x/\mathbf x^\top\mathbf x; its maximum and minimum are the largest and smallest eigenvalues. (Ch 4)
Ridge regression
Least squares with a penalty λ∣w∣2\lambda|\mathbf w|^2: (A⊤A+λI)w=A⊤b(A^\top A+\lambda I)\mathbf w=A^\top\mathbf b; improves conditioning. (Ch 10, 12)
Singular values / vectors
σi≥0\sigma_i\ge0, ui\mathbf u_i, vi\mathbf v_i with Avi=σiuiA\mathbf v_i=\sigma_i\mathbf u_i: the stretches and the input/output directions of the SVD. (Ch 6)
Spectral norm
∥A∥2=σ1\|A\|_2=\sigma_1, the largest factor by which AA stretches a vector. (Ch 6, 10)
Spectral theorem
Every real symmetric matrix is QΛQ⊤Q\Lambda Q^\top with orthogonal QQ and real diagonal Λ\Lambda. (Ch 4)
SVD
Singular value decomposition A=UΣV⊤A=U\Sigma V^\top: every matrix is rotate, stretch, rotate. (Ch 6)
Symmetric matrix
S=S⊤S=S^\top. (Ch 4)
Tensor
In ML, an array with any number of axes, such as (batch, tokens, features). (Ch 11)
Whitening
Transforming data so its features are uncorrelated with unit variance, using the eigen-decomposition of the covariance. (Ch 8, final tests)

Where to go next