17  Lesson 5: CNNs, ResNets, and Augmentation

Locality, spatial information, receptive fields, and residual learning

17.1 Learning goals

After studying this chapter, a student should be able to:

  • explain why convolution is a useful operation for images;
  • calculate the output shape, parameter count, and receptive field of a convolutional network;
  • describe how a CNN builds a hierarchy of learned features;
  • explain the roles of activation, normalization, pooling, and channel mixing;
  • read and evaluate a standard CNN architecture;
  • explain why very deep plain networks are difficult to train;
  • derive the main equations of a residual block and describe a complete ResNet; and
  • recognize important limits of CNNs, including shortcut learning, distribution shift, and weak global reasoning.

This chapter assumes familiarity with fully connected neural networks, gradient descent, and backpropagation. We begin with the problem that motivates CNNs, build the convolutional layer carefully, and then assemble complete architectures. Only after the basic theory is in place do we study residual networks and the main challenges of convolutional models.

When spatial concepts are discussed abstractly, tensors are written as \(H\times W\times C\). In architecture tables and implementation-oriented examples, we use the common channel-first convention \(C\times H\times W\).

17.2 Why convolutional networks?

An image can be stored as a vector and passed to a fully connected network; this is mathematically valid. The problem is that flattening an image hides useful structure from the model.

Consider a color image with height \(224\), width \(224\), and three color channels. It contains

\[ 224\times224\times3=150{,}528 \]

input values. A fully connected network with a single hidden layer containing only \(1{,}000\) hidden units would require

\[ 150{,}528\times1{,}000+1{,}000=150{,}529{,}000 \]

parameters. More importantly, the layer would learn a separate weight for every input position. If it learned to recognize a vertical edge near the left side of an image, it would not automatically use that knowledge to recognize the same edge near the right side.

A convolutional neural network, or CNN, uses two observations about images:

  1. Locality: nearby pixels often form meaningful local patterns such as edges, corners, and textures.
  2. Reuse across position: the same kind of pattern may appear at many locations in an image.

A convolutional layer therefore connects each output value to a small neighborhood and applies the same set of weights at every location. These choices are called inductive biases: assumptions built into a model before it sees any data. They do not guarantee that the model will learn the right solution, but they make suitable functions for image tasks easier to learn.

A fully connected layer treats every pixel-position pair separately, whereas a convolutional layer repeatedly applies a local detector.

flowchart LR
  subgraph FC[Fully connected view]
    A[Flattened image] --> B[Every input connected<br/>to every hidden unit]
  end
  subgraph CNN[Convolutional view]
    C[Image grid] --> D[Small local window]
    D --> E[Same detector reused<br/>across the grid]
  end

flowchart LR
  subgraph FC[Fully connected view]
    A[Flattened image] --> B[Every input connected<br/>to every hidden unit]
  end
  subgraph CNN[Convolutional view]
    C[Image grid] --> D[Small local window]
    D --> E[Same detector reused<br/>across the grid]
  end

The local, shared operation also supports hierarchical feature learning. Early layers usually learn simple, low-level features, such as edges, color contrasts, and basic orientations. Middle layers combine them into more complex patterns, including corners, curves, textures, and simple shapes. Later layers integrate information from larger regions and may respond to object parts, complete objects, or patterns that are especially useful for the target task. These features are not programmed by hand; they emerge during training as backpropagation adjusts the filters to reduce the final loss. We will study how backpropagation works in CNNs later in this chapter.

from pathlib import Path

import matplotlib.pyplot as plt

image_path = Path("chapters/05-cnn-resnet/images/cnn-feature-visualizations.jpeg")
image = plt.imread(image_path)
plt.figure(figsize=(7, 10))
plt.imshow(image)
plt.axis("off")
plt.show()
A grid of feature visualizations from early, middle, and late layers of a trained convolutional neural network.
Figure 17.1: Features learned at different depths of a trained CNN. Early layers respond mainly to edges and color patterns; middle layers capture textures and repeated structures; later layers respond to object parts and larger object-level patterns.

Source: Figure 2 from Zeiler and Fergus, “Visualizing and Understanding Convolutional Networks”.

Explore interactively: Use Numan Saeed’s AlexNet in 3D to inspect feature maps at different layers of a pretrained CNN. Compare the early and later layers: which patterns look like edges or textures, and which suggest larger structures or object parts? The demonstration uses precomputed activations for built-in example photographs. On a small screen, open the link in a separate tab for more space.

Credit: Numan Saeed, “AlexNet in 3D”, CC BY-NC-SA 4.0.

This motivates the main object of study: the convolutional layer. We next define exactly what it computes.

17.3 The convolutional layer

17.3.1 From a fully connected layer to a convolutional layer

A convolutional layer can be understood as a fully connected layer with two important restrictions:

  1. Local connectivity: each output uses only a small region of the input.
  2. Parameter sharing: the same weights are reused at every spatial location.

Consider a fully connected layer. If the input is a vector \(\mathbf{x}\), the pre-activation of output unit \(r\) is

\[ z_r=b_r+\sum_q W_{r,q}x_q, \]

followed by an activation function:

\[ y_r=\phi(z_r). \]

Here, every output unit has its own bias \(b_r\) and its own weight for every input value.

For an image, it is more useful to preserve the two-dimensional structure and its spatial information. Let \(X[p,q]\) denote the pixel at row \(p\) and column \(q\). A fully connected layer that produces a two-dimensional output could be written as

\[ Z[i,j] = b[i,j] + \sum_{p=0}^{H-1} \sum_{q=0}^{W-1} W[i,j,p,q]X[p,q]. \]

The output value at position \((i,j)\) is connected to every input pixel. Moreover, every output position has a different set of weights \(W[i,j,p,q]\). This leads to a large number of parameters and does not reuse a learned feature across image positions.

17.3.1.1 Step 1: Introduce local connectivity

Images usually contain useful local patterns, such as edges, corners, and textures. We therefore restrict each output to a small region of the input rather than connecting it to the complete image:

\[ Z[i,j] = b[i,j] + \sum_{u=0}^{K_h-1} \sum_{v=0}^{K_w-1} W[i,j,u,v]\, X[iS_h+u-P_h,\;jS_w+v-P_w]. \]

