Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 4: Neural Network Foundations

Build an MLP from scratch (NumPy)

P4.1045 min●●○ IntermediateReviewed Dec 2, 2026

Why this matters for machine learning

Writing the whole training program once, with no framework, shows that a neural network is a short loop over a few matrix products, and it teaches you the gradient rules, the shapes and the checks that every framework hides.

Before this: The forward pass in matrix form, Backpropagation: step by step with numbers, Matrix calculus for ML, NumPy: arrays and vectorization

After this lesson you can

  • Write a two-layer ReLU network with softmax and cross-entropy in vectorised NumPy: parameters, a forward pass that stores its values, and a backward pass whose every gradient has the shape of its parameter
  • Derive each line of the backward pass from the dense-layer rules of P1.C11, and trace it on the 3→4→23\to4\to2 network of P4.5 with real numbers
  • Check a backward pass with central finite differences, say what size of difference is a pass, and name what can make a correct backward pass fail the check
  • Train with mini-batch SGD, choose settings on a validation set, read learning curves for signs of overfitting, and read a confusion matrix

P4.5 ran a batch through a network. P4.8 ran one number backward through a network. This lesson puts the two together into a program that learns, with no framework: just NumPy and about 50 lines. When it works, you will have a network that reads handwritten digits.

Try it first. Draw a digit in the pad below, or load a test image, and watch ten bars show how sure the network is of each answer. This is the network you will build, with weights found by the training code of this lesson.

Draw here (32×32 dots)

What the network gets: 8×8 counts, 0 to 16

Test images

Nothing drawn yet. Draw a digit, or load a test image.

  1. 0 11%
  2. 1 3%
  3. 2 4%
  4. 3 10%
  5. 4 27%
  6. 5 7%
  7. 6 8%
  8. 7 18%
  9. 8 9%
  10. 9 4%

This network (64 → 32 → 10, trained for the lesson) got 264 of 270 held-out test images right (97.8%). Your drawing can be different from the training images, so a wrong answer here is normal. Empty pad: the numbers are shown but mean nothing.

Draw a digit with a finger or mouse (or use the arrow keys and Space to fill blocks, or the Test images buttons: the first held-out image of each digit, and the network misreads the 4). The network sees an 8 by 8 image of counts, and answers with ten probabilities. It is trained on 1,257 images; on 270 held-out images it was right 264 times. Your own drawing differs from the training images in size, centring and stroke thickness, so wrong answers are normal.

The rest of the lesson builds that network, one piece at a time. The pieces are the same for any size: the pad’s network has 64 inputs, 32 hidden neurons and 10 outputs (64→32→1064\to32\to10), and the same code with 784 inputs and 128 hidden neurons (784→128→10784\to128\to10, the network P4.5 counted) trains on the famous MNIST data in a Colab notebook.

The data, and the three sets

Digits in the browser. The in-browser data is the 8 by 8 digit images that scikit-learn bundles. It is a copy of the test part of the UCI data set “Optical Recognition of Handwritten Digits” (created by E. Alpaydin and C. Kaynak, dated 1998, licensed CC BY 4.0). People wrote digits on forms (the 1,797 images of scikit-learn’s copy come from 13 writers); the 32 by 32 black-and-white bitmaps were divided into 4 by 4 blocks, and each block became the count of its black pixels, an integer from 0 to 16. That gives 1,797 images of 8×8=648\times8=64 numbers each, about 180 per digit. The lesson page stores them in a 118 KB text file, so no big download is needed.

MNIST in Colab. MNIST has 60,000 training and 10,000 test images of 28×28=78428\times28=784 grey pixels. Its file is 11.5 MB, too big for the browser under this site’s rules, so the full run is in a Colab notebook (source on GitHub). The notebook downloads the file itself, uses only NumPy to train, and every number quoted from it below comes from running it.

Scaling. Pixel counts 00 to 1616 are divided by 1616, so every input is between 00 and 11. Keeping the inputs in a small range keeps the first layer’s outputs, and so the gradients, on a sensible scale.

Three sets (P3.A4). We shuffle once with a fixed seed and cut: 1,2571{,}257 images to train (set the weights), 270270 to validate (choose the learning rate, watch for overfitting) and 270270 to test (look at once, at the end). If you choose settings by looking at the test set, its score is no longer an honest estimate for new data.

Step 1: load the data and split it

First run downloads about 9 MB (Python 6, NumPy 3; once) and a 118 KB data file. The cells of this lesson share their variables, so run them in order.

