Convolutional Neural Networks

Updated · 11 min read
hardPython 3.13aideep-learningcnnconvolutionpoolingpytorch

A convolutional neural network (CNN) is a neural network built for images. Instead of connecting every pixel to every neuron, it slides small filters (also called kernels), often 3 × 3 pixels, across the image. Each filter looks for one simple pattern, such as an edge, wherever it appears. Layers of filters build up from edges to shapes to whole objects.

This lesson computes a convolution by hand, checks it in PyTorch, and then trains a CNN on the handwritten digits from "Training a Network in PyTorch".

The Parts of a CNN

PartDescription
Filter (kernel)It is used to detect one small pattern; a grid of weights such as 3 × 3, learned in training
ConvolutionSliding a filter over the image, multiplying and adding at each position
Feature mapThe output of one filter: a grid showing where its pattern was found
ChannelsColor images have 3 input channels; each filter in a layer makes one output channel
PoolingIt is used to shrink a feature map, keeping the strongest value in each small block
Padding and stridePadding adds a border so the size stays the same; stride is how far the filter moves each step

Example: Convolution by Hand

This program slides a 3 × 3 edge filter over a tiny 6 × 6 image that is dark on the left and bright on the right.

A filter slides over the image and lights up where its pattern is
Python
import numpy as np
 
# A 6x6 grayscale image: dark on the left (0), bright on the right (9)
image = np.array([
    [0, 0, 0, 0, 9, 9],
    [0, 0, 0, 0, 9, 9],
    [0, 0, 0, 0, 9, 9],
    [0, 0, 0, 0, 9, 9],
    [0, 0, 0, 0, 9, 9],
    [0, 0, 0, 0, 9, 9],
])
 
# A 3x3 filter that responds to dark-to-bright edges going left to right
kernel = np.array([
    [-1, 0, 1],
    [-1, 0, 1],
    [-1, 0, 1],
])
 
def convolve(image, kernel):
    k = kernel.shape[0]
    rows, cols = image.shape[0] - k + 1, image.shape[1] - k + 1
    out = np.zeros((rows, cols), dtype=int)
    for r in range(rows):
        for c in range(cols):
            patch = image[r:r + k, c:c + k]        # the 3x3 window under the filter
            out[r, c] = (patch * kernel).sum()     # multiply and add up
    return out
 
feature_map = convolve(image, kernel)
print("Feature map (6x6 image, 3x3 filter -> 4x4):")
print(feature_map)
 
def max_pool(x, size=2):
    rows, cols = x.shape[0] // size, x.shape[1] // size
    return x[:rows * size, :cols * size].reshape(rows, size, cols, size).max(axis=(1, 3))
 
print("After 2x2 max pooling (4x4 -> 2x2):")
print(max_pool(feature_map))
Output
Feature map (6x6 image, 3x3 filter -> 4x4):
[[ 0  0 27 27]
 [ 0  0 27 27]
 [ 0  0 27 27]
 [ 0  0 27 27]]
After 2x2 max pooling (4x4 -> 2x2):
[[ 0 27]
 [ 0 27]]

Explanation:

  • At each position, the filter covers a 3 × 3 window of the image. Each pixel is multiplied by the filter weight on top of it, and the 9 products are added up.
  • The filter subtracts the left column from the right column, so it gives 0 on flat areas and a large number where brightness jumps from left to right. Over the edge, the window holds three 0s and three 9s on its right side: 9 + 9 + 9 = 27.
  • The feature map is 4 × 4, smaller than the image, because a 3 × 3 filter fits in only 4 positions across 6 pixels.
  • Max pooling keeps the largest value in each 2 × 2 block. The 2 × 2 result still says "edge on the right" with a quarter of the numbers.

Example: The Same Thing in PyTorch

nn.Conv2d and nn.MaxPool2d do the same work. This program sets the filter by hand to check the result, then follows the shape of one 8 × 8 digit through a small CNN.

