AI voor Iedereen

Search

Search chapters and demos

πŸ‘οΈ Convolutional Neural Networks

Click one of the photos below. The neural network behind this demo says what is in it, with a probability for each of its five best guesses.

Loading demo

How can a program do that? To a computer, a photo is nothing more than a grid of numbers: every pixel is a number that says how light or dark that tiny dot is, from 0 (black) to 255 (white). A color photo has three such numbers per pixel (red, green and blue), but to keep things simple we mostly stick to grayscale in this chapter.

On the left a black-and-white photo of a cat with a small orange square on the border between the dark window frame and the cat's light fur; on the right that same patch enlarged as a grid of 8 by 8 numbers that run from 54 on the left to 175 on the right.
This is how the computer sees the photo: a grid of numbers. The square of 8 Γ— 8 pixels lies on the border between the dark window frame and the cat's light fur, and you can see that border in the numbers: low on the left, high on the right.

Recognizing a cat in that sea of numbers seems hopeless. Yet your eyes do not work pixel by pixel either. You first recognize small pieces (an edge here, a spot there), combine those into parts (an ear, an eye, a whisker) and finally those into a whole: a cat. A convolutional neural network (CNN) works exactly like that, from small to large.

Pyramid of CNN features: layer 1 detects edges and lines, layer 2 textures and corners, layer 3 parts such as eyes and wheels, layer 4 whole objects such as cats and cars.
The common thread of this chapter: a CNN builds up what it sees in a photo from small to large. The first layer finds edges, the next layers combine those into corners and textures, then into parts and finally into a whole object.

Such networks are inside the face recognition that unlocks your phone, in software that checks X-rays and skin spots, in apps that recognize plants, in self-driving cars that read traffic signs and in the programs that make handwritten archive documents readable for historians.

In this chapter we build up the idea step by step. First the building block: a small filter that looks for one pattern. Then how such a filter is really a neuron, and how you turn such neurons into a network that climbs from edges to objects. Finally how you can see where the network is looking, what it does well and where it goes wrong. The math is always kept apart in the in-depth sections; you can skip those without losing the thread.

πŸ”¦ The building block: a filter

πŸ” Looking for a pattern with a stamp

Suppose you want to know where in a grid of pixels there is a short vertical line. You make a small stamp of 3 Γ— 3 squares that holds the pattern you are looking for, and you place it on every position of the grid. At every position you ask the same question: how well does my stamp fit here?

Such a stamp is called a filter, also known as a kernel. Every square of the filter holds a number, in our example +1, 0 or βˆ’1:

  • +1 means "here I expect a filled pixel",
  • βˆ’1 means "here I expect an empty pixel",
  • 0 means "here I don't care".

The "how well does it fit" number is a weighted sum, just like the points tally of a neuron: multiply every pixel under the window by the filter number at the same position, and add everything up. A filled pixel where the filter expects one counts +1; a filled pixel where the filter expects none counts βˆ’1. The higher the total, the better the pattern fits here.

Try it yourself. The image below is a tiny grid of 7 Γ— 7 pixels (1 = filled, 0 = empty) with the letter T on it, and the filter looks for a short vertical line. Click "Play" or step through the positions with the arrows: the window moves one position at a time, in the middle you see the calculation, and on the right the result fills a new grid square by square. You can also click pixels to draw something yourself, and click the squares of the filter to look for a different pattern.

Loading demo

In the middle of the stem of the T, the filter gives a 3: all three squares under the middle column are filled and the side columns are empty. On the crossbar of the T, the same filter gives 0 or less, because there the side columns are filled too, and those count negatively. Look at the window in the middle of the crossbar yourself (the middle square of the top row in the grid on the right). Why does it come out at exactly 0?

Solution

πŸ—ΊοΈ The feature map