Output (computed in advance; run the cell to reproduce it)
images: (1797, 64)  labels: (1797,)
pixel range: 0.0 to 1.0
train 1257  validation 270  test 270
test class counts: [31 29 39 22 31 21 28 22 18 29]

The plan: four functions

The whole program is four short pieces.

  1. Parameters. W1\mathbf{W}_1 of shape (dhidden,din)(d_{\text{hidden}},d_{\text{in}}), b1\mathbf{b}_1, W2\mathbf{W}_2 of shape (10,dhidden)(10,d_{\text{hidden}}) and b2\mathbf{b}_2. The row-per-neuron layout is the one of P4.5, so a layer is X @ W.T + b.
  2. Forward pass. Compute the logits, and keep X\mathbf{X}, Z1\mathbf{Z}_1 and H\mathbf{H}, the cache that the backward pass needs (P4.5 explained why).
  3. Backward pass. Turn the loss into one gradient for every parameter.
  4. Update loop. Cut the training data into mini-batches and subtract η\eta times each gradient.

Parameters: small, random, with a seed

If all weights started equal, every neuron of a layer would get the same gradient and stay a copy of the others, so the start must be random. The scale matters too. We draw each weight from a normal distribution with mean 0 and standard deviation 2/din\sqrt{2/d_{\text{in}}} (a He-style scale, common with ReLU) and start every bias at 0. The seed makes the run repeat exactly. P4.12 explains why that scale is a good choice; a Go-deeper box near the end of this lesson shows what a bad one does.

The counts follow P4.5: a layer has dindout+doutd_{\text{in}}d_{\text{out}}+d_{\text{out}} parameters. For 64→32→1064\to32\to10 that is 2,048+32+320+10=2,4102{,}048+32+320+10=2{,}410. For 784→128→10784\to128\to10 it is 100,480+1,290=101,770100{,}480+1{,}290=101{,}770, the number of P4.5.

The forward pass, and keeping the numbers stable

The forward pass is the one of P4.5:

Z1=XW1⊤+b1,H=max⁡(Z1,0),Z2=HW2⊤+b2,P=softmax(Z2),\begin{aligned} \mathbf{Z}_1&=\mathbf{X}\mathbf{W}_1^\top+\mathbf{b}_1,\\ \mathbf{H}&=\max(\mathbf{Z}_1,0),\\ \mathbf{Z}_2&=\mathbf{H}\mathbf{W}_2^\top+\mathbf{b}_2,\\ \mathbf{P}&=\mathrm{softmax}(\mathbf{Z}_2), \end{aligned}

and the loss is the average of −ln⁡Pi,yi-\ln P_{i,y_i} over the batch. Two details make it work for real numbers (P1.G2).

Subtract the row maximum. ez\mathrm{e}^{z} overflows for zz above about 709709 in 64-bit floating point. Softmax does not change if every score in a row is shifted by the same number, so we subtract the row’s largest score first: the largest exponent is then e0=1\mathrm{e}^0=1.

Compute the loss from the logits. If a class has a tiny probability, PP can round to exactly 00 and −ln⁡0-\ln0 is infinite. The identity −ln⁡Py=−zy+ln⁡∑jezj-\ln P_{y}=-z_y+\ln\sum_j\mathrm{e}^{z_j} (P1.C11) avoids this: compute the second term with the maximum subtracted, ln⁡∑jezj=m+ln⁡∑jezj−m\ln\sum_j\mathrm{e}^{z_j}=m+\ln\sum_j\mathrm{e}^{z_j-m}.

Step 2: parameters, forward pass, loss

First run downloads about 9 MB (Python 6, NumPy 3; once) and a 118 KB data file. The cells of this lesson share their variables, so run them in order.

Output (computed in advance; run the cell to reproduce it)
W1 (32, 64) W2 (10, 32)
parameters: 2410
logits for 32 images: (32, 10)
loss at the start: 2.422 (ln 10 = 2.303)

Two checks on the output. The parameter count is 2,4102{,}410. And the loss before any training is about 2.42.4: a network that knows nothing gives each of the 10 digits about 0.10.1, and −ln⁡0.1=ln⁡10=2.303-\ln0.1=\ln10=2.303. A start far from 2.32.3 (say 1313) is a sign that the initial weights are too large.

Without them the naive softmax of (1000,1001,1002)(1000,1001,1002) is nan, while the stable one gives (0.0900,0.2447,0.6652)(0.0900,0.2447,0.6652), the numbers P1.C11 found for (1,2,3)(1,2,3). A true class with a very low score gets a probability that underflows to 00 and an infinite loss, while the loss from the logits is correct.

