Chapter 21 // Neural Networks

A Real Dataset.

Does the network we built on toy spirals work on real pictures?

Reading time
18 min
Data

Seven chapters have gone into building a network piece by piece, always on a few hundred invented points. This chapter is the test. We take the same pieces, change nothing about how they work, and point them at 70,000 photographs of clothing.

The network in the figures below is real. It was trained by the code at the end of this chapter, and your browser is running its forward pass.

Pictures are numbers

The dataset is called Fashion-MNIST. It holds 70,000 small greyscale photographs of clothing, each labelled with one of ten kinds: T-shirt, trouser, pullover, dress, coat, sandal, shirt, sneaker, bag and ankle boot. Sixty thousand are for training and ten thousand are held back for testing.

To a network a picture is not a picture. Each image is a grid of 28 by 28 squares, and each square, a , is one number from 0 to 255 saying how bright it is.

Figure

An image, one number at a time

Loading the trained network and 500 test images (about 600 KB)…
Sixteen of the test images. The large one is the selected image, enlarged so that single pixels are visible. Try it: move over the large image and watch the brightness change between the clothing and the background. Then pick a different image.

Our dense layers expect a list of features, not a grid. So each image is unrolled, row after row, into one list of 28×28=78428 \times 28 = 784 numbers. This is called . The network will have 784 inputs, one per pixel.

Flattening throws something away: the network is no longer told which pixels were neighbours. It can still learn a great deal, as we are about to see, and the next chapter introduces a kind of layer that keeps the grid.

Preparing the data

Two small steps come before any training, and both matter more than they look.

Scale the inputs. Pixel values run from 0 to 255. Fed in raw, they would make the first layer’s sums enormous and the first gradients wild. Subtracting 127.5 and dividing by 127.5 maps every pixel into the range −1 to 1, where the weights’ starting values and the learning rate behave as intended.

scaled=pixel−127.5127.5\text{scaled} = \frac{\text{pixel} - 127.5}{127.5}

Shuffle the examples. Datasets are often stored in order: all the T-shirts, then all the trousers. A network fed batches of only one class at a time would lurch toward predicting that class, then the next, and learn nothing stable. Shuffling makes every batch a fair mixture. We reshuffle before every pass through the data.

Checkpoint

Whatever scaling is applied to the training images, what must be done to a new image before the trained network sees it?

Training in batches

With 60,000 images we can no longer compute the gradient on all the data for every step, as we did on the spiral. Instead the data is cut into mini-batches, as described. The here is 128.

Training images60,000
Batch size128
Steps in one epoch60,000 ÷ 128, rounded up = 469
Epochs5
Total training steps2,345

The network is the one from the last four chapters, only larger: 784 inputs, two hidden layers of 64 ReLU neurons, and 10 softmax outputs. That is 55,050 learnable numbers. The optimizer is Adam with a learning rate of 0.001.

Figure

The real training run

Loading the trained network and 500 test images (about 600 KB)…
The grey line is the loss on individual batches. The orange line is the average over each epoch. This is a recording of the run that produced the network on this page. Try it: compare the jagged grey line with the smooth orange one. Then read down the test accuracy column.

The loss on single batches is jagged, because each batch is a different random handful of images. Its trend is unmistakable. Before training the network scored 8% on the test set, no better than guessing among ten classes. After one pass through the data it scored 84.6%, and after five, 86.9%.

Nothing was added to achieve this. The layers, the loss, the backward pass and the optimizer are the ones built on spiral data. The same machinery scales from 300 points to 60,000 images without change.

How good is it?

An accuracy of 86.9% says how often the network is right. It does not say where it goes wrong, and for that we need the confusion matrix from , now with ten classes instead of two.

Figure

Which clothes get mixed up

Loading the trained network and 500 test images (about 600 KB)…
Computed live from 500 test images, 50 of each kind. Dark cells on the diagonal are correct answers; orange cells are mistakes. Try it: click the orange cells to see the images behind each kind of mistake. Then click a dark cell on the diagonal for comparison.

The mistakes are not spread evenly. Trousers, sandals and sneakers are almost always right: 49 out of 50 each. Shirts are right only 33 times out of 50, and when they are wrong they are called T-shirts, pullovers or coats. The single commonest error is a T-shirt called a shirt.