The grid on the right in the demo is the actual result of the filter. It is a new, slightly smaller grid with one number at every position: how strongly the pattern of the filter is present there. Such a grid is called a feature map: a map that does not say what the photo looks like, but where a certain feature is. Sliding the filter over the whole grid, with that weighted sum at every position, is called a convolution.

Convolution, filter and feature map Definition

A convolution is an operation in which a small filter slides over an image. At every position, it multiplies the pixel values under the filter by the filter values and adds them up into one number. All those numbers together form the feature map: a new image that shows where the pattern of the filter occurs.

The feature map is slightly smaller than the image (5 Γ— 5 instead of 7 Γ— 7), because the window cannot look beyond the edge. In the in-depth section further on you see how to deal with that; for the idea it makes no difference.

βœ–οΈ The convolution as a formula

The value Pi,jβ€²P'_{i,j} at position (i,j)(i,j) of the feature map is the weighted sum of the 9 pixel values under the filter:

Pi,jβ€²=βˆ‘m=βˆ’11βˆ‘n=βˆ’11Km,nβ‹…Pi+m, j+nP'_{i,j} = \sum_{m=-1}^{1} \sum_{n=-1}^{1} K_{m,n} \cdot P_{i+m,\, j+n}

Here Pi,jP_{i,j} is the pixel value at position (i,j)(i,j) of the image and Km,nK_{m,n} the filter value at position (m,n)(m,n) in the 3 Γ— 3 filter, with (0,0)(0,0) the middle square. In a CNN, a bias bb is added per filter and the result goes through an activation function; you see that in the next section.

Strictly mathematically, this operation is a cross-correlation: in a true convolution the filter is flipped first. Because the network learns its filters itself anyway, that makes no difference in practice, and in deep learning the operation is simply called "convolution".

πŸ“· The same trick on a real photo

In a real photo the pixels are not 0 or 1 but gray values from 0 to 255 (or three layers of gray values together: one each for red, green and blue), and the filter values are not limited to βˆ’1, 0 and +1. Yet the calculation stays exactly the same: multiply and add. The demo below does that with a filter that looks for vertical edges (negative numbers on the left, positive on the right, called "Sobel vertical"). It opens on a simple drawing of three shapes; the thumbnails hold real photos. Click a point in the image to see the calculation for that pixel. Where the image jumps from dark to light, the total is large. On a flat area the pixels under the window are about the same, the positive and negative filter values cancel each other out and the total is almost zero.

Loading demo

Also try the horizontal variant and the Laplacian filter, which finds edges in every direction. In such edge detection filters the filter values add up to zero, so flat areas stay black and only the edges light up.

Other numbers in the filter give a very different effect. If you set all nine values to 1/9, the filter computes the average of the surrounding pixels at every position and the photo becomes blurry. A large positive value in the middle with negative values around it makes the photo sharper instead. These are the filters that photo editing programs have been using for decades.

Loading demo

🎨 Color photos: three numbers per pixel

A color photo consists of three layers or channels (red, green and blue), each a grid of numbers from 0 to 255. The handmade filters above are 2D: they process each channel separately with the same nine numbers. Click R, G or B in the demo to see that.

Loading demo

A learned CNN filter, on the other hand, is 3D: on a color photo a 3 Γ— 3 filter has not 9 but 3Γ—3Γ—3=273 \times 3 \times 3 = 27 weights, with separate values for each channel, and the three partial sums are added up into one number. That way the network can discover that a transition from red to green means something different from a transition from light to dark. Exactly the same happens in the deeper layers, where the "channels" are the feature maps of the previous layer: a filter then has 3Γ—3Γ—C3 \times 3 \times C weights if the previous layer produces CC maps.

πŸ€– Who designs the filters?

For decades, experts designed such filters by hand: this one for vertical edges, that one for corners, yet another one for spots. The clever thing about a CNN is that it learns the numbers in its filters by itself, from examples, with the same method as an ordinary neural network. You do not tell the network what to look for, only what the goal is (for example "tell cats apart from dogs"), and the network discovers by itself which patterns are useful for that.