Go deeper Run the naive version and watch it break
Why subtract the maximum

First run downloads about 9 MB (Python 6, NumPy 3; once) and a 118 KB data file. The cells of this lesson share their variables, so run them in order.

Output (computed in advance; run the cell to reproduce it)
naive softmax: [[nan nan nan]]
stable softmax: [[0.09   0.2447 0.6652]]
probability of class 0: 0.0
-log of it: inf
from the logits: 800.0

The naive softmax is nan because e1000\mathrm{e}^{1000} overflows to infinity and ∞/∞\infty/\infty is not a number. In the second example the true class has a score 800800 below the other, so its probability underflows to 00; the loss from the logits is 800800, the true value.

The backward pass, layer by layer

P4.8 sent one number backward through a graph, and P1.C11 gave the matrix rules for a dense layer. Here they are, in this lesson’s layout (examples as rows, W\mathbf{W} of shape (dout,din)(d_{\text{out}},d_{\text{in}}), G=∇ZL\mathbf{G}=\nabla_{\mathbf{Z}}\mathcal{L} with one row per example). We go from the loss backward, and every gradient has the shape of the thing it is the gradient of.

The rules. For softmax with cross-entropy, one example has the gradient p−y\mathbf{p}-\mathbf{y} with respect to its logits (P1.C11, P3.A8), where y\mathbf{y} is the one-hot target. The loss is the average over NN examples, so every row is also divided by NN. Then each dense layer follows the rules of P1.C11 with its input, and the ReLU multiplies by its slope. Going from the loss backward, with the shape of each result on the right (hh is the number of hidden neurons, 1\mathbf{1} a column of NN ones):

G2=(P−Y)/N(N,10)∇W2=G2⊤H(10,h)∇b2=G2⊤1(10,)G1=(G2W2)⊙[Z1>0](N,h)∇W1=G1⊤X(h,din)∇b1=G1⊤1(h,)\begin{aligned} \mathbf{G}_2&=(\mathbf{P}-\mathbf{Y})/N &&(N,10)\\ \nabla_{\mathbf{W}_2}&=\mathbf{G}_2^\top\mathbf{H} &&(10,h)\\ \nabla_{\mathbf{b}_2}&=\mathbf{G}_2^\top\mathbf{1} &&(10,)\\ \mathbf{G}_1&=(\mathbf{G}_2\mathbf{W}_2)\odot[\mathbf{Z}_1>0] &&(N,h)\\ \nabla_{\mathbf{W}_1}&=\mathbf{G}_1^\top\mathbf{X} &&(h,d_{\text{in}})\\ \nabla_{\mathbf{b}_1}&=\mathbf{G}_1^\top\mathbf{1} &&(h,) \end{aligned}

Here ∇W2\nabla_{\mathbf{W}_2} means ∇W2L\nabla_{\mathbf{W}_2}\mathcal{L}. In code, G2\mathbf{G}_2 is P with 11 subtracted at each example’s true class, then divided by NN. The bias gradient is the column sums of G\mathbf{G} (a 1-D array of length doutd_{\text{out}}, the column of P1.C11), because the bias is shared by all examples. The ReLU slope is 11 where Z1>0\mathbf{Z}_1>0 and 00 elsewhere (P4.4). That is why the forward pass kept Z1\mathbf{Z}_1: it says which neurons were active, and a neuron that was off for an example passes back nothing for that example. At exactly Z1=0\mathbf{Z}_1=0 the ReLU has a corner, and the code uses slope 00, a common convention. We do not need ∇XL\nabla_{\mathbf{X}}\mathcal{L}, because the data is not a parameter. (A deeper network would send G1W1\mathbf{G}_1\mathbf{W}_1 further back.)

The shape check. Every line has the same pattern: the gradient of a parameter is G⊤\mathbf{G}^\top times the layer’s input, and the gradient sent further back is G\mathbf{G} times the layer’s weights, with no transpose. If you write the line the other way round, the shapes fail to multiply, or the result is a transposed matrix, which is the error to look for.

Run it on the network of P4.5

The 3→4→23\to4\to2 network of P4.5 has N=4N=4 examples and the true classes y=(0,1,1,1)y=(0,1,1,1); its loss was 0.45260.4526. Check one row by hand: example 2 was the one the network got wrong (probability 0.81760.8176 for class 0, but the true class is 1), so its row of G2\mathbf{G}_2 is (0.8176, 0.1824−1)/4=(0.2044,−0.2044)(0.8176,\,0.1824-1)/4=(0.2044,-0.2044).

