A network in NumPy
Last updated
Lesson 6.4 found every gradient of a two-layer network for one example. This lesson does it for a whole batch at once, with one example per row, and puts the five steps of the training loop around it. The network learns to separate two interleaving moons, which no straight line can, then reads handwritten digits; and a network started with every weight equal shows why weights must start random.
By the end of this lesson you can
- Write the forward and backward passes of a two-layer network for a batch, with one example per row
- Train it with the five-step loop, and watch the decision boundary bend into shape
- Train the same code on handwritten digits and measure it on a test set
- Explain why weights must start random, not all equal
Forward
Two moons: 300 points of two classes, curled into each other so that no straight line separates them (lesson 4.9). The network has 2 inputs, 16 ReLU hidden units, and 2 outputs with a softmax.
With a batch, is , one example per row, and every layer is lesson 6.1's . The softmax works row by row, so each example gets its own probabilities:
The weights start random (step 6 says why), drawn with a spread of , a choice lesson 7.6 explains. The loss starts at 0.657, close to , what a network that guesses 50–50 gets.
Loss and backward
The loss is now the mean cross-entropy over the batch, . Lesson 6.4's backward pass works for each row, and the batch version just stacks the rows. Write for the matrix whose row is example 's error :
The bias gradients are the columns of summed. Compare with 6.4: the comes from the mean; for a column becomes for rows; and , one example's outer product, becomes , which adds up every example's outer product in one matrix product. The shapes say it all:
Every gradient has its parameter's shape. (You can gradient-check this too: lesson 6.4's numeric_grad works unchanged on the mean loss.)
The training loop
Now put it in the loop every model in this course is trained with (lesson 3.3): predict, measure the loss, find the gradient, step the weights, repeat.
Full-batch gradient descent with a learning rate of 0.5. The loss falls from 0.657 to 0.082 in 400 steps, and to 0.045 by step 2,000; the accuracy goes from 56% to 98.7%. Fifteen lines of NumPy, and nothing hidden.
Watching the boundary form
Where does the network draw its boundary? Predict at every point of a grid and colour it:
The boundary curls between the moons: something no linear model could draw. Here's the same network training in the page, the regions redrawn every 20 steps. Try 1 or 2 hidden units, then 16; try a learning rate of 3.
The weights are random, so the regions are a guess. Press Play.
With one hidden unit, the boundary stays a straight line: one ReLU makes one kink, and the softmax's boundary is still where two straight-ish scores cross. With 8 or more, it bends into a curl. The early steps do the most: the rough shape appears in the first few hundred, then the edges tidy up while the loss creeps down.
Digits
Nothing in the code cares that there were 2 inputs and 2 classes. Change the sizes to 64 inputs (an 8×8 image), 32 hidden units and 10 classes, and train on scikit-learn's handwritten digits:
96.7% of the 360 test digits right, after 500 steps of full-batch gradient descent. Lesson 3.P's softmax regression, a single layer, got 96.4% on its own, larger, test split: on tiny 8×8 digits even a single layer does well. Hidden layers earn their keep on harder data, like the 28×28 digits of project 6.P and the clothes of project 7.P. Lesson 6.9 trains a network like this with your own library, in mini-batches, and looks at what it gets wrong.
Wrong way: every weight started at zero
Why random weights? Try starting with every weight equal: all zeros, then all 0.5.
All zeros: 50% accuracy, and the 16 hidden units are all the same, so there's really only one. With every weight zero, every hidden unit outputs 0, so the second layer's gradients are 0; and is 0, so the first layer's are too. Only the output biases learn.
All 0.5: better, 84.7%, but still 1 distinct hidden unit of 16. The units start identical, so they compute the same output, get the same gradient, take the same step, and stay identical for ever. The network has 16 units' worth of parameters and the power of one. That's the symmetry problem:
All four units started at (0.5, 0.5). Train, and watch them move together.
Random starting weights break the symmetry: each unit starts different, so each gets a different gradient and learns something different. With random weights, the same code gets 98.7% and all 16 units distinct. (Biases can start at 0; the random weights already make the units differ.)
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- Nielsen, Neural Networks and Deep Learning, chapter 2: the backpropagation algorithm for a mini-batch: the four equations, applied to many examples at once
- Goodfellow, Bengio and Courville, Deep Learning, section 8.4: Parameter Initialization Strategies: why initial weights must break symmetry
- scikit-learn: make_moons and load_digits: the two datasets
- Smilkov, Carter, Sculley, Viégas and Wattenberg, Direct-manipulation visualization of deep networks, 2017: TensorFlow Playground, the in-browser network the boundary figure follows