Neural networks · lesson 9 of 10
Parts in this lesson
Afrom simplenet import Tensor, MLP, SGD, cross_entropyyour own library, imported like any other
Border = rng.permutation(len(X_train))a new shuffle every epoch
Cbatch = order[start:start + 32]one mini-batch of 32 examples
Dconfusion_matrix(y_val, val_pred)which digits are taken for which

Training on digits

Last updated

simplenet is finished: the reference copy is the file beside this lesson’s notebook, the same Value and Tensor you wrote, with a few more operations. Now use it the way you’ll use PyTorch in Stage 7. You’ll train a network on scikit-learn’s 8×8 handwritten digits in mini-batches, keep a validation set to watch it learn, and then read the results: a curve, a confusion matrix, the mistakes, and the weights themselves.

By the end of this lesson you can

  • Train an MLP with simplenet in shuffled mini-batches, with a training, validation and test split
  • Read a validation curve and say when more training stops helping
  • Read a confusion matrix and look at the mistakes behind it
  • Say why the batches must be shuffled

Data, model, loss, optimiser

Every training script has the same four parts, and this one is no different:

  • Data. The 1,797 digits, with pixels scaled from 0–16 to 0–1. Split three ways (lesson 2.9): 20% held back as a test set, then a quarter of the rest as a validation set. You'll train on the training set, make every decision by looking at the validation set, and use the test set once, at the very end.
  • Model. MLP([64, 32, 10]): 64 pixels in, 32 ReLU units, 10 logits out.
  • Loss. Softmax cross-entropy.
  • Optimiser. SGD with a learning rate of 0.3.

simplenet is the file simplenet.py beside the notebook, so from simplenet import ... works as with any module (Simple Python, lesson 2.7). On your own computer, keep it in the same folder as your notebook.

06-digits.ipynb

1,077 to train on, 360 to validate, 360 to test.

06-digits.ipynb

2,410 numbers to learn: 64×32+32 in the first layer, 32×10+10 in the second.

The mini-batch loop

Lesson 6.5 used every training example in every step. That's exact but slow when there are many examples, and the gradient of a random mini-batch of 32 points the same way on average, for a 32nd of the work (lesson 3.6). So each epoch, one pass through the training set:

  1. shuffle the training examples into a new random order,
  2. take them 32 at a time,
  3. for each batch: predict, loss, zero_grad(), backward(), step().

1,077 examples make 34 batches per epoch (the last has 21), so 30 epochs are 1,020 steps. After each epoch, measure the accuracy on both sets.

06-digits.ipynb

After one epoch, 80% of the validation digits are right; after 20, 96.9%.

The validation curve

Numbers every 5 epochs hide the shape. Plot every epoch:

06-digits.ipynb

Read the right-hand plot from left to right:

  • For the first 10 epochs, both curves climb together: the network is learning things that hold for digits it hasn't seen.
  • From about epoch 15, the training accuracy keeps climbing, to 99.8%, but the validation accuracy stays near 96–97%. The extra training is going into details of these 1,077 images. That gap is the start of overfitting (lesson 2.6).
  • The training loss keeps falling all the way. It can't tell you when to stop; only the validation set can.

That's how to choose the number of epochs: where the validation curve stops rising. Stopping there on purpose is early stopping (lesson 7.8).

The confusion matrix

One accuracy number hides which digits go wrong. A confusion matrix (lesson 2.8) has a row for each true digit and a column for each prediction, so the diagonal counts the right answers and everything off it is a mistake:

06-digits.ipynb

The diagonal holds 349 of the 360. Of the 11 mistakes, 4 are in column 1, digits taken for a 1 (a 4, a 5, an 8 and a 9), and 3 are in column 9 (a 5, a 7 and an 8). No digit has more than 2 wrong: the 4s, 5s, 8s and 9s have 2 each. On a set this small, one or two images make the difference, so don't read too much into a single cell.

Looking at mistakes, and at the weights

Numbers tell you how many; pictures tell you why. Draw the mistakes, each titled with its true digit and the network's answer:

06-digits.ipynb

At 8×8, many of these are hard for a person too. A model that makes only mistakes like these is near the limit of what the pixels can say. A mistake that's obvious to you would point at a bug or at a missing kind of example.

What has the first layer learned? Each hidden unit has 64 weights, one per pixel, so draw them as an 8×8 image. These are the weights from the run above, after 0 to 30 epochs:

Hidden unit viewereach first-layer unit's 64 weights as an 8×8 image
unit 1, epoch 0pink: weight above 0dark: weight below 0its biggest change: 0.00

Before training the weights are random, uniform between ±1/8: every unit is static.

Don't expect pictures of digits. The learned part of each unit is about as big as its random start, so the raw weights stay noisy; the change since epoch 0 shows what training added. Look for the pixels that never change: five of them are blank in every training image, so no gradient ever reaches their weights.

Then, once you've decided everything, and only then, the test set:

06-digits.ipynb

96.9% on 360 digits the network and you have never looked at. It's the number to report. If you now changed the model and ran the test again, it would become one more validation set (lesson 2.9).

Wrong way: batches that are never shuffled

Some datasets come sorted: every 0, then every 1, and so on. Train on them in that order, without shuffling:

06-digits.ipynb

The last batch's loss is 0.051, which looks fine, but only 43.6% of the validation digits are right, and 164 of the 360 are called 9. Each epoch ends with a run of batches that are all 9s, and each of those steps says "whatever this is, it's a 9". The last thing the network learned is the thing it believes. A mini-batch's gradient only points the right way on average if the batch is a fair sample of the data, and a batch of one class never is.

The fix is the line in step 2: rng.permutation, a new order every epoch. PyTorch's DataLoader(..., shuffle=True) does the same (lesson 7.2).

Check what you learned

The training accuracy is still rising at epoch 30, but the validation accuracy hasn’t risen since epoch 20. What should you do?
In a confusion matrix with rows for the true digit, what does the number in row 8, column 1 count?
Why does the unshuffled run in step 6 call so many digits 9?

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