Step 3: the backward pass with numbers

First run downloads about 9 MB (Python 6, NumPy 3; once) and a 118 KB data file. The cells of this lesson share their variables, so run them in order.

Output (computed in advance; run the cell to reproduce it)
loss: 0.4526
G2 = (P - Y) / N, shape (4, 2)
[[-0.019   0.019 ]
[ 0.2044 -0.2044]
[ 0.0001 -0.0001]
[ 0.0073 -0.0073]]
dW2 = G2.T @ H, shape (2, 4)
[[ 0.1854  0.431   0.3898  0.0001]
[-0.1854 -0.431  -0.3898 -0.0001]]
db2 = column sums: [ 0.1928 -0.1928]
dW1 (4, 3) db1 (4,) agree with backward(): True

Read the output:

  • Each row of G2\mathbf{G}_2 adds up to 00 (the two probabilities add to 11, and so do the two entries of the target). Example 2, the wrong one, has the largest entries: it pushes hardest. Examples 3 and 4 pass back almost nothing, because the network was already sure of them.
  • The two rows of ∇W2L\nabla_{\mathbf{W}_2}\mathcal{L} are exact opposites, because every row of G2\mathbf{G}_2 has the form (a,−a)(a,-a) (a softmax with two classes).
  • The first-layer gradients have the shapes (4,3)(4,3) and (4,)(4,) of W1\mathbf{W}_1 and b1\mathbf{b}_1, and agree with the backward function that the next cells use.

Check the backward pass

A backward pass is easy to get subtly wrong: a missing transpose that happens to run, a missing 1/N1/N, a wrong slope. The standard test needs no theory (P1.F3, P1.C11): for one parameter, nudge it up and down by a small hh, recompute the loss, and divide the difference by 2h2h. That central difference is an estimate of the same gradient. Do it for every entry of a small random network and compare with backward.

Step 4: gradient check

First run downloads about 9 MB (Python 6, NumPy 3; once) and a 118 KB data file. The cells of this lesson share their variables, so run them in order.

Output (computed in advance; run the cell to reproduce it)
W1 largest difference: 8.6e-12
b1 largest difference: 8.8e-12
W2 largest difference: 1.4e-11
b2 largest difference: 6.3e-12

All four differences are around 10−1110^{-11}. With h=10−5h=10^{-5}, rounding error and the approximation error of the central difference together leave about that much, so a correct backward pass agrees to roughly 10−810^{-8} or better. A difference of 10−210^{-2} or 10−110^{-1} in some entries means a bug. The pattern tells where: if only the first layer’s gradients differ and the second layer’s are right, the bug is in the hidden-layer step (the transpose, the ReLU, or W2\mathbf{W}_2).

Use a small network and a few examples: the check costs two forward passes per parameter, which is far too slow for a real model. The notebook runs it on 6 random entries of each parameter of the real 784→128→10784\to128\to10 network, with differences of about 10−1110^{-11} as well.

Go deeper When a correct backward pass fails the check: the ReLU corner

Run the same check on the 3→4→23\to4\to2 network of P4.5, with its whole-number weights. The gradients of W2\mathbf{W}_2 and b2\mathbf{b}_2 agree to about 10−1110^{-11}, but the gradients of W1\mathbf{W}_1 and b1\mathbf{b}_1 differ by up to 0.00950.0095. The reason: that network has several Z1\mathbf{Z}_1 entries that are exactly 00 (look at the table in P4.5). At a corner of the ReLU, nudging a weight up or down moves the output on one side only, so the central difference sees a slope of 0.50.5 where the code uses 00. The backward pass is fine; the check is at a point where the function has no derivative. With random real-valued weights, an exact 00 almost never happens, which is why the check above uses random numbers.

Mini-batch SGD

The update rule is gradient descent (P1.F3): θ←θ−η ∇θL\theta\leftarrow\theta-\eta\,\nabla_\theta\mathcal{L} for every parameter. Using all 1,257 training images for every step is wasteful, and using one image is noisy; the middle way (P1.F4) is a mini-batch: shuffle the training set, take 32 images, compute the gradient of their mean loss, and update. One pass over all the data is an epoch; with 1,257 images and batches of 32 it is 40 updates (39 of 32 images and one of 9). The shuffle is new every epoch.

The learning rate η=0.5\eta=0.5 was chosen by trying a few values on the validation set (batch size 32 is a common default). Small values learn slowly and a large one fails; the box after the cell shows the trial.

Step 5: train the network

