AI from scratch · Chapter 1

Matrices are moves

Every neural network, from a digit recognizer to the model behind a chatbot, is mostly one operation repeated billions of times: multiply by a matrix. So before any "AI", let's get a feel for what a matrix does. Not as a grid of numbers, but as a way of moving space. Drag everything.

1. A vector is an arrow

A vector is a pair of numbers, (x, y), but it's easier to think of it as an arrow from the origin: go x steps right, y steps up. Drag the tip of the blue arrow.

In machine learning, everything becomes a vector: a pixel image is a long list of brightness values, a word becomes a list of a few hundred numbers. Same idea, just with more than two directions to walk in.

The pictureAn arrow: how far right, how far up. Its length is how far the tip is from the start.
The mathA list of numbers \(v = (v_1, v_2, \dots, v_n)\). Its length comes from Pythagoras (in a right triangle, the long side squared equals the other two sides squared, added): \(\lVert v \rVert = \sqrt{v_1^2 + v_2^2 + \dots + v_n^2}\).

Drag the arrow to (3, 4). How long is it? (Predict first, then check the readout under the picture.)

\(\sqrt{3^2 + 4^2} = \sqrt{9 + 16} = \sqrt{25} = 5\). The arrow is the long side of a right triangle with sides 3 and 4.

2. Adding is walking one arrow, then the other

To add two vectors, walk along the first, then from its tip along the second. Where you end up is the sum. Drag both tips.

Notice you can go around the parallelogram either way and land in the same spot: a + b = b + a.

The pictureWalk \(a\), then walk \(b\). Stretching an arrow by 2 doubles each step.
The mathAdd and scale coordinate by coordinate: \(a + b = (a_1 + b_1,\ a_2 + b_2)\), \(\ c\,a = (c\,a_1,\ c\,a_2)\).

One more operation, the most important one in this whole course: the dot product. Multiply matching coordinates and add them up: \(a \cdot b = a_1 b_1 + a_2 b_2\). It's one number, and it measures how much two arrows point the same way: big and positive when they agree, zero when they're at right angles, negative when they oppose. The readout above shows it live; drag \(b\) around \(a\) and watch the sign flip as it crosses the right angle.

To say exactly how much, there's one more name to learn. Put an arrow of length 1 at an angle \(\theta\) (theta) from another arrow, and drop its shadow straight onto that arrow's line. The shadow's length is the cosine of the angle, \(\cos\theta\): 1 when the two point the same way, 0 at a right angle, −1 when they point opposite ways, and in between for everything else. (How high the tip sits above the line is the sine, \(\sin\theta\); turn the arrow round and round and both trace out waves. They come back in calculus.) With that, the dot product is the two lengths multiplied, times how much they agree:

\[ a \cdot b = a_1 b_1 + a_2 b_2 = \lVert a \rVert\,\lVert b \rVert \cos\theta \]

Remember this one. A neuron (chapter 3) is a dot product of inputs and weights. Attention (chapter 7) is dot products between words. A matrix, next section, is a stack of dot products.

The dot product is one number for how much two arrows agree: their lengths multiplied, times the cosine of the angle between them.

Why does \(a_1 b_1 + a_2 b_2\) know the angle?
  1. Draw \(a\), \(b\) and the arrow between their tips, \(a - b\): a triangle.
  2. The law of cosines (school geometry, Pythagoras with a correction for a non-right angle): \(\lVert a - b \rVert^2 = \lVert a \rVert^2 + \lVert b \rVert^2 - 2 \lVert a \rVert \lVert b \rVert \cos\theta\).
  3. Now the same length by coordinates: \((a_1 - b_1)^2 + (a_2 - b_2)^2 = a_1^2 + a_2^2 + b_1^2 + b_2^2 - 2(a_1 b_1 + a_2 b_2)\).
  4. The squares on both sides are \(\lVert a \rVert^2 + \lVert b \rVert^2\), so what's left must match: \(a_1 b_1 + a_2 b_2 = \lVert a \rVert \lVert b \rVert \cos\theta\).

Nothing in the argument needed two dimensions, which is why the same multiply-and-add measures angles between 768-number word vectors.

Where it breaks: big isn't the same as aligned

\(a = (1, 2)\) and \(b = (3, -1)\). What is \(a \cdot b\)?

\(1 \cdot 3 + 2 \cdot (-1) = 3 - 2 = 1\). Small and positive: the arrows are nearly at right angles, leaning slightly the same way.

Two arrows have a dot product of exactly 0. What do you know about them?

\(\cos 90^\circ = 0\), so \(\lVert a \rVert \lVert b \rVert \cos\theta = 0\). Perpendicular arrows share nothing: walking along one makes no progress along the other.

3. A matrix moves the whole plane

Here's the big idea. Two special arrows, î = (1, 0) and ĵ = (0, 1), are the plane's "steps". Any vector is "x of the first step plus y of the second". Now drag the tips of î and ĵ. The grid follows, and so does every vector on it, because v is still x of the new î plus y of the new ĵ.

Predict before you drag: the Rotate 90° button sends î to (0, 1) and ĵ to (−1, 0). Where does v = (2, 1) land?

\(v\) is "2 of î plus 1 of ĵ", and that recipe survives the move: \(2\cdot(0, 1) + 1\cdot(-1, 0) = (-1, 2)\). Press the button and check.

