AI from scratch · Linear algebra 1 · Stage 1: the math of learning

Systems of equations, rank and inverses

Chapter 1 showed a matrix as a move of the plane. This lesson asks the reverse question: given where something landed, where did it start? That's solving a system of equations, and it decides whether a model has one best answer, none, or infinitely many. You'll drag equations as lines, run elimination step by step, meet the inverse matrix (and why a nearly flat one is dangerous), and end by fitting linear regression exactly, with no training loop at all.

1. Two equations are two lines

A coffee and two bagels cost $7. Three coffees and a bagel cost $11. What does each cost? Call a coffee \(x\) and a bagel \(y\):

\[ \begin{aligned} x + 2y &= 7 \\ 3x + y &= 11 \end{aligned} \]

Each equation on its own allows many answers: every point on a line. The blue line is every \((x, y)\) with \(x + 2y = 7\), the yellow line every one with \(3x + y = 11\). The answer has to be on both, so it's where they cross. Drag the dots to tilt and move each line.

Read it off the picture (or solve it): what does a coffee cost?

The lines cross at \((3, 2)\): coffee $3, bagel $2. Check: \(3 + 2 \times 2 = 7\) and \(3 \times 3 + 2 = 11\).

Two lines can do only three things: cross once (one answer), run side by side (no answer), or lie on top of each other (infinitely many). Press Parallel and Same line twice to see the other two.

A shop says: "a coffee and a bagel are $5" and "two coffees and two bagels are $12". How many answers?

Halve the second: \(x + y = 6\). The first says \(x + y = 5\). Same tilt, different place: parallel lines, a contradiction. With $10 instead of $12 it would be the same line twice: true, but no new information.

2. Two pictures of \(Ax = b\)

Stack the numbers into a matrix and the system becomes one line, \(Ax = b\):

\[ \underbrace{\begin{pmatrix} 1 & 2 \\ 3 & 1 \end{pmatrix}}_{A} \underbrace{\begin{pmatrix} x \\ y \end{pmatrix}}_{x} = \underbrace{\begin{pmatrix} 7 \\ 11 \end{pmatrix}}_{b} \]

Read by rows, it's the two lines above. Read by columns, it's chapter 1's picture: "\(x\) of the first column plus \(y\) of the second must land on \(b\)". Which mix of the arrows (1, 3) and (2, 1) reaches the yellow target (7, 11)? Turn the knobs:

The column picture explains when there's an answer. If the two columns point in different directions, mixing them reaches every point of the plane, so every \(b\) has exactly one recipe. If they lie on one line, mixes of them stay on that line: a \(b\) off it is unreachable, and a \(b\) on it has endless recipes. And "columns on one line" is exactly chapter 1's determinant zero: the matrix squashes the plane flat.

\(Ax = b\) asks which mix of \(A\)'s columns lands on \(b\). Columns pointing in different directions reach everywhere, each spot by exactly one mix; columns on one line reach only that line.

The pictureRows: lines that must all pass through the answer. Columns: arrows you mix to land on the target.
The math\(\det A = a d - b c \neq 0\): exactly one solution, for every \(b\). \(\det A = 0\): none or infinitely many, depending on \(b\). The matrix is then called singular.

What is \(\det \begin{pmatrix} 1 & 2 \\ 3 & 1 \end{pmatrix}\), the coffee matrix? (So: does every pair of prices have exactly one answer?)

\(1 \times 1 - 2 \times 3 = -5\). Not zero, so whatever the two totals are, there's exactly one pair of prices that explains them. (The minus sign just says the move flips the plane over.)

3. Dependence and rank: how many equations really count