First run downloads about 9 MB (Python 6, NumPy 3; once) and a 118 KB data file. The cells of this lesson share their variables, so run them in order.

Output (computed in advance; run the cell to reproduce it)
epoch   loss (train/val)  acc (train/val)
epoch  1  loss 0.693 / 0.643  acc 0.770 / 0.804
epoch  2  loss 0.374 / 0.303  acc 0.864 / 0.893
epoch  3  loss 0.499 / 0.514  acc 0.828 / 0.841
epoch  5  loss 0.107 / 0.128  acc 0.972 / 0.963
epoch 10  loss 0.066 / 0.113  acc 0.986 / 0.963
epoch 20  loss 0.032 / 0.065  acc 0.995 / 0.981
epoch 30  loss 0.013 / 0.067  acc 0.998 / 0.974
seconds: 0.1
Go deeper Choosing the learning rate on the validation set

Add this loop after Step 5 to try six learning rates, 30 epochs each. The output is from a run on the machine used for this lesson (shown as text, not as a cell):

for lr in (0.01, 0.05, 0.1, 0.5, 1, 3):
    _, h = train(init_params([64, 32, 10]),
                 X_tr, y_tr, lr=lr)
    print(lr, "val acc %.4f" % h[-1][3])
0.01 val acc 0.9259
0.05 val acc 0.9667
0.1 val acc 0.9667
0.5 val acc 0.9741
1 val acc 0.9741
3 val acc 0.0889

Small steps learn slowly, η=3\eta=3 diverges to chance level (8.9%8.9\%), and 0.50.5 and 11 tie at 97.4%97.4\%; we use 0.50.5. Choose among such trials by the validation score, never the test score.

The accuracy climbs from 80%80\% to about 97%97\% in 30 epochs. The loss does not fall smoothly: at epoch 3 it went up. A large step like η=0.5\eta=0.5 can overshoot, and a mini-batch gradient is only an estimate. The widget below plots every epoch.

Learning curves and overfitting

Each epoch we measured the loss and accuracy on the training set and on the validation set. Plotting them is the standard way to see how training went.

05101520253000.20.40.60.81

training set validation set horizontal axis: epoch

After epoch 30: training loss 0.013, validation 0.067.

Learning curves of the network above, for all 30 epochs. Solid blue line: training set. Dashed pink line: validation set. Switch between loss and accuracy, and move the epoch slider to read the numbers.

What to look for:

  • Both losses fall at first. The network is learning something that works on images it has not trained on.
  • A gap opens. By epoch 30 the training loss is 0.0130.013 and the validation loss is 0.0670.067: five times larger. After epoch 20 the validation loss stopped improving and jumped around (0.0650.065 at epoch 20, 0.1110.111 at epoch 21, its lowest value 0.0580.058 at epoch 27, 0.0670.067 at epoch 30) while the training loss kept falling. The network is fitting the training images more closely than it fits new ones: this is overfitting (P3.A3).
  • The signs to watch for: training accuracy near 100%100\% (here 99.8%99.8\%) and validation accuracy lower and flat (97.4%97.4\%); validation loss flat or rising while training loss falls. The fixes (stop earlier, weight decay, dropout, more data) belong to P4.17. Here the effect is mild.

The validation curves are also noisy: with only 270 validation images, one image changes the accuracy by 0.40.4 percentage points, so small differences between epochs mean little.

The test set, once, and the confusion matrix

Now we use the test set, once. The confusion matrix (P3.A9) counts, for each true digit (row), how often each digit was predicted (column). Correct answers are on the diagonal.

Step 6: test accuracy and the confusion matrix

First run downloads about 9 MB (Python 6, NumPy 3; once) and a 118 KB data file. The cells of this lesson share their variables, so run them in order.

Output (computed in advance; run the cell to reproduce it)
test accuracy: 0.9778 (264 of 270)
rows: true digit, columns: predicted
0 | 31  0  0  0  0  0  0  0  0  0
1 |  0 28  0  0  1  0  0  0  0  0
2 |  0  0 39  0  0  0  0  0  0  0
3 |  0  0  0 22  0  0  0  0  0  0
4 |  0  0  0  0 29  0  0  2  0  0
5 |  0  0  0  0  0 21  0  0  0  0
6 |  0  1  0  0  0  0 26  0  1  0
7 |  0  0  0  0  0  0  0 22  0  0
8 |  0  0  0  0  0  0  0  0 18  0
9 |  0  0  0  0  0  0  0  0  1 28