Here:

  • \(i\) and \(j\) are the row and column of the output value.
  • \(u\) and \(v\) identify a position inside the selected local region.
  • \(K_h\) and \(K_w\) are the height and width of the local region.
  • \(S_h\) is the vertical stride: the number of rows by which the local region moves between output positions.
  • \(S_w\) is the horizontal stride: the number of columns by which the local region moves between output positions.
  • \(P_h\) is the amount of padding added to the top and bottom of the input.
  • \(P_w\) is the amount of padding added to the left and right of the input.
  • \(W[i,j,u,v]\) is the weight applied at local position \((u,v)\) when calculating output position \((i,j)\).
  • \(b[i,j]\) is the bias associated with output position \((i,j)\).

The input position associated with local position \((u,v)\) is therefore

\[ \bigl(iS_h+u-P_h,\;jS_w+v-P_w\bigr). \]

If an index falls outside the original image, the corresponding input value is supplied by the padding rule, which is usually zero padding.

At this point, the operation is locally connected, but every output position still has its own weights.

17.3.1.2 Step 2: Share the weights

In images, the same visual pattern—such as an edge, corner, or texture—can appear at different locations. Instead of learning separate weights for each location, we use one shared set of weights across the entire image.

\[ W[i,j,u,v]=K[u,v]. \]

This shared weight matrix \(K\) is called a kernel.

We also share the bias:

\[ b[i,j]=b. \]

Substituting these constraints into the locally connected layer gives

\[ Z[i,j] = b + \sum_{u=0}^{K_h-1} \sum_{v=0}^{K_w-1} K[u,v]\, X[iS_h+u-P_h,\;jS_w+v-P_w]. \]

The activation function is then applied elementwise:

\[ Y[i,j]=\phi\left(Z[i,j]\right). \]

This is the basic operation performed by a convolutional layer.

Thus, a convolutional layer is not obtained from a fully connected layer through a new learning rule. It is obtained by placing a particular structure on the connections and weights:

\[ \text{fully connected} \;\longrightarrow\; \text{local connections} \;\longrightarrow\; \text{shared local weights}. \]

Backpropagation and gradient descent are then used to learn the shared weights in the usual way.

17.3.2 The basic operation

Before examining the equation in more detail, we define its main components.

  • Input image \(X\): a two-dimensional array of pixel values. In this initial example, the image has only one channel.
  • Kernel \(K\): a small matrix of learnable weights, usually much smaller than the input image. For example, a \(3\times3\) kernel contains nine weights.
  • Local patch: the small region of the input currently covered by the kernel. It normally has the same height and width as the kernel.
  • Feature map: the two-dimensional output produced by applying the same kernel across the image.
  • Stride \(S\): the number of positions by which the kernel moves after each calculation.
  • Padding \(P\): additional values placed around the image boundary, usually zeros.
  • Bias \(b\): a learnable scalar added to every value produced by the kernel.
  • Activation function \(\phi\): a nonlinear function, such as ReLU, applied after the weighted sum.

For a single-channel input, the kernel is a matrix

\[ K\in\mathbb{R}^{K_h\times K_w}, \]

where \(K_h\) and \(K_w\) are the kernel height and width. For example, a \(3\times3\) kernel may have the form

\[ K= \begin{bmatrix} k_{0,0} & k_{0,1} & k_{0,2}\\ k_{1,0} & k_{1,1} & k_{1,2}\\ k_{2,0} & k_{2,1} & k_{2,2} \end{bmatrix}. \]

These values are model parameters. They are usually initialized randomly and learned through backpropagation rather than selected by hand.

At output position \((i,j)\), the kernel is placed over a local input patch. Corresponding kernel and input values are multiplied, the products are summed, and the bias is added:

\[ Z[i,j] = b + \sum_{u=0}^{K_h-1} \sum_{v=0}^{K_w-1} K[u,v]\, X[iS_h+u-P_h,\;jS_w+v-P_w]. \]

The result can also be viewed as the inner product between the kernel and the local input patch:

\[ Z[i,j]=b+\langle K,\mathcal{P}_{i,j}\rangle_F, \]

where \(\mathcal{P}_{i,j}\) is the local input patch used to calculate the output at position \((i,j)\). Its elements are defined as

\[ \mathcal{P}_{i,j}[u,v] = X[iS_h+u-P_h,\;jS_w+v-P_w], \]

for \(0\leq u<K_h\) and \(0\leq v<K_w\). Thus, \(\mathcal{P}_{i,j}\) has the same height and width as the kernel. The notation \(\langle K,\mathcal{P}_{i,j}\rangle_F\) denotes the elementwise multiplication of the kernel and the patch, followed by summation of all resulting values.

The same kernel is then moved to the next position and the calculation is repeated. Because the kernel weights are shared, the same pattern can be detected at different locations.

A convolutional kernel moving across an image

Figure: Illustration of a convolution operation with stride 1, padding 2, and a 3 × 3 kernel. GIF source.

17.3.3 Parameter reduction

The restrictions used by a convolutional layer can greatly reduce the number of parameters.

Suppose an \(H\times W\) input is mapped to an \(H_{\text{out}}\times W_{\text{out}}\) output.

A fully connected spatial layer would require approximately

\[ H_{\text{out}}W_{\text{out}}HW \]

weights because every output value has a separate connection to every input value.

A convolutional layer with one \(K_h\times K_w\) kernel requires only

\[ K_hK_w \]

weights, plus one bias.

For example, mapping a \(32\times32\) image to a \(32\times32\) output using a fully connected spatial layer would require

\[ (32\cdot32)(32\cdot32)=1{,}048{,}576 \]

weights.

A single \(3\times3\) convolutional kernel requires only

\[ 3\cdot3=9 \]

weights, plus one bias. The same nine weights are reused at every output position.

17.3.4 Convolution versus cross-correlation

Most deep-learning libraries compute cross-correlation rather than the classical mathematical definition of convolution. Cross-correlation applies the kernel directly:

\[ Z[i,j] = \sum_u\sum_v K[u,v]X[i+u,j+v]. \]

Classical convolution first flips the kernel horizontally and vertically:

\[ Z[i,j] = \sum_u\sum_v K[u,v]X[i-u,j-v]. \]

In a neural network, the kernel values are learned from data. A network can therefore learn the required pattern under either convention. For this reason, the cross-correlation operation is normally called convolution in deep learning.

