6.2 Convolutions for Images
In Section 6.1, we derived the convolutional layer on paper from two geometric principles: translation equivariance and locality. Now we see what that formula actually computes on an image, and whether gradient descent can discover useful kernels automatically from data.
Consider locating vertical edges where a bright region meets a dark one. Subtracting each pixel's right-hand neighbor () yields zero inside uniform regions, where white transitions to black, and where black returns to white. Sweeping the two-weight detector across every valid image location produces an edge map. In this section, we implement two-dimensional cross-correlation, test our hand-crafted edge detector, let gradient descent learn directly from data, show how a convolution becomes a single matrix multiplication (im2col), and derive how stacking layers widens a unit's receptive field.
6.2.1 Cross-Correlation#
6.2.1.1 The Operation#
Leaving channels aside for the moment, let the input be an matrix and the kernel be a matrix. The kernel defines a sliding window of shape . Placing the window's upper-left corner at , we multiply the covered input patch elementwise with and sum the products to produce the output entry at :
This is the two-dimensional cross-correlation of with , written with zero-based indices matching code. Whereas Section 6.1 centered offsets symmetrically from to , anchoring at the upper-left corner differs only by a fixed shift of while naturally handling even-sized kernels (such as a kernel or our edge detector) that have no center pixel.
Two-dimensional cross-correlation. The shaded portions are the first output element and the input and kernel elements used to compute it: .
In Figure 6.2.1, we slide a kernel across a input one pixel at a time, left to right and top to bottom. The window fits cleanly at four positions, yielding the output:
Notice that the output shrinks slightly along each axis because the kernel must stay wholly inside the input. Fitting a width- window into length leaves valid positions, so the output shape is
Thus a input with a kernel yields , a image with a kernel yields , and a Fashion-MNIST image with a kernel yields . Whenever we want to preserve spatial dimensions, we surround the input with a border of zeros (padding), which we examine alongside strides and dilation in Section 6.3.
6.2.1.2 Implementation#
We implement (6.2.1) directly in corr2d using a pair of loops over
every output coordinate.
def corr2d(X, K):
"""Compute 2D cross-correlation."""
h, w = K.shape
Y = d2l.zeros((X.shape[0] - h + 1, X.shape[1] - w + 1))
for i in range(Y.shape[0]):
for j in range(Y.shape[1]):
Y[i, j] = d2l.reduce_sum((X[i: i + h, j: j + w] * K))
return YTo verify corr2d against our hand calculation in Figure 6.2.1,
we construct the input tensor X and kernel K and
evaluate corr2d(X, K).
X = d2l.tensor([[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]])
K = d2l.tensor([[0.0, 1.0], [2.0, 3.0]])
corr2d(X, K)tensor([[19., 25.],
[37., 43.]])
The output reproduces Figure 6.2.1 entry for entry (and as shown in Section 6.1, strict mathematical convolution with a flipped kernel learns the exact same family of layers, so we follow standard deep learning terminology and call cross-correlation "convolution").
6.2.2 Convolutional Layers#
6.2.2.1 The Layer#
A two-dimensional convolutional layer cross-correlates its input with a learned
kernel and adds a scalar bias. Just like our MLP weights in
Chapter 4, we initialize the kernel from
and the bias to zero. Below, Conv2D registers both
parameters and invokes corr2d in its forward pass; a layer with a kernel of
height and width is called an convolutional layer.
class Conv2D(nn.Module):
def __init__(self, kernel_size):
super().__init__()
self.weight = nn.Parameter(0.01 * torch.randn(kernel_size))
self.bias = nn.Parameter(torch.zeros(1))
def forward(self, x):
return corr2d(x, self.weight) + self.biasUnlike a dense layer, a convolutional layer is not locked to a fixed input
resolution because its parameters depend only on the kernel size. The exact same
layer (5 parameters total) processes both our tensor
X and a image, returning outputs of shapes and
:
layer = Conv2D((2, 2))
layer(X).shape, layer(d2l.ones((6, 8))).shape(torch.Size([2, 2]), torch.Size([5, 7]))
6.2.2.2 Edge Detection#
We now test the vertical edge detector from the introduction on a
synthetic image whose middle four columns are black (0) and outer
columns are white (1).
X = d2l.ones((6, 8))
X[:, 2:6] = 0
Xtensor([[1., 1., 0., 0., 0., 0., 1., 1.],
[1., 1., 0., 0., 0., 0., 1., 1.],
[1., 1., 0., 0., 0., 0., 1., 1.],
[1., 1., 0., 0., 0., 0., 1., 1.],
[1., 1., 0., 0., 0., 0., 1., 1.],
[1., 1., 0., 0., 0., 0., 1., 1.]])
We define the kernel
At every position , this computes the horizontal finite difference , a discrete approximation (up to sign) of the horizontal derivative of brightness, which vanishes across flat regions and spikes wherever intensity jumps.
K = d2l.tensor([[1.0, -1.0]])
Cross-correlating the stripe image X with the
horizontal-difference kernel K via corr2d(X, K) produces the
edge map Y:
Y = corr2d(X, K)
Ytensor([[ 0., 1., 0., 0., 0., -1., 0.],
[ 0., 1., 0., 0., 0., -1., 0.],
[ 0., 1., 0., 0., 0., -1., 0.],
[ 0., 1., 0., 0., 0., -1., 0.],
[ 0., 1., 0., 0., 0., -1., 0.],
[ 0., 1., 0., 0., 0., -1., 0.]])
Sure enough, Y fires +1 along the white-to-black boundary, -1 along the
black-to-white boundary, and 0 everywhere else. Applying the exact same kernel
to the transposed image (turning the vertical stripe into a horizontal one)
yields all zeros:
corr2d(d2l.transpose(X), K)tensor([[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]])
Clearly [1, -1] responds strictly to vertical edges. Detecting horizontal
edges, diagonals, corners, or textures requires different kernels altogether.
6.2.2.3 Learning a Kernel#
Hand-crafting [1, -1] is easy when we know the exact feature we want, yet no
engineer can specify thousands of intermediate filters across a deep network by
hand. Can gradient descent recover the kernel [1, -1] from the input–output
pair (X, Y) alone? We test this using each framework's built-in 2D
convolutional layer (with bias omitted and weights initialized from
), minimizing squared error summed across all 42 output
entries over 10 gradient steps at learning rate . Because built-in layers
expect 4D tensors including batch and channel axes (Section 6.4), we
reshape X and Y accordingly.
conv2d = nn.Conv2d(1, 1, kernel_size=(1, 2), bias=False)
nn.init.normal_(conv2d.weight, std=0.01)
# Layers take (example, channel, height, width): one example, one channel
X = X.reshape((1, 1, 6, 8))
Y = Y.reshape((1, 1, 6, 7))
lr = 3e-2 # Learning rate
for i in range(10):
l = ((conv2d(X) - Y) ** 2).sum()
conv2d.zero_grad()
l.backward()
with torch.no_grad():
conv2d.weight -= lr * conv2d.weight.grad
if i % 3 == 0:
print(f'step {i}, loss {l:.3f}')step 0, loss 12.216
step 3, loss 0.840
step 6, loss 0.058
step 9, loss 0.004
Initially the loss sits near 12 (the near-zero random kernel misses all 12 edge pixels by roughly 1), and within just nine steps it drops below 0.01. Inspecting the learned kernel confirms what it found:
d2l.reshape(conv2d.weight.data, (1, 2))tensor([[ 0.9891, -0.9876]])
Both entries land within roughly 0.02 of [1, -1]. Nothing in this loop knew
anything about edges: given a loss signal, gradient descent discovered the
filter on its own. Here we supervised the single layer directly with Y; in a
deep CNN, backpropagation learns every layer's kernels end to end from the final
task loss alone.
6.2.3 Convolution as Matrix Multiplication#
While the nested loops in corr2d make the math transparent, visiting one
output pixel at a time in Python is far too slow for real workloads. A classic
remedy, and still one of the algorithms that libraries choose from, is to recast
cross-correlation as a single large matrix multiplication, the exact operation
GPUs execute at peak speed. Notice that every
output entry in Figure 6.2.1 is simply the dot product of the
flattened -element kernel with the corresponding
flattened input window. Extracting all
windows and
stacking them as rows yields a patch matrix; multiplying it by the flattened
kernel computes the entire cross-correlation in one shot. This standard layout
transformation is called im2col ("image to columns", or rows here).
Figure 6.2.2 carries it out on the example of
Figure 6.2.1.
The cross-correlation of Figure 6.2.1 as one matrix product. Each of the four windows of the input becomes a row of the patch matrix, and multiplying by the flattened kernel gives the flattened output. The shaded cells follow the first window to its row and to the output 19. The center pixel 4 lies in all four windows, so it appears in every row.
The trade-off is extra workspace memory, since each interior pixel is duplicated
into up to patches. Below we verify on
Figure 6.2.1 that this single matrix multiply matches corr2d
exactly:
X = d2l.tensor([[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]])
K = d2l.tensor([[0.0, 1.0], [2.0, 3.0]])
h, w = K.shape
h_o, w_o = X.shape[0] - h + 1, X.shape[1] - w + 1
patches = d2l.stack([d2l.reshape(X[i:i + h, j:j + w], (-1,))
for i in range(h_o) for j in range(w_o)])
Y_mat = d2l.reshape(d2l.matmul(patches, d2l.reshape(K, (-1, 1))), (h_o, w_o))
Y_mat, d2l.reduce_sum(d2l.abs(Y_mat - corr2d(X, K)))(tensor([[19., 25.],
[37., 43.]]),
tensor(0.))
The discrepancy is identically zero: one matrix product reproduces corr2d
perfectly.
Equivalently, we can unroll the kernel instead of the input into a sparse banded matrix multiplying the flattened image—the exact 2D analog of panel (c) in Figure 6.1.3, where every row repeats the same handful of kernel weights. Seeing a convolution as a structured dense layer brings us full circle to the derivation of Section 6.1 (and the exercises build explicitly).
6.2.4 Feature Maps and Receptive Fields#
A single convolutional layer sees only a patch the size of its kernel, whereas
recognizing whole objects demands integrating context across much wider areas.
Recall from Section 6.1.4 that a convolutional layer's
output is called a feature map (like our vertical edge map Y). For any
element in a feature map, its receptive field is the region of the input
image (or of an earlier layer) whose values can influence during forward
propagation—borrowing the neurophysiology term from Figure 6.1.
6.2.4.1 Stacked Layers#
In Figure 6.2.1, the shaded output 19 has a receptive
field covering the top-left four pixels of . Now stack a second
convolutional layer on top of the output
to produce a single scalar : depends on all four elements of ,
which together depend on all nine elements of . Stacking layers
expands the receptive field smoothly with depth.
How quickly does it grow? Each convolutional layer reaches pixels farther than a single element of its input, so stacking layers with kernel sizes yields a receptive field of side length
For a stack of consecutive layers, each layer adds 2 pixels, covering inputs: after two layers and after three (Figure 6.2.3). This linear growth is actually a blessing rather than a reason to reach for huge kernels: three stacked layers achieve the same receptive field as a single layer using far fewer parameters ( weights vs. 49 per channel pair) while interleaving three nonlinearities instead of one.
Receptive field of one unit after three one-dimensional layers with kernel size 3. Shaded cells are the units that the top unit depends on, and the lines connect each of them to its inputs. Each layer widens the receptive field by 2, to 7 inputs.
6.2.4.2 Effective Receptive Fields#
Keep in mind that measures the theoretical receptive field (every input pixel with any path to an output unit) without saying how strongly each pixel actually contributes. Measuring input gradients directly, Luo et al. (2016) showed that the effective receptive field decays sharply away from the center in a roughly Gaussian bell curve, in both untrained and trained networks. Deep units can theoretically see far across the image, but their sensitivity concentrates heavily near the center.
Counting paths explains the bell shape. An input at the edge of the receptive field reaches the output unit along a single chain of connections, whereas the center input can take many routes through the layers in between. Figure 6.2.4 counts them for the tower of Figure 6.2.3: the center input has seven paths to the top unit and each edge input has one. If all weights have a similar magnitude, the influence of an input grows with its number of paths.
Number of paths from each unit to the top unit of Figure 6.2.3 (three one-dimensional layers with kernel size 3). Each count is the sum of the counts of the units that the cell feeds. Darker cells have more paths than the other cells of their layer, and the bars repeat the counts of the input row: 1, 3, 6, 7, 6, 3, 1.
Two practical gaps remain in our basic layer: every unpadded convolution shrinks spatial dimensions while under-sampling border pixels, and a single kernel detects only one pattern. We address spatial sizing and borders next in Section 6.3, and multi-channel feature maps in Section 6.4.
6.2.5 Summary#
A convolutional layer applies two-dimensional cross-correlation with a learned
kernel plus a scalar bias, sliding the kernel across every valid window of the
input. A simple finite-difference kernel [1, -1] detects vertical
edges anywhere in an image, and gradient descent recovers those exact weights
from input–output data alone, just as deep CNNs learn entire hierarchies of
filters end to end. Mathematical convolution flips the kernel, making no
difference once kernels are learned. A convolution can be evaluated as a single
matrix multiplication (im2col), and stacking convolutional
layers widens each unit's receptive field linearly by per layer.
6.2.6 Exercises#
-
[code] Hand-designed kernels. Design some kernels manually.
- Given a directional vector , derive an edge-detection kernel that detects edges orthogonal to , i.e., edges in the direction .
- Derive a finite difference operator for the second derivative. Which structures in images respond most strongly to it?
- What is the minimum size of a kernel to obtain a derivative of order ?
- How would you design a blur kernel? Why might you want to use such a kernel?
- Load a photograph, convert it to one channel, and downsample it to
about pixels (
corr2dloops in Python). Apply the edge detector, the blur kernel, and the sharpening kernel "twice the identity minus the blur", and display each result next to the original. What does the edge map of a photograph show that the edge map of the black band could not?
Adapted from Stanford CS231n, Assignment 2, ConvolutionalNetworks notebook.
-
[code] Convolution as a banded matrix. The patch matrix of Section 6.2.3 unfolds the input. The opposite construction unrolls the kernel. Let be a input, a kernel, and the row-by-row flattening.
- Construct the matrix with , where is the cross-correlation of with . How many nonzero entries does each row have, and how many distinct values appear in ?
- Build in code from
Kand confirm that the product reproducescorr2d(X, K). - For an input and a kernel, count the entries of stored as a dense array, the nonzero entries of , and the entries of the patch matrix. How does each count grow with ?
- Keep the sparsity pattern of but give every row its own values. The result is a locally connected layer: the fourth-order tensor of Section 6.1 in , restricted to a window of offsets before translation equivariance ties the weights. For an input, count the parameters of this layer, of a fully connected layer with the same input and output shapes, and of the convolution.
Adapted from CMU 11-785, Homework 2 Part 1.
-
[code] Effective receptive field. ● The theoretical receptive field of this section bounds which inputs can influence an output; the effective receptive field measures how much they actually do (Luo et al., 2016). Build a stack of single-channel convolutional layers with no padding, no bias, and no nonlinearity on a input, using the built-in layer of Section 6.2.2.3. Draw every kernel entry independently from a standard normal distribution.
- For and a single draw of the kernels, backpropagate a unit gradient from an output unit near the center of the last layer to the input and plot the magnitude of the input gradient. Compare its support with the theoretical receptive field, and say where the magnitude is largest.
- Average the squared input gradient over 500 draws of the kernels, for and for . Sum each averaged map over its rows and normalize the resulting column profile to sum to one. How does the ratio of the profile's standard deviation to the theoretical side length change with depth?
- Figure 6.2.4 counts the paths for in one dimension. Show that for general the expected squared input gradient, summed over rows, is proportional to the convolution of copies of the vector . Derive how the standard deviation of the normalized profile grows with .
-
[code] Backward pass of a convolution. ● Let be the single-channel cross-correlation of an input with a kernel , as computed by
corr2d, and let be a scalar loss that depends on and only through .- Derive and in terms of , in the style of the backpropagation equations of Section 4.3.
- Implement your expression for
without automatic differentiation for the loss
, where is a fixed
random matrix of the shape of . Compare it with a
centered finite-difference gradient with step size on a
small random
XandK, and report the largest relative error. - Check your expression for against the kernel gradient that automatic differentiation computes in the experiment of Section 6.2.2.3.
Adapted from Michael Nielsen, Neural Networks and Deep Learning, Chapter 6, and Stanford CS231n, Assignment 2, ConvolutionalNetworks notebook.