The network is right on 264264 of 270270 test images, 97.8%97.8\%. The six mistakes are off the diagonal: two 44s read as 77, and one each of 11 read as 44, 66 as 11, 66 as 88 and 99 as 88. Two cautions about the number. With 270 test images, a difference of one image is 0.40.4 points, and the true accuracy on new images could easily be a point or two away from 97.8%97.8\%. And the split is random over images, so the same writers appear in the training, validation and test sets; handwriting from new people could be harder, as the drawing pad shows.

What the drawing pad does

When you draw in the pad, it follows the data set’s own recipe: you draw on a 32 by 32 bitmap, each 4 by 4 block is replaced by its count of black dots (0 to 16), and the 64 counts divided by 1616 go through exactly the forward pass above, with the weights from Step 5 (rounded to four decimals; the pad’s own test checks that its answers equal NumPy’s). The small grey picture shows the 64 numbers the network gets. Wrong answers are normal, for good reasons: the images were written on forms by 13 people and normalized by a preprocessing program, while your drawing may be off-centre, too thin or too thick, or a different style (a 77 with a bar, a 11 with a flag). The network learned the statistics of its training data, not what a digit is.

The same network on MNIST

The code is the same; only the sizes change: init_params([784, 128, 10]). In the Colab notebook, 10,00010{,}000 of the 60,00060{,}000 training images are held out for validation, and the official 10,00010{,}000 test images are used once. The best of the learning rates 0.030.03, 0.10.1 and 0.30.3 on the validation set after 3 epochs was 0.10.1, and 15 epochs of batches of 6464 (782782 updates per epoch) gave a test accuracy of 97.4%97.4\% (9,7439{,}743 of 10,00010{,}000). The most common confusion was a true 44 read as 99 (1818 times). Training accuracy reached 99.2%99.2\% against 97.3%97.3\% on validation, the same overfitting picture as above.

What a framework does instead

Everything above is what PyTorch does, minus the typing.

Go deeper Check our gradients against PyTorch

A cell at the end of the notebook computes the gradients of the same loss for the same weights and 8 images with PyTorch’s automatic differentiation (64-bit floats). This block is shown as text, since PyTorch does not run in the browser; its output comes from the notebook run:

import torch
tp = [torch.tensor(a, dtype=torch.float64,
                   requires_grad=True)
      for W, b in params for a in (W, b)]
W1t, b1t, W2t, b2t = tp
logits = (torch.relu(torch.tensor(Xb) @ W1t.T + b1t)
          @ W2t.T + b2t)
loss = torch.nn.functional.cross_entropy(
    logits, torch.tensor(yb))
loss.backward()     # replaces our whole backward()
loss: ours 2.652498, torch 2.652498
W1 largest difference: 2.8e-17
b1 largest difference: 2.8e-17
W2 largest difference: 1.1e-16
b2 largest difference: 5.6e-17
  • loss.backward() replaces backward: autograd (P2.6) records the forward pass as a graph and applies local rules like the ones above (P4.8, P4.9 builds such an engine).
  • cross_entropy takes the logits and combines the softmax and the loss in the stable form of this lesson.
  • An optimizer’s step() replaces the update line, and nn.Linear holds W\mathbf{W} with shape (out, in) and computes x @ W.T + b (P2.6, P2.7).
  • What a framework does not do for you: choose the learning rate, split the data, notice overfitting, or tell you that your loss is wrong. Those stay your job.
Go deeper What a bad starting scale does

The cell trains the same network for one epoch from three scales: the He-style scale of this lesson, a tiny 0.010.01 and a large 1.01.0.

Step 7: the scale of the starting weights

First run downloads about 9 MB (Python 6, NumPy 3; once) and a 118 KB data file. The cells of this lesson share their variables, so run them in order.

Output (computed in advance; run the cell to reproduce it)
He: sqrt(2/d_in)  start loss 2.32, after 1 epoch: val acc 0.804
tiny: 0.01        start loss 2.30, after 1 epoch: val acc 0.326
large: 1.0        start loss 13.65, after 1 epoch: val acc 0.741

The He-style start has a loss near 2.32.3 and the best validation accuracy after one epoch (80.4%80.4\%). The tiny start is also near 2.32.3 but learns slowly (32.6%32.6\%), probably because the signals and gradients are very small. The large start has a first loss of 13.6513.65, since its logits are far too large, and does worse (74.1%74.1\%). This is one run each, with one seed: it shows the effect and does not measure it. P4.12 explains the scale properly.

Other changes to try: edit lr or batch in Step 5, remove the / N in backward and rerun the gradient check (the difference becomes large), or change the hidden size from 32 to 8 or 128.