17.3.4.1 A small numerical example

Let

\[ X= \begin{bmatrix} 1&1&0\\ 1&0&0\\ 1&1&1 \end{bmatrix}, \qquad K= \begin{bmatrix} 1&-1\\ 1&-1 \end{bmatrix}. \]

With stride \(1\), no padding, and bias \(0\), the top-left output is

\[ (1)(1)+(1)(-1)+(1)(1)+(0)(-1)=1. \]

Repeating the calculation at all valid positions gives

\[ Y= \begin{bmatrix} 1&1\\ 1&0 \end{bmatrix}. \]

The kernel compares the left and right columns of each patch. It therefore behaves like a simple detector of vertical intensity changes. In a CNN, values such as \(1\) and \(-1\) are not fixed in advance; optimization learns them from data.

A kernel forms one output value from each local input patch and then moves to the next position.

flowchart LR
  A[Input image] --> B[Select local patch]
  B --> C[Elementwise products]
  C --> D[Sum products<br/>and add bias]
  D --> E[One output value]
  E --> F[Move kernel<br/>and repeat]

flowchart LR
  A[Input image] --> B[Select local patch]
  B --> C[Elementwise products]
  C --> D[Sum products<br/>and add bias]
  D --> E[One output value]
  E --> F[Move kernel<br/>and repeat]

17.3.5 Channels, filters, and feature maps

A color image has several input channels. If \(X_c\) denotes input channel \(c\), one output channel is

\[ Y_o[i,j]=b_o+ \sum_{c=1}^{C_{\text{in}}} \sum_{u=0}^{K_h-1} \sum_{v=0}^{K_w-1} W_{o,c,u,v}\, X_c[iS_h+u-P_h,\;jS_w+v-P_w]. \]

For a single-channel input, one two-dimensional kernel is sufficient to produce a feature map. For a multi-channel input, one kernel is applied to each input channel. The complete collection of these kernels is called a filter. Note that the words filter and kernel are sometimes used interchangeably, but it is important to know their difference.

The responses from all input channels are added, together with a bias, at each spatial position. Repeating this calculation across the image produces a two-dimensional output called a feature map. Therefore, each filter produces one feature map, corresponding to one output channel. A layer with \(C_{\text{out}}\) filters produces \(C_{\text{out}}\) output channels. The complete weight tensor therefore has shape

\[ C_{\text{out}}\times C_{\text{in}}\times K_h\times K_w. \]

17.3.6 Kernel size, stride, padding, and dilation

Four quantities determine how a convolution samples space:

  • Kernel size \(K\): the number of sampled positions in the local window. A \(3\times3\) kernel is the most common basic choice.
  • Stride \(S\): how far the kernel moves between outputs. Stride \(2\) roughly halves the spatial resolution.
  • Padding \(P\): values added around the border. Padding can preserve spatial size and lets border pixels participate in more windows.
  • Dilation \(D\): spacing between kernel elements. Dilation enlarges the covered region without adding kernel parameters.

For one spatial dimension, the output size is

\[ O=\left\lfloor\frac{I+2P-D(K-1)-1}{S}\right\rfloor+1. \]

The same formula is applied separately to height and width.

Example. Suppose \(I=32\), \(K=3\), \(P=1\), \(S=2\), and \(D=1\). Then

\[ O=\left\lfloor\frac{32+2-2-1}{2}\right\rfloor+1 =\lfloor15.5\rfloor+1=16. \]

Thus a \(32\times32\) feature map becomes \(16\times16\).

17.3.7 Parameters and computation

A dense convolution has

\[ K_hK_wC_{\text{in}}C_{\text{out}} \]

weights. It also usually has one bias for each output channel, giving \(C_{\text{out}}\) bias values in total. The input height and width do not appear in the parameter count because the same weights are reused at every spatial location.

For example, a \(3\times3\) convolution with 32 input channels and 64 output channels contains

\[ 3\times3\times32\times64=18{,}432 \]

weights.

The computational cost is larger than the parameter count because these weights are applied repeatedly across the input. To calculate one output value, the layer uses a local region containing

\[ K_hK_wC_{\text{in}} \]

input values. It multiplies each input value by its corresponding weight and adds the results. This calculation is performed:

  • at each of the \(H_{\text{out}}W_{\text{out}}\) output positions; and
  • for each of the \(C_{\text{out}}\) output channels.

The approximate number of multiply-add operations is therefore

\[ H_{\text{out}}W_{\text{out}}K_hK_wC_{\text{in}}C_{\text{out}}. \]

For example, if the previous \(3\times3\) convolution produces an output of size \(32\times32\), it requires approximately

\[ 32\times32\times3\times3\times32\times64 = 18{,}874{,}368 \]

multiply-add operations. Here, a multiply-add operation consists of multiplying an input by a weight and adding the result to an accumulated sum. Some sources count one multiply-add as one operation, while others count the multiplication and addition separately, giving approximately twice as many floating-point operations.

The distinction is important: the parameter count measures how many values the model must learn and store, whereas the operation count measures how much computation is required for a forward pass. A convolution can therefore have relatively few parameters but still be computationally expensive when it is applied to a large input.

17.4 Spatial properties of convolution

17.4.1 Translation equivariance is not invariance

Let \(T_\delta\) shift an image by displacement \(\delta\), and let \(f\) be a stride-1 convolution on an infinite grid, or on a finite grid where boundary effects can be ignored. Then

\[ f(T_\delta X)=T_\delta f(X). \]

This is translation equivariance: shifting the input shifts the output in the corresponding way. It is valuable because a detector can respond to a feature wherever it appears.

Translation invariance would instead mean

\[ g(T_\delta X)=g(X), \]

so the final output does not change under a shift. A classification network can become approximately translation invariant through later operations such as pooling, downsampling, global average pooling, and training with shifted examples. However, this invariance is not provided by convolution alone.

For example, if a vertical edge moves five pixels to the right, the feature detecting that edge should also activate about five pixels to the right. In contrast, a translation-invariant classifier would produce the same final class prediction regardless of this movement.

17.4.2 Receptive fields

The receptive field of a feature is the region of the original input that can influence it. A feature in an early convolutional layer depends on only a small part of the image. As more convolutional layers are stacked, each feature combines information from several features in the previous layer and therefore depends on a progressively larger part of the original image.