The 64 learned filters of the first convolutional layer of AlexNet, arranged in a grid of 8 by 8. The filters show edges in all kinds of directions, color transitions and fine stripe patterns.
The 64 filters that the first layer of AlexNet, a well-known CNN, learned by itself from more than a million photos. Nobody designed them: the network discovered that edges in all kinds of directions, color transitions and fine stripes are useful building blocks. (The PyTorch version of AlexNet uses 64 filters instead of the 96 from the original paper.)

You will see further on exactly how that learning works. First we look at how such a filter fits into a network.

🧠 A filter is a neuron

πŸ”Œ The same calculating unit as a neuron

Look again at the calculation in the mini demo: nine pixel values, each multiplied by a number from the filter, added up into one total. That is exactly the neuron from the chapter on neural networks. There, the items on a tray were the inputs and each item had a weight; here the nine pixels under the window are the inputs and the nine filter values are the weights. So one filter at one position is one neuron.

The demo below draws that same calculation as a neuron: the nine pixels come in from the left, every arrow carries a weight, and the total is in the middle. Switch between "Table" and "Neuron" to see that the numbers are exactly the same.

Loading demo

One thing is new. A negative total means "what is here is closer to the opposite of my pattern", and for recognizing a vertical line that is no more useful than finding nothing. That is why a CNN sets every negative total to zero and leaves positive totals alone. That simple rule is called ReLU (short for rectified linear unit) and is the activation function of almost every CNN. Where the Alma neuron (the one that judged trays in the student restaurant) sent its total through an S-curve to turn it into a probability, the CNN neuron simply cuts off the negative part and puts a zero there. Switch the ReLU toggle in the demo off and on to see the difference in the feature map.

Neuron in a CNN Definition

A neuron in a CNN is one square of a feature map. It is the number you get by placing the filter on one position of the image and computing the weighted sum there (plus a bias), followed by the activation function ReLU, which sets negative totals to zero. Its weights are the filter values, and the small window it looks at is called its receptive field.

πŸͺŸ Two clever tricks

If you slide the filter over the whole image, you get a whole grid of such neurons: one per square of the feature map. Compared with the neurons of an ordinary neural network, they have two special properties, and the whole power of a CNN revolves around them.

Trick 1: every neuron looks at only a small piece. In a multilayer perceptron, every neuron is connected to all the inputs. A CNN neuron sees only the nine pixels under its window. That matches how photos are put together: an eye is formed by a group of pixels that lie next to each other, not by pixels spread over the whole photo. What happens in the other corner of the photo does not matter for that one eye. This is called local connectivity.

Comparison of a fully connected network (left, every pixel connected to every neuron) and local connectivity in a CNN (right, every neuron connected to only a small window of the input).
Left: a fully connected network connects every pixel to every neuron. Right: in a CNN every neuron looks at only a small window of the image.

Trick 2: all the neurons of one map use the same weights. The filter that finds a vertical line in the top left is the same one that finds one in the bottom right. After all, a line looks the same everywhere, so there is no point in learning separate weights for every position. This is called weight sharing: one filter, nine numbers, reused at every position of the photo.

Weight sharing: the same 3Γ—3 filter with the same weights is applied at three different positions in the image.
Weight sharing: the same filter with the same nine numbers is applied at every position of the image. Those nine numbers only need to be learned once.

See it with real filters from a trained network. Choose a filter from the first layer of AlexNet and a photo below: the same filter lights up wherever its pattern occurs, whether it is a cat, a car or a flower.

Loading demo

βš–οΈ Why not simply connect every pixel to every neuron?

The network that recognized digits of 28 Γ— 28 pixels in the chapter on neural networks connected every pixel to every neuron of the next layer. For digits of 28 Γ— 28 pixels that still worked, with just over 12,700 weights. Why don't we simply do the same for photos?

