Deep Learning · Computer Vision
How a Model Learns to Recognize Images
A Convolutional Neural Network (CNN) is a neural network built to learn visual patterns while keeping track of where those patterns occur. We will follow one image all the way from raw pixels to a class prediction, calculate a convolution by hand, see how filters are learned and reused, understand padding, stride and pooling, trace tensor shapes, and build a small image classifier.
The Job: Turn a Picture Into an Informed Decision
Consider a camera above a factory conveyor belt. For each product, the system must answer: acceptable or damaged? A scratch may appear near the top, middle or bottom. It may be short or long, but its local visual pattern is similar wherever it appears.
A CNN solves this task in stages. First it learns small reusable pattern detectors. Early layers may respond to borders or colour changes. Later layers combine nearby responses into textures and parts, then combine parts into evidence for a whole object. A final classifier converts that evidence into scores for the possible answers.
What a CNN does from beginning to end
Values move from left to right to make a prediction. Learning later adjusts the filters and classifier weights.
The name now becomes less mysterious: neural network means connected layers with trainable weights; convolutional refers to the repeated local calculation used to create those early and intermediate feature maps.
Why Ordinary Dense Connections Are Wasteful for Images
A computer receives an image as numbers arranged in a grid. In a 224 × 224 colour image, the first 224 is the number of pixel columns across the image, the second 224 is the number of pixel rows from top to bottom, and the 3 is the number of colour values stored at every location.
224 pixel columns (width)
pixel locations
Zoom in on one colour pixel
Pixel = [210, 95, 40]
The three aligned grids are called the Red, Green and Blue channels. They describe the colour at every pixel location.
Now compare two ways of connecting those 150,528 values to 64 outputs. A parameter is a trainable number—a weight or bias—that training is allowed to change.
Dense layer: every input connects to every neuron
150,528 inputs × 64 neurons because every one of the 64 neurons needs a separate weight for every image value.
150,528 × 64 = 9,633,792 weights
+ 64 biases (one per neuron)
= 9,633,856 parameters
Convolution: 64 small filters are reused
3 filter rows × 3 filter columns × 3 RGB channels × 64 filters, plus one bias for each filter.
3 × 3 × 3 × 64 = 1,728 weights
+ 64 biases
= 1,792 parameters
The dramatic reduction comes from two ideas. Local connectivity means one output examines a small nearby patch rather than the whole image. Weight sharing means the same filter weights are reused at the top, middle and bottom instead of learning a new copy at every location. The filter can therefore search for the same scratch pattern wherever it appears.
Vocabulary for Reading a CNN Diagram
Before calculating anything, connect each term to a physical role. A filter is not a ready-made “cat detector.” It begins with small weight values and is adjusted by training until its responses help reduce the loss.
| Term | Meaning in plain language |
|---|---|
| Pixel | One location in an image grid. A colour pixel usually contains red, green and blue numbers. |
| Channel | One aligned grid of values. RGB input has 3 channels; a hidden CNN can have dozens or hundreds of learned feature channels. |
| Patch / local region | The small part of the input currently covered by a filter. |
| Filter / kernel | A small learnable grid of weights. It asks the same numerical pattern question at many image positions. |
| Feature map | The grid of responses produced by one filter as it visits every valid position. |
| Stride | How many cells the filter moves between positions. Larger stride produces fewer output locations. |
| Padding | Extra border values added around the input, often zeros, to control output size and include border positions. |
| Receptive field | The region of the original image that can influence one hidden activation. |
| Bias | One additional trainable number added to a filter's response. Each output filter normally has one bias shared across its positions. |
| Pooling | A fixed summary operation that replaces a small window with one value, often its maximum or average. |
| Logit | A raw class score produced by the classifier before softmax turns scores into probabilities. |
Calculate One Convolution by Hand
Before calculating anything, we need to know what the filter is trying to do. A filter, also called a kernel, is a small grid of numerical weights. Instead of asking one enormous question about the entire image, it asks the same small local question at many positions.
3 columns
3 rows × 3 columns = 9 weights
The weights form a small pattern test
If a patch is bright on the left and dark on the right, the positive side contributes more than the negative side, so the total response becomes positive.
At one position, the layer pairs the filter with the equally sized image patch, multiplies values in matching cells, adds the products, and finally adds one bias. In our hand calculation the bias is 0, so it does not change the result. The sum becomes one number because the purpose is to summarize how strongly that whole patch matches this filter.
One output at row i, column j
zi,j = b + Σu Σv Xi+u,j+vKu,v
X is the input grid, K is the filter, u and v visit positions inside the filter, b is one learned bias for the output channel, and z is the filter response.
From nine matching pairs to one feature-map cell
Green marks the first input patch, amber marks the filter, and pink marks the output cell produced by their calculation.
5 × 5 input: first 3 × 3 patch highlighted
×
matching cells
3 × 3 filter
→
multiply, then add
3 × 3 feature map
Exactly what is multiplied
Each patch value is paired only with the filter weight in the same row and column. This produces nine products:
+ 1 + 0 + 0
+ 1 + 0 + 0
We add the nine products because together they measure how closely the whole patch matches the filter's pattern. The strong positive total, 3, says this patch has the bright-left, dark-right change that our teaching filter rewards. One patch produces one summary number, so that number occupies one feature-map cell.
Move the same filter one cell at a time
Position 1
Rows 1–3, columns 1–3
result = 3
Move right → Position 2
Rows 1–3, columns 2–4
1 + 1 + 1 = 3
Visit all 9 positions
Repeat across each row, then move down
complete feature map
With stride 1 and no padding, the filter has three horizontal starting columns—1, 2 and 3—and three vertical starting rows. Therefore it visits 3 × 3 = 9 positions, producing the nine cells in the final 3 × 3 feature map.
What Changes for a Colour Image?
The hand calculation used one 2D grid only to make the nine products visible. An RGB image has three aligned input grids, so a first-layer filter must look through all three. A 3 × 3 RGB filter therefore contains a 3 × 3 slice for Red, another for Green, and another for Blue.
An RGB filter covers all three colour channels
The earlier arithmetic used one grid so the multiplication was easy to see. A real first-layer filter for a colour image has depth as well as height and width.
3 × 3 × 3 = 27 weights
Add 27 products
+ one bias
one output value
A Short ReLU Reminder
A convolution is commonly followed by the ReLU activation function: ReLU(x) = max(0, x). Positive responses remain, while negative responses become zero. For example, [3, −2, 5] becomes [3, 0, 5]. This lets the next layer focus on where the current filter produced a positive response. The Activation Functions lesson explains the function in full.
Filters Are Learned Through the Same Training Loop
The values 1, 0, −1 belonged only to our teaching filter. A real CNN normally begins with small initialized filter weights. A forward pass uses them to make a prediction; the loss measures the error; backpropagation calculates how every weight contributed to that error; and the optimizer adjusts the weights. Repeating this cycle over many labelled images allows useful filters to emerge. The image does not directly supply the filter values, and the values do not remain fixed during training.
A CNN builds a hierarchy rather than recognizing an object in one jump
Every later value depends on a wider area of the original image, called its receptive field.
Pixels
light
dark
colour
Early feature maps
— edge
╱ diagonal
⌜ corner
Middle feature maps
curve
texture
small part
Later representation
eye
wheel
leaf spots
Prediction
cat
car
disease
A receptive field grows through connected local views
Layer 1 value
sees 3 × 3 pixels
Layer 2 value
combines a 3 × 3 area of Layer 1
Deeper value
depends on a larger image area
Padding and Stride Control Where the Filter Visits
Padding adds border cells around the input, usually zeros. It lets a filter visit locations near an image edge without hanging outside the available grid. Stride is simply how far the filter moves after each calculation. These choices determine how many legal filter positions—and therefore how many output cells—exist.
Padding changes what happens at the border
No padding
5 × 5 input
3 × 3 output
Padding = 1
zeros form a border
5 × 5 output
Without padding, the filter cannot be centred on an edge pixel without extending beyond the image. A one-cell zero border gives it legal positions around the edge and preserves the 5 × 5 spatial size when the filter is 3 × 3 and stride is 1.
Stride is the distance moved after each calculation
Stride = 1
Visit neighbouring starting positions.
Stride = 2
Skip one position each time, so fewer outputs are created.
The visual gives the intuition; the following formula counts the positions precisely. It applies to one spatial direction at a time, so calculate it once for height and once for width.
Output size for one spatial dimension
Nout = floor((N + 2P − K) / S) + 1
N is the input height or width, K is the filter height or width, P is the border added on each side, and S is the movement step. floor means discard any incomplete final placement. This beginner formula assumes dilation 1, which is the default used in our code.
No padding
5 input cells − 3 filter cells leaves room for starting positions 1, 2 and 3.
N=5, K=3, P=0, S=1
floor((5−3)/1)+1
= 3
“Same” spatial size
Padding 1 adds one cell to both sides, so 2P = 2.
N=5, K=3, P=1, S=1
floor((5+2−3)/1)+1
= 5
Stride 2
Move two cells per calculation instead of one, creating fewer positions.
N=5, K=3, P=1, S=2
floor((5+2−3)/2)+1
= 3
Pooling Summarizes Nearby Responses
After a feature has been detected, the exact pixel location may be less important than whether a strong response exists nearby. A pooling window is a small region examined at one time. Max pooling replaces that region with its largest value; average pooling replaces it with the mean. Neither operation has trainable weights.
4 × 4 feature map
→
2 × 2 max pool
stride 2
2 × 2 result
Pooling reduces memory and lets later values summarize wider regions, but it throws information away. For tasks that need precise locations—such as segmentation—architectures preserve or later restore spatial detail. Many modern classifiers use strided convolutions for intermediate downsampling and global average pooling near the end. “Global” means the window covers an entire feature map: a 32 × 32 map has 1,024 values, and averaging them produces one summary value for that channel.
Follow the Tensor Shapes Through a Small Classifier
A tensor is a multidimensional arrangement of numbers, and its shape states how many values exist along each dimension. PyTorch image batches use N × C × H × W: number of images, channels, height in rows, and width in columns.
Decode 32 × 3 × 64 × 64 instead of memorizing it
N
32
images in this batch
C
3
RGB channels per image
H
64
pixel rows (height)
W
64
pixel columns (width)
Now follow those meanings through the complete model. Height and width describe where responses occur; channels describe which learned filters produced them.
| Stage | Operation | Output for batch of 32 | Meaning |
|---|---|---|---|
| Input | 32 colour images | 32 × 3 × 64 × 64 | Three RGB numbers at each location |
| Block 1 | 3×3 Conv: 3 input channels → 16 filters; padding 1; then ReLU | 32 × 16 × 64 × 64 | One map from each of 16 filters; padding preserves height and width |
| Downsample | 2×2 MaxPool, stride 2 | 32 × 16 × 32 × 32 | Each non-overlapping 2×2 window becomes one value, halving height and width; 16 channels remain |
| Block 2 | 3×3 Conv: 16 input channels → 32 filters; padding 1; then ReLU | 32 × 32 × 32 × 32 | Each of 32 filters combines information from all 16 incoming maps |
| Aggregate | Adaptive global average pool to 1×1 | 32 × 32 × 1 × 1 | For every image, each of its 32 maps is averaged into one number |
| Flatten | Remove the two size-1 spatial dimensions | 32 × 32 | Each image is now represented by a list of 32 learned values |
| Classifier | Linear: 32 inputs → 4 classes | 32 × 4 | Four raw class scores, called logits, for each image |
From Raw Class Scores to the Predicted Class
The final linear layer produces one number per possible class. These raw numbers are called logits. A logit is evidence, not yet a probability: it may be negative, and the logits do not need to add to 1. Softmax converts the set into probabilities while preserving their order, and the largest probability becomes the predicted class.
Logits: raw scores
They may be negative and do not have to add to 1.
Softmax
Probabilities
They are between 0 and 1 and add to 1.
highest
Prediction
Cat
CrossEntropyLoss. It performs the softmax-and-log calculation internally in a numerically stable way. Apply softmax yourself only when you need readable probabilities for interpretation or display.Implement the Shape Trace in PyTorch
The code follows the preceding table. In Conv2d(3, 16, kernel_size=3, padding=1), 3 means three incoming RGB channels, 16 means sixteen learned filters and output maps, kernel_size=3 means each filter is 3 × 3 spatially, and padding=1 adds one border cell on every side.
import torch
from torch import nn
class SmallCNN(nn.Module):
def __init__(self, classes=4):
super().__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 16, kernel_size=3, padding=1),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2),
nn.Conv2d(16, 32, kernel_size=3, padding=1),
nn.ReLU(),
nn.AdaptiveAvgPool2d((1, 1)),
)
self.classifier = nn.Linear(32, classes)
def forward(self, images):
maps = self.features(images) # [N, 32, 1, 1]
features = maps.flatten(start_dim=1) # [N, 32]
return self.classifier(features) # [N, 4] logits
model = SmallCNN(classes=4)
images = torch.randn(32, 3, 64, 64)
labels = torch.randint(0, 4, (32,))
logits = model(images)
loss = nn.CrossEntropyLoss()(logits, labels)
loss.backward() # gradients now exist for filters and classifier weights
print(logits.shape) # torch.Size([32, 4])
print(float(loss))AdaptiveAvgPool2d((1, 1)) does: it divides each incoming feature map into regions as needed and averages it to the requested output height 1 and width 1. The number of channels stays 32.flatten(start_dim=1) does: it keeps dimension 0—the batch of 32 images—and joins each image's remaining 32 × 1 × 1 values into a list of 32 values.For a real project, load normalized training/validation data, use an optimizer, call zero_grad() before each backward pass, and monitor held-out metrics. The previous training-loop and augmentation lessons cover those pieces.
Choose a CNN When Its Assumptions Fit the Task
| Situation | Good starting point | Reason |
|---|---|---|
| Small or medium image dataset | Pretrained CNN + fine-tuning | Strong local visual bias and mature pretrained backbones |
| Mobile or edge image inference | Efficient CNN family | Convolutions can offer a practical speed/accuracy/memory trade-off |
| Very large-scale vision with strong pretraining | Compare CNN and Vision Transformer | Transformers model global relationships differently; the best choice is empirical |
| Tabular rows with unrelated columns | Tree model or MLP | Neighbouring columns usually do not have image-like spatial meaning |
| Tiny, fixed problem with handcrafted measurements | Classical ML baseline | A CNN may add needless data and compute requirements |
| Precise pixel labelling | Segmentation CNN such as U-Net | A classification head alone discards the spatial output needed |
Common CNN Mistakes and Limits
Shape mismatch in the classifier
Print N×C×H×W after each stage. Prefer adaptive/global pooling when input sizes may vary.
Wrong channel order
PyTorch layers expect N×C×H×W, while many image arrays arrive as N×H×W×C. Permute deliberately.
Softmax before CrossEntropyLoss
Pass logits directly. Applying softmax first changes the intended numerically stable calculation.
Feature maps become 0×0
Too many valid convolutions or pooling operations shrink small inputs. Recalculate the output-size formula.
High accuracy from backgrounds
Inspect errors and saliency cautiously; collect diverse backgrounds and use valid augmentation.
Assuming complete shift/rotation invariance
Test controlled transformations. Use appropriate augmentation or architecture changes when the task requires them.
The CNN in One Connected Explanation
A CNN learns small filters, reuses each filter across an image, records the responses in feature maps, combines local responses into increasingly large patterns, reduces spatial size when useful, and turns the final representation into class scores. Backpropagation and an optimizer learn every filter from labelled examples.
- Local connectivity asks about nearby pixels.
- Weight sharing detects the same pattern at different positions with the same parameters.
- Padding, stride and pooling control spatial size and information loss.
- Channels hold different learned pattern responses.
- The output-size and parameter-count calculations let you verify an architecture before training.