Skip to main content
LearnMLAcademy
Advanced10 min read

CNNs and Image Classification

Master convolutional kernels, feature maps, and pooling layers for vision, with feature-map visuals, architecture comparisons, and image exercises.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

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.

A convolutional neural network image classification journeyAn image goes through convolution, ReLU, pooling, deeper pattern extraction and a classifier to produce class scores.Input image64 × 64 × 3Convolutionfind local patternsReLUkeep useful signalPoolingsmaller mapsDeeper layersparts → objectsClassifierclass scorescat 0.82dog 0.18early layers learn small patternslater layers combine them into larger patterns
This is a common teaching architecture, not a rule that every modern CNN follows. Many networks replace flattening with global average pooling, change the downsampling strategy, or use residual blocks.

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)

224 pixel rows (height)
224 × 224
pixel locations

Zoom in on one colour pixel

Red210
Green95
Blue40

Pixel = [210, 95, 40]

The three aligned grids are called the Red, Green and Blue channels. They describe the colour at every pixel location.

224 pixels wide × 224 pixels high × 3 colour values per pixel = 150,528 numerical input values. We multiply by 3 because every colour pixel stores three numbers, not one.

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.

TermMeaning in plain language
PixelOne location in an image grid. A colour pixel usually contains red, green and blue numbers.
ChannelOne aligned grid of values. RGB input has 3 channels; a hidden CNN can have dozens or hundreds of learned feature channels.
Patch / local regionThe small part of the input currently covered by a filter.
Filter / kernelA small learnable grid of weights. It asks the same numerical pattern question at many image positions.
Feature mapThe grid of responses produced by one filter as it visits every valid position.
StrideHow many cells the filter moves between positions. Larger stride produces fewer output locations.
PaddingExtra border values added around the input, often zeros, to control output size and include border positions.
Receptive fieldThe region of the original image that can influence one hidden activation.
BiasOne additional trainable number added to a filter's response. Each output filter normally has one bias shared across its positions.
PoolingA fixed summary operation that replaces a small window with one value, often its maximum or average.
LogitA 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
1
0
-1
1
0
-1
1
0
-1

3 rows × 3 columns = 9 weights

The weights form a small pattern test

+1reward brightness on the left
0ignore the middle
−1subtract brightness on the right

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.

Where did 1, 0 and −1 come from? We deliberately chose them for this hand-worked teaching example. They are not taken from the image, they are not universal CNN constants, and real CNN filters are not fixed to these values. A real filter starts with initialized weights and training changes them.

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

1
1
0
0
0
1
1
0
0
0
1
1
0
0
0
0
0
0
1
1
0
0
0
1
1

×

matching cells

3 × 3 filter

1
0
-1
1
0
-1
1
0
-1

→

multiply, then add

3 × 3 feature map

3
3
0
2
1
-1
1
-1
-2

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 × 1 = 1
1 × 0 = 0
0 × (−1) = 0
1 × 1 = 1
1 × 0 = 0
0 × (−1) = 0
1 × 1 = 1
1 × 0 = 0
0 × (−1) = 0
1 + 0 + 0
+ 1 + 0 + 0
+ 1 + 0 + 0
=
3first feature-map cell

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

3
?
?
?
?
?
?
?
?

Move right → Position 2

Rows 1–3, columns 2–4

1 + 1 + 1 = 3

3
3
?
?
?
?
?
?
?

Visit all 9 positions

Repeat across each row, then move down

complete feature map

3
3
0
2
1
-1
1
-1
-2

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.

The complete feature map above has been checked against the shown input and filter. Deep-learning libraries commonly perform this operation as cross-correlation while using the familiar name “convolution”; they do not flip the filter first.

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.

Red channelimage patch: 3 × 3
Green channelimage patch: 3 × 3
Blue channelimage patch: 3 × 3
×
3 × 3 filter slice for Red
3 × 3 filter slice for Green
3 × 3 filter slice for Blue

3 × 3 × 3 = 27 weights

→

Add 27 products
+ one bias

↓

one output value

One filter → one feature mapThe same 3 × 3 × 3 filter visits every spatial position. Its output values form one 2D response grid.
64 filters → 64 output channelsEach filter has different weights and produces its own feature map. Stacking 64 maps gives an output with 64 channels.

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

The labels above are conceptual. A trained feature map is a grid of numerical responses, and individual channels do not always correspond to one clean human concept.

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

The deeper value does not receive the whole original image directly. It receives earlier values that have already collected information from overlapping local regions. For two stride-1, 3 × 3 convolutions, a Layer 2 value is influenced by a 5 × 5 region of the original image.
Translation equivariance, not magic position independence: if an input pattern shifts, a convolutional feature tends to shift with it. Pooling, global aggregation, data augmentation and the full architecture can make the final prediction less sensitive to small shifts, but a CNN is not automatically invariant to every translation, rotation or scale change.

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

000000000000000000000000

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

1→2→3→4→5

Visit neighbouring starting positions.

Stride = 2

1────→3────→5

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