First, the number of weights explodes. A photo of 224 Γ— 224 pixels has 50,000 pixels; if you connect those to the same 16 neurons, you already have 800,000 weights in the first layer alone, and with 128 neurons (still few for photos) you are at 6.4 million. All of those have to be learned, which takes many examples and a lot of computing power and drives up the risk of overfitting. A 3 Γ— 3 filter needs only ten numbers (nine weights and a bias).

Second, such a network does not know that pixels have neighbors. To that network, pixel (10, 10) is a separate input that has nothing to do with pixel (10, 11) next to it, and it would learn just as well if you shuffled all the pixels of all the photos in the same way. What we do know about photos (neighbors belong together, and a pattern counts equally everywhere) is exactly what local connectivity and weight sharing build in.

In general, a convolutional layer with FF filters of kΓ—kk \times k on CC input channels has FΓ—(kΓ—kΓ—C+1)F \times (k \times k \times C + 1) parameters. So a layer with 64 filters of 3 Γ— 3 on 32 feature maps has 64Γ—(3Γ—3Γ—32+1)=18,49664 \times (3 \times 3 \times 32 + 1) = 18{,}496 of them. A fully connected layer that computed the same 64 outputs from feature maps of 56Γ—56Γ—3256 \times 56 \times 32 would need 56Γ—56Γ—32Γ—64β‰ˆ6.456 \times 56 \times 32 \times 64 \approx 6.4 million weights.

πŸ—οΈ From filter to network

One filter finds one pattern. To get from edges to a cat, you need more: several filters, a way to keep the maps compact, layers that build on each other and a final step that turns all those maps into one answer. We look at those building blocks one by one and then put them together.

πŸ—‚οΈ Several filters, several maps

A layer of a CNN does not contain one filter but a whole series, usually 32 or 64. Every filter looks for a different pattern and produces its own feature map: one map shows where the vertical edges are, another where the horizontal ones are, yet another where the photo goes from light to dark. So the result of one layer is a stack of feature maps, one per filter.

An input image is processed by three different filters, which produces three separate feature maps: horizontal edges, vertical edges and texture.
Several filters per layer: every filter looks for a different pattern and produces its own feature map.

🏊 Summarizing with pooling

Such a stack is big: 64 maps that are almost as large as the photo itself. Besides, you do not need to know down to the pixel where an edge is; "somewhere in this corner" is enough. That is why a feature map is usually made smaller after the convolution, with pooling. The most common form is max pooling: you divide the map into blocks of 2 Γ— 2 and keep only the highest number of each block. So the question per block is: was the pattern found anywhere here?

Max pooling: a grid of 4 by 4 is reduced to a grid of 2 by 2 by taking the maximum of every block of 2 by 2.
Max pooling (2 Γ— 2): of every block of 2 Γ— 2 values you keep only the maximum. That makes the map half as wide and half as high.

Follow it step by step in the demo below, and also try switching to average pooling, which takes the average instead of the maximum.

Loading demo

Pooling has two advantages. The map shrinks to a quarter of its size, so the next layer has much less computing to do. And the network becomes more tolerant of small shifts: if an edge moves one pixel, the highest number in the block usually stays the same.

πŸͺœ Layer upon layer: from edges to objects

Now comes the step that really makes a CNN a deep network. The second layer applies filters again, but not to the photo: to the stack of feature maps of the first layer. At every position, a filter in layer 2 looks into all the maps at once, each with its own weights, and adds those partial sums up into one new number. That way one neuron in layer 2 can see: "here is a horizontal edge and right next to it a vertical edge", in other words a corner.

Move the window over the maps of layer 1 in the demo below. At every position, the filter of layer 2 looks at the same 3 Γ— 3 patch in all the maps, and those partial sums are added up into one number in the new map. Increase the number of feature maps in layer 1 and watch the number of weights of the filter grow with it.

