Skip to content

Artificial IntelligencePyTorch from scratch

3. CNNs and transfer learning

Guide · PyTorch, CNN, Transfer Learning · updated on 24/11/2026

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.

Convolution

The kernel slides across the image computing a weighted sum at each position.

1
2
3
4
Input image:        (H, W)
Kernel:             (k, k)
Output:             (H - k + 1, W - k + 1)   ← no padding
                    (H, W)                    ← with padding=1 and k=3
  • 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.

1
2
3
# This learns 32 different 3×3 filters over a greyscale image
conv = nn.Conv2d(in_channels=1, out_channels=32, kernel_size=3, padding=1)
# Parameters: 32 × (1 × 3 × 3) + 32 biases = 320
- How much does an image shrink between layers?

Each convolutional or pooling layer reduces the spatial dimensions of the input according to:

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

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:

\[H_{out} = \left\lfloor \frac{H - K_H}{S_H} \right\rfloor + 1\]

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:

\[H_{out} = \left\lfloor \frac{H - K_H + 2P_H}{S_H} \right\rfloor + 1 \text{ ; } W_{out} = \left\lfloor \frac{W - K_W + 2P_W}{S_W} \right\rfloor + 1\]

In practice, the same padding, stride and kernel size are applied in both spatial dimensions. The two expressions then reduce to:

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

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.

Pooling

A typical CNN architecture

The basic building block of most CNNs follows this pattern:

[Conv2d → BatchNorm → ReLU → MaxPool]  ×  N  →  Flatten  →  Linear
CNN

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:

\[\hat{x} = \frac{x - \mu_{\text{batch}}}{\sqrt{\sigma^2_{\text{batch}} + \varepsilon}} \qquad \text{then} \qquad y = \gamma \cdot \hat{x} + \beta\]
  • Advantages in practice
    • Faster convergence: allows higher learning rates
    • Acts as regularisation: reduces the need for Dropout
    • Stabilises training: gradients flow more consistently
1
2
3
4
# Always place BatchNorm AFTER the Conv and BEFORE the activation
nn.Conv2d(32, 64, 3, padding=1),
nn.BatchNorm2d(64),   # ← normalises across the batch
nn.ReLU()

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.

Transfer learning
  • 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:

# Step 1: load the pretrained model
model = torchvision.models.resnet18(weights='IMAGENET1K_V1')

# Step 2: freeze everything
for param in model.parameters():
    param.requires_grad = False

# Step 3: replace the classifier head
model.fc = nn.Linear(512, 10)  # only this layer is trained

# Step 4: optionally, unfreeze the last block for fine-tuning
for param in model.layer4.parameters():
    param.requires_grad = True

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:

\[\frac{\partial L}{\partial w_1} = \frac{\partial L}{\partial a_n} \cdot \frac{\partial a_n}{\partial a_{n-1}} \cdots \frac{\partial a_2}{\partial a_1} \cdot \frac{\partial a_1}{\partial w_1}\]

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.

Capa:       50   49   48  ...   3    2    1
Gradiente: 0.9  0.8  0.7  ...  0.001  0.0001  ≈ 0  ← desvanecido

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:

Residual block

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:

\[H(x) = F(x) + x \implies F(x) = H(x) - x\]

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:

\[\frac{\partial L}{\partial x} = \frac{\partial L}{\partial \text{output}} \cdot \underbrace{\left(\frac{\partial F(x)}{\partial x} + 1\right)}_{\geq 1 \text{ always}}\]

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.

1
2
3
4
5
6
7
train_transforms = transforms.Compose([
    transforms.RandomHorizontalFlip(p=0.5),
    transforms.RandomRotation(degrees=10),
    transforms.ColorJitter(brightness=0.2, contrast=0.2),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.5], std=[0.5])
])

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.

1
2
3
4
5
6
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

model = SimpleCNN().to(device)       # move the model's weights to the device

images = images.to(device)           # move every batch of data too
labels = labels.to(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.MNIST and wrap it in a DataLoader with batch_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) with labels
Show solution
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
import matplotlib.pyplot as plt


torch.manual_seed(42)
################  --- FIRST TIME USING THE GPU!!! --- ################
# If the GPU is detected, device = 'cuda'. Otherwise, device='cpu'
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(f'Using device: {device}')

