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.
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 (), and the same code with 784 inputs and 128 hidden neurons (, 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 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 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 to are divided by , so every input is between and . 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: images to train (set the weights), to validate (choose the learning rate, watch for overfitting) and 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.
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.
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.
- Parameters. of shape , , of shape and . The row-per-neuron layout is the one of P4.5, so a layer is
X @ W.T + b. - Forward pass. Compute the logits, and keep , and , the cache that the backward pass needs (P4.5 explained why).
- Backward pass. Turn the loss into one gradient for every parameter.
- Update loop. Cut the training data into mini-batches and subtract 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 (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 parameters. For that is . For it is , the number of P4.5.
The forward pass, and keeping the numbers stable
The forward pass is the one of P4.5:
and the loss is the average of over the batch. Two details make it work for real numbers (P1.G2).
Subtract the row maximum. overflows for above about 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 .
Compute the loss from the logits. If a class has a tiny probability, can round to exactly and is infinite. The identity (P1.C11) avoids this: compute the second term with the maximum subtracted, .
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.
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 . And the loss before any training is about : a network that knows nothing gives each of the 10 digits about , and . A start far from (say ) is a sign that the initial weights are too large.
Without them the naive softmax of is nan, while the stable one gives , the numbers P1.C11 found for . A true class with a very low score gets a probability that underflows to and an infinite loss, while the loss from the logits is correct.
Go deeper Run the naive version and watch it break
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.
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 overflows to infinity and is not a number. In the second example the true class has a score below the other, so its probability underflows to ; the loss from the logits is , 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, of shape , 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 with respect to its logits (P1.C11, P3.A8), where is the one-hot target. The loss is the average over examples, so every row is also divided by . 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 ( is the number of hidden neurons, a column of ones):
Here means . In code, is P with subtracted at each example’s true class, then divided by . The bias gradient is the column sums of (a 1-D array of length , the column of P1.C11), because the bias is shared by all examples. The ReLU slope is where and elsewhere (P4.4). That is why the forward pass kept : it says which neurons were active, and a neuron that was off for an example passes back nothing for that example. At exactly the ReLU has a corner, and the code uses slope , a common convention. We do not need , because the data is not a parameter. (A deeper network would send further back.)
The shape check. Every line has the same pattern: the gradient of a parameter is times the layer’s input, and the gradient sent further back is 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 network of P4.5 has examples and the true classes ; its loss was . Check one row by hand: example 2 was the one the network got wrong (probability for class 0, but the true class is 1), so its row of is .
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.
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 adds up to (the two probabilities add to , 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 are exact opposites, because every row of has the form (a softmax with two classes).
- The first-layer gradients have the shapes and of and , and agree with the
backwardfunction 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 , a wrong slope. The standard test needs no theory (P1.F3, P1.C11): for one parameter, nudge it up and down by a small , recompute the loss, and divide the difference by . That central difference is an estimate of the same gradient. Do it for every entry of a small random network and compare with backward.
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.
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 . With , rounding error and the approximation error of the central difference together leave about that much, so a correct backward pass agrees to roughly or better. A difference of or 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 ).
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 network, with differences of about as well.
Go deeper When a correct backward pass fails the check: the ReLU corner
Run the same check on the network of P4.5, with its whole-number weights. The gradients of and agree to about , but the gradients of and differ by up to . The reason: that network has several entries that are exactly (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 where the code uses . The backward pass is fine; the check is at a point where the function has no derivative. With random real-valued weights, an exact almost never happens, which is why the check above uses random numbers.
Mini-batch SGD
The update rule is gradient descent (P1.F3): 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 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.
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.
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.0889Small steps learn slowly, diverges to chance level (), and and tie at ; we use . Choose among such trials by the validation score, never the test score.
The accuracy climbs from to about in 30 epochs. The loss does not fall smoothly: at epoch 3 it went up. A large step like 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.
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 and the validation loss is : five times larger. After epoch 20 the validation loss stopped improving and jumped around ( at epoch 20, at epoch 21, its lowest value at epoch 27, 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 (here ) and validation accuracy lower and flat (); 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 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.
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.
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 of test images, . The six mistakes are off the diagonal: two s read as , and one each of read as , as , as and as . Two cautions about the number. With 270 test images, a difference of one image is points, and the true accuracy on new images could easily be a point or two away from . 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 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 with a bar, a 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, of the training images are held out for validation, and the official test images are used once. The best of the learning rates , and on the validation set after 3 epochs was , and 15 epochs of batches of ( updates per epoch) gave a test accuracy of ( of ). The most common confusion was a true read as ( times). Training accuracy reached against 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-17loss.backward()replacesbackward: 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_entropytakes the logits and combines the softmax and the loss in the stable form of this lesson.- An optimizer’s
step()replaces the update line, andnn.Linearholds with shape(out, in)and computesx @ 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 and a large .
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.
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 and the best validation accuracy after one epoch (). The tiny start is also near but learns slowly (), probably because the signals and gradients are very small. The large start has a first loss of , since its logits are far too large, and does worse (). 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 with , , and , the rules above repeat for every layer:
starting from . 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
In the network, a batch has images. What is the shape of ?
is , so its transpose is , and is . The product is , the shape of , as a gradient must be. The shape would be the weight layout used by Keras, not by this lesson. The shape is the shape of itself, and is the shape of the data.
A gradient check of a hand-written backward pass shows differences of about for and , but differences of about for and (random weights, random data). Where is the bug most likely?
The second layer's gradients are right, so and the second layer's rules are right. Only the gradients that depend on the hidden-layer step are wrong: the product with (for example a wrong transpose that happens to fit, or the wrong ReLU slope). A wrong would spoil every gradient, including the second layer's. The learning rate is not part of the gradient, and the check does not use it. Subtracting the maximum does not change the probabilities.
You try learning rates , and and want to pick one. Which score should decide?
The validation set exists for choosing settings: it is data the weights were not fitted to, so it is a fair comparison. If you pick by the test score, the test score is no longer an honest estimate for new data, because you have used it to choose. The training loss and accuracy always improve with a larger fit and say little about new data.
A softmax is computed as
exp(z) / exp(z).sum()and givesnanfor . Which change fixes it without changing the probabilities?Subtracting the same number from every score does not change the softmax, and subtracting the largest one makes the biggest exponent , so nothing overflows. Dividing the scores by does change the probabilities, because softmax is not unchanged by scaling. Adding makes the overflow worse. The logarithm of scores is meaningless for negative scores and is not the softmax.
During training, the training loss keeps falling, but the validation loss stops improving and then wobbles. What does this show?
A growing gap between the training and validation losses is the standard sign of overfitting. A bug in the backward pass would show up in the gradient check and would affect the training images too, not only the validation images. A learning rate of zero would stop the training loss falling too. The size of the validation set affects how noisy the curve is, not whether a gap opens.
Exercises
- How many parameters does a network have?
Show answer
The first layer has and the second has , so the total is . - In the output of Step 3, each row of adds up to . Explain why this must happen for any network with softmax and cross-entropy.
Show answer
A row of adds up to (it is a probability distribution) and a row of the one-hot adds up to too, so the row of adds up to . It matches the fact that adding the same number to every logit changes nothing, so the loss has no slope in that direction. - MNIST has training images in the notebook and the batch size is 64. How many updates happen in one epoch?
Show answer
, so there are full batches and one batch of images: updates. - A friend removes the division by in
backward, soG2 = P - Y. The gradient check fails. What is the relation between the two gradients, and what happens in training with and batches of 32?Show answer
Every gradient is times too large: the code differentiates times the mean, the sum of the per-example losses, and the gradient check shows a ratio of exactly . Training behaves as if the learning rate were times larger: with and batches of 32 that is , and the network stays at chance level (about accuracy). The right learning rate would then depend on the batch size. - Add a second hidden layer, . Which lines of the backward pass change, and what is the new pattern?
Show answer
The gradient at the logits is the same, and each layer repeats the three lines of the Math tab, working back from the last: , then and , then and . The forward pass must also keep the extra layer’s and . - The test accuracy of the digit network is on images. How much does it change if the network gets one more image right?
Show answer
One image is percentage points, so of would be . 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.