Real datasets repeat themselves: the same quantity in two units, a total next to its parts. A repeated column is a repeated equation, and this section counts how many of your equations (or features) really count. Add a third sentence: "four coffees and three bagels cost $18". Is that new information? No: it's the first two receipts added together, \((x + 2y) + (3x + y) = 7 + 11\). An equation that's a mix of others is linearly dependent on them: it can be true (and then it adds nothing) or contradict them (and then there's no answer), but it can never pin down anything new.

The rank of a matrix counts the equations that really count: the most rows you can pick with none being a mix of the others. Remarkably, it's always the same as the most independent columns. In the column picture, rank is the dimension of everywhere \(Ax\) can reach: a point (rank 0), a line (rank 1), the plane (rank 2), and so on.

Why do independent rows and independent columns always come out equal?
  1. Elimination's moves (subtract a multiple of one row from another, swap rows) can all be undone, so they never change which mixes of rows are possible: the number of independent rows stays the same.
  2. They don't change which mixes of columns give zero either: if \(Ax = 0\), the same \(x\) still solves the eliminated system, and back. So the number of independent columns stays the same too.
  3. At the end, the matrix is a staircase. The rows with a pivot are independent (each starts where the ones above have nothing), and so are the pivot columns, for the same reason. Every other row is all zeros, and every other column is a mix of the pivot columns.
  4. One pivot per pivot row and one per pivot column: both counts are the number of pivots.

What is the rank of \(\begin{pmatrix} 1 & 2 & 3 \\ 2 & 4 & 6 \\ 1 & 0 & 1 \end{pmatrix}\)?

Row 2 is twice row 1, so it adds nothing. Rows 1 and 3 point in different directions, so they're independent. Rank 2: three equations, but only two of them count, and with three unknowns that leaves a whole line of answers (or none).

Why an ML engineer cares: a dataset is a matrix, one row per example, one column per feature. If one column is a mix of others (price in dollars and price in cents, or "rooms" alongside "bedrooms + other rooms"), the matrix loses rank and a linear model's knobs stop having one best value: you can shift weight between the twin columns forever without changing a single prediction. And when stage 6 fine-tunes a big model with LoRA, it's betting the change it needs is low rank: a huge matrix of updates built from a few independent columns.

A house-price dataset has columns "area in m²" and "area in ft²" (always 10.76 times the first). What happens to a linear model's weights?

Any weight on ft² can be traded for 10.76 times it on m². The fix is to drop one twin, or to add a penalty on big weights (regularization, chapter 11), which picks one sensible answer out of the infinitely many.

4. Elimination, step by step

With three unknowns, each equation is a plane in 3D and drawing stops helping. What a computer does instead is Gaussian elimination: use the first equation to remove \(x\) from all the others, then the new second to remove \(y\) from the ones below, and so on, until the last row has one unknown. Then solve from the bottom up. The only moves allowed are ones that keep the answers the same: subtract a multiple of one row from another, or swap two rows.

On "one answer", the first step is "row 2 minus 2 × row 1". Before pressing it: what will row 2's \(y\) number become?

Row 2 has \(y\)-number 1, row 1 has 1, so \(1 - 2 \times 1 = -1\). (Its \(x\)-number becomes \(2 - 2 \times 1 = 0\): that's the point of the step.)

Run "a contradiction" to the end. Its last row becomes \(0x + 0y + 0z = 1\). What does that row tell you, and how is it different from the repeated equation's last row?

"0 = 1" can never be true, so there's no answer at all: the third equation contradicts the other two. The repeated system ends with "0 = 0", always true, so it just drops out, leaving two equations for three unknowns and a whole line of answers. Either way the rank is 2: elimination counts the rank as the rows left with a pivot (a first nonzero number).

Here's elimination as code, written the way libraries do it: before each step it swaps up the row with the biggest number in the current column (partial pivoting), because dividing by a tiny pivot magnifies rounding errors.

Elimination on \(n\) unknowns takes about \(n^3/3\) multiplications: a thousand unknowns is a third of a billion, a fraction of a second. That cube is why, for millions of unknowns (a neural network's weights), nobody solves equations: gradient descent takes cheap steps instead.

5. The identity and the inverse

The identity matrix \(I\) has 1s down the diagonal and 0s elsewhere: it's the move that doesn't move anything, \(Iv = v\). The inverse \(A^{-1}\) is the move that undoes \(A\): \(A^{-1} A = A A^{-1} = I\). If you had it, solving would be one multiplication: \(x = A^{-1} b\).

Drag the columns of \(A\) (green and red, as in chapter 1). The dashed arrows are the columns of \(A^{-1}\), the move that puts the grid back. Then press Nearly flat.

The math, step by step

For a 2×2 matrix there's a formula: swap the diagonal, negate the other two, divide by the determinant:

\[ \begin{pmatrix} a & b \\ c & d \end{pmatrix}^{-1} = \frac{1}{ad - bc} \begin{pmatrix} d & -b \\ -c & a \end{pmatrix} \]

Check it on \(A = \begin{pmatrix} 2 & 1 \\ 1 & 1 \end{pmatrix}\): \(\det A = 2 - 1 = 1\), so \(A^{-1} = \begin{pmatrix} 1 & -1 \\ -1 & 2 \end{pmatrix}\), and multiplying, row 1 times column 1 is \(1 \cdot 2 + (-1) \cdot 1 = 1\), row 1 times column 2 is \(1 \cdot 1 + (-1) \cdot 1 = 0\): the identity, as promised.

Dividing by the determinant is the whole story. When \(\det A = 0\), the plane was squashed flat, many points landed on the same spot, and no move can tell them apart again: no inverse. When \(\det A\) is tiny, the inverse exists but is huge, so a tiny change in \(b\) (a rounding error, a noisy measurement) makes a huge change in \(x\). That's an ill-conditioned system, the same stretched valley that will make gradient descent zigzag in Calculus 3.

Determinants multiply, because areas do: doing \(B\) then \(A\) scales area by \(\det B\), then by \(\det A\), so \(\det(AB) = \det A \cdot \det B\). Undoing must scale it back, so \(\det(A^{-1}) = 1 / \det A\).

For \(A = \begin{pmatrix} 2 & 1 \\ 1 & 1 \end{pmatrix}\), what's the bottom-right number of \(A^{-1}\)?

Swap the diagonal (2 and 1 trade places), negate the off-diagonal, divide by \(\det A = 1\): \(\begin{pmatrix} 1 & -1 \\ -1 & 2 \end{pmatrix}\). Bottom-right is 2. Drag the picture back to Reset and the readout agrees.

A matrix stretches areas by 4. By how much does its inverse stretch them?

\(\det(A^{-1}) = 1/4 = 0.25\): undoing a ×4 must shrink everything back by 4.

\(\det A = 2\) and \(\det B = 3\). What is \(\det(AB)\)?

\(2 \times 3 = 6\): the area triples, then doubles.

The inverse undoes a move, and exists only if nothing was squashed. Dividing by the determinant is the price of undoing: a nearly flat matrix makes small errors huge.

A practical rule: in code, almost never compute an inverse just to solve \(Ax = b\). Elimination is faster and loses less to rounding. In NumPy that's np.linalg.solve(A, b), not np.linalg.inv(A) @ b.

6. Linear regression with no training loop

Start 2's six taxi rides give six equations for two knobs, \(a \cdot \text{km} + b = \text{minutes}\), one per ride. Six lines through a two-knob plane don't meet in one point: there's no exact answer. Least squares asks for the next best thing, the \((a, b)\) with the smallest squared error. That best line is the one whose leftover errors are perpendicular to the table's columns (chapter 1's dot product of zero; the box below shows why). Writing that down needs one new piece of notation. The transpose \(X^\top\) ("X transpose") is the same table flipped over its diagonal, so its rows are \(X\)'s columns: a 6×2 table of rides becomes a 2×6 one. That's all it does, but it's useful: \(X^\top v\) takes the dot product of every column of \(X\) with \(v\), one number per column, which is exactly how you ask "is this error perpendicular to every column?". In NumPy it's X.T. The best line works out to

\[ X^\top X \, w = X^\top y \]

with \(X\) the rides' table (a column of km and a column of 1s), \(y\) the minutes, \(w = (a, b)\). These are the normal equations: always a square system, 2 equations for 2 knobs here, which our solve handles in one go.

Run it: what slope \(a\) does least squares find?

\(a = 1007/377 \approx 2.671\) minutes per km, \(b \approx 5.923\). Start 2 found a mean squared error of 0.958 with \(a = 2.5\); the exact answer gets about 0.089, and no line does better. Gradient descent walks to this same point; the normal equations jump straight there.

Least squares finds the reachable point \(Xw\) closest to \(y\), and closest means the leftover error is perpendicular to everything reachable.

Why do the normal equations give the best fit?
  1. Whatever the knobs, \(Xw\) is a mix of \(X\)'s columns. With 2 columns and 6 rides, the reachable predictions form a flat plane inside 6-dimensional space, and \(y\) usually sits off it.
  2. The closest point of a plane to an outside point is straight below it: the error \(y - Xw\) is perpendicular to the plane (a plumb line hangs straight down to the floor: the shortest way down is the perpendicular one).
  3. Perpendicular to the plane means perpendicular to each column: column · error = 0 for both. Stacked up, that's \(X^\top (y - Xw) = 0\).
  4. Multiply out: \(X^\top X\, w = X^\top y\). Calculus 2 reaches the same equations a second way, by setting the gradient to zero.
Where it breaks: when least squares misleads

So why does ML bother with gradient descent? Because this only works when the error is a bowl (a linear model with squared error), and only while \(X^\top X\) is small enough to eliminate: with \(n\) features it's \(n \times n\), and the cost grows like \(n^3\). A network bends its inputs (chapter 1's ReLU), its error isn't a simple bowl, and it has millions of knobs. Gradient descent works for all of it.

7. What to carry forward

All lessons: AI from scratch.

Last updated