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?
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?
- One
- None
- Infinitely many
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.
What is \(\det \begin{pmatrix} 1 & 2 \\ 3 & 1 \end{pmatrix}\), the coffee matrix? (So: does every pair of prices have exactly one answer?)
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?
- 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.
- 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.
- 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.
- 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}\)?
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?
- The predictions get worse
- The model gets more accurate, thanks to the extra column
- Infinitely many weight pairs give the same predictions, so the weights mean nothing on their own
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?
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?
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}\)?
A matrix stretches areas by 4. By how much does its inverse stretch them?
\(\det A = 2\) and \(\det B = 3\). What is \(\det(AB)\)?
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?
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?
- 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.
- 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).
- Perpendicular to the plane means perpendicular to each column: column · error = 0 for both. Stacked up, that's \(X^\top (y - Xw) = 0\).
- 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
- Twin columns. If one feature is a mix of others, \(X^\top X\) is singular and the normal equations have no single answer (section 3). Nearly twin columns are worse in a quiet way: \(X^\top X\) squares how ill-conditioned \(X\) is (linear algebra 3), so libraries'
lstsqworks from \(X\) itself instead. - One wild point. Squaring makes a 10-minute error count 100 times as much as a 1-minute one, so a single mistyped ride can tilt the whole line toward it. Chapter 12 and probability 2 meet losses and summaries that care less about outliers.
- A straight line where the truth bends. The best line is still a line. Least squares answers "which line?", never "is a line right?"; a plot of the errors answers that.
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
- A system \(Ax = b\) has rows (equations as lines or planes that must all meet) and columns (arrows to mix so they land on \(b\)).
- \(\det A \neq 0\): one answer for every \(b\). \(\det A = 0\) (singular): none or infinitely many.
- Rank counts the independent rows, which always equals the independent columns. Duplicate features cost a dataset rank.
- Elimination clears columns below each pivot, then solves bottom up; about \(n^3/3\) work.
- The inverse undoes a move and exists only when \(\det A \neq 0\); a tiny determinant means a fragile, ill-conditioned problem. \(\det(AB) = \det A \det B\), \(\det A^{-1} = 1/\det A\).
- Least squares is a square system, \(X^\top X w = X^\top y\): linear regression solved exactly.
All lessons: AI from scratch.
Last updated