Neural networks · lesson 5 of 10
Parts in this lesson
AD2 = (P - Y) / nthe output error for a batch, averaged
BdW2 = D2.T @ A1a weight gradient summed over the batch
CD1 = (D2 @ W2) * (Z1 > 0)the hidden error, for every example at once
DW1 -= lr * dW13.3: a step of gradient descent

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, X is (n,2), one example per row, and every layer is lesson 6.1's Z=XW⊤+b. The softmax works row by row, so each example gets its own probabilities:

network.ipynb

The weights start random (step 6 says why), drawn with a spread of 2/nin, a choice lesson 7.6 explains. The loss starts at 0.657, close to ln⁡2=0.693, what a network that guesses 50–50 gets.

Loss and backward

The loss is now the mean cross-entropy over the batch, ℒ=1n∑iLi. Lesson 6.4's backward pass works for each row, and the batch version just stacks the rows. Write D[l] for the matrix whose row i is example i's error δ[l]⊤:

D[2]=1n(P−Y)∂ℒ∂W[2]=D[2]⊤A[1]D[1]=(D[2]W[2])⊙ReLU⁡'(Z[1])∂ℒ∂W[1]=D[1]⊤X

The bias gradients are the columns of D summed. Compare with 6.4: the 1n comes from the mean; W⊤δ for a column becomes DW for rows; and δa⊤, one example's outer product, becomes D⊤A, which adds up every example's outer product in one matrix product. The shapes say it all:

network.ipynb

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.

network.ipynb

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:

network.ipynb

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.

Boundary growth2 → 8 ReLU → 2, trained in the page
loss, every 20 steps03,000 stepsstep 0 · 50% right

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:

network.ipynb

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.

network.ipynb

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 D[2]W[2] 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:

Symmetryeach hidden unit's two weights as a point
weight on x₁ →, on x₂ ↑unit 1: (0.5, 0.5)unit 2: (0.5, 0.5)unit 3: (0.5, 0.5)unit 4: (0.5, 0.5)1 distinct unit of 4after 0 steps

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

X is (300, 2), W1 is (16, 2) and D1 is (300, 16). What shape is D1.T @ X, and what is it?
A network’s hidden weights all start at 0.3. After training, what do you expect?
In the step 3 notebook, change lr = 0.5 to lr = 5 and run it. What happens to the printed loss?

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.

All sources for Simple Machine Learning