AI from scratch · Stage 2: how a network learns

Deep networks, layer by layer

Chapter 3 built one neuron and chapter 4 pushed blame backward through two. Real networks have many layers of many neurons, and they train on a whole batch of examples at once. This lesson writes that down properly: the notation every paper uses, the matrix shapes (most deep learning bugs are shape bugs), backprop for any depth, and two things that decide whether training works at all, how you start the weights and how deep you go. Then you train one on a spiral, live.

1. The notation: layer \(l\), unit \(i\), example \(m\)

Number the layers 0 (the input) to \(L\) (the output). Layer \(l\) has \(n_l\) units. Each layer does what chapter 1 called "move, then bend": a matrix and a bias, then an activation \(g\):

\[ z^{[l]} = W^{[l]} a^{[l-1]} + b^{[l]}, \qquad a^{[l]} = g(z^{[l]}), \qquad a^{[0]} = x \]

Square brackets count layers. \(W^{[l]}\) has one row per unit in layer \(l\) and one column per unit feeding it, so its shape is \((n_l, n_{l-1})\); \(b^{[l]}\) has shape \((n_l, 1)\). Type a network's layer sizes to see every shape and the number of knobs:

A deep network is "move, then bend" repeated. Each layer's shapes follow from two numbers: how many units it has, and how many feed it.

How many parameters (weights plus biases) does a 2, 16, 16, 1 network have? Work it out, then check the table.

Layer 1: \(16 \times 2 + 16 = 48\). Layer 2: \(16 \times 16 + 16 = 272\). Layer 3: \(1 \times 16 + 1 = 17\). Total 337. The middle square layer dominates: parameter counts grow with width squared.

2. A whole batch is one matrix

Running examples one at a time in a loop wastes the hardware. Instead, stack \(m\) examples as the columns of a matrix \(X\) with shape \((n_0, m)\). Then one matrix product computes the layer for all of them at once:

\[ Z^{[l]} = W^{[l]} A^{[l-1]} + b^{[l]}, \qquad (n_l, m) = (n_l, n_{l-1}) \cdot (n_{l-1}, m) + (n_l, 1) \]

Adding a \((n_l, 1)\) bias to a \((n_l, m)\) matrix isn't strictly allowed, so every library broadcasts it: copies the column across all \(m\) examples. Capital letters for batches, small for one example. This is vectorization, and it's why GPUs (stage 4) matter: one big matrix product runs thousands of times faster than the same arithmetic in a loop.

A batch is one matrix, one column per example, so a single matrix product runs a layer for every example at once.

A batch of 500 examples enters a 2, 16, 16, 1 network. What's the shape of \(Z^{[1]}\)?

\((16, 2) \cdot (2, 500) = (16, 500)\): one row per unit, one column per example. Writing the shapes under every line of a formula is the fastest bug-finder in deep learning. (PyTorch puts examples in rows, \((m, n)\), and writes \(XW^\top\); same idea, transposed.)

3. Backprop for any depth

Chapter 4's relay of blame, written once for every layer and every example at once. With a sigmoid output and cross-entropy loss (chapter 5), the blame at the output is just "prediction minus truth". Then each layer hands blame back through its weights and its activation's slope:

stepformulashape
output blame\(dZ^{[L]} = A^{[L]} - Y\)\((n_L, m)\)
weight gradient\(dW^{[l]} = \frac{1}{m}\, dZ^{[l]} A^{[l-1]\top}\)\((n_l, n_{l-1})\), same as \(W^{[l]}\)
bias gradient\(db^{[l]} = \frac{1}{m} \sum_{\text{columns}} dZ^{[l]}\)\((n_l, 1)\), same as \(b^{[l]}\)
blame to the layer below\(dA^{[l-1]} = W^{[l]\top} dZ^{[l]}\)\((n_{l-1}, m)\)
through the bend\(dZ^{[l-1]} = dA^{[l-1]} \odot g'(Z^{[l-1]})\)\((n_{l-1}, m)\)

\(\odot\) is element-by-element multiplication. The shapes check themselves: every gradient has exactly the shape of the thing it updates, and \(W^\top\) is the only way to get from \(n_l\) rows back to \(n_{l-1}\). The bias gradient sums over the examples because one bias serves them all (Calculus 2: a value used many times collects blame from every use). These are the same vector-Jacobian products from Calculus 2, batched.

Blame goes back through each layer's transposed weights and its activation's slope, and every gradient has the shape of the thing it updates.

Why does the blame go back through \(W^\top\)?
  1. Unit \(j\) in layer \(l-1\) feeds every unit \(i\) of layer \(l\), through the weight \(W_{ij}\): \(z_i = \sum_j W_{ij} a_j + b_i\), so \(\partial z_i / \partial a_j = W_{ij}\).
  2. A value used in several places collects the blame from every use (chapter 4): \(\partial L / \partial a_j = \sum_i W_{ij}\, \partial L / \partial z_i\).
  3. That sum runs down column \(j\) of \(W\), which is row \(j\) of \(W^\top\): stacked for every \(j\), it's \(W^\top dZ\). The forward pass reads \(W\) by rows ("what feeds me?"); the backward pass reads it by columns ("whom did I feed?").

4. Train one: a spiral

Two interleaved spirals, 100 points each. No straight line, or small set of them, separates them. The background shows what the network currently answers everywhere: blue or red, paler where it's unsure. Press Train.

Things to try, each one a lesson of its own:

Why does starting with all weights at zero never work?

With identical starting weights, the units are interchangeable: same inputs, same outputs, same blame, same update, forever. Sixteen units act like one. Random starting values break the symmetry so each unit can specialize.

5. How big should the random start be?

Too small, and signals shrink layer after layer: with weights around 0.01 the activations a few layers in are nearly zero, so the gradients are too, and a deep network sits frozen (that's the "× 0.01" option). Too big, and they explode, or tanh units saturate where their slope is 0 (Calculus 1's vanishing gradients). The fix is to keep each layer's output about as spread out as its input.

The math, step by step

One unit sums \(n_{l-1}\) inputs times weights: \(z = \sum_j w_j a_j\). If the weights and inputs are independent with mean 0, variances add (Probability 3), so \(\operatorname{Var}(z) = n_{l-1} \operatorname{Var}(w) \operatorname{Var}(a)\). To keep \(\operatorname{Var}(z) = \operatorname{Var}(a)\), choose

\[ \operatorname{Var}(w) = \frac{1}{n_{l-1}} \;\;\text{(Xavier, for tanh)}, \qquad \operatorname{Var}(w) = \frac{2}{n_{l-1}} \;\;\text{(He, for ReLU)} \]

ReLU gets the extra 2 because it zeroes half its inputs, halving the variance. So in code: W = randn(n_l, n_prev) * sqrt(2 / n_prev). Stage 4's "making deep nets train" adds normalization layers that keep this balance during training too.

Random starting weights break the symmetry between units; their size must keep signals from shrinking or growing as they pass through the layers.

A ReLU layer takes 32 inputs. With He initialization, what's the standard deviation of its starting weights?

\(\sqrt{2/32} = \sqrt{1/16} = 0.25\).

6. Why deep and not just wide?

One hidden layer can in principle approximate any reasonable function, but it may need absurdly many units. Depth lets a network reuse what earlier layers built. The cleanest picture is a fold. Two ReLU units make a tent: up, then down, on \([0, 1]\). Feed the tent into another tent and you get two teeth; again, four. Each layer of just 2 units doubles the number of straight pieces:

A single hidden layer of ReLUs makes one straight piece per unit (roughly), so matching \(2^k\) pieces takes about \(2^k\) units; depth does it with \(2k\). Real tasks are built the same way, from parts of parts: edges → corners → shapes → objects in an image (chapter 6), letters → words → phrases in text. Deep networks match that structure. A classic example: the parity of \(n\) bits (is the count of 1s odd?) takes a one-hidden-layer network about \(2^{n-1}\) units but a deep tree of XORs only about \(n\).

Depth reuses earlier work: \(k\) layers can build \(2^k\) pieces that a single layer would need about \(2^k\) units for.

Where it breaks: deeper isn't automatically better

How many straight pieces does the sawtooth have after 5 layers?

\(2^5 = 32\), from just 10 ReLU units. A single hidden layer would need about 32.

7. Parameters vs hyperparameters

who sets itexamples
Parameterstraining, by gradient descentevery \(W^{[l]}\) and \(b^{[l]}\)
Hyperparametersyou, before training (then you compare runs on validation data, chapter 11)number of layers and units, activation, learning rate, number of steps, initialization, batch size, regularization strength \(\lambda\)

Choosing hyperparameters is empirical: try, measure on held-out data, adjust. Applied deep learning is a loop of exactly that, and stage 4 shows how to search them sensibly (random search, log scales for the learning rate).

Which of these does gradient descent learn?

Biases and weights are parameters. Everything that shapes how training runs is a hyperparameter.

8. The whole network in code

Everything above in one program: initialize, forward, loss, backward, update, for any list of layer sizes. Batch as columns; NumPy refuses any product whose shapes don't fit, as section 2 showed.

9. What to carry forward

All lessons: AI from scratch.

Last updated