For example, one \(3\times3\) convolution observes a \(3\times3\) region. With stride \(1\), stacking two such layers increases the receptive field to \(5\times5\), while three layers increase it to \(7\times7\). This allows deeper layers to recognize larger and more complex patterns even though each individual layer processes only a small local region.

Growth of the receptive field across stacked 3 by 3 convolutional layers

Figure: Stacking small convolutional layers progressively enlarges the region of the original image that can influence a feature. Figure Source.

Downsampling operations, such as pooling or strided convolution, make the theoretical receptive field grow even faster because each position in a downsampled feature map corresponds to a larger step in the original image. In practice, the effective receptive field may be concentrated within only part of this theoretical region.

17.5 Core CNN components

17.5.1 Nonlinear activation

A convolution without a bias is a linear operation; with a bias, it is affine. If several convolutional layers are stacked without nonlinear activations, their composition is still linear or affine and can be represented by one larger operation of the same kind. An activation function prevents this collapse.

The standard example is the rectified linear unit:

\[ \mathrm{ReLU}(z)=\max(0,z). \]

ReLU is simple and gives a gradient of \(1\) for positive inputs. For negative inputs its gradient is \(0\), so a unit that receives only negative values may stop updating. Leaky ReLU, GELU, and SiLU are common alternatives, but ReLU is sufficient for understanding the basic architecture.

17.5.2 Downsampling: pooling and strided convolution

Downsampling reduces spatial resolution. Max pooling returns the maximum value in a window,

\[ y=\max_{x\in\mathcal{R}}x, \]

while average pooling returns the mean,

\[ y=\frac{1}{|\mathcal{R}|}\sum_{x\in\mathcal{R}}x. \]

A stride-2 convolution learns both filtering and downsampling. Pooling has no learned filter parameters, whereas strided convolution can decide which local combinations should be retained.

Downsampling has three main effects:

  1. it lowers later computational cost;
  2. it lets later units cover a larger input region; and
  3. it removes exact spatial detail.

The third effect is a genuine tradeoff. A classifier may not need the precise location of every edge, but segmentation or small-object recognition may. Downsampling can also cause aliasing when high-frequency patterns are sampled too sparsely.

Average and max pooling operations in CNN

Figure: Examples of 2 × 2 max-pooling and average-pooling operations. Figure Source.

17.5.3 Normalization

For a CNN feature channel, batch normalization computes statistics over the batch and spatial locations associated with that channel:

\[ \hat{x}=\frac{x-\mu_B}{\sqrt{\sigma_B^2+\epsilon}}, \qquad y=\gamma\hat{x}+\beta, \]

where \(\mu_B\) and \(\sigma_B^2\) are batch statistics, and \(\gamma,\beta\) are learned parameters. This keeps activation scales controlled and often makes optimization easier.

During evaluation, batch normalization uses stored running estimates rather than the statistics of the current batch. This distinction is part of the mathematical definition of the model, not merely a software detail. When batches are very small, their statistics may be unreliable; group normalization is a common alternative because it normalizes groups of channels within each example.

17.5.4 Global average pooling

If the final tensor has shape \(H\times W\times C\), global average pooling produces one value per channel:

\[ z_c=\frac{1}{HW}\sum_{i=1}^{H}\sum_{j=1}^{W}X_{i,j,c}. \]

The result is a \(C\)-dimensional vector. Compared with flattening a large feature map, global average pooling drastically reduces the number of weights in the final classifier and encourages each channel to summarize whether a feature is present across the image.

17.5.5 The special role of 1 × 1 convolution

A \(1\times1\) kernel does not combine neighboring locations, but it combines channels. At each location,

\[ y_o[i,j]=b_o+\sum_{c=1}^{C_{\text{in}}}W_{o,c}x_c[i,j]. \]

It is therefore a learned linear projection of the channel vector at every pixel. It can reduce channels before an expensive convolution, expand channels afterward, or align two branches that must be added.

We next examine how these components learn and introduce several useful convolution variants before assembling them into a complete network.

17.6 Learning in convolutional networks

17.6.1 Backpropagation through convolution

Convolution does not require a new learning rule. It forms part of the network’s computation graph, so its gradients are calculated using the same chain rule used in fully connected networks.

For a simplified one-dimensional valid convolution with a kernel containing \(K\) weights,

\[ y_i=\sum_{u=0}^{K-1}w_u x_{i+u}, \]

where \(i\) identifies the output position and \(u\) identifies a position inside the kernel.

Because the same weight is reused at different output positions, the loss depends on \(w_u\) through every output \(y_i\). The chain rule therefore gives

\[ \frac{\partial L}{\partial w_u} = \sum_i \frac{\partial L}{\partial y_i} \frac{\partial y_i}{\partial w_u}. \] From the convolution equation,

\[ \frac{\partial y_i}{\partial w_u} = \frac{\partial}{\partial w_u} \left( \sum_{v=0}^{K-1}w_vx_{i+v} \right). \]

All terms with \(v\neq u\) have derivative zero because they do not contain \(w_u\). The only remaining term is \(w_ux_{i+u}\), so

\[ \frac{\partial y_i}{\partial w_u} = \frac{\partial}{\partial w_u} \left(w_ux_{i+u}\right) = x_{i+u}. \]

Substituting this result gives

\[ \frac{\partial L}{\partial w_u} = \sum_i \frac{\partial L}{\partial y_i}x_{i+u}. \]

The summation over \(i\) is a direct consequence of parameter sharing: every output position that uses \(w_u\) contributes to its gradient. Modern deep-learning frameworks calculate these gradients automatically, but the equation shows how ordinary backpropagation applies to shared convolutional weights.

17.6.2 Backpropagation through pooling

For average pooling over \(n\) inputs, each input receives \(1/n\) of the upstream gradient. For max pooling, the gradient is sent to the element selected as the maximum during the forward pass; the other elements receive zero from that output. If several elements tie for the maximum, the exact routing convention depends on the implementation.

For example, if

\[ \max(1,4,2,3)=4 \]

and the upstream gradient is \(g\), the local input gradient is

\[ (0,g,0,0). \]

This routing behavior is one reason max-pooling switches must effectively be remembered for backward computation.

17.6.3 Optimization and regularization

