Artificial IntelligencePyTorch from scratch
3. CNNs and transfer learning
Author: Ángel Fernández Caravaca
Date: March 18, 2026
Why not just use an MLP for images?¶
A fully connected MLP treats an image as a flat vector. A 28×28 greyscale image becomes 784 numbers, and a 224×224 RGB image becomes 150,528 numbers. Connecting that to even a modest hidden layer makes the number of parameters shoot up immediately.
Above all, MLPs are spatially blind: they don't know that pixel (10, 10) is next to pixel (10, 11). They treat each input independently, so they can't detect local patterns such as edges, textures or shapes that may appear anywhere in the image.
Convolutional neural networks solve both problems.
The convolution operation¶
A convolution slides a small matrix called a kernel (or filter) across the image. At each position, it computes the dot product between the kernel's weights and the patch of image underneath it. The result is a single number in the feature map.
The kernel slides across the image computing a weighted sum at each position.
- Key parameters of
nn.Conv2d
| Parameter | Meaning |
|---|---|
in_channels |
Number of input channels (1 for greyscale, 3 for RGB) |
out_channels |
Number of filters learnt: each one produces a feature map |
kernel_size |
Size of the sliding window (usually 3×3 or 5×5) |
stride |
How many pixels are skipped between positions (default: 1) |
padding |
Zeros added around the border to preserve the spatial size |
- Why several filters?
Each filter learns to detect a different pattern: one may detect horizontal edges, another vertical edges, another corners. With out_channels=32 you learn 32 different detectors at once.
Each convolutional or pooling layer reduces the spatial dimensions of the input according to:
where \(I\) is the input size, \(K\) the filter/kernel size, \(P\) the padding and \(S\) the stride. For example, a \(32\times32\) image with a \(3\times3\) kernel, no padding and stride 1 gives a \(30\times30\) output. Stacking several layers without padding makes the spatial dimensions shrink progressively; that is why same padding (\(P = \lfloor K/2 \rfloor\)) is usually used to preserve them.
Formula

