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.
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)
- (500, 16)
- (16, 500)
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:
| step | formula | shape |
|---|---|---|
| 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\)?
- 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}\).
- 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\).
- 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:
- All zero: the loss sits at 0.693 (a coin flip, \(\ln 2\)) forever.
- Random × 0.01 with three hidden layers: it barely moves for thousands of steps.
- One wide layer, same 337 parameters: it learns, but far more slowly. In our tests it reached about 82% after 8000 steps, while two layers of 16 hit 100% by about 4000.
- Learning rate 10: the loss jumps around or blows up (Calculus 3's \(2/k\) limit). 0.05: it crawls.
Why does starting with all weights at zero never work?
- Zero weights make every gradient zero
- Every unit in a layer computes the same thing and gets the same gradient, so they stay identical copies forever
- The learning rate is too small
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?
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
- Harder to train. Until 2015, plain networks beyond about 20 layers got worse, even on their own training data: blame faded or exploded through the long chain. Residual connections (each layer adds its output to its input, stage 5) fixed it, and networks of 100+ layers became normal.
- Can isn't will. The sawtooth shows what depth can represent, not what gradient descent will find. Many functions a deep network could draw are ones training never reaches.
- Not every problem is parts of parts. For tables of features (prices, ages, counts), a forest of shallow trees often beats a deep network (chapter 13): there's no hierarchy of edges and shapes to reuse.
How many straight pieces does the sawtooth have after 5 layers?
7. Parameters vs hyperparameters
| who sets it | examples | |
|---|---|---|
| Parameters | training, by gradient descent | every \(W^{[l]}\) and \(b^{[l]}\) |
| Hyperparameters | you, 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?
- The learning rate
- The bias of the third unit in layer 2
- The number of hidden layers
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
- Layer \(l\): \(Z^{[l]} = W^{[l]} A^{[l-1]} + b^{[l]}\), \(A^{[l]} = g(Z^{[l]})\). \(W^{[l]}\) is \((n_l, n_{l-1})\); a batch is \((n, m)\) with examples as columns; biases broadcast.
- Backprop for any depth: \(dZ^{[L]} = A^{[L]} - Y\), \(dW = \frac1m dZ\,A^\top\), \(db\) sums over examples, \(dA = W^\top dZ\), times \(g'\). Every gradient has its parameter's shape.
- Random initialization breaks symmetry; scaled initialization (\(1/n\) Xavier, \(2/n\) He) keeps signals from vanishing or exploding.
- Depth builds on itself: each layer can double the pieces; deep beats wide for the same parameters on structured problems.
- Parameters are learned; hyperparameters are chosen by you and checked on validation data.
All lessons: AI from scratch.
Last updated