How a neural network reads handwritten digits
Reading a handwritten digit is easy for people and was hard for computers for decades: everyone writes a 7 a little differently, and no simple rule says which pixels make a 7. Neural networks solved it by learning from examples instead of rules. This page explains how the Digit Recognizer app turns your drawing into numbers, how its small network weighs them, how it was trained, and where it still goes wrong.
A problem without rules
Try to write down rules for recognising a 4: two lines meeting at an angle, a vertical stroke on the right, maybe a closed top, maybe not, slanted or upright, thick or thin. Every rule has exceptions, and the exceptions have exceptions. In the 1980s and 1990s postal services and banks needed machines that could read postcodes and the amounts on cheques, and the methods that worked best did not use hand-written rules at all: they learned from thousands of labelled examples. By the late 1990s, Yann LeCun's convolutional networks from Bell Labs were reading more than a tenth of all cheques written in the United States.
MNIST, the classic dataset
MNIST, the Modified National Institute of Standards and Technology database, was put together by Yann LeCun, Corinna Cortes and Christopher Burges in 1998 from digits written by American census employees and high-school students. It holds 60,000 training digits and 10,000 test digits by different writers, each a 28 × 28 image of grey levels. For a quarter of a century it has been the first benchmark of new machine learning methods: a straight-line classifier gets about 92 % of the test digits right, a small network like the app's about 98 %, and the best convolutional networks over 99.7 %, close to the limit set by digits that even people cannot read.
Preparing the drawing
A network that has seen MNIST expects its input made the same way, so the app repeats the recipe. It takes the bounding box of your ink, the dashed rectangle on the pad, and scales it so that its longer side fits 20 pixels while the shape keeps its proportions; a 1 stays tall and thin. The strokes are drawn into the grid with soft edges, so a pixel half covered by ink becomes a mid grey. Then the picture is moved so that its centre of mass, the average position of the ink weighted by how dark it is, lands exactly in the middle of the 28 × 28 grid, which leaves a margin of about four pixels around the digit. A digit drawn small in a corner and one drawn across the whole pad end up as nearly the same 784 numbers. In the photo editor the same steps are applied to a picture: the ink is found against the background, cropped, averaged down into the 20 × 20 box and centred.
The network: weighted sums, ReLU and softmax
The app's network is a multilayer perceptron with 784 inputs, a hidden layer of 64 units, a second hidden layer of 32 units and 10 outputs. Every unit of a layer is connected to every unit of the layer before: it multiplies each input by a weight, adds them up with a bias, and passes the sum through the rectified linear unit, ReLU(x) = max(0, x), which lets positive signals through and silences negative ones. Without such a bend the layers would collapse into one straight-line classifier. The ten outputs zₖ are turned into probabilities by the softmax, pₖ = e^zₖ / Σ e^zⱼ, which makes them positive and adds them up to one; the digit with the largest probability is the answer and the second largest is the runner-up. In all the network has 52,544 weights and 106 biases.
What the hidden units learn
A first-layer unit's 784 weights can be drawn as a 28 × 28 picture, and the app does so: orange where ink makes the unit fire, blue where ink holds it back. Nobody designed these pictures; they came out of training. Many look like pieces of strokes in particular places, a curve at the top, a bar through the middle, a gap on the left where a 3 or a 7 has no ink, and many are mixtures that are hard to name, because the network spreads what it knows over many units. The second layer combines these detectors into larger clues, and the output layer weighs the clues for each digit. The lines in the picture show the connections that carry the most signal for the drawing on the pad.
Training: backpropagation and Adam
Training started from small random weights. For a batch of 128 training digits the network computed its probabilities, and the loss measured how wrong they were: the cross-entropy, minus the logarithm of the probability given to the correct digit, which is zero for a certain right answer and grows without limit for a confident wrong one. Backpropagation, the chain rule applied layer by layer from the output back to the input, gives the derivative of the loss with respect to every weight, and the Adam optimiser takes a small step against it. To make the network robust to handwriting unlike the samples, every training digit was also used in copies that were rotated by up to 14°, slanted, stretched and drawn thicker or thinner, then normalised again exactly as the app normalises a drawing, and about 5,000 digits typed in 84 typefaces were added so that printed digits are read too. After 14 passes over these 260,000 images, which took about a minute on an ordinary processor with numpy, 98.1 % of the 10,000 test digits were right. The weights were then rounded to 8-bit integers with one scale per unit, which kept the accuracy and shrank them to about 52 KB.
Where it fails, and what does better
The network sees grey values, not pen movements, and it has learned the habits of the MNIST writers. A 4 with a closed top shares most of its ink with a 9, a 1 with a long flag is a 7 without its bar, a 7 with a crossbar was rare in the American training data, and the probabilities split accordingly. Anything that is not a digit, a letter or a doodle, still gets a digit, often with high confidence, because a softmax classifier must choose among the classes it knows; real systems add a reject option or a separate check. Convolutional networks, which slide small learned filters over the image so a stroke is recognised wherever it is, reach under 0.3 % error on MNIST, and today's handwriting recognisers read whole words and lines using the order of the strokes as well as their shape.
Поширені запитання
Why 28 × 28 pixels?
That is the format of MNIST. The digits were first scaled to fit a 20 × 20 box and then placed in a 28 × 28 image centred by their centre of mass, which leaves room for the digit to be off-centre without being cut off. Any network trained on MNIST expects input in this form, so the app turns your drawing into exactly that.
Is this a deep neural network?
It has two hidden layers, so it is a small deep network, but much shallower than the networks used for photographs or speech. A multilayer perceptron like this treats every pixel separately; convolutional networks such as LeNet-5 (1998) share their weights across positions and do better on images with fewer weights.
How accurate is the app's network?
It classifies 98.1 % of the 10,000 MNIST test digits correctly, about one mistake in 50. On drawings made with a mouse the accuracy is usually similar for clearly written digits and lower for unusual styles, because mouse strokes are smoother and more even than pen on paper.
Can the network learn from my drawings?
No. Its weights were trained once, offline, and are fixed in the page; recognising a drawing only runs the network forwards. Learning from new drawings would need their correct labels, the backward pass and many examples, and would risk making the network worse at the digits it already knows.
Готові спробувати?
Відкрийте PictorX у браузері — без встановлення і без кредитної картки.
Open the digit recognizer