Suppose an input image of size \(H \times W\). The convolution uses a kernel of size \(K_H \times K_W\), a padding of \(P_H \times P_W\) and a stride of \(S_H \times S_W\), where the subscript indicates the dimension along which each quantity is applied.
As an intuition for this derivation, keep in mind that "the size of a convolution's output depends on the number of times the kernel can be applied over the input".
According to the figure, applying the kernel for the first time consumes \(K_H \times K_W\) pixels and leaves \((H - K_H) \times (W - K_W)\) pixels still to cover. Depending on the stride, which represents the step between consecutive convolutions, the number of times the kernel can be applied is:
where the \(+1\) corresponds to the first convolution. Taking into account the padding, which enlarges the input image symmetrically on both sides, the shape of the output is:
In practice, the same padding, stride and kernel size are applied in both spatial dimensions. The two expressions then reduce to:
Example
For a \(45 \times 50\) input and a \(3 \times 3\) kernel:
| Stride | Padding | \(H_{out}\) | \(W_{out}\) | Output | Note |
|---|---|---|---|---|---|
| 2 | 0 | \(\lfloor\frac{45-3}{2}\rfloor+1=22\) | \(\lfloor\frac{50-3}{2}\rfloor+1=24\) | \(22\times24\) | Downsampling: the stride greatly reduces the resolution |
| 1 | 0 | \(\lfloor\frac{45-3}{1}\rfloor+1=43\) | \(\lfloor\frac{50-3}{1}\rfloor+1=48\) | \(43\times48\) | padding='valid' |
| 1 | 1 | \(\lfloor\frac{45-3+2}{1}\rfloor+1=45\) | \(\lfloor\frac{50-3+2}{1}\rfloor+1=50\) | \(45\times50\) | Preserves the input shape: equivalent to padding='same' (\(P = \lfloor K/2 \rfloor\)) |
| 1 | 2 | \(\lfloor\frac{45-3+4}{1}\rfloor+1=47\) | \(\lfloor\frac{50-3+4}{1}\rfloor+1=52\) | \(47\times52\) | Padding can increase the resolution above that of the input |
Note
here I have used the word resolution, but it doesn't refer to the image looking more or less blurry. It has to do with the spatial correspondence between the input and the output: the convolution produces a completely new image (with new values).
Pooling: reducing the spatial dimensions¶
After the convolution, the feature maps are usually large. Pooling reduces their spatial size while keeping the most important information. This makes the network faster, less prone to overfitting and more robust to small translations of the image.
For example, MaxPooling keeps the strongest activation in each region, whereas AveragePooling takes the mean.
A typical CNN architecture¶
The basic building block of most CNNs follows this pattern:
In these architectures, the first layers detect simple features (edges) and the deeper ones combine them into complex patterns (shapes, objects). Specifically, as we go deeper: - The spatial dimensions shrink (because of pooling) - The number of channels grows (more abstract features) - The receptive field grows (each neuron "sees" a larger area of the original image)
Note: this is the most common CNN building block, but you can play around with the structure.
Batch Normalization¶
Training deep networks is unstable: the distribution of the activations changes as the parameters are updated, and later layers have to adapt constantly. This is called internal covariate shift.
BatchNorm2d normalises each layer's output across the batch so that it has mean ≈ 0 and standard deviation ≈ 1, and then applies trainable scale (γ) and shift (β) parameters:
- Advantages in practice
- Faster convergence: allows higher learning rates
- Acts as regularisation: reduces the need for Dropout
- Stabilises training: gradients flow more consistently
Transfer learning and fine-tuning¶
Training a deep CNN from scratch requires millions of labelled images and days of compute. Transfer learning lets you reuse a model already trained on a large dataset (ImageNet: 1.2 M images, 1000 classes) and adapt it to your own problem.
The intuition: the first layers of a CNN trained on ImageNet learn universal features (edges, textures, colours) that are useful for any vision task. Only the last layers are task-specific.
Those final layers are trained for the specific task. That is fine-tuning.
- The two strategies
| Strategy | What is done | When to use it |
|---|---|---|
| Feature extraction | Freeze every layer. Replace and train only the final classifier. | Small dataset, similar domain |
| Fine-tuning | Unfreeze some of the last layers. Train them with a small lr. | Medium dataset or change of domain |
The example we will develop in this entry consists of:
ResNets and residual connections¶
As networks get deeper, gradients tend to vanish before reaching the first layers: this is the vanishing gradient problem.
During backpropagation, gradients are computed by repeatedly applying the chain rule through each layer:
Each term of this product is a partial derivative of an activation function. With sigmoid or tanh, these derivatives are always less than 1, often much less. Multiply 50 numbers less than 1 and the result is practically zero. The first layers receive a gradient of ~0 and stop learning completely.
ResNet is an architecture that solved this in 2015 by introducing skip connections (also called residual connections). In it, instead of learning F(x), the block learns the residual F(x) + x:
Instead of learning the full transformation H(x), the block only has to learn the residual: the difference between the desired output and the identity:
This has two very powerful consequences:
1. A highway for the gradient: the skip connection creates a direct path for gradients to flow backwards, skipping the weight layers entirely. However deep the network is, the gradient can always travel along these shortcuts without being multiplied until it disappears:
The +1 guarantees that the gradient is never squashed to zero.
2. Easier optimisation: if a layer isn't needed, it is much easier to drive F(x) → 0 (turning the block into an identity) than to learn H(x) = x from scratch through a stack of non-linear transformations. In practice, the network can ignore the layers that don't help.
Additional information: data augmentation¶
A model generalises better when it has seen more variation during training. Data augmentation applies random transformations to the images on the fly, which in practice multiplies the size of the dataset.
Important
Augmentation is applied only to the training set. The validation and test sets use only ToTensor() + Normalize().
Moving tensors to the device¶
PyTorch can run computations on the CPU or on a GPU. To use the GPU, both the model and the data must be on the same device. The .to(device) method moves a tensor or a model to the given device.
Common mistake: forgetting to move the data. If the model is on the GPU but the input tensor is on the CPU, PyTorch will raise a RuntimeError. Both must always be on the same device.
- Why does it matter?
| CPU | GPU | |
|---|---|---|
| Suited to | Small models, debugging | Large models, matrix operations |
| Speed | Slow for deep learning | 10–100× faster for training |
Important
.to(device) on a tensor returns a new tensor: it doesn't modify it in place. Always reassign: x = x.to(device). On a model it does modify it in place, so reassigning is optional, although it is the convention.
Exercises¶
Use the official documentation while solving the exercises.
Exercise 1 Build and train a CNN on MNIST¶
Build a CNN from scratch to classify the handwritten digits of MNIST. Define the architecture with two convolutional blocks followed by a linear classifier. Train it for 5 epochs and show the test accuracy: the goal is to reach at least 98 %. At the end, plot the training loss curve.
- Load MNIST with
torchvision.datasets.MNISTand wrap it in aDataLoaderwithbatch_size=64 - Architecture:
Conv2d(1→32, k=3, p=1)→ReLU→MaxPool2d(2)→Conv2d(32→64, k=3, p=1)→ReLU→MaxPool2d(2)→Flatten→Linear(64·7·7, 128)→ReLU→Linear(128, 10) - Loss:
nn.CrossEntropyLoss; optimiser:Adam(lr=1e-3) - Training loop: zero the gradients → forward → loss → backward → step
- Evaluation: compare
model(images).argmax(dim=1)withlabels
Show solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 | |

Exercise 2 Transfer learning on FashionMNIST with ResNet-18¶
Load a pretrained ResNet-18 and use it to classify FashionMNIST (10 clothing categories). Freeze all the existing layers so their weights don't change and replace only the last linear layer so that it has 10 output classes. Train only that last layer for 3 epochs and show the test accuracy.
- Load
torchvision.models.resnet18(weights='IMAGENET1K_V1')and freeze all the parameters withrequires_grad = False - Replace
model.fcwith a newnn.Linear(512, 10): it is the only layer that will be trained - ResNet-18 expects 3-channel inputs: apply
Grayscale(num_output_channels=3)andResize((64, 64))in the transform - Use
Adamwithlr=1e-3and pass the optimiser onlymodel.fc.parameters(), not the whole model - After training, show how many parameters were trained versus the total (it should be ~5 K out of 11 M)
Show solution

Summary¶
This entry covers CNNs and transfer learning in PyTorch. It starts by justifying the use of CNNs over MLPs for image data and explains convolutions, pooling and how the shape of tensors changes between layers. It then introduces Batch Normalization, ResNets and data augmentation, and ends with two hands-on exercises: training a CNN from scratch on MNIST and applying transfer learning with a pretrained ResNet-18 on FashionMNIST.