What a Convolutional Network Sees
An image classifier receives a photo as a tensor of colour values and returns one score per class. In between, a convolutional network does not look at the photo all at once. It looks for small patterns everywhere in the image, then for combinations of those patterns, and finally condenses everything it found into one list of numbers that describes the whole photo. Knowing how that works explains why these networks need so few weights, why the shape of the data changes the way it does from layer to layer, and which part of a pretrained network can be reused for new classes.
A small filter slid across the image
Start with a greyscale image: one grid of brightness values. A filter (also called a kernel) is a much smaller grid of weights, typically 3 by 3. To apply it, you lay the filter over the top-left 3 by 3 patch of the image, multiply each pixel by the weight lying on it, and add the nine products into one number. Then you move the filter one pixel to the right and do the same again, row by row, until it has visited every position. That sliding multiply-and-add is a convolution.
The number at each position says how well the patch under the filter matches the pattern the weights hold. The filter below has weights of -1 on its left column, 0 in the middle and +1 on the right. On a flat patch, dark or bright, the left and right columns cancel and the result is 0. Where the image turns from dark on the left to bright on the right, the right column outweighs the left one and the result is high. This filter is a detector of vertical edges.
- 0
- 0
- 0
- 1
- 1
- 1
- 0
- 0
- 0
- 1
- 1
- 1
- 0
- 0
- 0
- 1
- 1
- 1
- 0
- 0
- 0
- 1
- 1
- 1
- 0
- 0
- 0
- 1
- 1
- 1
- 0
- 0
- 0
- 1
- 1
- 1
- -1
- 0
- +1
- -1
- 0
- +1
- -1
- 0
- +1
- 0
- 3
- 3
- 0
- 0
- 3
- 3
- 0
- 0
- 3
- 3
- 0
- 0
- 3
- 3
- 0
In the marked patch, the three -1 weights and the three 0 weights lie on dark pixels (0) and the three +1 weights lie on bright pixels (1), so the sum is \(3 \times (1 \times 1) = 3\), the marked output value. The output is smaller than the image, 4 by 4 instead of 6 by 6, because a 3 by 3 filter fits only four positions across six pixels. Adding a border of zeros around the image (padding) lets the filter visit every pixel and keeps the size unchanged.
In a trained network nobody writes these weights by hand. They are learned by the same training loop as any other layer: the loss measures how wrong the class scores are, and the optimizer adjusts every filter weight a little to reduce it. The network ends up with the filters that are useful for telling its classes apart.
PyTorch provides this as torch.nn.Conv2d. Strictly speaking, it computes a cross-correlation: the filter is not flipped as in the mathematical definition of convolution. For learned filters this makes no difference.
One filter, every position
The key design choice is that the same filter, with the same nine weights, is used at every position. That has two consequences.
First, a pattern is found wherever it appears. A vertical edge in the top-left corner and one in the bottom-right corner give the same high value, because the same weights look at both. A pattern worth detecting in one place is worth detecting in any other place, so a cat is recognised by its ear whether the ear is at the top of the photo or at the side.
Second, the layer needs very few weights. A layer in which every output is connected to every pixel needs a separate weight for each pixel and each output: a single such output on a 200 by 200 colour image already has 200 x 200 x 3 = 120,000 weights. A convolution layer only stores its filters, however large the image is. A well-known example is the first layer of AlexNet, an early ImageNet network. It has 96 filters of 11 by 11 pixels, and together they produce 96 output grids of 55 by 55 values.
The 34,944 parameters are 96 filters of 11 x 11 x 3 weights plus one bias each. Giving every one of the 55 x 55 x 96 outputs its own 363 weights (11 x 11 x 3) and a bias would take about 3,000 times as many. Fewer weights means less memory, less to learn from a limited set of photos, and less risk of overfitting, where a model memorises its training images instead of learning patterns that carry over.
True or false?
A filter that detects a horizontal edge has to be trained separately for the top and the bottom half of the image.
False. The same filter slides over every position, so once it holds the edge pattern it finds that edge anywhere in the image.
Doubling the width and height of the input image leaves the number of weights in a convolution layer unchanged.
True. The layer stores only its filters. A larger image means more positions to visit and a larger output, but the same weights.
Feature maps and channels
The grid of values one filter produces is a feature map: a map of where in the image its pattern appears. The 4 by 4 output above is the feature map of a vertical-edge filter.
One pattern is not enough to recognise anything, so a convolution layer holds many filters, each learning a different pattern: edges at various angles, a change from green to red, a small bright spot. Each filter produces its own feature map, and the layer stacks them. A layer with 16 filters turns its input into 16 feature maps, which the next layer reads as 16 channels, exactly as a photo has 3 channels for red, green and blue.
A filter also reaches through all the channels of its input. On a colour photo, a 3 by 3 filter is really 3 x 3 x 3: one 3 by 3 grid of weights per colour channel, and the products from all three are added into one number. That is how a filter can respond to colour, for example a yellow patch, which only shows as a combination of red and green values. In PyTorch a layer's weights therefore have the shape (filters, input channels, filter height, filter width).
import torch
from torch import nn
conv = nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3, padding=1)
print(conv.weight.shape) # torch.Size([16, 3, 3, 3]): 16 filters of 3 x 3 x 3
photo = torch.rand(1, 3, 224, 224) # a batch of one colour image
print(conv(photo).shape) # torch.Size([1, 16, 224, 224]): 16 feature mapsThe layer above has 16 x 3 x 3 x 3 = 432 weights and 16 biases, whatever the size of the photo. With padding=1, a border of one zero on every side, each feature map keeps the 224 by 224 size of the input. Only the number of channels changes: 3 in, 16 out. The next layer's filters are then 3 x 3 x 16 and combine the 16 maps in their own ways.
True or false?
In a normal convolution layer on a colour photo, each filter looks at only one of the three colour channels.
False. Each filter spans every input channel, which is why its weight has the shape (input channels, height, width). Only a special variant, the depthwise convolution, filters each channel on its own.
A convolution layer with 64 filters outputs 64 channels, whatever the number of channels it receives.
True. Each filter produces one feature map, and the number of filters is the number of output channels.
Downsampling: smaller maps, more channels
If every layer kept the full size of a photo, a deep network would compute millions of values per layer, and each value would still only see a few pixels. Networks therefore shrink the grid as they go. The usual way is a stride of 2: the filter moves two pixels at a time instead of one, so it visits every second position and the feature map comes out half as wide and half as high, a quarter of the values. Another way is a pooling layer, which takes the largest or the average value of every 2 by 2 block and has no weights at all. Many modern networks downsample only with stride-2 convolutions.
The size of a convolution's output follows from the input size \(H\), the filter size \(K\), the padding \(P\) on each side and the stride \(S\):
output height (the width works the same way)
For a 224 by 224 photo, a 3 by 3 filter with a padding of 1 and a stride of 2 gives \(\lfloor (224 + 2 - 3) / 2 \rfloor + 1 = 112\). With a stride of 1 the same layer would give 224.
While the grid shrinks, the number of channels usually grows. The total amount of data stays manageable, and the network gets more channels where it needs them: deeper down, there are many more possible combinations of patterns to tell apart than there are kinds of edges. Not every layer does both. Some keep the grid and change the channels, some keep both and only refine the maps.
- 3 x 224 x 224
- the photo
- 16 x 112 x 112
- after the first layer
- 24 x 28 x 28
- after three halvings
- 576 x 7 x 7
- the last feature maps
The picture shows the shapes, written as channels x height x width, at four points in MobileNetV3-Small, a small pretrained network from torchvision. The grid goes from 224 to 7 while the channels go from 3 to 576.
Downsampling also changes what each value can see. A value in the first feature map comes from a 3 by 3 patch of pixels. When that layer has a stride of 2, neighbouring values in its map come from patches two pixels apart in the photo. A 3 by 3 filter in the next layer reads three such neighbours in each direction, and together their patches cover a 7 by 7 area of the photo. Each further layer widens this area, the value's receptive field, and by the last feature maps a single value draws on a large part of the photo.
True or false?
A convolution with stride 2 and suitable padding turns a 56 by 56 feature map into a 28 by 28 one.
True. Visiting every second position halves both the height and the width, which leaves a quarter of the values.
Downsampling always needs a pooling layer.
False. A convolution with a stride of 2 shrinks the grid as well, and many current networks downsample only that way.
From edges to parts of objects
Because each layer reads the feature maps of the layer before, and each of its values covers a larger area of the photo, the patterns grow in size and meaning from layer to layer. A filter in the second layer does not see pixels. It sees where the first layer found edges and colours, and it can respond to a particular arrangement of them, such as two edges meeting in a corner.
Researchers have looked inside trained networks by finding the image patches that make a filter respond most. Zeiler and Fergus did this for a network trained on ImageNet (Visualizing and Understanding Convolutional Networks) and found a clear progression:
- Edges, colour blobs layer 1
- Corners, edge and colour mixes layer 2
- Textures layer 3: mesh, text
- Parts of objects layer 4: dog faces, bird legs
- Whole objects layer 5: keyboards, dogs
- Edges, colour blobs to Corners, edge and colour mixes
- Corners, edge and colour mixes to Textures
- Textures to Parts of objects
- Parts of objects to Whole objects
Nobody programmed these stages. Edge filters appear in the first layer because edges are useful for almost every class, and the parts appear later because combining the earlier patterns is what lets the network tell a dog from a keyboard. The same tendency shows in other networks: the first layer of most networks trained on photos learns edge and colour detectors, and the authors of MobileNetV3 note that such first-layer filters are often mirror images of each other.
The progression is a tendency, not a precise plan. Individual filters in deep layers often respond to mixtures of things that have no single name, and visualisations of the deepest layers can look like collages. What holds reliably is the direction: early layers capture general, local patterns, later layers capture larger and more class-specific ones.
This is also why a network trained on one large collection of photos is useful for other photos. Its early layers in particular hold patterns (edges, colours and textures) that appear in almost any photograph.
True or false?
A filter in a deep layer of a network can respond to a dog's face even though it never sees pixels directly.
True. It reads the feature maps of the layer before, which already mark eyes, fur texture and edges, and responds to their arrangement over a large receptive field.
The edge filters of the first layer are written by the network's designers, and only the later layers are learned.
False. Every filter starts from random weights and is learned in training. Edge detectors appear on their own because they help with almost every class.
One vector for the whole photo, then the class scores
After the last convolution layer, the photo is a stack of small feature maps: in MobileNetV3-Small, 576 maps of 7 by 7. Each map says where in the photo its pattern was found. To decide on a class, the network mostly needs to know whether and how strongly each pattern is present, not exactly where.
Global average pooling answers that: it averages each feature map into a single number. 576 maps of 7 by 7 become 576 numbers, one per pattern. Those numbers form the feature vector: one fixed-length description of the whole photo. In PyTorch this is nn.AdaptiveAvgPool2d(1), which gives one value per channel for any input size, so the vector has the same length for a photo of 224 by 224 as for a larger one.
- Last feature maps 576 x 7 x 7
- Average each map global average pooling
- Feature vector 576 numbers
- Classifier Linear 576 to 1024, Linear 1024 to 1000
- Class scores 1000 raw scores
- Last feature maps to Average each map
- Average each map to Feature vector
- Feature vector to Classifier
- Classifier to Class scores
The final layers turn the vector into class scores. Together they are called the classifier (or the head), and they are ordinary fully connected Linear layers like those of any small network. In MobileNetV3-Small the classifier has a Linear layer from 576 to 1,024 numbers, an activation, dropout during training, and a last Linear layer from 1,024 to 1,000: one score for each ImageNet class. The scores are raw values, not probabilities; softmax turns them into probabilities that add up to 1.
This split gives a network two parts with different jobs. Everything up to the feature vector describes what is in the photo. The classifier only maps that description to a fixed list of classes. To recognise different classes, the description can stay and only the classifier has to change.
True or false?
Global average pooling turns 576 feature maps of 7 by 7 into 576 numbers.
True. It averages each map into one number, so there is one value per channel.
The last layer of the network outputs probabilities that add up to 1.
False. It is a Linear layer, so it outputs raw scores. Softmax, applied separately, turns them into probabilities.
Tracing one photo through a whole network
Putting the pieces together, you can follow the shape of one photo through every stage of a real network. The table traces a 224 by 224 colour photo through MobileNetV3-Small in torchvision. Its convolution part, model.features, is a sequence of 13 stages: a first 3 by 3 convolution, 11 blocks of a few convolutions each, and a last 1 by 1 convolution. A 1 by 1 filter looks at a single position across all channels, so it mixes channels without changing the grid.
| Stage | What it does | Output shape |
|---|---|---|
| photo | prepared input | 3 x 224 x 224 |
| features[0] | 16 filters of 3 x 3, stride 2 | 16 x 112 x 112 |
| features[1] | block, stride 2 | 16 x 56 x 56 |
| features[2] | block, stride 2 | 24 x 28 x 28 |
| features[3] | block | 24 x 28 x 28 |
| features[4] | block, stride 2 | 40 x 14 x 14 |
| features[5] to [6] | blocks | 40 x 14 x 14 |
| features[7] to [8] | blocks | 48 x 14 x 14 |
| features[9] | block, stride 2 | 96 x 7 x 7 |
| features[10] to [11] | blocks | 96 x 7 x 7 |
| features[12] | 576 filters of 1 x 1 | 576 x 7 x 7 |
| avgpool | average each map | 576 x 1 x 1 |
| flatten | the feature vector | 576 |
| classifier | Linear 576 to 1024 | 1024 |
| classifier | Linear 1024 to 1000 | 1000 |
Read the table from top to bottom and the pattern of the earlier sections appears. Every stride-2 stage halves the height and the width. The channels grow from 3 to 96 over the blocks and jump to 576 in the last 1 by 1 convolution, at the same 7 by 7 grid. The average pool removes the grid entirely, and the classifier works on a plain vector. In a batch, every shape gets one more dimension in front, the number of images: a batch of 8 photos enters as (8, 3, 224, 224) and leaves as (8, 1000).
You can print this trace yourself. The model's forward method runs features, then avgpool, then flattens the result and runs classifier, so calling the same parts in that order shows every shape along the way:
import torch
from torchvision.models import mobilenet_v3_small, MobileNet_V3_Small_Weights
model = mobilenet_v3_small(weights=MobileNet_V3_Small_Weights.DEFAULT)
model.eval() # evaluation mode: fixed batch-norm statistics, no dropout
x = torch.rand(1, 3, 224, 224) # stands in for one prepared photo
with torch.no_grad():
for i, stage in enumerate(model.features):
x = stage(x)
print(i, tuple(x.shape)) # 0 (1, 16, 112, 112) ... 12 (1, 576, 7, 7)
x = model.avgpool(x) # (1, 576, 1, 1)
x = torch.flatten(x, 1) # (1, 576): the feature vector
scores = model.classifier(x) # (1, 1000): one raw score per class
print(tuple(scores.shape))A random tensor is enough here, because the shapes depend only on the input size and the layers, not on what the photo shows. The bundled preprocessing of these weights crops photos to 224 by 224, which is why the trace starts there. A different input size would change the grid sizes along the way, but the average pool still ends with 576 numbers.
True or false?
In MobileNetV3-Small, every block both halves the grid and adds channels.
False. Only some stages have a stride of 2. Several blocks keep both the grid and the channels, one halves the grid at 16 channels, and the last 1 by 1 convolution raises the channels without changing the grid.
The feature vector of MobileNetV3-Small has 576 numbers, one per final feature map.
True. The average pool turns each of the 576 maps of 7 by 7 into one number. The 1,024-wide layer after it is already part of the classifier.