ποΈ 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.
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.

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.
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.
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?
πΊοΈ 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.
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 at position of the feature map is the weighted sum of the 9 pixel values under the filter:
Here is the pixel value at position of the image and the filter value at position in the 3 Γ 3 filter, with the middle square. In a CNN, a bias 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.
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.
π¨ 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.
A learned CNN filter, on the other hand, is 3D: on a color photo a 3 Γ 3 filter has not 9 but 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 weights if the previous layer produces 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.

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.
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.
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.
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.
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.
βοΈ 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 filters of on input channels has parameters. So a layer with 64 filters of 3 Γ 3 on 32 feature maps has of them. A fully connected layer that computed the same 64 outputs from feature maps of would need 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.
π 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?
Follow it step by step in the demo below, and also try switching to average pooling, which takes the average instead of the maximum.
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.
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.
With layers of filters (stride 1, without pooling), the receptive field is pixels wide: for three layers of 3 Γ 3 that is . 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 consecutive 3 Γ 3 convolutions together have a receptive field of 5 Γ 5, but per channel they use only 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 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.
π 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
So you can see a CNN as two parts:
- 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.
- Classification (right): an ordinary neural network that decides, based on those features, what is in the photo.
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.
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 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.
The width (or height) of the output follows from
with the filter size, the padding on each side and the stride. For an input of 224 pixels and a 3 Γ 3 filter: without padding and with stride 1 that gives ; with padding 1 it stays ; with padding 1 and stride 2 it becomes , 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.
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.
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.
π§ Limitations
- π Rotating is not shifting: a CNN recognizes an object at any position, but not automatically at any angle. A photo turned on its side is not recognized automatically; the network must have seen rotated examples.
-
π Texture over shape: research from 2019 (external link) showed that CNNs trained on ordinary photos mostly go by texture, while people pay attention to shape: the network calls a cat with elephant skin an elephant. That partly explains why it looked at the fur of the wolf.
-
π Needs a lot of labeled data: every training photo must carry the right label ("cat", "dog", "car"), and that is manual work. Thanks to its built-in preference for local patterns, a CNN needs fewer examples than a fully connected network, but it still needs many more than a decision tree or k-nearest neighbors. Transfer learning (below) helps enormously here.
-
π» Computing power: you can train a small CNN on a laptop, but the large models take days to weeks on clusters of graphics cards.
πΌοΈ 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.
β»οΈ 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.
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.
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.
π§ͺ 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.

This is how it works:
- Click Get Started and choose Image Project.
- Create classes (for example "thumbs up" and "thumbs down").
- Record examples with your webcam: make a hand gesture, show an object, and so on.
- Click Train Model; training takes only a few seconds.
- 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.

πΉοΈ Demos
Experiment further with the full simulators and demos featured above.





π£οΈ 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.