Loading demo

Every layer builds on the previous one in this way, and that gives the hierarchy from the figure at the start of the chapter:

  • Early layers find simple patterns: edges, lines, color transitions.
  • Middle layers combine those into corners, curves and textures (stripes, dots, fur).
  • Deep layers recognize parts and objects: an eye, a wheel, a petal, a cat's head.

Compare it with how you would describe a house: lines and corners form rectangles, rectangles become windows and doors, and windows and doors with a roof on top are a house. Because every layer combines the maps of the previous one, a neuron in a deep layer "sees", through the intermediate steps, an ever larger piece of the original photo. That is how a network with only small 3 Γ— 3 filters can still recognize a cat that fills half the photo.

πŸ”­ The receptive field grows with every layer

The receptive field of a neuron is the part of the original photo that can influence its value. For a neuron in the first layer, that is exactly the 3 Γ— 3 window. A neuron in the second layer looks at a 3 Γ— 3 window in the feature maps, and each of those 9 values itself came from a 3 Γ— 3 window in the photo: together those cover an area of 5 Γ— 5 pixels. After three layers it is 7 Γ— 7.

The receptive field grows with every layer: after 1 layer 3Γ—3, after 2 layers 5Γ—5, after 3 layers 7Γ—7 pixels.
The receptive field grows with every extra convolutional layer.

With LL layers of kΓ—kk \times k filters (stride 1, without pooling), the receptive field is r=LΓ—(kβˆ’1)+1r = L \times (k - 1) + 1 pixels wide: for three layers of 3 Γ— 3 that is 3Γ—2+1=73 \times 2 + 1 = 7. Pooling speeds up the growth: after a 2 Γ— 2 pooling every square already stands for two pixels, so each following layer counts double. That is how a deep network with only 3 Γ— 3 filters still reaches a receptive field that covers the whole photo.

Two small filters instead of one large one Remark

Two consecutive 3 Γ— 3 convolutions together have a receptive field of 5 Γ— 5, but per channel they use only 2Γ—9=182 \times 9 = 18 weights, while one 5 Γ— 5 convolution needs 25. Moreover, there is an extra ReLU between the two layers, which makes the network more expressive. That is why modern architectures prefer to stack many small filters rather than a few large ones.

🎯 From feature maps to one answer

After the last convolutional and pooling layer, you have a stack of small feature maps, for example 64 maps of 7 Γ— 7, each of which says where a certain complex feature is. How does that become "cat" or "dog"?

First, all the maps are flattened: you simply put all the numbers one after the other in one long row, in this example 64Γ—7Γ—7=3,13664 \times 7 \times 7 = 3{,}136 numbers. Nothing is lost in the process; it is only a rearrangement. That long row is the input of an ordinary fully connected network, exactly the multilayer perceptron from the chapter on neural networks, with one output neuron per class at the end and softmax to turn those into probabilities. The class with the highest probability is the answer.

Play the animation below to follow that step square by square. Then click a class to see which squares of the maps push that class up the most.

Loading demo

πŸ”— The complete architecture

You now know all the building blocks. A typical CNN stacks them like this:

Convolution β†’ ReLU β†’ Pooling β†’ Convolution β†’ ReLU β†’ Pooling β†’ … β†’ Flatten β†’ Fully connected β†’ Softmax

Architecture diagram of a CNN: input image, convolution with ReLU, max pooling, convolution with ReLU, max pooling, flatten, fully connected layer and softmax output.
The typical architecture of a CNN. On the left, the convolutional and pooling layers find increasingly complex features; on the right, a fully connected network turns those into a probability per class.

So you can see a CNN as two parts:

  1. Feature extraction (left): the convolutional and pooling layers turn the photo step by step into a stack of small feature maps that say which patterns are where. The network learns this part by itself; nobody has to think up which features matter.
  2. Classification (right): an ordinary neural network that decides, based on those features, what is in the photo.
