Deep Learning from the Outside: Examples In, Predictions Out
Some tasks are easy for people and very hard to write down as rules, such as reading a handwritten digit. Deep learning solves tasks like these another way: a program is shown many examples with their correct answers and adjusts itself until its own answers match. This page looks at that idea from the outside: what such a program learns from, the cycle that trains it, the library that does the work, and what an image looks like to a program that only ever sees numbers.
Rules a person writes, or examples a program learns from
Most programs follow rules a person wrote. A program that adds up a shopping bill does exactly what its author told it to, and the author could explain every step. That works whenever a person can say precisely how the task is done.
Now try to write the rules for recognising a handwritten 7. It has a line across the top and a line going down. But some people cross the down stroke, some curve the top, some write it leaning, small or thick, and a quick 1 can look almost the same. Every rule you add meets handwriting that breaks it. The difficulty is not the programming: nobody can state the rules at all, even though anyone can read the digit.
Learning from examples turns the problem round. Instead of writing the rules, you collect many examples of the task done right: thousands of images of handwritten digits, each with the digit it shows. A learning program starts out answering badly, compares its answers with the correct ones, and changes itself a little at a time until it answers well. Nobody writes down how to recognise a 7; the program ends up with its own way of doing it, built from the examples.
- A person writes the rules
- Rules in code followed step by step
- Answer
- A person to Rules in code
- Rules in code to Answer
- Examples input and correct answer
- Learning program adjusts itself on the examples
- Answer predicted for a new input
- Examples to Learning program
- Learning program to Answer
This approach fits tasks where examples are easy to collect and rules are hard to state: reading handwriting, recognising objects in photos, turning speech into text. It is the wrong tool where the rules are known and must be followed exactly, such as calculating tax or sorting a list: a learned program would only be an approximate copy of rules you already have.
True or false?
A program that learns from examples still needs a person to write the rules for the task, only in a simpler form.
False. Nobody writes the rules. The program is given examples with correct answers and adjusts itself until its answers match them.
Learning from examples suits tasks people do easily but cannot explain step by step.
True. Reading handwriting is a good case: anyone can do it, nobody can list the rules, and examples are easy to collect.
A neural network, seen from the outside
The learning program is usually a neural network. From the outside it is simply a function: an input goes in, a prediction comes out. For a digit reader, the input is an image and the output is one score for each digit from 0 to 9; the digit with the highest score is the prediction.
What makes it learnable is that the function contains many adjustable numbers. Think of a function that converts a temperature with two dials, \( \text{output} = a \times \text{input} + b \). Turn \(a\) to 1.8 and \(b\) to 32, and it turns 10 degrees Celsius into 50 degrees Fahrenheit. With other settings it gives other answers. Nobody has to know the right settings in advance: if you have examples of correct conversions, you can turn the dials a little at a time until the outputs match. A neural network works the same way, only with thousands or millions of dials instead of two, and the right settings are found from the examples, never written by hand.
A network is built in layers. The first layer computes from the input numbers, the next layer computes from what the first produced, and so on until the last layer gives the scores. Deep learning is the training of such networks built from several layers in a row; the word deep refers to that stack of layers, not to anything mysterious about the method.
- Image pixel numbers
- Layers adjustable numbers
- 10 scores one per digit
- Prediction highest score
- Image to Layers
- Layers to 10 scores
- 10 scores to Prediction
Seen this way, everything a network knows lives in its adjustable numbers. Before training they are set to random values, so the scores are meaningless and the predictions are guesses. Training changes nothing about the computation itself; it only changes those numbers.
True or false?
Training a network changes the steps of its computation.
False. The computation stays fixed. Training only changes the adjustable numbers the computation uses.
The deep in deep learning refers to a network made of several layers, each computing from the one before.
True. Deep describes the stack of layers between the input and the output.
The training cycle
Every training run, from a small digit reader to a very large model, is made of the same four parts:
- The data: the examples, each an input with its correct answer.
- The model: the network, a function with adjustable numbers that turns an input into a prediction.
- A measure of how wrong the model is: one number, called the loss, that is small when the predictions match the correct answers and large when they do not.
- A rule that adjusts the model a little: it changes each adjustable number by a small amount in the direction that makes the loss smaller.
These parts work in a cycle. The model predicts for some examples, the loss says how wrong those predictions were, the rule nudges the numbers, and the cycle starts again with more examples.
- Examples inputs and answers
- Model predicts
- Measure the loss how wrong
- Adjust a little loss goes down
- Examples to Model predicts
- Model predicts to Measure the loss
- Measure the loss to Adjust a little
- Adjust a little to Examples: repeat
The adjustment is small on purpose. A handful of examples gives only a rough idea of which way the numbers should move, and a large change made to fix a few examples can break the answers for many others. Many small steps, each taken from different examples, add up to a model that does well on all of them. That is why training repeats the cycle thousands of times, and why one pass through all the examples is rarely enough.
The temperature function shows one turn of the cycle. Suppose its dials start at \(a = 1\) and \(b = 0\), and an example says 10 degrees Celsius should give 50. The function answers 10, which is 40 too low, so the loss is large. The rule raises both dials slightly, the next answer is a little closer to 50, and the loss shrinks. Repeat that over many examples and the dials settle near 1.8 and 32.
True or false?
The loss is one number that tells the training how wrong the current predictions are.
True. A lower loss means predictions closer to the correct answers, and the adjusting rule works to make it smaller.
Each turn of the cycle sets the adjustable numbers straight to their final values.
False. Each turn moves them only a little. The good values are reached by repeating the cycle many times.
What PyTorch provides
You could write every part of the cycle yourself in plain Python, but it would be slow and the adjusting rule would be hard to get right. PyTorch is a Python library that does the heavy work. Its documentation describes it as an optimized tensor library for deep learning using GPUs and CPUs (a tensor is its name for a grid of numbers), and it gives you three things the cycle needs.
| What PyTorch gives | What it is for |
|---|---|
| Tensors | Grids of numbers that hold the data and the model's adjustable numbers, with fast maths on whole grids at once. |
| Automatic differentiation | Works out, from the loss, which way and how much to change every adjustable number, so you never derive it by hand. |
| Building blocks | Ready-made layers, loss functions and adjusting rules, plus tools to load data and serve it in batches. |
A tensor is PyTorch's container for numbers: a single number, a row of numbers, a table, or a stack of tables, all of one type. Images, labels, scores and the network's adjustable numbers are all tensors. The part that works out the adjustments is called torch.autograd, which the documentation calls the automatic differentiation engine that powers neural network training. A companion library, torchvision, adds what is specific to images, including ready-to-download datasets.
The short example below makes a tiny tensor and asks it for its shape, how many rows and columns it has, and for its type of number.
import torch
numbers = torch.tensor([[0, 128], [255, 64]])
print(numbers.shape) # torch.Size([2, 2]): 2 rows of 2 numbers
print(numbers.dtype) # torch.int64: whole numbersA GPU can make training much faster, but it is optional: PyTorch runs on an ordinary laptop processor, and a small network for handwritten digits trains on one in a reasonable time.
A labelled dataset
The data of the cycle comes as a labelled dataset: a collection of examples, each an input paired with its correct answer, called its label. For a digit reader, the input is an image and the label is the digit it shows, a whole number from 0 to 9.
A well-known dataset of this kind is the MNIST database of handwritten digits, by Yann LeCun, Corinna Cortes and Chris Burges, built from handwriting collected by NIST (the US National Institute of Standards and Technology). Each image is 28 by 28 pixels in shades of grey, with the digit scaled to a standard size and centred in the image. Every image belongs to one of ten classes, the possible answers, which here are the digits 0 to 9.
The authors split the data themselves into a part to train on and a part kept for testing, and ship the two parts as separate files. The reason is simple: a model can do well on the very examples it was adjusted on without having learned anything general. The test part answers the question that matters, how well the model reads digits it has never seen. MNIST makes that test strict: the test images were drawn by different people from the training images, so a good result means the model reads new handwriting, not only familiar writers.
torchvision downloads MNIST for you. train=True gives the training part and train=False the test part; download=True fetches the files into the folder given as root the first time and reuses them after that. Indexing the dataset gives one example as a pair: the image and its label.
from torchvision import datasets
train = datasets.MNIST(root="data", train=True, download=True)
test = datasets.MNIST(root="data", train=False, download=True)
print(len(train), len(test))
image, label = train[0]
print(type(image).__name__, type(label).__name__)60000 10000
Image intWithout further instructions, the image comes back as a picture object from the Pillow imaging library and the label as a plain Python int. A picture object is convenient to look at, but a model needs numbers, which is where the next idea comes in.
True or false?
The test part of a dataset is used to adjust the model, just later than the training part.
False. The test part is kept out of training altogether, so it can show how the model does on examples it has never seen.
In MNIST, the people who wrote the test digits are different from those who wrote the training digits.
True. The test images were drawn by different individuals, so a good test result means the model reads unfamiliar handwriting.
An image is a grid of numbers
A greyscale image is stored as a grid with one number per pixel, the brightness of that pixel. In the usual 8-bit format, which allows 256 different values per pixel, each number is a whole number from 0 to 255: 0 is the darkest possible shade, 255 the brightest, and the values in between are shades of grey. There is no colour, no stroke and no notion of a digit in the file, only the grid.
The small grid below is a made-up 8 by 8 image of a 7, drawn as a bright stroke on a dark background. Each cell shows its stored number and is shaded by it. The soft values along the edges of the stroke, such as 40 or 120, are what makes a scaled-down drawing look smooth instead of jagged; MNIST images have such grey edges too.
An MNIST image is the same idea at 28 by 28: 784 numbers, each from 0 to 255. A torchvision dataset keeps all its images in one tensor, data, and all its labels in another, targets. Reading one image from data shows it exactly as it is stored.
pixels = train.data[0]
print(pixels.shape) # torch.Size([28, 28]): 28 rows of 28 pixels
print(pixels.dtype) # torch.uint8: whole numbers from 0 to 255
print(pixels[14]) # one row of the image, 28 brightness valuesThis is all a model ever receives. It never sees a 7 as a shape; it sees 784 numbers and has to learn which patterns among them go with which label. That is also why the same digit written a little to the left looks, to the model, like a quite different list of numbers, and why it needs many varied examples to learn from.
Before images go into a model, their numbers are usually converted to fractions between 0 and 1, so 0 stays 0 and 255 becomes 1; the pixels and their order stay the same, only the scale changes.
True or false?
A model that reads digits receives the image as a shape it can recognise, such as lines and curves.
False. It receives only the grid of brightness numbers. Any notion of lines or curves has to be learned from those numbers.
An MNIST image read from the dataset's data tensor is a 28 by 28 grid of whole numbers from 0 to 255.
True. It has shape 28 by 28 and type torch.uint8, which holds whole numbers from 0 to 255.