Once gradients have been computed, Stochastic Gradient Descent (SGD), SGD with momentum, or an adaptive optimizer updates the parameters. These optimization methods are discussed in the chapter on optimization. The central principles are the same as for fully connected networks, but CNNs often have enough capacity to fit accidental visual patterns. These are unintended correlations—such as backgrounds, watermarks, borders, lighting conditions, or camera artifacts—that happen to be associated with particular classes in the training data but may not remain reliable on new images. Regularization therefore matters.

  • Weight decay penalizes large weights, encouraging the network to learn simpler and less extreme parameter values.
  • Dropout randomly sets some activations to zero during training, reducing the network’s dependence on particular units or feature combinations.
  • Data augmentation creates modified training images—such as shifted, cropped, or flipped versions—while keeping the label unchanged, helping the model generalize to these variations.
  • Early stopping stops training when validation performance no longer improves, preventing the model from continuing to fit training-specific patterns.

These methods affect learning, but they do not change the definition of convolution. Before assembling complete architectures, it is useful to study several variants that change what a convolutional layer can do or how much it costs.

17.7 Important convolution variants

17.7.1 Grouped convolution

In a standard convolution, every output channel uses every input channel. A grouped convolution divides the channels into \(G\) groups. Each output channel sees only the input channels in its group.

The input and output channel counts must be divisible by \(G\), so that the channels can be partitioned evenly.

The weight count becomes

\[ K_hK_w\frac{C_{\text{in}}C_{\text{out}}}{G}, \]

which is \(1/G\) of the dense-convolution count. The saving comes with a restriction: information cannot mix directly across groups within that layer. Later layers or explicit channel-mixing operations must connect the groups.

At the extremes, \(G=1\) gives ordinary convolution. When \(G=C_{\text{in}}\), each group contains one input channel; with one spatial filter per input channel and \(C_{\text{out}}=C_{\text{in}}\), this is depthwise convolution. Some implementations allow multiple filters per input channel, known as a depth multiplier.

Grouped convolution was famously used in AlexNet to divide computation between two GPUs, with each GPU processing a separate group of channels. Later architectures, such as ResNeXt, adopted it as an architectural design choice, while efficient networks such as MobileNet use its depthwise form to reduce computation.

17.7.2 Dilated convolution

A dilation rate larger than one inserts gaps between sampled kernel positions. A one-dimensional kernel of size \(K\) and dilation \(D\) has effective size

\[ K_{\text{eff}}=D(K-1)+1. \]

Thus, a size-3 kernel with dilation 2 covers five input positions while still using only three weights. A common use case is segmentation, where the model needs wider context to classify each pixel but must preserve spatial resolution for accurate boundaries. However, repeatedly using large dilation rates can miss local interactions and produce grid-like sampling artifacts.

17.7.3 Transposed convolution and upsampling

A transposed convolution is a learned operation that can increase the spatial resolution of a feature map when configured with a stride greater than one. Its exact output size also depends on the kernel size, padding, and any output-padding setting. It is commonly used in segmentation decoders, autoencoders, and generative models. Despite its name, it is not the inverse of convolution and cannot automatically recover information lost during downsampling.

Unlike dilated convolution, which enlarges the receptive field while usually preserving resolution, transposed convolution directly increases the output resolution.

17.8 Designing a CNN from input to prediction

The preceding sections introduced the main parts of a convolutional network separately. We can now combine them into a complete image classifier. The example below accepts a \(32\times32\) RGB image and produces logits for \(10\) classes. Its purpose is to make each design decision and tensor transformation explicit; the same process applies to other image sizes and class counts.

17.8.1 Plan the architecture

A CNN is usually divided into a backbone, which extracts features, and a prediction head, which converts those features into the output required by the task. The backbone begins with a stem that processes the raw image and is commonly organized into repeated blocks and stages. Blocks within a stage usually share the same spatial resolution and output-channel count.

Between stages, a CNN commonly reduces spatial resolution while increasing the number of channels. If stage \(l\) produces a tensor of shape \(H_l\times W_l\times C_l\), the next stage often follows

\[ H_{l+1}<H_l,\qquad W_{l+1}<W_l,\qquad C_{l+1}>C_l. \]

Downsampling reduces the cost of later operations and expands their receptive fields, while additional channels allow the network to represent a wider variety of higher-level features.

General architecture of a convolutional neural network, showing feature extraction and classification stages

Figure: A typical CNN gradually reduces spatial resolution while increasing feature depth, then uses a prediction head to produce class scores. Source: Irisbox, Wikimedia Commons

17.8.2 Define the input and output

Before choosing layers, specify the tensors at both ends of the model. Using the channel-first convention, a batch of \(N\) RGB images has shape

\[ N\times3\times32\times32, \]

The classifier must return one score for each class, so its output has shape

\[ N\times10. \]

These scores are logits. They are not probabilities and do not need a softmax layer inside the network when the training loss accepts logits directly.

17.8.3 Assemble the feature extractor

A useful starting point is a sequence of stages. Within a stage, stride-1 convolutions preserve spatial resolution and learn new features. Between stages, pooling reduces the height and width, and the following convolution increases the channel count. This gives the model progressively coarser spatial representations with more feature channels.

Part Operation Output shape for one image
Input RGB image \(3\times32\times32\)
Stage 1 \(3\times3\) conv, 32 channels, padding 1; batch normalization; ReLU \(32\times32\times32\)
\(3\times3\) conv, 32 channels, padding 1; batch normalization; ReLU \(32\times32\times32\)
Downsample 1 \(2\times2\) max pooling, stride 2 \(32\times16\times16\)
Stage 2 \(3\times3\) conv, 64 channels, padding 1; batch normalization; ReLU \(64\times16\times16\)
\(3\times3\) conv, 64 channels, padding 1; batch normalization; ReLU \(64\times16\times16\)
Downsample 2 \(2\times2\) max pooling, stride 2 \(64\times8\times8\)
Stage 3 \(3\times3\) conv, 128 channels, padding 1; batch normalization; ReLU \(128\times8\times8\)
\(3\times3\) conv, 128 channels, padding 1; batch normalization; ReLU \(128\times8\times8\)
Pooling Global average pooling \(128\)
Head Linear layer \(10\) logits