Convolutional neural network Definition

A convolutional neural network (CNN) is a neural network for data with a grid structure, such as images. Instead of connecting every pixel to every neuron, it uses small filters that slide over the input and look for the same local pattern at every position. Successive layers combine simple patterns into increasingly complex ones, and a fully connected part at the end turns those into a prediction.

πŸ”¬ See for yourself

In the demo below you see AlexNet at work, a real CNN that knows 1000 kinds of objects. Click the layers in the architecture diagram to look at the feature maps of that layer, and click a map to see how that one filter "sees" the photo. The first layer shows edges and color transitions; the deeper you go, the more abstract and the smaller the maps become, until people can hardly read them anymore. On the right are the softmax probabilities: the longest bar is the prediction.

Loading demo

Switch photos and watch the first layer: edge-detecting filters always highlight edges, whether it is a dog, a car or a flower. The deep layers respond much more specifically to the kind of object.

πŸ‹οΈ How does a CNN learn?

A CNN learns just like an ordinary neural network: guess, compare, adjust. All the filter values start out random. The network looks at a training photo, predicts a class, compares it with the right answer and, through backpropagation, nudges all the weights a little: those of the filters, the biases and the weights of the fully connected part. After hundreds of thousands of photos, the random filters have become the edge and texture detectors you saw earlier.

Because one filter is reused at every position of the photo, it also learns from every position at once: the adjustments of all the positions are added up into one change of those same nine numbers. That is part of why a CNN needs far fewer examples than a fully connected network with millions of separate weights.

πŸ“ Stride, padding and the size of the output

Two settings determine how the filter moves over the input:

  • Stride: how many pixels the filter moves per step. With stride 1 it visits every position; with stride 2 it skips one each time, so the feature map becomes half as wide. That is an alternative to pooling for making the maps smaller.
  • Padding: a border of zeros around the input. Without padding ("valid"), the map shrinks by kβˆ’1k - 1 pixels at every layer, as in the mini demo (7 Γ— 7 became 5 Γ— 5); with a border of one pixel ("same"), a 3 Γ— 3 filter keeps the map the same size. The latter is the standard in practice.

Experiment with both below and watch the size of the output.

Loading demo

The width (or height) of the output follows from

output=⌊inputβˆ’k+2psβŒ‹+1\text{output} = \left\lfloor \frac{\text{input} - k + 2p}{s} \right\rfloor + 1

with kk the filter size, pp the padding on each side and ss the stride. For an input of 224 pixels and a 3 Γ— 3 filter: without padding and with stride 1 that gives 224βˆ’3+1=222224 - 3 + 1 = 222; with padding 1 it stays 224224; with padding 1 and stride 2 it becomes ⌊223/2βŒ‹+1=112\lfloor 223 / 2 \rfloor + 1 = 112, a halving.

πŸ”₯ Where does the network look?

πŸ—ΊοΈ A heatmap of attention

The network says "cat" with 95% confidence, but where in the photo is it actually looking? At the ears, the whiskers or at the carpet? With a decision tree you follow the splits and you know why; with a CNN with millions of weights that is not so easy.

Grad-CAM (external link) answers that question. It works out which places in the last feature maps contributed most to the prediction and draws that as a heatmap over the photo:

  • red and yellow: these places tipped the balance,
  • blue: these places hardly played a role.
Loading demo

That is more than a pretty picture. Suppose a doctor uses a CNN that recognizes pneumonia on X-rays. Is the model looking at the lungs, or at a text label in the corner that happens to appear only on the X-rays of sick patients? Grad-CAM makes that visible: if the model looks at the right place, that gives confidence; if it looks elsewhere, you know something is wrong.

πŸ•΅οΈ Surprising insights