Depth: two ways to see it

Intuition

Training is a factory with two shifts. In the day shift (forward), raw material flows through two machines and a quality inspector compares the product with the order (the loss). In the night shift (backward), the inspector’s note travels back through the machines in reverse order. Each machine uses the note and its own record of what it did that day (the cache) to work out how to adjust its settings. Then everyone adjusts a little and the next day begins. The picture breaks at one point: in a factory you could ask each machine to change one setting and see what happens, but backward is the cheaper way to get all the answers from a single note.

Math

For layers ℓ=1,…,L\ell=1,\dots,L with H0=X\mathbf{H}_0=\mathbf{X}, Zℓ=Hℓ−1Wℓ⊤+bℓ\mathbf{Z}_\ell=\mathbf{H}_{\ell-1}\mathbf{W}_\ell^\top+\mathbf{b}_\ell, Hℓ=fℓ(Zℓ)\mathbf{H}_\ell=f_\ell(\mathbf{Z}_\ell) and Gℓ=∇ZℓL\mathbf{G}_\ell=\nabla_{\mathbf{Z}_\ell}\mathcal{L}, the rules above repeat for every layer:

∇WℓL=Gℓ⊤Hℓ−1,Gℓ−1=(GℓWℓ)⊙fℓ−1′(Zℓ−1),\begin{aligned} \nabla_{\mathbf{W}_\ell}\mathcal{L}&=\mathbf{G}_\ell^\top\mathbf{H}_{\ell-1},\\ \mathbf{G}_{\ell-1}&=(\mathbf{G}_\ell\mathbf{W}_\ell)\odot f_{\ell-1}'(\mathbf{Z}_{\ell-1}), \end{aligned}

starting from GL=(P−Y)/N\mathbf{G}_L=(\mathbf{P}-\mathbf{Y})/N. A network of any depth is a loop over the layers in reverse. The backward pass costs about two matrix products per layer, each as large as the forward one, so about twice the forward arithmetic.

Common mistakes

Quiz

Check your understanding

  1. In the 784→128→10784\to128\to10 network, a batch has N=64N=64 images. What is the shape of ∇W1L=G1⊤X\nabla_{\mathbf{W}_1}\mathcal{L}=\mathbf{G}_1^\top\mathbf{X}?

  2. A gradient check of a hand-written backward pass shows differences of about 10−1110^{-11} for W2\mathbf{W}_2 and b2\mathbf{b}_2, but differences of about 0.30.3 for W1\mathbf{W}_1 and b1\mathbf{b}_1 (random weights, random data). Where is the bug most likely?

  3. You try learning rates 0.030.03, 0.10.1 and 0.30.3 and want to pick one. Which score should decide?

  4. A softmax is computed as exp(z) / exp(z).sum() and gives nan for z=(1000,1001,1002)\mathbf{z}=(1000,1001,1002). Which change fixes it without changing the probabilities?

  5. During training, the training loss keeps falling, but the validation loss stops improving and then wobbles. What does this show?