# ----- Data --------------------------------------------------------
transform = transforms.ToTensor()

train_dataset = torchvision.datasets.MNIST(root='./data', train=True,  download=True, transform=transform)
test_dataset  = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform)

train_loader = DataLoader(train_dataset, #TODO
                          batch_size=64, #TODO
                          shuffle=True #TODO
                          )  # shuffle only for training!
test_loader  = DataLoader(test_dataset,
                          batch_size=64, #TODO
                          shuffle=False #TODO
                          )

# ----- Model --------------------------------------------------------
class SimpleCNN(nn.Module):
    def __init__(self):
        super().__init__()
        self.features = nn.Sequential(
            nn.Conv2d(in_channels=1, #TODO
                      out_channels=32, #TODO
                      kernel_size=3, #TODO
                      padding=1 #TODO
                      ),
            nn.ReLU(), # TODO: add ReLU
            nn.MaxPool2d(2), # TODO: add MaxPool2d with kernel_size=2
            nn.Conv2d(in_channels=32, #TODO
                      out_channels=64, #TODO
                      kernel_size=3, #TODO
                      padding=1#TODO
                      ),
            nn.ReLU(),      # TODO: add ReLU
            nn.MaxPool2d(2) # TODO: add MaxPool2d with kernel_size=2
        )
        self.classifier = nn.Sequential(
            nn.Flatten(),
            nn.Linear(64*7*7, 128),  # hint: after two MaxPool2d(2), 28x28 becomes 7x7; we have 64 channels
            nn.ReLU(),
            nn.Linear(128, 10),  # hint: how many digit classes are there?
        )

    def forward(self, x):
        return self.classifier(self.features(x))

model = SimpleCNN().to(device)
print(model)
print(f'Trainable parameters: {sum(p.numel() for p in model.parameters() if p.requires_grad):,}')

# ----- Loss and optimiser --------------------------------------------------------
criterion = nn.CrossEntropyLoss()  #TODO # use CrossEntropyLoss
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3) #TODO # use Adam with lr=1e-3

# ----- Training loop --------------------------------------------------------
train_losses = []
EPOCHS = 5

for epoch in range(1, EPOCHS + 1):
    model.train() # Important with MaxPool and BatchNormalization layers! (It is good practice to always write it)
    running_loss = 0.0
    for images, labels in train_loader:
        images, labels = images.to(device), labels.to(device) # .to(device) sends the tensor to the GPU (and with it every computation already done and still to come)
        optimizer.zero_grad()    #TODO() # reset gradients
        outputs = model(images)
        loss = criterion(outputs, labels)
        loss.backward()          #TODO() # backpropagation
        optimizer.step()         #TODO() # update weights
        running_loss += loss.item()
    avg_loss = running_loss / len(train_loader)
    train_losses.append(avg_loss)
    print(f'Epoch {epoch}/{EPOCHS}  |  Loss: {avg_loss:.4f}')

# ----- Evaluation --------------------------------------------------------
model.eval()
correct = total = 0
with torch.no_grad():
    for images, labels in test_loader:
        images, labels = images.to(device), labels.to(device)
        preds = model(images).argmax(dim=1)
        correct += (preds == labels).sum().item()
        total   += labels.size(0)

print(f'\nTest Accuracy: {100 * correct / total:.2f}%')