Sometimes such a heatmap reveals something unexpected. The network below has no "sunflower" class, so it calls the flower a daisy. Grad-CAM shows that it mostly looks at the petals, which are shaped like the petals of a daisy. Click the second prediction, ladybug: for that one the network still looks at those petals, but now also at the blurred background on both sides of the flower, where there is no ladybug at all. The slider adjusts the transparency of the heatmap.

Loading demo

So a CNN also learns patterns that are in the training data by coincidence. A cow recognizer that only saw cows in meadows can learn that green grass means "cow", and miss a cow on the beach. With the wolf in the demo you see something similar: for "red wolf" the network mostly looks at the fur and the surroundings, not at the head. The model then performs well on the test data, but for the wrong reason: the black box problem of neural networks in practice.

πŸ’ͺ Strengths & limitations

πŸ† Strengths

  • πŸ”„ A pattern counts everywhere: because the same filter slides over the whole photo, a CNN recognizes a cat in the top left just as well as in the bottom right. Convolutions are by nature translation equivariant: if the photo shifts, the feature map simply shifts with it. In practice, pooling and data augmentation also make the network robust to small shifts.

  • ⚑ Few weights: thanks to local connectivity and weight sharing, a CNN has far fewer weights than a fully connected network for the same photo. That makes it faster to train and less prone to overfitting.

  • 🧱 It finds the features by itself: you do not have to think up which patterns are important. The network learns them from the data, from edges to ears.

How many weights you save that way depends on the resolution of the photo. Slide the resolution up below and compare a fully connected layer with a convolutional layer.

Loading demo

🚧 Limitations

A cat at different positions is recognized correctly every time, but a rotated cat is classified wrongly.
A shifted cat (top) is recognized, a rotated cat (bottom) not necessarily.

πŸ–ΌοΈ Data augmentation

To soften the limitations around data and rotation, you apply data augmentation. You artificially create more training data by randomly rotating, flipping and cropping existing photos and slightly adjusting their brightness or colors. That way the network sees much more variation and learns to be more robust, without you having to collect and label extra photos.

A photo of a cat by the window in the middle, surrounded by eight modified copies: flipped, rotated, cropped, shifted, with noise, brighter, darker and with different colors.
Data augmentation: by making variations of existing training photos, the network learns to be more robust without collecting extra data.

♻️ Reusing trained layers

A CNN that was trained on millions of photos has already learned what edges, textures and shapes are, and that knowledge is useful for almost any image task. So if you want your own network that recognizes plant diseases, you do not start from scratch. You take a pretrained network (usually trained on ImageNet (external link), a collection of over a million photos in 1000 classes), replace only the last layer with a new one with your classes, and train it briefly on your own photos. This is called transfer learning.

Transfer learning: a model pretrained on ImageNet with 1000 classes is reused. The early layers are frozen and only the last layers are trained again for a new task with 3 classes.
Transfer learning: the early layers of a pretrained model are frozen and reused. Only the last layers are trained again for the new task.

The pretrained network supplies the "visual vocabulary", and you only teach it the last step: which combinations of patterns belong to your classes. Compare it with someone who can already read and learns a new alphabet: the basics are already there, only the details are different. That way a few hundred photos already get you far, instead of the millions you would otherwise need. For medical image analysis, too, you often start from a network that knows ordinary photos, and you only teach it which patterns point to a tumor or a fracture.

πŸŽ›οΈ Feature extraction or fine-tuning?

There are two common ways to reuse a pretrained network:

  • Feature extraction: you freeze all the pretrained layers and train only a new classification head on your data. That is fast and cheap, and it works well with little data or when your task resembles the original one.
  • Fine-tuning: you also train (part of) the deeper convolutional layers, with a low learning rate, so that the learned features adapt to your task. That often gives better results, but takes more data and computing power, and the risk of overfitting is larger.

In practice you start with feature extraction. If the accuracy is disappointing, you gradually unfreeze more layers from back to front, while keeping an eye on whether the validation accuracy rises too.

🌍 CNNs today