These are the mistakes a person would make with a blurry 28-pixel image. The network is not confusing a boot with a bag. It struggles exactly where the classes really do look alike, which is some evidence that it has learned something sensible about shape.

Using the network

Training is over. What remains is the reason for all of it: using the network on images it has never seen. This is called , and it needs only a forward pass. No loss, no backward pass, no updates.

Figure

The trained network, running in your browser

Loading the trained network and 500 test images (about 600 KB)…
Each bar is the network's probability for one class. The dark bar is its answer. Try it: step through a dozen images. Then press the mistake button a few times and look at how confident the network was each time it was wrong.

It is worth being clear about what the “trained network” is. It is 55,050 numbers. Your browser downloaded them as a 220-kilobyte file, placed them into three weight matrices and three bias vectors, and multiplied. Saving a model means writing those numbers to a file. Loading it means reading them back into a network of the same shape. The architecture is the recipe, and the weights are everything that was learned.

The code at the end of the chapter demonstrates this directly. A freshly created network of the same shape scores 5% on the test set. After the saved numbers are copied into it, with no training at all, it scores 86.9%.

Checkpoint

You want to send a trained network to a colleague so they can use it. What do they need?

In code

The complete program is code/ch21_fashion.py. It wires the classes from the previous chapters into a Model, and its training loop is the one from the backpropagation chapter with a loop over batches added.

def scale(images):
    return (images.astype(np.float32) - 127.5) / 127.5        # 0..255 becomes -1..1

model = Model(rng)                                             # 784 -> 64 -> 64 -> 10
optimizer = Optimizer_Adam(learning_rate=0.001, decay=1e-4)

for epoch in range(1, epochs + 1):
    order = rng.permutation(len(X_train))                      # a fresh shuffle every epoch
    for start in range(0, len(order), batch_size):
        batch = order[start:start + batch_size]
        loss = model.forward(X_train[batch], y_train[batch])   # forward pass and loss
        model.backward(y_train[batch])                         # backward pass
        optimizer.update(model.dense)                          # update

    print(epoch, model.evaluate(X_test, y_test))               # accuracy on the held-out test set

saved = model.get_parameters()                                 # saving: just the numbers
fresh = Model(np.random.default_rng(123))
fresh.set_parameters(saved)                                    # loading: put them back
print(model.predict(X_test[:5]))                               # inference: forward pass only

Running it prints the table in the training figure: 84.6% after the first epoch and 86.9% after the fifth.

Key Takeaways

  • An image is a grid of numbers. A dense network reads it flattened into one list: 784 inputs for 28 × 28 pixels.
  • Scale inputs to a small range and shuffle before every epoch. New inputs must be scaled the same way.
  • Large datasets are trained in mini-batches: here 469 steps per epoch.
  • A confusion matrix shows which classes are mixed up, which accuracy alone hides.
  • A trained model is its architecture plus its weights. Inference is a forward pass.
You can now
  • Describe how an image becomes the input to a dense network.
  • Prepare image data for training: scale it, shuffle it and cut it into batches.
  • Count the weights in a network and the steps in an epoch.
  • Read a ten-class confusion matrix, and save and reload a trained model.

Exercises

Try each one before opening its solution. Getting stuck for a few minutes is where most of the learning happens.

Exerciseby hand

The network has 784 inputs, two hidden layers of 64 neurons and 10 outputs. How many weights and biases does it have in total?

Hint

Each layer has (inputs × neurons) weights, plus one bias for each neuron.

Solution

Each layer has one weight for every pair of input and neuron, plus one bias per neuron.

  • First hidden layer: 784×64+64=50,240784 \times 64 + 64 = 50{,}240
  • Second hidden layer: 64×64+64=4,16064 \times 64 + 64 = 4{,}160
  • Output layer: 64×10+10=65064 \times 10 + 10 = 650

That makes 55,050 numbers. More than nine tenths of them are in the first layer, because every one of its neurons is connected to every pixel.

Exerciseby hand

There are 60,000 training images and the batch size is 128. How many steps are in one epoch, and how many images are in the last batch? How many updates does the network receive in five epochs?

Hint

Divide 60,000 by 128. The remainder forms a last, smaller batch.

Solution