# ----- Loss curve --------------------------------------------------------
plt.figure(figsize=(7, 4))
plt.plot(range(1, EPOCHS + 1), train_losses, marker='o', color='steelblue', linewidth=2)
plt.title('Training Loss — CNN on MNIST')
plt.xlabel('Epoch'); plt.ylabel('Loss')
plt.xticks(range(1, EPOCHS + 1))
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
Output
Using device: cuda
SimpleCNN(
  (features): Sequential(
    (0): Conv2d(1, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (1): ReLU()
    (2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (3): Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (4): ReLU()
    (5): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  )
  (classifier): Sequential(
    (0): Flatten(start_dim=1, end_dim=-1)
    (1): Linear(in_features=3136, out_features=128, bias=True)
    (2): ReLU()
    (3): Linear(in_features=128, out_features=10, bias=True)
  )
)
Trainable parameters: 421,642
Epoch 1/5  |  Loss: 0.1853
Epoch 2/5  |  Loss: 0.0496
Epoch 3/5  |  Loss: 0.0344
Epoch 4/5  |  Loss: 0.0255
Epoch 5/5  |  Loss: 0.0196

Test Accuracy: 99.02%

Output of cell 3

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 with requires_grad = False
  • Replace model.fc with a new nn.Linear(512, 10): it is the only layer that will be trained
  • ResNet-18 expects 3-channel inputs: apply Grayscale(num_output_channels=3) and Resize((64, 64)) in the transform
  • Use Adam with lr=1e-3 and pass the optimiser only model.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
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
import matplotlib.pyplot as plt

torch.manual_seed(42)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(f'Using device: {device}')

# ---  Data --------------------------------------------------------
# ResNet-18 expects 3-channel images. FashionMNIST has 1 channel and is 28x28,
# so we resize it and replicate the channel.
transform = transforms.Compose([
    transforms.Resize((64, 64)),                         # increase size: 28x28 -> 64x64
    transforms.Grayscale(num_output_channels=3),   #TODO  # 1 channel -> ? channels
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
])

train_dataset = torchvision.datasets.FashionMNIST(root='./data', train=True,  download=True, transform=transform)
test_dataset  = torchvision.datasets.FashionMNIST(root='./data', train=False, download=True, transform=transform)

train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
test_loader  = DataLoader(test_dataset,  batch_size=64, shuffle=False)

# ----- Load pretrained ResNet-18 --------------------------------------------------------
model = torchvision.models.resnet18(weights='IMAGENET1K_V1')

# Freeze ALL the layers: we want to reuse the learnt features, not retrain them
for param in model.parameters():
    param.requires_grad = False #TODO # True or False?

# ----- Replace the classifier head --------------------------------------------------------
# model.fc now has 1000 output classes (ImageNet). We need 10.
# A new nn.Linear automatically has requires_grad=True.
model.fc = nn.Linear(512, 10)  # TODO (??, ??) # hint: ResNet-18 produces 512 features

model = model.to(device)

# Check: only model.fc should be trainable
trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
total     = sum(p.numel() for p in model.parameters())
print(f'Trainable: {trainable:,} / {total:,} parameters')  # ~5K / 11M expected

# ----- Loss and optimiser --------------------------------------------------------------------
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.fc.parameters(), #TODO # which submodule needs optimising?
                             lr=1e-3) #

# ----- Training loop ------------------------------------------------------------------------
train_losses = []
EPOCHS = 3

for epoch in range(1, EPOCHS + 1):
    model.train()
    running_loss = 0.0
    for images, labels in train_loader:
        images, labels = images.to(device), labels.to(device)
        optimizer.zero_grad()
        loss = criterion(model(images), labels)
        loss.backward()
        optimizer.step()
        running_loss += loss.item()
    avg_loss = running_loss / len(train_loader)
    train_losses.append(avg_loss)
    print(f'Epoch {epoch}/{EPOCHS}  |  Loss: {avg_loss:.4f}')

# ----- Evaluation ------------------------------------------------------------------------------
model.eval()
correct = total_samples = 0
with torch.no_grad():
    for images, labels in test_loader:
        images, labels = images.to(device), labels.to(device)
        preds = model(images).argmax(dim=1)
        correct       += (preds == labels).sum().item()
        total_samples += labels.size(0)

print(f'\nTest Accuracy: {100 * correct / total_samples:.2f}%')

# ----- Loss curve -----------------------------------------------------------------------------------------------------
plt.figure(figsize=(7, 4))
plt.plot(range(1, EPOCHS + 1), train_losses, marker='o', color='darkorange', linewidth=2)
plt.title('Training Loss — ResNet-18 Transfer Learning on FashionMNIST')
plt.xlabel('Epoch'); plt.ylabel('Loss')
plt.xticks(range(1, EPOCHS + 1))
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
Output
1
2
3
4
5
6
7
8
Using device: cuda
Downloading: "https://download.pytorch.org/models/resnet18-f37072fd.pth" to /home/afdezcaravaca/.cache/torch/hub/checkpoints/resnet18-f37072fd.pth
Trainable: 5,130 / 11,181,642 parameters
Epoch 1/3  |  Loss: 0.7493
Epoch 2/3  |  Loss: 0.5993
Epoch 3/3  |  Loss: 0.5802

Test Accuracy: 80.13%

Output of cell 5


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.

See also