Convolutional Neural Networks: Building Image Features From the Ground Up
Definition
Convolutional Neural Network (CNN)
A neural network designed for data with spatial structure, above all images.
A plain multi-layer perceptron can be pointed at an image, but it handles one badly for two reasons.
Connecting every pixel of a 200 by 200 colour image to every node in the first hidden layer needs 120,000 weights per node, which is unaffordable.
An MLP also treats each pixel position as unrelated to its neighbours, so a cat learned in the top-left corner is unrecognised in the bottom-right.
A CNN fixes both by applying the same small filter across the whole image, which cuts the weight count enormously and makes the detected features work anywhere in the frame.
Analogy
A CNN reads an image the way you would inspect a large painting through a small cardboard window.
You slide the window over the canvas, noting what you see in each position, rather than trying to take in every brushstroke at once.
The same window works wherever you hold it, which is why the feature it detects is not tied to one location.
The Six Stages of a CNN
Input layer
Receives the raw pixel values, arranged as a grid with one channel for greyscale or three for colour.
Convolutional layers
Slide learned filters, also called kernels, across the input to produce feature maps that mark where each feature occurs.
Activation functions
Apply a non-linear function, almost always ReLU, to every value in the feature map.
Pooling layers
Shrink each feature map, keeping the strongest responses and discarding exact positions.
Fully connected layers
Combine the features found anywhere in the image into evidence for each class.
Output layer
Produces the final prediction, usually through a softmax function that turns the scores into probabilities.
Convolution: Sliding a Filter Over the Image
A filter is a small grid of weights, commonly 3 by 3, whose values are learned during training rather than set by hand.
At each position the filter's weights are multiplied by the pixel values underneath and the products are added, which is a dot product.
The resulting number goes into the feature map at the corresponding position, so a high value marks a position where the filter's pattern is present.
Each convolutional layer applies many filters at once, producing one feature map per filter.
Example
A filter tuned to vertical edges holds positive weights down one column and negative weights down the other.
Where the image has a light-to-dark vertical boundary, the dot product is large and the feature map lights up.
Where the image is flat, the positive and negative weights cancel and the feature map stays near zero.
The network is never told to look for vertical edges, and filters like this emerge because they reduce the training error.
Pooling: Shrinking the Feature Map
Max pooling takes the largest value in each small window, typically 2 by 2, and discards the rest.
Halving the width and height cuts the number of values by four, which reduces computation in every later layer.
Keeping only the maximum records that a feature was present in the region while forgetting its exact position, which is why a shape shifted a few pixels still registers.
The cost is deliberate information loss, so pooling too aggressively throws away detail the classification needed.
Analogy
Pooling is like summarising a paragraph in one sentence.
You keep the point that was made and lose the exact wording.
Do it too often and there is nothing left to reason with.
From Feature Maps to a Decision
After the last pooling layer the feature maps are flattened into a single list of values.
The fully connected layers then work like an ordinary MLP, with every value connected to every node.
These layers do the reasoning, weighing up which combinations of detected features point to which class.
The output layer carries one node per class, and softmax scales its values so they are all positive and sum to 1.
Example
In a cat-versus-dog classifier the softmax output might read 0.8 for cat and 0.2 for dog.
Those numbers are the model's confidence, so the image is labelled cat with 80% confidence.
The values always sum to 1, which is what makes them readable as probabilities rather than raw scores.
The Four Design Choices That Shape a CNN
Number of Layers
More convolutional layers let the network build features from features, so it can represent more abstract structure.
Depth is what allows a network to move from edges, to textures, to object parts, to whole objects.
Deeper networks need more training data and more computation, and they overfit more readily on a small data set.
Depth also makes training harder, because the error signal weakens as it is propagated back through many layers.
Common Mistake
Depth is not free accuracy.
A three-layer CNN trained on 500 images will usually beat a thirty-layer CNN trained on the same 500 images, because the deep network memorises them.
Match the depth to the amount of data available.
Kernel Size and Stride
Kernel size sets how much of the image each filter sees at once.
A small kernel such as 3 by 3 captures fine local detail and uses few weights.
A large kernel such as 7 by 7 captures broader structure in one step but costs far more weights per filter.
Stride sets how far the filter moves between positions.
A stride of 1 evaluates every position and gives a detailed feature map the same size as the input.
A stride of 2 skips every other position, which halves the feature map's width and height and speeds the network up at the cost of resolution.
Note
Modern designs favour stacking small kernels over using one large one.
Two 3 by 3 layers cover the same area as one 5 by 5 layer, using fewer weights and adding an extra non-linearity in between.
This is a useful example of a design decision made on the trade-off rather than on which option sounds more powerful.
Activation Function Selection
The role of an activation function and the shapes of ReLU, sigmoid and tanh are covered under artificial neural networks.
ReLU is the default in CNN hidden layers because it costs one comparison to compute and keeps the error signal strong through many layers.
Leaky ReLU is used when too many nodes have stopped responding, since it lets a small signal through for negative inputs instead of zero.
Softmax belongs in the output layer of a multi-class classifier, and sigmoid in the output layer of a two-class one.
Common Mistake
Using sigmoid or tanh in the hidden layers of a deep CNN causes the vanishing gradient problem.
Both functions flatten out at their extremes, so the error signal shrinks towards zero as it passes back through each layer and the early layers barely learn.
ReLU does not flatten for positive inputs, which is the main reason it replaced them.
The Loss Function
The loss function measures how wrong a prediction was and is the quantity training minimises.
Cross-entropy loss is the standard choice for classification, and it compares the predicted probabilities against the correct label.
It punishes confident mistakes heavily, so predicting 0.99 for the wrong class costs far more than predicting 0.6 for it.
Mean squared error is used instead when a CNN predicts a number, such as the position of a bounding box.
Choosing the wrong loss function undermines everything else, since the network will optimise faithfully towards the wrong target.
Note
Loss and the evaluation metrics are not the same thing.
Loss is what training minimises and must be smoothly differentiable, whereas accuracy, precision and recall are what humans read afterwards.
This is why a report shows both a falling loss curve and a rising accuracy figure.
Spatial Hierarchies and Where CNNs Are Used
A spatial hierarchy is the layered progression of features the network learns, from local to global.
Early layers respond to edges and colour gradients, middle layers to textures and corners, and late layers to object parts.
The word adaptively in the syllabus statement points at the key fact: the filters are learned from the data, not designed by an engineer.
Image classification assigns one label to a whole photograph.
Object detection finds and labels several objects and returns their positions.
Medical imaging flags anomalies in X-rays and MRI scans, where a CNN can be trained on more labelled scans than a radiologist sees in a career.
Autonomous vehicles use CNNs to read lane markings, signs and pedestrians from camera feeds.
Active recall
Give two reasons a plain MLP handles images badly.
Name the six stages of a CNN in order.
What is a feature map, and how is one produced?
Explain what max pooling does and one thing it costs you.
What is the effect of increasing the stride from 1 to 2?
Why is ReLU preferred over sigmoid in the hidden layers of a deep CNN?
What does cross-entropy loss measure, and how does it differ from accuracy?