Exercises

  1. How many parameters does a 784→256→10784\to256\to10 network have?
    Show answerThe first layer has 784⋅256+256=200,960784\cdot256+256=200{,}960 and the second has 256⋅10+10=2,570256\cdot10+10=2{,}570, so the total is 203,530203{,}530.
  2. In the output of Step 3, each row of G2\mathbf{G}_2 adds up to 00. Explain why this must happen for any network with softmax and cross-entropy.
    Show answerA row of P\mathbf{P} adds up to 11 (it is a probability distribution) and a row of the one-hot Y\mathbf{Y} adds up to 11 too, so the row of P−Y\mathbf{P}-\mathbf{Y} adds up to 00. It matches the fact that adding the same number to every logit changes nothing, so the loss has no slope in that direction.
  3. MNIST has 50,00050{,}000 training images in the notebook and the batch size is 64. How many updates happen in one epoch?
    Show answer50,000=781⋅64+1650{,}000=781\cdot64+16, so there are 781781 full batches and one batch of 1616 images: 782782 updates.
  4. A friend removes the division by NN in backward, so G2 = P - Y. The gradient check fails. What is the relation between the two gradients, and what happens in training with η=0.5\eta=0.5 and batches of 32?
    Show answerEvery gradient is NN times too large: the code differentiates NN times the mean, the sum of the per-example losses, and the gradient check shows a ratio of exactly NN. Training behaves as if the learning rate were NN times larger: with η=0.5\eta=0.5 and batches of 32 that is η=16\eta=16, and the network stays at chance level (about 10%10\% accuracy). The right learning rate would then depend on the batch size.
  5. Add a second hidden layer, 64→32→16→1064\to32\to16\to10. Which lines of the backward pass change, and what is the new pattern?
    Show answerThe gradient at the logits G3=(P−Y)/N\mathbf{G}_3=(\mathbf{P}-\mathbf{Y})/N is the same, and each layer repeats the three lines of the Math tab, working back from the last: ∇W3L=G3⊤H2\nabla_{\mathbf{W}_3}\mathcal{L}=\mathbf{G}_3^\top\mathbf{H}_2, then G2=(G3W3)⊙[Z2>0]\mathbf{G}_2=(\mathbf{G}_3\mathbf{W}_3)\odot[\mathbf{Z}_2>0] and ∇W2L=G2⊤H1\nabla_{\mathbf{W}_2}\mathcal{L}=\mathbf{G}_2^\top\mathbf{H}_1, then G1=(G2W2)⊙[Z1>0]\mathbf{G}_1=(\mathbf{G}_2\mathbf{W}_2)\odot[\mathbf{Z}_1>0] and ∇W1L=G1⊤X\nabla_{\mathbf{W}_1}\mathcal{L}=\mathbf{G}_1^\top\mathbf{X}. The forward pass must also keep the extra layer’s Z\mathbf{Z} and H\mathbf{H}.
  6. The test accuracy of the digit network is 97.8%97.8\% on 270270 images. How much does it change if the network gets one more image right?
    Show answerOne image is 1/270=0.371/270=0.37 percentage points, so 265265 of 270270 would be 98.1%98.1\%. This is why differences below a point or so between two networks on a test set this small mean little.

Next: P4.11 shows why networks of this kind can approximate almost any function, P4.12 explains the scale of the starting weights, and P4.13 replaces the plain update rule with better optimizers. P4.9 builds an automatic-differentiation engine, which replaces the hand-written backward of this lesson.

Key takeaways

  • Four functions are the whole network. init_params makes small random weights of shape (dout,din)(d_{\text{out}},d_{\text{in}}) and zero biases; forward computes X @ W.T + b and the ReLU and keeps X\mathbf{X}, Z1\mathbf{Z}_1 and H\mathbf{H}; backward returns one gradient per parameter; and a loop subtracts η\eta times each gradient.
  • The backward pass in six lines. With G2=(P−Y)/N\mathbf{G}_2=(\mathbf{P}-\mathbf{Y})/N: ∇W2L=G2⊤H\nabla_{\mathbf{W}_2}\mathcal{L}=\mathbf{G}_2^\top\mathbf{H} and ∇b2L\nabla_{\mathbf{b}_2}\mathcal{L} is the column sums of G2\mathbf{G}_2; then G1=(G2W2)⊙[Z1>0]\mathbf{G}_1=(\mathbf{G}_2\mathbf{W}_2)\odot[\mathbf{Z}_1>0], ∇W1L=G1⊤X\nabla_{\mathbf{W}_1}\mathcal{L}=\mathbf{G}_1^\top\mathbf{X} and ∇b1L\nabla_{\mathbf{b}_1}\mathcal{L} is the column sums of G1\mathbf{G}_1. Each gradient has the shape of its parameter.
  • Check, then trust. Nudge each parameter by ±h\pm h and compare (L+−L−)/2h(\mathcal{L}_+-\mathcal{L}_-)/2h with backward. With h=10−5h=10^{-5} a correct backward pass agrees to about 10−1110^{-11} on random numbers. A mismatch in the first layer only, with a correct second layer, points at the hidden-layer step.
  • Stable by construction. Subtract the row maximum before the exponential, and compute the loss from the logits with the log-sum-exp form. The naive softmax of (1000,1001,1002)(1000,1001,1002) is all nan; the stable one gives (0.0900,0.2447,0.6652)(0.0900,0.2447,0.6652).
  • Three data sets, three jobs. Fit the weights on the training set, choose the learning rate and watch for overfitting on the validation set, and report the test set once. The 64→32→1064\to32\to10 network reaches 97.8%97.8\% (264264 of 270270) on held-out digit images; the 784→128→10784\to128\to10 network reaches 97.4%97.4\% on the 10,00010{,}000 MNIST test images.
  • Curves and the confusion matrix. Training loss keeps falling while validation loss flattens: that gap is overfitting. A confusion matrix shows which digits are mixed up, such as 44 and 99 on MNIST.
Found a mistake? Tell us