Python
import torch
from torch import nn
 
image = torch.tensor([[0, 0, 0, 0, 9, 9]] * 6, dtype=torch.float32)
x = image.reshape(1, 1, 6, 6)                 # (images, channels, height, width)
 
conv = nn.Conv2d(in_channels=1, out_channels=1, kernel_size=3, bias=False)
with torch.no_grad():
    conv.weight[:] = torch.tensor([[-1., 0., 1.]] * 3)   # the same edge filter as before
print("Conv2d output:")
print(conv(x)[0, 0].detach())
print("After MaxPool2d(2):")
print(nn.MaxPool2d(2)(conv(x))[0, 0].detach())
 
# A real CNN learns many filters at once; watch the shape change layer by layer
torch.manual_seed(0)
cnn = nn.Sequential(
    nn.Conv2d(1, 16, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
    nn.Conv2d(16, 32, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
    nn.Flatten(), nn.Linear(32 * 2 * 2, 10),
)
x = torch.zeros(1, 1, 8, 8)                   # one 8x8 grayscale digit
for layer in cnn:
    x = layer(x)
    print(f"{type(layer).__name__:10} -> {tuple(x.shape)}")
print("Parameters:", f"{sum(p.numel() for p in cnn.parameters()):,}")
Output
Conv2d output:
tensor([[ 0.,  0., 27., 27.],
        [ 0.,  0., 27., 27.],
        [ 0.,  0., 27., 27.],
        [ 0.,  0., 27., 27.]])
After MaxPool2d(2):
tensor([[ 0., 27.],
        [ 0., 27.]])
Conv2d     -> (1, 16, 8, 8)
ReLU       -> (1, 16, 8, 8)
MaxPool2d  -> (1, 16, 4, 4)
Conv2d     -> (1, 32, 4, 4)
ReLU       -> (1, 32, 4, 4)
MaxPool2d  -> (1, 32, 2, 2)
Flatten    -> (1, 128)
Linear     -> (1, 10)
Parameters: 6,090

Explanation:

  • PyTorch gives the same 4 × 4 and 2 × 2 results as the hand calculation. Images go in as (images, channels, height, width).
  • The first Conv2d(1, 16, ...) learns 16 filters, so one grayscale image becomes 16 feature maps. padding=1 keeps them 8 × 8.
  • Each MaxPool2d(2) halves the height and width: 8 to 4 to 2.
  • The second convolution combines the 16 maps into 32 new ones, which can detect bigger patterns made of edges, such as loops and corners.
  • Flatten turns the 32 × 2 × 2 maps into 128 numbers, and a Linear layer gives one score per digit. The whole network has 6,090 parameters.

Example: A CNN vs a Dense Network

This program trains the CNN and the dense network from "Training a Network in PyTorch" the same way, then tests both on the normal test digits and on the same digits moved one pixel to the right.

Python
import torch
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
 
digits = load_digits()
X = torch.tensor(digits.images / 16, dtype=torch.float32).unsqueeze(1)   # (1797, 1, 8, 8)
y = torch.tensor(digits.target)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
 
def train(model):
    batches = DataLoader(TensorDataset(X_train, y_train), batch_size=32, shuffle=True)
    optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
    for _ in range(20):
        for images, labels in batches:
            optimizer.zero_grad()
            nn.functional.cross_entropy(model(images), labels).backward()
            optimizer.step()
    return model.eval()
 
def accuracy(model, images):
    with torch.no_grad():
        return (model(images).argmax(dim=1) == y_test).float().mean().item()
 
torch.manual_seed(0)
mlp = train(nn.Sequential(nn.Flatten(), nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, 10)))
torch.manual_seed(0)
cnn = train(nn.Sequential(
    nn.Conv2d(1, 16, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
    nn.Conv2d(16, 32, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
    nn.Flatten(), nn.Linear(128, 10),
))
 
shifted = torch.roll(X_test, shifts=1, dims=3)        # move every test digit 1 pixel right
shifted[..., 0] = 0                                   # blank the column that wrapped around
for name, model in [("Dense network (MLP)", mlp), ("CNN", cnn)]:
    params = sum(p.numel() for p in model.parameters())
    print(f"{name:20} {params:5,} parameters  test {accuracy(model, X_test):.1%}"
          f"  shifted 1 pixel {accuracy(model, shifted):.1%}")
Output
Dense network (MLP)  2,410 parameters  test 97.8%  shifted 1 pixel 46.2%
CNN                  6,090 parameters  test 97.8%  shifted 1 pixel 69.3%

Explanation:

ModelParametersTest accuracyMoved 1 pixel
Dense network (MLP)2,41097.8%46.2%
CNN6,09097.8%69.3%
  • On the normal test images, both score 97.8%. These 8 × 8 digits are small and centered, so a dense network does well.
  • Moving every digit one pixel breaks the dense network: it falls to 46.2%. Each of its weights is tied to one pixel position, so a shifted digit looks like a different pattern.
  • The CNN holds up much better, at 69.3%, because the same filter is used at every position and pooling ignores small shifts. It still drops, because it never saw shifted digits in training.
  • On real photos with millions of pixels, this sharing matters even more: a dense layer on a 224 × 224 color photo would need over 150,000 weights per neuron, while a 3 × 3 filter has 27.

Famous CNNs

ModelYearWhat it showed
LeNet-51998CNNs can read handwritten digits on checks
AlexNet2012A deep CNN trained on GPUs won the ImageNet contest by a large margin, starting the deep learning boom
VGG2014Stacking many small 3 × 3 filters works well
ResNet2015"Skip connections" let networks train with 100 or more layers; ResNet-18 has 18
EfficientNet, MobileNet2017 to 2019Accurate CNNs small and fast enough for phones

Common Mistakes

Wrong input shape. Conv2d expects (batch, channels, height, width). A single grayscale image needs unsqueeze to add the missing dimensions.

Losing track of sizes. Each convolution without padding and each pooling layer shrinks the image. Print the shape after every layer, as in the second example.

Expecting a CNN to handle any change. CNNs handle small shifts better than dense networks, but not rotations, very different sizes or new lighting unless the training data includes them.

Training a big CNN from scratch on a few hundred images. It will overfit. Start from a pretrained CNN instead; see "Transfer Learning".

Interview Corner

Why are CNNs better than dense networks for images?

They share each small filter across every position, so they need far fewer weights and recognize a pattern wherever it appears. Pooling adds tolerance to small shifts, and stacked layers build edges into shapes and objects.

What does a pooling layer do?

It shrinks each feature map, usually keeping the maximum value in each 2 × 2 block. This reduces computation and makes the network less sensitive to exactly where a feature appears.

Practice

Exercise: a horizontal edge. Change the filter in the first program to [[-1, -1, -1], [0, 0, 0], [1, 1, 1]]. What feature map do you get for the same image, and why? Then make an image with a horizontal edge and try again.

Check your understanding:

  1. Why is the feature map 4 × 4 when the image is 6 × 6?
  2. What does padding=1 do in Conv2d(1, 16, kernel_size=3, padding=1)?
  3. Why did the dense network fall to 46.2% on shifted digits?

Quick check: CNNs

4 questions
1Over the edge, what value did the filter produce?
2What does 2 × 2 max pooling do to a 4 × 4 feature map?
3On digits moved one pixel, how did the CNN do?
4Who chooses the filter weights in a real CNN?

Key Takeaways

Quick reference

NeedCode
Convolution layernn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1)
Max poolingnn.MaxPool2d(2)
Flatten for a Linear layernn.Flatten()
Image tensor shape(batch, channels, height, width)
Add a channel dimensionx.unsqueeze(1)
Shift test imagestorch.roll(x, shifts=1, dims=3)

Was this tutorial helpful?

Lesson 141 of 186