Padding of 1 makes each \(3\times3\) stride-1 convolution preserve height and width. Each max-pooling layer then halves both spatial dimensions. The channel count rises from 32 to 64 and then to 128 after downsampling, allowing the network to represent more feature types while the reduced feature maps keep the computational cost manageable.

Batch normalization and ReLU follow each convolution. Batch normalization controls activation scale during training, while ReLU lets stacked layers represent nonlinear functions. A different activation or normalization method can be substituted, but the tensor shapes must remain compatible with the next layer.

The complete forward path can be summarized as

\[ \begin{aligned} X &\rightarrow [\mathrm{Conv}_{3\times3}(32)\rightarrow\mathrm{Norm}\rightarrow\mathrm{ReLU}]\times2 \\ &\rightarrow \mathrm{MaxPool}_{2\times2} \\ &\rightarrow [\mathrm{Conv}_{3\times3}(64)\rightarrow\mathrm{Norm}\rightarrow\mathrm{ReLU}]\times2 \\ &\rightarrow \mathrm{MaxPool}_{2\times2} \\ &\rightarrow [\mathrm{Conv}_{3\times3}(128)\rightarrow\mathrm{Norm}\rightarrow\mathrm{ReLU}]\times2 \\ &\rightarrow \mathrm{GlobalAveragePool} \rightarrow \mathrm{Linear}(128,10) \rightarrow z. \end{aligned} \]

Here, \(z\in\mathbb{R}^{10}\) is the logit vector for one image.

17.8.4 Build the prediction head

After the final convolution, the tensor contains \(128\) feature maps of size \(8\times8\). Flattening this tensor would create a vector with

\[ 128\times8\times8=8{,}192 \]

values. A direct 10-class linear layer would therefore require

\[ 8{,}192\times10+10=81{,}930 \]

parameters. Global average pooling instead produces a 128-dimensional vector, so the linear head requires only

\[ 128\times10+10=1{,}290 \]

parameters. It lets each channel summarize its average activation across the image, which can provide a useful signal about the presence of a learned feature. This is appropriate for image classification, where the output describes the whole image. Tasks that require spatial predictions, such as segmentation, must preserve or restore spatial resolution instead of discarding it in this way.

17.8.5 Check the parameter count

Assume that each convolution is followed by batch normalization, so the redundant convolutional bias is omitted. The convolutional kernels contain

\[ \begin{aligned} &(3\times3\times3\times32) +(3\times3\times32\times32)\\ &+(3\times3\times32\times64) +(3\times3\times64\times64)\\ &+(3\times3\times64\times128) +(3\times3\times128\times128)\\ &=286{,}560 \end{aligned} \]

weights. The six batch-normalization layers add two learned values per output channel, for another

\[ 2(32+32+64+64+128+128)=896 \]

parameters. Including the 1,290 parameters in the classifier, the network has

\[ 286{,}560+896+1{,}290=288{,}746 \]

learned parameters.

17.8.6 Connect the model to the loss

For an input image \(x\) and parameters \(\theta\), the network computes

\[ z=f_\theta(x). \]

For a one-hot target \(y\) and \(K=10\) classes, softmax converts the logits to probabilities,

\[ p_k=\frac{e^{z_k}}{\sum_{m=1}^{K}e^{z_m}}, \]

and cross-entropy measures the prediction error:

\[ L=-\sum_{k=1}^{K}y_k\log p_k. \]

Backpropagation sends the gradient of this loss through the linear head, global average pooling, and every convolutional stage. The optimizer then updates the convolutional filters, batch-normalization parameters, and classifier weights. If data augmentation or dropout is used, both are applied only during training. During evaluation, dropout is disabled, training-only augmentations are omitted, and batch normalization uses its stored statistics.

17.8.7 Validate the design before scaling it

Before adding more layers or channels, verify four properties:

  1. Every layer produces the shape expected by the next layer.
  2. The final features have a receptive field large enough for the task.
  3. The parameter count and computation fit the available data and hardware.
  4. The prediction head preserves the information required by the task.

This regular stack of small convolutions resembles the design logic used by early plain CNNs. Making such networks much deeper, however, does not guarantee lower training error. The next section explains the optimization problems that appear in deep plain networks and motivates residual connections.

17.9 Why deep plain networks are difficult to train

17.9.1 Greater depth is useful only when it can be optimized

Depth expands the number of transformations a network can compose. It can enlarge receptive fields, reuse intermediate features, and represent complex functions efficiently. Expressive power alone, however, does not tell us whether gradient-based optimization can find a good function.

Suppose a shallow network already performs well. A deeper network formed by adding several layers should be able to match it if the new layers implement identity mappings:

\[ h(x)=x. \]

Yet experiments with deep plain networks—ordinary stacks without shortcut connections—showed that adding layers could increase training error. Because training error itself became worse, this was not simply test-set overfitting.

17.9.2 Vanishing and exploding gradients

Consider a deep composition

\[ h_L=f_L\circ f_{L-1}\circ\cdots\circ f_1(x). \]

Backpropagation multiplies a sequence of Jacobian matrices:

\[ \frac{\partial L}{\partial h_0} = \frac{\partial L}{\partial h_L} \frac{\partial h_L}{\partial h_{L-1}} \cdots \frac{\partial h_1}{\partial h_0}. \]

If these transformations repeatedly shrink vector magnitudes, gradients vanish; if they repeatedly enlarge them, gradients explode. ReLU, careful initialization, and normalization reduce these problems, but long chains of learned transformations can still be difficult to coordinate.

17.9.3 The degradation problem

The degradation problem is the observation that a deeper plain network may have higher training error than a shallower counterpart. It is not caused by the deeper model lacking capacity. Rather, optimization has difficulty using the extra layers without disturbing a representation that already works.

Learning an identity map with several nonlinear layers requires their parameters to coordinate precisely. Residual learning changes the parameterization so that keeping the input becomes the easiest behavior rather than a special one.

17.10 Residual learning

17.10.1 Learning a correction

Let \(H(x)\) be the desired mapping of a block. A residual block asks its nonlinear branch to learn

\[ F(x)=H(x)-x. \]

The block output is then

\[ y=F(x;W)+x, \]

where \(W\) represents the parameters of the residual branch. If the best mapping is close to the identity, the branch only needs to learn a small correction. Setting its weights so that \(F(x)\approx0\) gives \(y\approx x\).