60,000/128=468.7560{,}000 / 128 = 468.75, so there are 468 full batches and one smaller one: 469 steps.

The full batches use 468×128=59,904468 \times 128 = 59{,}904 images, leaving 96 for the last batch.

Five epochs give 5×469=2,3455 \times 469 = 2{,}345 updates. On the spiral, one update used all the data. Here each update sees about a fifth of one percent of it, and that is enough.

Exerciseby hand

Pixels are scaled by subtracting 127.5 and dividing by 127.5. What do the pixel values 0, 255 and 51 become? Why must an image given to the finished network be scaled the same way?

Hint

Apply (pixel − 127.5) ÷ 127.5 to each value.

Solution
  • 0 becomes −127.5/127.5=−1-127.5 / 127.5 = -1
  • 255 becomes 127.5/127.5=1127.5 / 127.5 = 1
  • 51 becomes −76.5/127.5=−0.6-76.5 / 127.5 = -0.6

The network’s weights were learned for inputs between −1 and 1. Hand it a raw image and its first layer receives numbers over a hundred times larger than it has ever seen. The sums are enormous and the output is meaningless. The scaling is part of the model, as much as the weights are.

Exercisethink

The confusion matrix shows that shirts are often mistaken for T-shirts, pullovers and coats, while trousers are almost never mistaken for anything. Why might that be? Would changing a threshold help? What would?

Hint

Think about how the outlines of those four garments compare at 28 by 28 pixels.

Solution

Shirts, T-shirts, pullovers and coats have nearly the same outline at 28 by 28 pixels: a torso and two sleeves. They differ in small details such as collars, buttons and sleeve length, which take up only a few pixels. Trousers have a shape nothing else shares.

There is no threshold to move. The network picks the class with the highest probability, and the trouble is that it gives the wrong class the highest probability.

What helps is a network that can see small local details, which a flattened image makes hard, because the pixels of a collar are scattered across the list of 784 inputs. Layers that keep the picture as a grid do much better. More training examples of the confused classes also help.

Exercisewith the figure

In the figure “Which clothes get mixed up”, click the cell for shirts that the network called T-shirts, and look at the images. Then click the diagonal cell for trousers. What do the mistaken images have in common, and why are trousers so easy?

Hint

Imagine each image blurred. Which garments would you still tell apart?

Solution

Look at what the mistaken images share: each is a torso with two sleeves, and whatever makes it a shirt, a collar or a row of buttons, is a handful of pixels at this size. A person would hesitate over several of them too. The network’s errors are concentrated where the classes really do look alike.

Trousers are right 49 times out of 50 because their outline, two long legs, is shared by nothing else in the dataset. A network that only compares overall shapes can separate them easily and has trouble exactly where the difference lies in small details.

Going further

Where this part of the book ends

You have now built, from a single weighted sum, everything inside a working neural network: layers, activations, a loss, backpropagation, optimizers, regularization and three kinds of output. Modern networks are far larger and use more specialised layers, but they are trained by this loop. The two chapters that follow introduce two of those layers: one made for images, and one made for sequences such as text.

Doing better than 87%

This network ignores the fact that an image is a grid. Convolutional layers, which look at small patches and reuse the same weights everywhere, typically pass 90% on this dataset. Training longer, adding dropout, or making the hidden layers wider also helps a little. The remaining mistakes, shirts against T-shirts and coats, are hard for people too.

Frameworks

In practice nobody writes backward passes by hand. Libraries such as PyTorch provide the layers, compute the gradients automatically and run on graphics processors. Having built each piece once, you know what every line of such a program is doing.

References and further reading

Last updated Spotted a mistake? Suggest an editWhat changed

In this chapter
  1. Top of the chapter
  2. 21.1Pictures are numbers
  3. 21.2Preparing the data
  4. 21.3Training in batches
  5. 21.4How good is it?
  6. 21.5Using the network
  7. 21.6In code
  8. Exercises
Search‹ Previous
Search

    The Book of Machine Learning
    Search
    Reading settings
    Text size
    Colours

    Saved in this browser only.

    Keyboard shortcuts
    /
    Search the book
    ← →
    Previous and next chapter
    g
    Glossary
    c
    Table of contents
    e
    Jump to the exercises
    t
    Reading settings
    ?
    Show this list
    Esc
    Close a window or pop-in