Paul's Python CoursePPC

Project 4 of 14, for Aaesha

Handwritten Digit Recogniser

Perception, from sixty-four greys: a NumPy network learns to read 1,797 real handwritten digits, 8 by 8 greys, with softmax, cross-entropy, mini-batches and Adam, and a test on 297 digits it has never seen.

About 2 hours, in 13 steps.

Sign up free to open itLog in

Act 7 needs a free account, so your work is saved as you go. Act 1 is open to everyone.

The brief

  • AaeshaYou read handwriting without trying, and nobody can quite say how. Let's see what a network makes of it.
  • AaeshaWe've got 1,797 real handwritten digits, scanned to eight by eight squares of grey, and some of the fours look like nines.
  • NeilAnd some of the nines look like fours that gave up halfway.
  • AaeshaEvery network so far has said yes or no, but this one has to pick one answer out of ten.

In digits.py, teach the network from the Optimiser Benchmark to read handwritten digits: 1,797 of them, each an 8 by 8 grid of greys from 0 to 16, loaded by notebooks.py. training.py holds init_params, batches and Adam from that Job.

  1. one_hot(labels, classes): a row per label, with 1 in that label's column and 0 everywhere else.
  2. softmax(Z): each row of scores into chances that add up to 1, without overflowing however big the scores are.
  3. cross_entropy(P, labels): the mean, over the rows, of minus the log of the chance each row gives its right answer.
  4. forward(X, params): a ReLU hidden layer, then softmax. It returns the chances, one row per image, and a cache, as in Neural Network from Scratch.
  5. backward(X, labels, params, cache): the gradient for every weight and bias. The blame at the scores is the chances minus the one-hot answers, divided by the number of rows. No loops.
  6. accuracy(P, labels): the fraction of rows whose biggest chance is on the right digit.
  7. train(X, labels, params, optimiser, epochs, batch_size, rng): mini-batch training, as in the Optimiser Benchmark. It returns the cross-entropy on every row of X after each epoch.
  8. Run as a program, it learns from 1500 of the digits, then reads the 297 it was never shown.
What it prints
Loss: 0.543 after the first epoch, 0.029 after the last
Read 293 of 297 digits it had never seen
Misread: 4 as 7, 9 as 5, 9 as 8, 8 as 1

What you learn

What's in it

  1. A picture is a grid of numbers
  2. The digits
  3. Ten scores into ten chances
  4. Too sure to count
  5. The answer as a row
  6. How wrong is a choice?
  7. Knowing nothing
  8. The tidiest gradient
  9. How Paul would do it
  10. Fix Yahya's version
  11. Reading handwriting
  12. Ship it