A residual block transforms the input along one branch while the shortcut carries it directly to an addition.

A residual block

Figure: Single Residual Block. Fig. Source.

The shortcut is not merely a convenient wire in a drawing. It changes the function family’s parameterization and creates a direct route for information.

17.10.2 Gradient flow through the shortcut

For \(y=F(x)+x\), the local derivative is

\[ \frac{\partial y}{\partial x} =\frac{\partial F(x)}{\partial x}+I. \]

Therefore,

\[ \frac{\partial L}{\partial x} =\frac{\partial L}{\partial y} \left(\frac{\partial F(x)}{\partial x}+I\right). \]

The identity term provides a path that does not depend on multiplying through every weight in the residual branch. It does not make vanishing gradients mathematically impossible, because many blocks, nonlinearities, and interactions remain. It does make optimization substantially easier in practice.

Across several residual blocks,

\[ x_{l+1}=x_l+F_l(x_l), \]

so, ignoring dimension-changing blocks for the moment,

\[ x_L=x_0+\sum_{l=0}^{L-1}F_l(x_l). \]

Each \(x_l\) is the complete representation produced by all the blocks before block \(l\). For example,

\[ x_1=x_0+F_0(x_0), \]

and the next block uses this new value:

\[ x_2=x_1+F_1(x_1) =x_0+F_0(x_0)+F_1(x_1). \]

The intermediate value \(x_1\) has not disappeared. Its information is already contained in \(x_0+F_0(x_0)\), and it is also the input used to calculate the next update \(F_1(x_1)\). The final equation therefore starts with \(x_0\) and adds only the new correction learned by each block. Listing every \(x_l\) as another separate term would count information from earlier blocks more than once.

In simple terms, each residual block receives the current representation, makes a correction, and passes the updated representation to the next block. The blocks refine the representation rather than replacing it entirely.

17.10.3 Addition requires matching shapes

The expression \(F(x)+x\) requires both tensors to have the same height, width, and channel count. When shapes already match, the shortcut can be the identity. If they do not, a learned projection \(W_s\) is commonly used:

\[ y=F(x;W)+W_sx. \]

A \(1\times1\) convolution is a natural projection because it can change the number of channels. With stride \(2\), it can also reduce spatial resolution to match a downsampling residual branch.

17.10.4 Addition versus concatenation

Residual shortcuts use elementwise addition. Addition keeps the output channel count unchanged and encourages the residual branch to modify an existing representation. Concatenation places features side by side, increasing channel count and preserving them separately. Both are useful architectural operations, but they have different meanings and costs.

The general residual equation leaves several implementation choices open. We focus on the basic residual block used in ResNet-18 and ResNet-34.

17.11 The basic residual block

In the original ResNet-18 and ResNet-34 design, a basic residual block uses a convolution–normalization–activation sequence followed by a second convolution and normalization. The branch learns \(F(x)\), which is added to the shortcut; the sum is then passed through the final activation:

\[ \tilde{y}=F(x)+s(x), \qquad y=\mathrm{ReLU}(\tilde{y}). \]

When the input and output shapes match, \(s(x)=x\), so the shortcut passes the input unchanged. At the start of a new stage, the residual branch may use stride 2 to reduce spatial resolution and increase the channel count. The shortcut then uses a stride-2 \(1\times1\) projection so that both branches have the same shape before addition.

Deeper ResNets sometimes replace the two \(3\times3\) convolutions with a \(1\times1\)-\(3\times3\)-\(1\times1\) bottleneck branch to reduce computation, but the same shortcut principle applies.

We can now see how basic residual blocks form a complete network.

17.12 Complete ResNet architecture

A complete ResNet combines a stem, several stages of residual blocks, and a classification head. Blocks within a stage keep the same spatial resolution and channel count. The first block of each later stage downsamples the feature map and increases the channel count, using a projection shortcut to keep both branches compatible.

The structure of ResNet-18 for a \(224\times224\) input is shown below.

Part Main operation Output shape
Input — \(224\times224\times3\)
Stem \(7\times7\) conv, stride 2; max pool \(56\times56\times64\)
Stage 1 2 basic blocks \(56\times56\times64\)
Stage 2 2 basic blocks; first downsamples \(28\times28\times128\)
Stage 3 2 basic blocks; first downsamples \(14\times14\times256\)
Stage 4 2 basic blocks; first downsamples \(7\times7\times512\)
Head Global average pool; linear layer \(K\) logits

A simplified spatial and channel trace through ResNet-18.

After Stage 4, global average pooling converts the \(7\times7\times512\) feature tensor into a 512-dimensional vector, and the linear layer produces \(K\) class logits. ResNet-18 uses two basic blocks in each stage. ResNet-34 follows the same architecture but uses \((3,4,6,3)\) blocks across its four stages.

For small images such as \(32\times32\) inputs, the large stem is often replaced with a \(3\times3\), stride-1 convolution without max pooling. The overall pattern remains the same: a stem extracts initial features, residual stages gradually reduce resolution while increasing channels, and the head produces the final prediction.

Residual connections make this architecture easier to optimize, but they do not remove the generalization and robustness problems examined next.

17.14 Evaluating a CNN

17.14.1 Accuracy and class-sensitive metrics

For \(N\) examples, classification accuracy is

\[ \text{accuracy}=\frac{\text{number of correct predictions}}{N}. \]

Accuracy is appropriate when classes are balanced and errors have similar importance. Otherwise it can hide poor minority-class behavior. For one class treated as positive,

\[ \text{precision}=\frac{TP}{TP+FP}, \qquad \text{recall}=\frac{TP}{TP+FN}, \]

and

\[ F_1=2\frac{\text{precision}\cdot\text{recall}} {\text{precision}+\text{recall}}. \]

Precision asks how often positive predictions are correct; recall asks how many actual positives are found. A confusion matrix shows how predictions are distributed across true and predicted classes, making systematic confusions visible.

For tasks with many plausible classes, top-\(k\) accuracy counts an example as correct when the true class appears among the \(k\) highest-scoring classes. It should supplement, not conceal, top-1 performance.

17.14.2 Confidence and calibration

Suppose a model assigns confidence near \(0.8\) to many predictions. It is well calibrated at that confidence if roughly \(80\%\) of those predictions are correct. Calibration is different from accuracy: a model can rank classes well while being systematically overconfident.

