Kernels & Filters
How convolutional filters detect local features by sliding a small weight matrix across the input.
The Building Blocks section assembled the machinery of a deep network: linear layers transform data, activation functions introduce non-linearity, and regularization techniques keep models from overfitting. For many tasks — tabular data, simple classification — this is enough. But images present a different challenge. A standard linear layer applied directly to image pixels fails at scale, wasting parameters on patterns it is structurally unable to learn. This section introduces the solution: the convolutional layer.
Why Linear Layers Fail for Images
Consider a modest RGB image. Flattened, it has input values. A single fully connected layer with output neurons requires million parameters — for one layer of moderate size. This is both memory-expensive and sample-inefficient: the model needs enormous amounts of training data to learn million weights reliably.
More fundamentally, the parameter count is the least of the problems. A fully connected layer treats every input pixel identically. It cannot exploit two properties that all images share:
Spatial locality. Meaningful features — edges, corners, textures — are formed by groups of nearby pixels. A pixel at position is far more informative in combination with its neighbours than with a pixel at a distant corner of the image.
Translation equivariance. A horizontal edge in the top-left of an image looks the same as a horizontal edge in the bottom-right. A fully connected layer must learn to detect each feature independently at every spatial location, using entirely separate weights. There is no mechanism to share the knowledge that "a horizontal edge looks like this" across positions.
The Key Idea: Local Connectivity and Weight Sharing
Two structural changes resolve both problems.
Local connectivity restricts each output neuron to depend on only a small neighbourhood of the input, called its receptive field. Rather than connecting every output to every input, a 3×3 filter connects each output to a 3×3 patch — just 9 inputs instead of hundreds of thousands.
Weight sharing goes further: the same set of weights is applied at every spatial position. A single filter that detects horizontal edges uses the same 9 parameters whether it is looking at the top-left or the bottom-right of the image. This encodes translation equivariance directly into the architecture, and it reduces the parameter count from millions to single digits for the feature itself.
These two ideas together define the convolution operation.
The Convolution Operation
A filter (also called a kernel) is a small matrix of learnable weights, typically or . Applied to an input , it produces one output value per spatial position by computing the element-wise product between the filter and the corresponding input patch, then summing:
This is the dot product of the filter weights with each local input patch, computed at every valid position .
Numerical example. Using the input (so the top-left cell is , increasing by in each direction) and the filter (which sums the four axis-adjacent neighbours):
For position , the input patch is :
The filter slides across every valid position of the input. For a input and filter with no padding, there are valid positions, producing a output called a feature map.
Feature Maps and Multiple Filters
The output of one filter is a two-dimensional feature map: a grid where each value encodes how strongly that filter's pattern was detected at that location. A large value at position means the input contained a strong match for the filter's learned pattern in the patch centred at .
A single filter can detect a single type of feature. A real convolutional layer applies different filters simultaneously, each learning to detect a different pattern. The feature maps are stacked along a new depth dimension, producing a three-dimensional output tensor of shape .
Early layers in a deep network typically learn low-level features: edges at various orientations, colour gradients, simple textures. Later layers, receiving stacked feature maps as their input, combine these into progressively higher-level patterns: corners, shapes, object parts.
Input Channels
Natural images have three colour channels (RGB). A filter that operates on a three-channel input has shape — a separate slice per input channel. The output at each position is the sum of the dot products across all input channels:
Each filter still produces a single 2D feature map, but it now combines information from all input channels. Applying such filters to a -channel input produces a -to- channel transformation.
Padding
Without padding, every filter application consumes a border of pixels, so the feature map shrinks relative to the input. In a deep network this progressive shrinkage can eliminate spatial resolution long before the network is done processing.
Valid padding (no padding): the output is strictly smaller than the input.
Same padding: add rows and columns of zeros to each border so the output has the same spatial dimensions as the input.
Same padding is the default for most modern architectures. It preserves spatial dimensions through a stack of convolutional layers, giving later layers full-resolution feature maps to work with.
Output Size and Parameter Count
For a layer with stride (the filter moves one step at a time), kernel size , and padding :
Applying filters of size to a -channel input, with one bias per filter:
Example. A layer with filters of size applied to a -channel RGB input:
Compare this to a fully connected layer from inputs to outputs: million parameters. The convolutional layer achieves the same spatial feature extraction with fewer parameters, purely because of weight sharing.
Connection to Linear Layers
A convolutional layer is a linear layer with two constraints baked in: local connectivity (each output depends on a small input region) and weight sharing (all positions use the same weights). The convolution operation is still a matrix multiplication — just a highly structured one with most weights tied to the same values.
The choice of kernels as the standard is not arbitrary: three stacked layers have the same receptive field as one layer, but with roughly half the parameters and two extra activation functions in between. Depth of layers is the dominant design pattern in modern convolutional architectures.
In Code
import torch
import torch.nn as nn
# ── Numerical example: cross-shaped kernel on a 5×5 input ──────────────────
# Conv2d expects (batch, C_in, H, W) for the input; its weight is (C_out, C_in, kH, kW)
conv = nn.Conv2d(in_channels=1, out_channels=1, kernel_size=3, padding=0)
x = torch.tensor([[[[1.,2.,3.,4.,5.],
[2.,3.,4.,5.,6.],
[3.,4.,5.,6.,7.],
[4.,5.,6.,7.,8.],
[5.,6.,7.,8.,9.]]]]) # (1, 1, 5, 5)
# Set the kernel weights by hand (they are learnable parameters, normally initialised randomly)
with torch.no_grad():
conv.weight[:] = torch.tensor([[[[0.,1.,0.],
[1.,0.,1.],
[0.,1.,0.]]]]) # (1, 1, 3, 3)
conv.bias[:] = 0.
# No padding: H_out = H_in − k + 1 = 5 − 3 + 1 = 3
out = conv(x)
print(out.shape) # torch.Size([1, 1, 3, 3])
print(out[0, 0])
# tensor([[12., 16., 20.],
# [16., 20., 24.],
# [20., 24., 28.]])
# Gradient flows back through the kernel
out.sum().backward()
print(conv.weight.grad.shape) # torch.Size([1, 1, 3, 3]) — ∂L/∂kernel, same shape as the kernel
# ── Same padding: padding=1 keeps the output the same size as the input ─────
conv_same = nn.Conv2d(in_channels=1, out_channels=1, kernel_size=3, padding=1)
print(conv_same(x).shape) # torch.Size([1, 1, 5, 5]) — spatial dims preserved
# ── Multiple filters with bias: 3-channel input → 32 feature maps ───────────
conv_multi = nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, padding=1)
x_rgb = torch.randn(1, 3, 256, 256) # (batch, C_in, H, W)
print(conv_multi(x_rgb).shape) # torch.Size([1, 32, 256, 256])
print(conv_multi.weight.shape) # torch.Size([32, 3, 3, 3])
print(sum(p.numel() for p in conv_multi.parameters())) # 896 = 32 filters × (3×3×3 weights + 1 bias)
A convolutional filter is a learned feature detector that scans the entire input for one type of pattern. Stacking many filters produces rich multi-channel feature representations, and stacking many layers builds increasingly abstract descriptions of the input. The next article examines the complementary operation: downsampling, which progressively reduces spatial resolution to increase the receptive field of later layers and control computational cost.