Newer architectures such as vision transformers (external link) (ViT) are becoming more and more popular, but CNNs remain an important part of modern computer vision. Many advanced systems combine CNN-like ideas with attention mechanisms from the world of transformers. The basic principles of this chapter (local filters, shared weights, hierarchical feature extraction) are still used in those newer models too.

Today CNNs are also used for:

  • πŸ” Object detection: not only what is in an image, but also where (with bounding boxes)
  • 🎭 Semantic segmentation: deciding for every pixel which object it belongs to
  • 🎨 Image generation: as part of generative models such as diffusion models
  • 🎬 Video analysis: motion detection and action recognition

🐼 Adversarial attacks

🎭 Invisible noise, big consequences

In 2015, Goodfellow and colleagues (external link) demonstrated something remarkable. They took a photo of a panda that the network correctly recognized with 57.7% confidence. Then they added a tiny amount of noise, so small that the human eye sees no difference at all. But the network classified the modified photo as a gibbon, with 99.3% confidence.

Adversarial example: a panda image recognized with 57.7% confidence, plus invisible noise, results in an identical-looking image that is classified as a gibbon with 99.3% confidence.
The famous adversarial panda example: invisible noise completely changes the prediction.

To us the image looks identical, but the network is completely fooled. Not a little, but wrong with full conviction. This is called an adversarial example: an input that was deliberately modified to fool the network, without the change being visible to people.

How is that possible? With backpropagation, the attackers compute exactly which pixels they must change to confuse the network as much as possible. Every pixel changes by only a fraction (invisible to the eye), but all those small changes together push the input across the decision boundary of the network into a completely different class. In some cases, changing one single pixel (external link) is even enough.

Below you can try it yourself on the photos from the CNN demo. The cat suddenly becomes a bucket and the giant panda a dog. The middle image shows the added noise (amplified ten times, otherwise it would be invisible). Notice how drastically the predictions change.

Loading demo

πŸ§ͺ Train an image recognizer yourself

With Google's Teachable Machine (external link) you train your own image recognizer, directly in your browser and without writing any code.

Screenshot of Google Teachable Machine: on the left two classes, Cat and Dog, each with four sample images; on the right a preview of the classification.
Google Teachable Machine: create classes, collect examples with your webcam and train an image recognizer in a few seconds.

This is how it works:

  1. Click Get Started and choose Image Project.
  2. Create classes (for example "thumbs up" and "thumbs down").
  3. Record examples with your webcam: make a hand gesture, show an object, and so on.
  4. Click Train Model; training takes only a few seconds.
  5. Test it with new images from your webcam: does it recognize your classes?

It is that fast because of transfer learning: Teachable Machine takes a pretrained CNN (MobileNet) and trains only the last layer on your images. Also try what happens if you record a class only in daylight and then test it in the dark: you will see with your own eyes how a network learns coincidental patterns (the lighting) instead of what you meant.

πŸ§ͺ Hands-on

In this Jupyter notebook you use CNNs yourself in Python, with the PyTorch library. First a network that has already seen more than a million photos recognizes the photos from the demo, and you look at the filters of its first layer. Then you teach a network to recognize ten kinds of food from only a hundred doodles per kind: first with a small CNN trained from scratch, then by reusing the trained network, as Teachable Machine does.

A network that has seen more than a million photos recognizes the photos from the demo. Then you teach a network to recognize ten kinds of food from only a hundred doodles per kind: first with a small CNN from scratch, with and without data augmentation, then by reusing the trained network, with its mistakes and a heatmap of where it looks.

πŸ•ΉοΈ Demos

πŸ—£οΈ Feedback

Just like machine learning algorithms, we also love learning from your feedback to improve the course.

Let us know how informative and how difficult you found this chapter, and where it could be better.

How informative did you find this chapter?
Was the difficulty of this chapter right for your level of knowledge and skill? This chapter was...
Anonymous with random ID