One summary measure is the expected calibration error. Divide predictions into confidence bins \(B_m\), then calculate

\[ \mathrm{ECE}= \sum_{m=1}^{M}\frac{|B_m|}{N} \left|\mathrm{acc}(B_m)-\mathrm{conf}(B_m)\right|. \]

The value depends on the binning scheme, so a reliability diagram is often more informative than one number. Most importantly, softmax confidence is not a guarantee that an input is familiar or that the prediction is correct.

17.14.3 Error analysis and robustness

Evaluation should answer more than “what is the average score?” Useful questions include:

  • Which classes are confused with each other?
  • Does performance change across relevant subgroups or image sources?
  • Does the model depend on background rather than foreground?
  • What happens under blur, noise, compression, shifts, crops, or scale changes?
  • Are errors confidently wrong or appropriately uncertain?

Controlled transformations help isolate weaknesses. A transformation should be label-preserving for the task: horizontally flipping an ordinary animal photograph may be valid, while flipping text or a left-turn traffic sign may change the meaning.

17.14.4 Interpretability tools

Feature visualizations, occlusion tests, and saliency methods can help investigate what evidence influences a CNN. Grad-CAM, for example, uses gradients flowing into a convolutional layer to produce a coarse, class-specific map of image regions that influenced a target score. Such a map can reveal that a prediction depends on an object, its background, or another correlated region.

These visualizations are diagnostic evidence, not causal proof or a complete explanation of the model. Their resolution and stability are limited, and different explanation methods may emphasize different regions. They should therefore be combined with controlled interventions—such as masking, counterfactual edits, or subgroup tests—rather than treated as definitive explanations.

Evaluation methods are architecture-independent, but architecture strongly shapes what can be learned. The final summary brings together the chapter’s main design principles, optimization ideas, and limitations.

17.15 Chapter summary

A CNN is built around a shared local linear operation. Local connectivity reduces the number of parameters, while parameter sharing lets one detector operate throughout an image. Stacking convolutions with nonlinear activations produces hierarchical features and expands receptive fields.

Stride, padding, dilation, and kernel size determine output geometry. Pooling and strided convolution reduce spatial resolution; normalization controls feature scales; \(1\times1\) convolution mixes channels; and global average pooling summarizes the final spatial representation. Grouped, depthwise, dilated, and transposed convolutions modify cost or spatial behavior for particular needs.

Deeper plain CNNs can be difficult to optimize even when they have enough representational capacity. A residual block changes the learned mapping from \(H(x)\) to a correction \(F(x)\), producing \(y=F(x)+x\). The identity shortcut makes preservation easy and creates a direct route for gradients. Basic residual blocks are organized into stages to form complete ResNets.

Residual learning solves an optimization problem, not every visual-learning problem. CNNs can still rely on shortcuts, fail under distribution shift, overemphasize texture, lose spatial detail, respond poorly to corruptions, and assign high confidence to unfamiliar inputs. Their computational cost and limited interpretability also matter. A sound understanding of CNNs therefore includes both their elegant inductive biases and the conditions under which those biases fail.

For executable investigations of these ideas, work through the lab. The additional material provides gradient derivations, receptive-field calculations, and worked exercises.

17.16 Review questions

These questions mix calculations with explanation, diagnosis, and design. For open-ended questions, state your assumptions and the evidence you would seek.

17.16.1 Check the foundations

  1. Compare a fully connected layer, a locally connected layer without weight sharing, and a convolutional layer. What assumption does each make about an image?
  2. Calculate the output size of a \(5\times5\) convolution applied to a \(64\times64\) input with padding \(2\), stride \(2\), and dilation \(1\).
  3. How many weights are in a \(3\times3\) convolution with 32 input and 128 output channels? How does this change with four groups?
  4. Calculate the receptive field of three stride-1 \(3\times3\) convolutions followed by stride-2 \(2\times2\) pooling. Why are two \(3\times3\) convolutions still not equivalent to one \(5\times5\) convolution?

17.16.2 Explain and diagnose

  1. Critique the claim “CNNs are translation invariant.” What is equivariant, and what operations move the network toward invariance?
  2. A deeper plain CNN has higher training error than a shallower one. Why is this not ordinary overfitting, and how can a residual connection help?
  3. A wildlife classifier associates cows with pasture and polar bears with snow. Design two counterfactual tests for shortcut learning.
  4. A classifier gives 99.8% confidence to television static. Explain why this can happen and why calibration is not the same as out-of-distribution detection.

17.16.3 Design and evaluate

  1. A residual branch produces \(128\times28\times28\) while its shortcut carries \(64\times56\times56\). Design a valid projection shortcut and explain its effect on gradient flow.
  2. Design a three-stage CNN for \(64\times64\) RGB images under a one-million-parameter budget. Give the shape after each stage and justify the downsampling.
  3. For pixel-accurate segmentation, compare stacked small kernels, dilation, and additional downsampling as ways to enlarge the receptive field.
  4. Design an evaluation plan for a consequential CNN application. Include a likely shortcut, subgroup and distribution-shift tests, calibration, interpretability, and an abstention rule.

17.17 Selected further reading

Begin with a visual explanation, manipulate an interactive model, and then read one architecture paper and one critical paper closely.

17.17.1 Watch and explore

  • Numan Saeed (2026), AlexNet in 3D, MAAI7602: Applied Computer Vision, MBZUAI. The demonstration embedded above lets you inspect precomputed feature maps and individual output calculations in a pretrained AlexNet.
  • 3Blue1Brown, Convolutions in Image Processing. An animated route from sliding kernels to blur, edge detection, and the general idea of convolution. While watching, pause before each reveal and predict the output image.
  • StatQuest, Image Classification with Convolutional Neural Networks. A compact, friendly explanation of filters, feature maps, pooling, and why a shifted pattern can still be recognized.
  • Wang et al., CNN Explainer. Inspect a live network from input pixels to softmax, click individual activations, and connect the convolution equation to the complete architecture.
  • Stanford CS231n, Convolutional Neural Networks: Architectures, Convolution and Pooling Layers. A visual reference for output geometry, parameter sharing, layer patterns, and classic architectures; use it to check the calculations in this chapter.

17.17.2 Read more deeply

17.17.3 Question the model