That's all a 2×2 matrix is: the columns say where î and ĵ land. Multiplying a vector by the matrix means "find where it lands". The shaded square started with area 1; its new area is the determinant. It goes negative when space gets flipped over, and zero when the plane is squashed onto a line. Then information is lost: many vectors land on the same spot, and you can't undo the move.

A matrix is a move of the whole plane. Its columns are where the two steps land, and every other arrow follows, because every arrow is made of those steps.

Where else this move shows up: a software radio works with arrows all day, and turning one arrow by another is exactly this, the matrix whose columns are (c, d) and (−d, c), a turn plus a stretch with no shear or flip. Radio from scratch, chapter 2 builds a receiver on it.

Why do two columns decide where everything goes?
  1. Any arrow is a recipe: \(v = x\,\hat\imath + y\,\hat\jmath\).
  2. The moves a matrix makes keep grid lines straight, parallel and evenly spaced, and keep the origin in place. In symbols: moving a sum is the sum of the moved parts, and moving a stretched arrow stretches the moved arrow. That's what linear means.
  3. So the recipe survives the move: \(M v = x\,(M\hat\imath) + y\,(M\hat\jmath)\). Know the two landing spots, and you know where every arrow lands.
Where it breaks: moves a matrix can't make
The math, step by step

Write where î and ĵ land as the two columns of a matrix. Then "where does \(v = (x, y)\) land?" is

\[ \begin{pmatrix} a & b \\ c & d \end{pmatrix} \begin{pmatrix} x \\ y \end{pmatrix} = x \begin{pmatrix} a \\ c \end{pmatrix} + y \begin{pmatrix} b \\ d \end{pmatrix} = \begin{pmatrix} a x + b y \\ c x + d y \end{pmatrix} \]

Two ways to read the same arithmetic. By columns (high level): \(x\) steps of the new î plus \(y\) steps of the new ĵ. By rows (how a computer does it): each output number is a dot product of one row with \(v\): \(ax + by\) is \((a, b) \cdot (x, y)\). A matrix is a stack of dot products.

The determinant is the area of the square after the move, with a sign for flips: \(\det = ad - bc\). For the shear \(\begin{pmatrix} 1 & 1 \\ 0 & 1 \end{pmatrix}\): \(1\cdot 1 - 1 \cdot 0 = 1\), the square slants but keeps its area. For "squash flat" \(\begin{pmatrix} 1 & 2 \\ 0.5 & 1 \end{pmatrix}\): \(1 \cdot 1 - 2 \cdot 0.5 = 0\), the columns point the same way and the plane collapses onto a line.

Doing one move after another is matrix multiplication: \(B(Av) = (BA)v\), where each column of \(BA\) is \(B\) applied to a column of \(A\). Order matters: rotate-then-shear is a different move from shear-then-rotate.

What is the determinant of \(\begin{pmatrix} 2 & 1 \\ 1 & 0.5 \end{pmatrix}\)?

\(2 \cdot 0.5 - 1 \cdot 1 = 0\). The second column (1, 0.5) is half the first (2, 1), so both basis arrows land on the same line: the plane is squashed flat and the move can't be undone.

4. A neural network layer: a move, then a bend

If you stack matrices you only get another matrix: still straight lines, still a single move. Networks get their power from one tiny extra step after each matrix: a bend. The most common one, ReLU, just says "negative numbers become zero". Watch what it does to the moved grid: everything left of the vertical axis gets folded onto it, everything below the horizontal axis onto that.

Drag î and ĵ again: the layer is "move, then fold". Stack dozens of these, each with its own matrix, and the folds can carve space into almost any shape, like one region for "cat" and another for "dog". Training a network is searching for the matrices that put the folds in the right places. That's where we're headed: next chapter, gradients, how a network finds which way to nudge every number.

The math, step by step

A real layer also adds a bias vector \(b\) (it shifts the plane before the fold, which the picture above leaves out), and its matrix needn't be square. A layer from \(n\) numbers to \(m\) numbers is

\[ h = \operatorname{ReLU}(W x + b), \qquad W \in \mathbb{R}^{m \times n},\ b \in \mathbb{R}^{m},\ \operatorname{ReLU}(z) = \max(0, z) \text{ for each number} \]

Read the middle part as "\(W\) is a table of \(m\) rows and \(n\) columns of ordinary numbers, and \(b\) a list of \(m\) of them": \(\mathbb{R}\) stands for the real numbers, any point on the number line, and \(\in\) is "is in" from the math warm-up. It has \(m \cdot n + m\) adjustable numbers, the parameters. A digit reader that takes 784 pixels to 128 hidden numbers to 10 scores has \(784 \cdot 128 + 128 + 128 \cdot 10 + 10 = 101{,}770\) of them.

Why the bend is essential: without it, two layers collapse into one. \(W_2 (W_1 x) = (W_2 W_1) x\), a single matrix, however many you stack. With ReLU in between, that algebra no longer works, and each layer can fold space somewhere new.

A layer is a move, then a fold. Without the fold, any stack of layers is still a single move.

You stack 50 layers, each just a matrix with no bend in between. What can the stack do that one layer can't?

\(W_{50} \cdots W_2 W_1 = W\), one matrix. That's why every layer in a real network ends with a bend like ReLU.

How many parameters does one layer from 784 inputs to 128 outputs have (weights and biases)?

\(784 \times 128\) weights, one per input-output pair, plus 128 biases: \(100{,}352 + 128 = 100{,}480\).

Inspired by 3Blue1Brown's Essence of Linear Algebra, which goes much deeper. All lessons: AI from scratch.

Last updated