1
7
2
3
5
4
1
6
8
2
9
0
3
1
4
5

→

2 × 2 max pool
stride 2

2 × 2 result

7
6
8
9
The highlighted 2 × 2 window contains 1, 7, 5 and 4, so max pooling keeps 7 as the highlighted output. Stride 2 then moves to the next non-overlapping window. The four windows produce 7, 6, 8 and 9. Pooling lowers width and height, but it discards exact location and the other values; it does not change the number of channels.

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)

Conv 3 → 16Each image enters with 3 RGB channels. The layer owns 16 different filters, so it returns 16 feature maps.
Conv 16 → 32Each second-layer filter is 3 × 3 × 16 because it must see all 16 incoming maps. There are 32 such filters, so 32 maps leave.
Pool to 1 × 1, then flattenAverage every final map into one number. For each image, 32 × 1 × 1 then becomes a simple list of 32 values for the classifier.

Now follow those meanings through the complete model. Height and width describe where responses occur; channels describe which learned filters produced them.

StageOperationOutput for batch of 32Meaning
Input32 colour images32 × 3 × 64 × 64Three RGB numbers at each location
Block 13×3 Conv: 3 input channels → 16 filters; padding 1; then ReLU32 × 16 × 64 × 64One map from each of 16 filters; padding preserves height and width
Downsample2×2 MaxPool, stride 232 × 16 × 32 × 32Each non-overlapping 2×2 window becomes one value, halving height and width; 16 channels remain
Block 23×3 Conv: 16 input channels → 32 filters; padding 1; then ReLU32 × 32 × 32 × 32Each of 32 filters combines information from all 16 incoming maps
AggregateAdaptive global average pool to 1×132 × 32 × 1 × 1For every image, each of its 32 maps is averaged into one number
FlattenRemove the two size-1 spatial dimensions32 × 32Each image is now represented by a list of 32 learned values
ClassifierLinear: 32 inputs → 4 classes32 × 4Four 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

Cat2.3
Dog0.8
Horse−1.1

They may be negative and do not have to add to 1.

→

Softmax

Probabilities

Cat0.79
Dog0.18
Horse0.03

They are between 0 and 1 and add to 1.

→

highest

Prediction

Cat

During training, pass the logits directly to PyTorch's 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.

small_cnn.py
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))
What 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.
What 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

SituationGood starting pointReason
Small or medium image datasetPretrained CNN + fine-tuningStrong local visual bias and mature pretrained backbones
Mobile or edge image inferenceEfficient CNN familyConvolutions can offer a practical speed/accuracy/memory trade-off
Very large-scale vision with strong pretrainingCompare CNN and Vision TransformerTransformers model global relationships differently; the best choice is empirical
Tabular rows with unrelated columnsTree model or MLPNeighbouring columns usually do not have image-like spatial meaning
Tiny, fixed problem with handcrafted measurementsClassical ML baselineA CNN may add needless data and compute requirements
Precise pixel labellingSegmentation CNN such as U-NetA 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.

Important limits: CNNs can require substantial labelled data and compute, learn spurious shortcuts, fail under distribution shift or adversarial perturbations, and remain difficult to interpret. A confident score is not proof that the model used the right visual evidence.

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.

Continue Learning

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "CNNs and Image Classification"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Summary / Key Takeaways

  • A CNN learns local visual patterns from pixel arrays.
  • A shared filter slides across the image to create a feature map.
  • Stride, padding, kernel size, channels, and dilation determine shape and coverage.
  • Stacked nonlinear layers combine edges into complex features.
  • Pooling or strided convolution reduces spatial resolution.
  • Evaluate accuracy, robustness, localization, latency, memory, and bias.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
Why can one CNN filter detect an edge in different image locations?
Question 2 of 5numerical/formula
For input width 5, kernel 3, padding 0, stride 1, what is output width?
Question 3 of 5interpretation
What does a feature-map value represent?
Question 4 of 5interpretation
What does stride 2 usually do compared with stride 1?
Question 5 of 5practical selection
Why can pooling hurt segmentation?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1Why can one CNN filter detect an edge in different image locations?▼

Correct Answer: The same weights slide across the image

Weight sharing applies one learned local detector at every valid position.

2For input width 5, kernel 3, padding 0, stride 1, what is output width?▼

Correct Answer: 3

The formula floor((5-3+0)/1)+1 gives 3 positions.

3What does a feature-map value represent?▼

Correct Answer: The filter's response at one spatial position

Each value summarizes how strongly the local patch matches the learned pattern.

4What does stride 2 usually do compared with stride 1?▼

Correct Answer: Reduces spatial output resolution

The kernel moves two positions at a time, so it produces fewer spatial responses.

5Why can pooling hurt segmentation?▼

Correct Answer: It discards precise spatial detail

Segmentation needs accurate locations, while pooling deliberately summarizes neighbourhoods.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Optional Learning Resources

These resources may complement the lesson. They are optional and are not required to use ML Academy.

As an Amazon Associate I earn from qualifying purchases. Other links are identified separately when they are not affiliate links.

Next