Code
# on Google Colab, PyTorch comes preinstalled; timm may not
import sys
if "google.colab" in sys.modules:
!pip install -q timmColab link
So far we’ve used simple networks: MLPs and a small CNN. Today we’ll meet the architectures that marked the evolution of deep learning, understand why each one emerged, and use real, pre-trained models downloaded from Hugging Face.
Plan
The attention mechanism (Transformers, ViT) and self-supervised learning are for class 7 (dl7_atencao.ipynb), and embeddings with dimensionality reduction for class 8 (dl8_embeddings.ipynb).
For each architecture there’s a fact sheet 🗂️ with the year, whether it’s old or recent, the type of training, why it matters, its strengths and its limitations.
import os
os.environ.setdefault("HF_HUB_DISABLE_PROGRESS_BARS", "1") # clean output when downloading from Hugging Face
os.environ.setdefault("HF_HUB_VERBOSITY", "error")
import time
import zipfile
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.patheffects as pe
from matplotlib.patches import Rectangle
from matplotlib.colors import ListedColormap
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import datasets, transforms
from skimage import data, io
from PIL import Image
# chart colors and style
AZUL, LARANJA, VERDE, CINZA, TINTA = "#2a78d6", "#eb6834", "#1baf7a", "#898781", "#52514e"
plt.rcParams.update({
"axes.spines.top": False, "axes.spines.right": False,
"axes.edgecolor": CINZA, "axes.labelcolor": TINTA,
"xtick.color": TINTA, "ytick.color": TINTA,
"axes.grid": True, "grid.color": "#e6e5e1", "figure.dpi": 110,
})
torch.manual_seed(42)
np.random.seed(42)
# large networks (ResNet-50, U-Net) benefit from a GPU, including the Mac's (MPS); small networks run better on CPU
DEVICE = "cuda" if torch.cuda.is_available() else ("mps" if torch.backends.mps.is_available() else "cpu")
DEVICE_PEQUENO = "cuda" if torch.cuda.is_available() else "cpu"
print(f"PyTorch {torch.__version__} | large networks: {DEVICE} | small networks: {DEVICE_PEQUENO}")PyTorch 2.14.1 | redes grandes: mps | redes pequenas: cpu
Let’s see how CNN architectures, residual connections, encoder-decoders and attention mechanisms have evolved over time.
Notice three “eras”: CNNs (convolutions), very deep networks with residual connections, and Transformers, which today are increasingly trained in a self-supervised way (without labels).
marcos = [ # (year, name, family, vertical label offset)
(1998, "LeNet-5", "CNN", 1), (2012, "AlexNet", "CNN", 1), (2014, "VGG", "CNN", -1),
(2014.6, "GoogLeNet", "CNN", 1.9), (2015.2, "ResNet", "Residual / encoder-decoder", -1.9),
(2015.6, "U-Net", "Residual / encoder-decoder", 1), (2017, "Transformer", "Attention", -1),
(2020, "ViT", "Attention", 1), (2021, "MAE, DINO", "Self-supervised", -1),
(2022, "ConvNeXt", "CNN", 1.9), (2023, "DINOv2, Prithvi", "Self-supervised", 1),
(2025, "DINOv3", "Self-supervised", -1),
]
cores_familia = {"CNN": AZUL, "Residual / encoder-decoder": VERDE, "Attention": LARANJA, "Self-supervised": "#4a3aa7"}
fig, ax = plt.subplots(figsize=(15, 3.6))
ax.axhline(0, color=CINZA, lw=1.5, zorder=1)
for ano, nome, familia, dy in marcos:
cor = cores_familia[familia]
ax.plot([ano, ano], [0, dy * 0.8], color=cor, lw=1, zorder=1)
ax.scatter(ano, 0, s=90, color=cor, zorder=3, edgecolor="white", lw=1.5)
ax.text(ano, dy, nome, ha="center", va="center", color=TINTA, fontsize=10,
bbox={"boxstyle": "round,pad=0.3", "facecolor": "white", "edgecolor": cor})
for familia, cor in cores_familia.items():
ax.scatter([], [], s=70, color=cor, label=familia)
ax.set(xlim=(1996, 2027), ylim=(-2.6, 2.6), yticks=[], title="Architectures that marked deep learning")
ax.spines["left"].set_visible(False)
ax.grid(False)
ax.legend(frameon=False, loc="upper center", bbox_to_anchor=(0.5, -0.12), ncols=4)
plt.show()
In previous classes, we “flattened” the MNIST image into a vector of 784 numbers.
One of the biggest problems is that we lose all the image’s spatial information: we lose objects and their neighbors, throwing away Tobler’s first law. It’s also inefficient to vectorize large images: we’d end up with extremely large networks that overfit easily.
MNIST 784 entradas -> 1ª camada densa com 128 neurônios = 100,352 pesos
foto 224 × 224 RGB 150,528 entradas -> 1ª camada densa com 128 neurônios = 19,267,584 pesos
imagem Sentinel-2 512 × 512, 13 bandas 3,407,872 entradas -> 1ª camada densa com 128 neurônios = 436,207,616 pesos
So the problems of using dense layers directly on pixels can be summarized as:
Convolution addresses these shortcomings of MLPs for images with a kernel, also known as a filter (e.g. 3 × 3): the same filter slides over the image and has only 9 weights. This creates weights shared across the whole image, which helps networks generalize.
At each position, we multiply the filter (kernel) by the pixels underneath it, element by element, and sum. The result becomes one pixel of the output, the feature map.
def convolucao_manual(imagem, kernel):
"""2D convolution (no padding, stride 1)."""
H, W = imagem.shape
k = kernel.shape[0]
saida = torch.zeros(H - k + 1, W - k + 1)
for i in range(H - k + 1):
for j in range(W - k + 1):
janela = imagem[i:i + k, j:j + k]
saida[i, j] = (janela * kernel).sum() # multiply element-wise and sum
return saida
imagem = torch.tensor([[0, 0, 0, 0, 0, 0],
[0, 9, 9, 9, 9, 0],
[0, 9, 0, 0, 9, 0],
[0, 9, 0, 0, 9, 0],
[0, 9, 9, 9, 9, 0],
[0, 0, 0, 0, 0, 0]], dtype=torch.float32)
kernel = torch.tensor([[-1, 0, 1],
[-1, 0, 1],
[-1, 0, 1]], dtype=torch.float32) # detects vertical edges
saida = convolucao_manual(imagem, kernel)
# written in PyTorch
saida_torch = F.conv2d(imagem[None, None], kernel[None, None])[0, 0] # (batch, channel, H, W)
print(f"entrada {tuple(imagem.shape)} * kernel {tuple(kernel.shape)} - output {tuple(saida.shape)}")
print(f"same as PyTorch's F.conv2d? {torch.equal(saida, saida_torch)}")entrada (6, 6) * kernel (3, 3) - saída (4, 4)
igual ao F.conv2d do PyTorch? True
def desenha_matriz(ax, m, titulo, destaque=None, cmap="Blues", vmin=None, vmax=None):
ax.imshow(m, cmap=cmap, vmin=vmin, vmax=vmax)
for i in range(m.shape[0]):
for j in range(m.shape[1]):
ax.text(j, i, f"{m[i, j]:g}", ha="center", va="center", fontsize=11, color=TINTA,
path_effects=[pe.withStroke(linewidth=3, foreground="white")])
if destaque:
(i, j, k) = destaque
ax.add_patch(Rectangle((j - 0.5, i - 0.5), k, k, fill=False, edgecolor=LARANJA, lw=3))
ax.set(title=titulo, xticks=[], yticks=[])
ax.grid(False)
i, j = 1, 0 # highlighted position
fig, axes = plt.subplots(1, 3, figsize=(14, 4.5), width_ratios=[6, 3, 4])
desenha_matriz(axes[0], imagem.numpy(), "6 × 6 input (a square)", destaque=(i, j, 3))
desenha_matriz(axes[1], kernel.numpy(), "3 × 3 kernel\n(vertical edge)", cmap="RdBu_r", vmin=-2, vmax=2)
desenha_matriz(axes[2], saida.numpy(), "4 × 4 output (feature map)", destaque=(i, j, 1), cmap="RdBu_r", vmin=-30, vmax=30)
janela = imagem[i:i + 3, j:j + 3]
plt.suptitle(f"Highlighted position: sum(window × kernel) = {(janela * kernel).sum():g}", y=1.0)
plt.tight_layout()
plt.show()
Notice that the output has fewer pixels than the input, because no padding was used.
Detail: what PyTorch calls convolution is, mathematically, a correlation. This makes no difference for neural networks, since they just learn the kernel weights.
The big idea behind CNNs (Convolutional Neural Networks): instead of designing filters by hand, we let the kernel values be trainable weights. The network discovers by itself, through gradient descent, which filters are useful for the task.
nn.Conv2d layer| Parameter | What it controls |
|---|---|
in_channels |
input channels (1 for grayscale, 3 for RGB, 13 for Sentinel-2) |
out_channels |
how many filters the layer learns = how many feature maps it produces |
kernel_size |
filter size (3 × 3 is the most common) |
stride |
the step the filter slides with (2 = the output is half the size) |
padding |
zero borders added (with padding=1 and a 3 × 3 kernel, the output has the same size) |
Output size: \(\text{output} = \left\lfloor \frac{\text{input} + 2 \cdot \text{padding} - \text{kernel}}{\text{stride}} \right\rfloor + 1\)
Number of weights: \(\text{out\_channels} \times (\text{in\_channels} \times k \times k) + \text{out\_channels}\) (biases).
Notice that it doesn’t depend on the image size.
x = torch.randn(1, 3, 512, 512) # an RGB image (512 × 512)
configs = [
dict(in_channels=3, out_channels=16, kernel_size=3, stride=1, padding=0),
dict(in_channels=3, out_channels=16, kernel_size=3, stride=1, padding=1),
dict(in_channels=3, out_channels=32, kernel_size=5, stride=2, padding=1),
dict(in_channels=3, out_channels=64, kernel_size=7, stride=2, padding=3), # ResNet-50's 1st layer
]
linhas = []
for cfg in configs:
conv = nn.Conv2d(**cfg)
linhas.append({**cfg, "pesos do kernel": tuple(conv.weight.shape), "nº de parâmetros": sum(p.numel() for p in conv.parameters()),
"saída": tuple(conv(x).shape)})
pd.DataFrame(linhas)| in_channels | out_channels | kernel_size | stride | padding | pesos do kernel | nº de parâmetros | saída | |
|---|---|---|---|---|---|---|---|---|
| 0 | 3 | 16 | 3 | 1 | 0 | (16, 3, 3, 3) | 448 | (1, 16, 510, 510) |
| 1 | 3 | 16 | 3 | 1 | 1 | (16, 3, 3, 3) | 448 | (1, 16, 512, 512) |
| 2 | 3 | 32 | 5 | 2 | 1 | (32, 3, 5, 5) | 2432 | (1, 32, 255, 255) |
| 3 | 3 | 64 | 7 | 2 | 3 | (64, 3, 7, 7) | 9472 | (1, 64, 256, 256) |
Max pooling splits the map into windows (usually 2 × 2) and keeps only the largest value of each. It halves the size, has no weights, and makes the network tolerant to small shifts.
m = torch.tensor([[1, 3, 2, 0],
[4, 6, 1, 1],
[0, 2, 9, 5],
[1, 1, 3, 7]], dtype=torch.float32)
pool = F.max_pool2d(m[None, None], kernel_size=2)[0, 0]
fig, axes = plt.subplots(1, 2, figsize=(8, 3.8), width_ratios=[4, 2])
desenha_matriz(axes[0], m.numpy(), "4 × 4 input")
for (i, j) in [(0, 0), (0, 2), (2, 0), (2, 2)]:
axes[0].add_patch(Rectangle((j - 0.5, i - 0.5), 2, 2, fill=False, edgecolor=LARANJA, lw=2.5))
desenha_matriz(axes[1], pool.numpy(), "max pooling 2 × 2")
plt.tight_layout()
plt.show()
🗂️ Fact sheet: Convolution and CNN (LeNet-5)
Year 1989 (first CNN trained with backprop, LeCun) and 1998 (LeNet-5) Old or new? Old: the idea is over 35 years old, but convolution is still in practically every vision model Type of training supervised: labeled images (for LeNet-5, digits on bank checks) Why it matters proved that learned filters beat hand-designed ones; introduced the conv → pooling → dense layers pattern Strengths few parameters (weight sharing), a sense of neighborhood, invariance to small shifts; works well with little data Limitations each filter only sees a small region (local receptive field); relationships between distant parts of the image require many layers Still used? the operation, yes, everywhere; LeNet-5 itself is a teaching example
A classic CNN has two halves:
Flatten) and goes through dense layers, like the MLP from previous classes.Let’s build LeNet-5 and follow the tensor’s shape layer by layer:
lenet = nn.Sequential(
nn.Conv2d(1, 6, kernel_size=5, padding=2), nn.ReLU(), nn.MaxPool2d(2), # block 1
nn.Conv2d(6, 16, kernel_size=5), nn.ReLU(), nn.MaxPool2d(2), # block 2
nn.Flatten(), # map -> vector #FC
nn.Linear(16*5*5, 120), nn.ReLU(), # dense layers (FULLY CONNECTED)
nn.Linear(120, 84), nn.ReLU(),
nn.Linear(84, 10),
)
x = torch.zeros(1, 1, 28, 28)
linhas = [{"camada": "entrada", "formato da saída": tuple(x.shape), "parâmetros": 0}]
for camada in lenet:
x = camada(x)
linhas.append({"camada": camada.__class__.__name__, "formato da saída": tuple(x.shape),
"parâmetros": sum(p.numel() for p in camada.parameters())})
tabela = pd.DataFrame(linhas)
tabela| camada | formato da saída | parâmetros | |
|---|---|---|---|
| 0 | entrada | (1, 1, 28, 28) | 0 |
| 1 | Conv2d | (1, 6, 28, 28) | 156 |
| 2 | ReLU | (1, 6, 28, 28) | 0 |
| 3 | MaxPool2d | (1, 6, 14, 14) | 0 |
| 4 | Conv2d | (1, 16, 10, 10) | 2416 |
| 5 | ReLU | (1, 16, 10, 10) | 0 |
| 6 | MaxPool2d | (1, 16, 5, 5) | 0 |
| 7 | Flatten | (1, 400) | 0 |
| 8 | Linear | (1, 120) | 48120 |
| 9 | ReLU | (1, 120) | 0 |
| 10 | Linear | (1, 84) | 10164 |
| 11 | ReLU | (1, 84) | 0 |
| 12 | Linear | (1, 10) | 850 |
conv_params = sum(p.numel() for c in lenet if isinstance(c, nn.Conv2d) for p in c.parameters())
dense_params = sum(p.numel() for c in lenet if isinstance(c, nn.Linear) for p in c.parameters())
total = conv_params + dense_params
fig, ax = plt.subplots(figsize=(9, 2.2))
ax.barh([0], [conv_params], color=AZUL, height=0.5, label=f"convolutional: {conv_params:,} ({conv_params / total:.0%})")
ax.barh([0], [dense_params], left=[conv_params], color=LARANJA, height=0.5, label=f"dense: {dense_params:,} ({dense_params / total:.0%})")
ax.set(yticks=[], xlabel="number of parameters", title=f"Where are LeNet-5's {total:,} parameters?")
ax.legend(frameon=False, loc="upper center", bbox_to_anchor=(0.5, -0.45), ncols=2)
ax.grid(axis="y", visible=False)
plt.show()
Facts about this shallow convolutional network: the convolutional layers do almost all the “seeing”, but hold only ~4% of the parameters. Most of the model sits in the dense layers at the end, right after Flatten. In bigger networks it gets worse: in VGG-16, ~90% of the 138 million parameters are in the three dense layers. We’ll see later how modern architectures solved this.
We train LeNet-5 for one epoch on MNIST (about 10 seconds) and look inside it.
mnist = datasets.MNIST("data", train=True, download=True, transform=transforms.ToTensor())
X_mnist = mnist.data.float().div(255).unsqueeze(1)
y_mnist = mnist.targets
torch.manual_seed(0)
lenet = lenet.to(DEVICE_PEQUENO)
otimizador = torch.optim.Adam(lenet.parameters(), lr=1e-3)
inicio = time.time()
for lote in torch.randperm(50000).split(128):
otimizador.zero_grad()
perda = F.cross_entropy(lenet(X_mnist[lote].to(DEVICE_PEQUENO)), y_mnist[lote].to(DEVICE_PEQUENO))
perda.backward()
otimizador.step()
with torch.no_grad():
acc = (lenet(X_mnist[50000:].to(DEVICE_PEQUENO)).argmax(1).cpu() == y_mnist[50000:]).float().mean()
print(f"LeNet-5, 1 epoch: validation accuracy = {acc:.2%} ({time.time() - inicio:.0f} s)")LeNet-5, 1 época: acurácia de validação = 95.84% (4 s)
torch.Size([1, 6, 14, 14])
digito = X_mnist[50000:50001].to(DEVICE_PEQUENO)
with torch.no_grad():
mapas1 = lenet[:3](digito)[0].cpu() # after block 1: (6, 14, 14)
mapas2 = lenet[:6](digito)[0].cpu() # after block 2: (16, 5, 5)
filtros1 = lenet[0].weight.detach().cpu()[:, 0]
fig = plt.figure(figsize=(16, 6.5))
grade = fig.add_gridspec(3, 16, height_ratios=[1, 1, 1])
ax = fig.add_subplot(grade[:, :3]); ax.imshow(digito[0, 0].cpu(), cmap="gray_r"); ax.set_title("28 × 28 input"); ax.axis("off")
for k in range(6):
ax = fig.add_subplot(grade[0, 4 + 2 * k:6 + 2 * k]); ax.imshow(filtros1[k], cmap="RdBu_r"); ax.axis("off")
if k == 0: ax.set_title("6 learned filters (5 × 5)", loc="left", fontsize=10)
ax = fig.add_subplot(grade[1, 4 + 2 * k:6 + 2 * k]); ax.imshow(mapas1[k], cmap="viridis"); ax.axis("off")
if k == 0: ax.set_title("block 1: 6 maps 14 × 14", loc="left", fontsize=10)
for k in range(12):
ax = fig.add_subplot(grade[2, 4 + k]); ax.imshow(mapas2[k], cmap="viridis"); ax.axis("off")
if k == 0: ax.set_title("block 2: 16 maps 5 × 5 (12 shown)", loc="left", fontsize=10)
plt.suptitle("Feature Maps")
plt.show()
In block 1, each map still looks like the digit: they’re filtered versions (edges in different directions). In block 2, the maps are small and abstract: each pixel summarizes a large region of the original image.
The receptive field is the part of the original image that influences one pixel of a map. Each convolution and each pooling enlarges that part. That’s why deep networks can recognize whole objects with small filters: the first layers see edges, the middle ones see parts (eyes, wheels, roofs) and the last ones see objects.
def campo_receptivo(camadas):
"""camadas: list of (name, kernel, stride). Returns the receptive field after each one."""
r, salto, linhas = 1, 1, []
for nome, k, s in camadas:
r = r + (k - 1) * salto
salto *= s
linhas.append({"camada": nome, "campo receptivo (pixels)": f"{r} × {r}"})
return pd.DataFrame(linhas)
print("LeNet-5:")
display(campo_receptivo([("conv 5×5", 5, 1), ("pool 2×2", 2, 2), ("conv 5×5", 5, 1), ("pool 2×2", 2, 2)]))
print("10 consecutive 3×3 convolutions, with a 2×2 pool every 2:")
display(campo_receptivo([(f"conv 3×3 #{i + 1}" if i % 3 < 2 else "pool 2×2", 3 if i % 3 < 2 else 2, 1 if i % 3 < 2 else 2)
for i in range(15)]).tail(4))LeNet-5:
| camada | campo receptivo (pixels) | |
|---|---|---|
| 0 | conv 5×5 | 5 × 5 |
| 1 | pool 2×2 | 6 × 6 |
| 2 | conv 5×5 | 14 × 14 |
| 3 | pool 2×2 | 16 × 16 |
10 convoluções 3×3 seguidas, com um pool 2×2 a cada 2:
| camada | campo receptivo (pixels) | |
|---|---|---|
| 11 | pool 2×2 | 76 × 76 |
| 12 | conv 3×3 #13 | 108 × 108 |
| 13 | conv 3×3 #14 | 140 × 140 |
| 14 | pool 2×2 | 156 × 156 |
For 14 years, CNNs like LeNet were limited to small problems. In 2012 three things came together: a huge labeled dataset (ImageNet, 1.2 million images, 1,000 classes), GPUs and a few simple ideas (ReLU, dropout). The result was AlexNet, and from then on the rule seemed to be: the deeper, the better.
Fact sheet: AlexNet
Year 2012 (Krizhevsky, Sutskever and Hinton) Old or new? Old, but it’s ground zero of modern deep learning Type of training supervised on ImageNet (1.2 million labeled images, 1,000 classes), on 2 GPUs Why it matters won the ImageNet 2012 challenge by a huge margin (top-5 error of ~15%, versus ~26% for 2nd place) and convinced the community that deep networks work Strengths popularized ReLU (much faster training than with sigmoid), dropout and GPU training Limitations 8 layers and ~60 million parameters, most in the dense layers; large filters (11 × 11) and many ad hoc details Still used? not in production; it has historical value
🗂️ Fact sheet: VGG
Year 2014 (Simonyan and Zisserman, Oxford) Old or new? Old Type of training supervised on ImageNet Why it matters showed that depth matters (16 to 19 layers) and that stacking 3 × 3 convolutions is enough: two 3 × 3s have the receptive field of one 5 × 5 with fewer parameters Strengths simple, regular architecture, easy to understand and implement; widely used as a feature extractor Limitations heavy: ~138 million parameters (VGG-16), ~90% in the dense layers; slow; can’t go much deeper without training degrading Still used? rarely; it shows up in perceptual loss and teaching examples
If depth helps, why not 100 layers? The ResNet authors noticed something strange: beyond a certain point, deeper networks got worse, even on the training set. It wasn’t overfitting: the network simply couldn’t be optimized. The signal (and the gradient) has to cross dozens of layers, and it degrades along the way.
Instead of asking a block of layers to learn the full transformation \(H(x)\), ResNet asks it to learn only the difference (the residual) \(F(x) = H(x) - x\), and adds the input back:
\[\text{output} = \text{ReLU}\big(F(x) + x\big)\]
x ──────────────────────────┐ (shortcut: the input passes straight through)
│ │
▼ │
conv 3×3 → BatchNorm → ReLU │
▼ │
conv 3×3 → BatchNorm │
▼ │
+ ◄─────────────────────────┘
▼
ReLU
Two consequences:
In code, the difference between a plain block and a residual block is one + x:
class Bloco(nn.Module):
"""Block with two 3×3 convolutions. residual=True adds the skip connection."""
def __init__(self, canais, residual=True):
super().__init__()
self.residual = residual
self.conv1 = nn.Conv2d(canais, canais, 3, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(canais)
self.conv2 = nn.Conv2d(canais, canais, 3, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(canais)
def forward(self, x):
y = self.bn2(self.conv2(F.relu(self.bn1(self.conv1(x)))))
if self.residual:
y = y + x # skip connection: add the input back
return F.relu(y)
class RedeProfunda(nn.Module):
def __init__(self, n_blocos, residual, canais=16):
super().__init__()
self.entrada = nn.Sequential(nn.Conv2d(1, canais, 3, padding=1, bias=False), nn.BatchNorm2d(canais), nn.ReLU())
self.blocos = nn.Sequential(*[Bloco(canais, residual) for _ in range(n_blocos)])
self.saida = nn.Linear(canais, 10)
def forward(self, x):
x = self.blocos(self.entrada(x))
return self.saida(x.mean(dim=(2, 3))) # global average pooling (see section 2.6)
for n_blocos in [10, 28]:
rede = RedeProfunda(n_blocos, residual=True)
print(f"{n_blocos} blocks = {2 * n_blocos + 2} weighted layers, {sum(p.numel() for p in rede.parameters()):,} parameters")10 blocos = 22 camadas com pesos, 47,066 parâmetros
28 blocos = 58 camadas com pesos, 131,162 parâmetros
We train four networks on MNIST (downscaled to 14 × 14, to be fast), with exactly the same number of parameters, the same optimizer and the same batches:
(This cell takes about 2 minutes.)
X_peq = F.avg_pool2d(X_mnist[:10000], 2) # 14 × 14 so the experiment is fast
y_peq = y_mnist[:10000]
def experimento(n_blocos, residual, passos=300):
torch.manual_seed(0)
rede = RedeProfunda(n_blocos, residual).to(DEVICE_PEQUENO)
# gradient norm in each block, at the very start (before training)
F.cross_entropy(rede(X_peq[:256].to(DEVICE_PEQUENO)), y_peq[:256].to(DEVICE_PEQUENO)).backward()
grad_blocos = [b.conv1.weight.grad.norm().item() for b in rede.blocos]
rede.zero_grad()
otimizador = torch.optim.SGD(rede.parameters(), lr=0.05, momentum=0.9)
gerador = torch.Generator().manual_seed(0)
perdas = []
for _ in range(passos):
idx = torch.randint(0, 9000, (64,), generator=gerador)
otimizador.zero_grad()
perda = F.cross_entropy(rede(X_peq[idx].to(DEVICE_PEQUENO)), y_peq[idx].to(DEVICE_PEQUENO))
perda.backward()
otimizador.step()
perdas.append(perda.item())
rede.eval()
with torch.no_grad():
acc = (rede(X_peq[9000:].to(DEVICE_PEQUENO)).argmax(1).cpu() == y_peq[9000:]).float().mean().item()
return {"perdas": np.array(perdas), "grad": grad_blocos, "acc": acc}
inicio = time.time()
resultados = {}
for n_blocos in [10, 28]:
for residual in [False, True]:
nome = f"{2 * n_blocos + 2} camadas, {'residual' if residual else 'comum'}"
resultados[nome] = experimento(n_blocos, residual)
print(f"{nome:<26} validation accuracy = {resultados[nome]['acc']:.1%}")
print(f"({time.time() - inicio:.0f} s)")22 camadas, comum acurácia de validação = 81.7%
22 camadas, residual acurácia de validação = 92.2%
58 camadas, comum acurácia de validação = 23.4%
58 camadas, residual acurácia de validação = 92.6%
(137 s)
estilos = {"22 camadas, comum": (CINZA, "--"), "22 camadas, residual": (CINZA, "-"),
"58 camadas, comum": (LARANJA, "--"), "58 camadas, residual": (AZUL, "-")}
suaviza = lambda s, j=20: np.convolve(s, np.ones(j) / j, mode="valid")
fig, axes = plt.subplots(1, 3, figsize=(17, 4.5), width_ratios=[1.3, 1, 0.8])
for nome, r in resultados.items():
cor, ls = estilos[nome]
axes[0].plot(suaviza(r["perdas"]), color=cor, ls=ls, lw=2, label=nome)
axes[0].set(xlabel="training step", ylabel="training loss (moving average)", title="TRAINING loss")
axes[0].legend(frameon=False)
for nome in ["58 camadas, comum", "58 camadas, residual"]:
cor, ls = estilos[nome]
axes[1].plot(range(1, 29), resultados[nome]["grad"], color=cor, ls=ls, lw=2, marker="o", ms=4, label=nome)
axes[1].set(yscale="log", xlabel="block (1 = near the input)", ylabel="gradient norm",
title="Gradient in each block, at the start")
axes[1].legend(frameon=False)
nomes = list(resultados)
accs = [resultados[k]["acc"] for k in nomes]
axes[2].barh(nomes[::-1], accs[::-1], color=[estilos[k][0] for k in nomes[::-1]], height=0.6)
for y, v in enumerate(accs[::-1]):
axes[2].text(v + 0.01, y, f"{v:.0%}", va="center", color=TINTA)
axes[2].set(xlim=(0, 1.1), xlabel="validation accuracy", title="Result")
axes[2].grid(axis="y", visible=False)
plt.tight_layout()
plt.show()
Reading the plots:
Two details that appear in real ResNets:
stride=2), \(x\) and \(F(x)\) don’t have the same shape and can’t be added. The solution is to pass \(x\) through a 1 × 1 convolution in the shortcut.conv 1×1 (reduce channels) -> conv 3×3 -> conv 1×1 (expand). It’s cheaper than two 3 × 3 convolutions with many channels.class BlocoBottleneck(nn.Module):
"""ResNet-50 block: 1×1 (reduce) - 3×3 - 1×1 (expand), with a projection in the shortcut if needed."""
def __init__(self, entrada, meio, saida, stride=1):
super().__init__()
self.ramo = nn.Sequential(
nn.Conv2d(entrada, meio, 1, bias=False), nn.BatchNorm2d(meio), nn.ReLU(),
nn.Conv2d(meio, meio, 3, stride=stride, padding=1, bias=False), nn.BatchNorm2d(meio), nn.ReLU(),
nn.Conv2d(meio, saida, 1, bias=False), nn.BatchNorm2d(saida),
)
self.atalho = nn.Identity()
if stride != 1 or entrada != saida: # different shapes: 1×1 projection in the shortcut
self.atalho = nn.Sequential(nn.Conv2d(entrada, saida, 1, stride=stride, bias=False), nn.BatchNorm2d(saida))
def forward(self, x):
return F.relu(self.ramo(x) + self.atalho(x))
x = torch.randn(1, 256, 56, 56)
for nome, bloco in {"same shape (shortcut = identity)": BlocoBottleneck(256, 64, 256),
"shrink and deepen (shortcut = 1×1 conv, stride 2)": BlocoBottleneck(256, 128, 512, stride=2)}.items():
print(f"{nome:<48} {tuple(x.shape)} → {tuple(bloco(x).shape)} {sum(p.numel() for p in bloco.parameters()):,} parameters")
dois_3x3 = 2 * (256 * 256 * 9)
print(f"\ncomparison: two 3×3 convolutions with 256 channels would have {dois_3x3:,} parameters")mesmo formato (atalho = identidade) (1, 256, 56, 56) → (1, 256, 56, 56) 70,400 parâmetros
reduz e aprofunda (atalho = conv 1×1, stride 2) (1, 256, 56, 56) → (1, 512, 28, 28) 379,392 parâmetros
comparação: duas convoluções 3×3 com 256 canais teriam 1,179,648 parâmetros
Remember that in LeNet and VGG almost all the parameters were in the dense layers after Flatten?
ResNet replaces that with global average pooling (GAP): it takes the mean of each whole map, turning (2048, 7, 7) into a vector of 2,048 numbers, and only then applies one linear layer.
canais, h, w, classes = 2048, 7, 7, 1000
flatten_denso = canais * h * w * classes
gap_denso = canais * classes
print(f"Flatten (2048 × 7 × 7 = {canais * h * w:,}) → dense to 1000: {flatten_denso:>12,} weights")
print(f"GAP (2048) → dense to 1000: {gap_denso:>12,} weights ({flatten_denso // gap_denso}× fewer)")Flatten (2048 × 7 × 7 = 100,352) → densa de 1000: 100,352,000 pesos
GAP (2048) → densa de 1000: 2,048,000 pesos (49× menos)
🗂️ Fact sheet: ResNet (Residual Network)
Year 2015 (He, Zhang, Ren and Sun, Microsoft Research) Old or new? Classic: 10 years old and still one of the most widely used starting points Type of training supervised on ImageNet; today there are self-supervised versions Why it matters skip connections solved the degradation problem and made it possible to train networks with 50, 101, 152 and even 1,000 layers; won ImageNet 2015 (top-5 error of 3.6%, below the estimate for humans). The residual idea is now in practically every architecture, including Transformers Strengths trains stably at great depth; GAP instead of giant dense layers (ResNet-50 has ~25 million parameters, versus 138 for VGG-16); a great backbone for other tasks (detection, segmentation) Limitations it’s still a CNN: local receptive field, long-range relationships only in the final layers; with large amounts of data, Transformers usually beat it Still used? a lot: as a baseline, as the backbone of U-Nets and detectors, and in remote sensing
Hugging Face is the “GitHub of AI models”. The Hub openly hosts:
| What | Examples |
|---|---|
| Models (over a million) | ResNets, ViTs, LLMs, foundation models for Earth observation (Prithvi, Clay, DOFA) |
| Datasets | labeled images, text, time series, satellite images |
| Spaces | demo apps running in the browser |
Each model has a model card: who trained it, on what data, the license, metrics and how to use it. Instead of training a ResNet-50 from scratch (days of GPU time on ImageNet), we download the ready-made weights in seconds.
Libraries that talk to the Hub:
| Library | What for |
|---|---|
huggingface_hub |
search, download and upload files, models and datasets |
timm (PyTorch Image Models) |
hundreds of vision architectures (ResNet, ConvNeXt, ViT, DINOv2) with pre-trained weights |
transformers |
language, vision and multimodal models |
datasets |
load Hub datasets with one line |
To download public models and datasets, you don’t need an account. An account and a token are needed for: private or restricted (gated, like some LLMs) models, uploading your own models and datasets, and getting higher download limits.
hf auth login (the token is saved on your computer);from huggingface_hub import login; login();HF_TOKEN environment variable (for example in your .env). Never put the token in code or on GitHub.Without a token, the Hub shows a warning asking for an HF_TOKEN to get higher limits. For this class you can ignore it (we turned the warning off at the start of the notebook).
The same search as on the website can be done in code. The most downloaded timm ResNet-50s:
timm/resnet50.a1_in1k 1,588,866 downloads
timm/wide_resnet50_2.racm_in1k 856,501 downloads
timm/resnet50.fb_swsl_ig1b_ft_in1k 183,546 downloads
timm/resnet50d.ra2_in1k 106,276 downloads
timm/resnet50_gn.a1h_in1k 52,963 downloads
timm/resnet50.tv_in1k 28,652 downloads
For the case study we’ll use LandCover.ai: aerial orthophotos of Poland (25–50 cm per pixel) with masks of 5 classes (background, building, forest, water, road). The isaaccorley/landcoverai version has 100 tiles of 512 × 512 pixels (70 training, 15 validation, 15 test), in a 9 MB zip.
hf_hub_download downloads the file to a local cache: the second time, it doesn’t download again.
Source: Boguszewski et al. (2021), LandCover.ai, CC BY-NC-SA 4.0 license (non-commercial use).
caminho_zip = hf_hub_download(repo_id="isaaccorley/landcoverai", filename="landcoverai100.zip", repo_type="dataset")
print(f"file in cache: {caminho_zip}")
PASTA_LC = "data/landcoverai"
if not os.path.exists(PASTA_LC):
zipfile.ZipFile(caminho_zip).extractall(PASTA_LC)
ids = {s: open(f"{PASTA_LC}/{s}.txt").read().split() for s in ["train", "val", "test"]}
print({s: len(v) for s, v in ids.items()})arquivo no cache: /Users/macuser/.cache/huggingface/hub/datasets--isaaccorley--landcoverai/snapshots/5cdf9299bd6c1232506cf79373df01f6e6596b50/landcoverai100.zip
{'train': 70, 'val': 15, 'test': 15}
With timm, loading a model from the Hub takes one line.
The hf-hub: prefix says where to download from.
We use timm/resnet50.a1_in1k: a ResNet-50 trained in a supervised way on ImageNet-1k (1,000 classes) with the modern “A1” recipe from the paper ResNet strikes back (2021).
import timm
from timm.data import ImageNetInfo
inicio = time.time()
resnet50 = timm.create_model("hf-hub:timm/resnet50.a1_in1k", pretrained=True).eval()
print(f"loaded in {time.time() - inicio:.0f} s: {sum(p.numel() for p in resnet50.parameters()) / 1e6:.1f} million parameters")
# the model itself says how images should be prepared (size, normalization)
config = timm.data.resolve_data_config({}, model=resnet50)
transformacao = timm.data.create_transform(**config)
print(config)carregada em 1 s: 25.6 milhões de parâmetros
{'input_size': [3, 224, 224], 'interpolation': 'bicubic', 'mean': [0.485, 0.456, 0.406], 'std': [0.229, 0.224, 0.225], 'crop_pct': 0.95, 'crop_mode': 'center'}
Let’s classify four images: three photos from scikit-image and an aerial tile from LandCover.ai.
classes_imagenet = ImageNetInfo()
imagens = {
"cat": data.chelsea(),
"coffee": data.coffee(),
"astronaut": data.astronaut(),
"aerial photo": io.imread(f"{PASTA_LC}/output/{ids['test'][0]}.jpg"),
}
# how do we run inference?
xdata = data.astronaut()
# add the batch dimension
x = transformacao(Image.fromarray(xdata)).unsqueeze(0)
# torch.no_grad avoids computing gradients: an explicit way of saying we only want inference
with torch.no_grad():
prob = resnet50(x).softmax(dim=1)[0]
prob.shapetorch.Size([1000])
torch.return_types.topk(
values=tensor([0.6986, 0.0402, 0.0328]),
indices=tensor([812, 560, 573]))
fig, axes = plt.subplots(1, 4, figsize=(17, 5))
for ax, (nome, img) in zip(axes, imagens.items()):
x = transformacao(Image.fromarray(img)).unsqueeze(0)
with torch.no_grad():
prob = resnet50(x).softmax(dim=1)[0]
top = prob.topk(3)
texto = "\n".join(f"{p:.0%} {classes_imagenet.index_to_description(int(i))[:28]}" for p, i in zip(top.values, top.indices))
ax.imshow(img)
ax.set_title(nome, fontsize=12)
ax.text(0.5, -0.04, texto, transform=ax.transAxes, ha="center", va="top", fontsize=9.5, color=TINTA)
ax.axis("off")
plt.suptitle("ResNet-50 pre-trained on ImageNet 1K", y=0.98)
plt.tight_layout()
plt.show()
For everyday photos, ResNet-50 gets it right or close: ImageNet has no “astronaut” class, so it points to the space shuttle in the background. For the aerial photo, the predictions make no sense: ImageNet has 1,000 classes of objects photographed from the side (dogs, cups, cars), and none of them is “forest seen from above” or “roof”.
It’s a domain shift!!!
Does that mean ResNet-50 is useless for aerial images? No. The first-layer filters detect edges, textures and colors, things that exist in any image. Look at the 64 7 × 7 filters of the first layer:
filtros = resnet50.conv1.weight.detach() # (64, 3, 7, 7)
filtros = (filtros - filtros.amin(dim=(1, 2, 3), keepdim=True)) / (filtros.amax(dim=(1, 2, 3), keepdim=True) - filtros.amin(dim=(1, 2, 3), keepdim=True))
fig, axes = plt.subplots(4, 16, figsize=(16, 4.3))
for ax, f in zip(axes.flat, filtros):
ax.imshow(f.permute(1, 2, 0))
ax.axis("off")
plt.suptitle("The 64 RGB 7 × 7 filters learned by ResNet-50's 1st layer", y=1.0)
plt.show()
Edges in various directions, color blobs, striped patterns: the network learned by itself filters very similar to those in section 1.3. These generic features are exactly what we want to reuse. That’s the principle of transfer learning.
In Part 4 we’ll put these features to work on an aerial image segmentation problem.
So far, every network has classified whole images: “this image is a 7”, “this image is a cat”. In remote sensing, we almost always want more: where the forest is, which pixels are water, where the buildings are. That’s semantic segmentation: one class for every pixel.
| Task | Question | Network output |
|---|---|---|
| Classification | “what’s in this image?” | a vector of classes: (batch, n_classes) |
| Semantic segmentation | “which class does each pixel belong to?” | a class map: (batch, n_classes, H, W) |
For this the network has to do two seemingly contradictory things: understand context (which requires shrinking the image, as ResNet does) and return the original resolution, pixel by pixel. U-Net solves both.
🗂️ Fact sheet: U-Net
Year 2015 (Ronneberger, Fischer and Brox), created to segment cells in microscopy images Old or new? Classic, but still state of the art in segmentation; it’s also the basis of the diffusion models that generate images Type of training supervised: every pixel of the image has a label (segmentation mask) Why it matters solved semantic segmentation (one class per pixel) with few labeled images; became the standard in medicine and remote sensing (land use, buildings, water, deforestation, fires) Strengths U shape: the encoder understands what is in the image, the decoder recovers where; long skip connections carry fine detail from the encoder straight to the decoder; accepts any pre-trained backbone as the encoder Limitations needs pixel-by-pixel labeled masks (expensive to produce); the decoder can be heavy on large images; global context limited by the convolutional encoder Still used? a lot: it’s probably the most widely used architecture for satellite image segmentation
U-Net is shaped like a U:

Three pieces of code:
| Piece | What it does |
|---|---|
DuplaConv (double conv) |
two 3 × 3 convolutions, each with BatchNorm and ReLU: the U-Net’s “brick” |
nn.MaxPool2d(2) |
goes down one level: half the height and width |
Subida (up) |
nn.ConvTranspose2d (a convolution that enlarges the image, with learned weights) + concatenation with the skip + DuplaConv |
class DuplaConv(nn.Sequential):
"""conv 3×3 → BatchNorm → ReLU, twice. Keeps height and width."""
def __init__(self, entrada, saida):
super().__init__(
nn.Conv2d(entrada, saida, 3, padding=1, bias=False), nn.BatchNorm2d(saida), nn.ReLU(inplace=True),
nn.Conv2d(saida, saida, 3, padding=1, bias=False), nn.BatchNorm2d(saida), nn.ReLU(inplace=True),
)
class Decoder(nn.Module):
"""Doubles the size, concatenates the encoder skip connection and applies a DuplaConv."""
def __init__(self, entrada, saida):
super().__init__()
self.sobe = nn.ConvTranspose2d(entrada, saida, kernel_size=2, stride=2)
self.conv = DuplaConv(2 * saida, saida) # 2×: the upsampled channels + the skip channels
def forward(self, x, skip):
x = self.sobe(x)
x = torch.cat([x, skip], dim=1) # the U-Net skip connection: channel concatenation
return self.conv(x)
class UNet(nn.Module):
def __init__(self, canais_entrada=3, n_classes=5, base=16):
super().__init__()
c = [base, 2 * base, 4 * base, 8 * base, 16 * base] # 16, 32, 64, 128, 256 channels
self.pool = nn.MaxPool2d(2)
self.enc1, self.enc2 = DuplaConv(canais_entrada, c[0]), DuplaConv(c[0], c[1])
self.enc3, self.enc4 = DuplaConv(c[1], c[2]), DuplaConv(c[2], c[3])
self.fundo = DuplaConv(c[3], c[4])
self.dec4, self.dec3 = Decoder(c[4], c[3]), Decoder(c[3], c[2])
self.dec2, self.dec1 = Decoder(c[2], c[1]), Decoder(c[1], c[0])
self.saida = nn.Conv2d(c[0], n_classes, kernel_size=1) # one "logit" per class at each pixel
def forward(self, x, mostra=False):
e1 = self.enc1(x) # encoder: going down
e2 = self.enc2(self.pool(e1))
e3 = self.enc3(self.pool(e2))
e4 = self.enc4(self.pool(e3))
f = self.fundo(self.pool(e4))
d4 = self.dec4(f, e4) # decoder: going up, receiving the skips
d3 = self.dec3(d4, e3)
d2 = self.dec2(d3, e2)
d1 = self.dec1(d2, e1)
y = self.saida(d1)
if mostra:
for nome, t in [("entrada", x), ("enc1", e1), ("enc2", e2), ("enc3", e3), ("enc4", e4), ("fundo", f),
("dec4", d4), ("dec3", d3), ("dec2", d2), ("dec1", d1), ("saída", y)]:
print(f"{nome:<8} {str(tuple(t.shape)):<22}")
return y
unet = UNet()
with torch.no_grad():
unet(torch.zeros(1, 3, 256, 256), mostra=True)
print(f"\nparameters: {sum(p.numel() for p in unet.parameters()):,} "
f"(the original paper's U-Net, with base=64, would have {sum(p.numel() for p in UNet(base=64).parameters()):,})")entrada (1, 3, 256, 256)
enc1 (1, 16, 256, 256)
enc2 (1, 32, 128, 128)
enc3 (1, 64, 64, 64)
enc4 (1, 128, 32, 32)
fundo (1, 256, 16, 16)
dec4 (1, 128, 32, 32)
dec3 (1, 64, 64, 64)
dec2 (1, 32, 128, 128)
dec1 (1, 16, 256, 256)
saída (1, 5, 256, 256)
parâmetros: 1,942,645 (a U-Net do artigo original, com base=64, teria 31,037,893)
Notice the U shape in the numbers: the height goes from 256 down to 16 at the bottom and back to 256, while the channels go from 16 to 256 and back. The output has 5 channels (one per class) with the same size as the input.
We use the LandCover.ai data downloaded in Part 3: 100 orthophotos of Poland with 5-class masks. We downscale the images from 512 to 256 pixels to train quickly.
NOMES_LC = ["background", "building", "forest", "water", "road"]
CORES_LC = ["#d9d9d9", "#e34948", "#1baf7a", "#2a78d6", "#eda100"]
cmap_lc = ListedColormap(CORES_LC)
TAMANHO = 256 # downscaled from 512 to 256 to train quickly
def carrega_split(split):
imgs = np.stack([io.imread(f"{PASTA_LC}/output/{i}.jpg") for i in ids[split]])
mascaras = np.stack([io.imread(f"{PASTA_LC}/output/{i}_m.png")[..., 0] for i in ids[split]])
X = torch.tensor(imgs).permute(0, 3, 1, 2).float() / 255 # (N, 3, 512, 512)
Y = torch.tensor(mascaras).long() # (N, 512, 512)
X = F.interpolate(X, size=TAMANHO, mode="bilinear", antialias=True)
Y = F.interpolate(Y[:, None].float(), size=TAMANHO, mode="nearest")[:, 0].long() # mask: nearest neighbor
return X, Y
X_tr, Y_tr = carrega_split("train")
X_te, Y_te = carrega_split("test")
# the same normalization used in ResNet-50's pre-training (ImageNet)
media, desvio = torch.tensor(config["mean"])[:, None, None], torch.tensor(config["std"])[:, None, None]
normaliza = lambda x: (x - media) / desvio
print(f"train: {tuple(X_tr.shape)} {tuple(Y_tr.shape)} test: {tuple(X_te.shape)}")
frac = torch.bincount(Y_tr.flatten(), minlength=5) / Y_tr.numel()
print("fraction of pixels per class:", {n: f"{f:.1%}" for n, f in zip(NOMES_LC, frac)})treino: (70, 3, 256, 256) (70, 256, 256) teste: (15, 3, 256, 256)
fração de pixels por classe: {'fundo': '63.4%', 'edificação': '1.3%', 'floresta': '29.2%', 'água': '4.0%', 'estrada': '2.0%'}
fig, axes = plt.subplots(2, 5, figsize=(16, 6.8))
for k, idx in enumerate([0, 7, 14, 21, 35]):
axes[0, k].imshow(X_tr[idx].permute(1, 2, 0))
axes[1, k].imshow(Y_tr[idx], cmap=cmap_lc, vmin=0, vmax=4, interpolation="nearest")
axes[0, k].axis("off"); axes[1, k].axis("off")
axes[0, 0].set_title("aerial image", loc="left")
axes[1, 0].set_title("mask (label of each pixel)", loc="left")
for nome, cor in zip(NOMES_LC, CORES_LC):
axes[1, 4].scatter([], [], marker="s", s=120, color=cor, label=nome)
axes[1, 4].legend(frameon=False, loc="upper left", bbox_to_anchor=(1.02, 1))
plt.tight_layout()
plt.show()
For each pixel, the U-Net returns 5 logits (one per class). The path to the mask is the same as in classification, just applied to every pixel:
softmax over the class dimension (dim=1) → probabilities that sum to 1 at each pixel;argmax over the same dimension → the most likely class of each pixel = the predicted mask.The loss is also the same cross-entropy as in classification, computed at every pixel and then averaged. F.cross_entropy accepts this directly: logits (batch, classes, H, W) and labels (batch, H, W).
torch.manual_seed(0)
unet = UNet()
x, y = normaliza(X_tr[:4]), Y_tr[:4]
with torch.no_grad():
logits = unet(x) # (4, 5, 256, 256)
probs = logits.softmax(dim=1) # probabilities per pixel
mascara = probs.argmax(dim=1) # (4, 256, 256): the class of each pixel
perda = F.cross_entropy(logits, y) # mean cross-entropy over all pixels
print(f"input {tuple(x.shape)} → logits {tuple(logits.shape)} → mask {tuple(mascara.shape)}")
print(f"sum of probabilities at an arbitrary pixel: {probs[0, :, 100, 100].sum():.3f}")
print(f"loss of the NOT yet trained network: {perda:.3f} (a uniform guess among 5 classes would give ln 5 = {np.log(5):.3f})")
fig, axes = plt.subplots(1, 3, figsize=(12, 4))
axes[0].imshow(X_tr[0].permute(1, 2, 0)); axes[0].set_title("image")
axes[1].imshow(Y_tr[0], cmap=cmap_lc, vmin=0, vmax=4, interpolation="nearest"); axes[1].set_title("true label")
axes[2].imshow(mascara[0], cmap=cmap_lc, vmin=0, vmax=4, interpolation="nearest"); axes[2].set_title("untrained U-Net")
for ax in axes:
ax.axis("off")
plt.tight_layout()
plt.show()entrada (4, 3, 256, 256) → logits (4, 5, 256, 256) → máscara (4, 256, 256)
soma das probabilidades em um pixel qualquer: 1.000
perda da rede ainda NÃO treinada: 1.874 (um chute uniforme entre 5 classes daria ln 5 = 1.609)

The training loop is the usual one (as we saw in class 4), but let’s highlight two particularities of segmentation:
The function below trains only the parameters with requires_grad=True: we’ll reuse it in section 4.4 with a frozen encoder. (About 1 minute on GPU, 2–3 on CPU.)
def treina_segmentacao(modelo, epocas=20, lote=8, lr=1e-3, nome=""):
torch.manual_seed(0)
modelo = modelo.to(DEVICE)
otimizador = torch.optim.Adam([p for p in modelo.parameters() if p.requires_grad], lr=lr)
gerador = torch.Generator().manual_seed(0)
historico, inicio = [], time.time()
for epoca in range(epocas):
modelo.train()
perdas = []
for idx in torch.randperm(len(X_tr), generator=gerador).split(lote):
x, y = normaliza(X_tr[idx]), Y_tr[idx]
k = int(torch.randint(0, 4, (1,), generator=gerador)) #augmentation # rotation by k × 90°, identical for image and mask
x, y = torch.rot90(x, k, dims=(2, 3)), torch.rot90(y, k, dims=(1, 2))
otimizador.zero_grad()
perda = F.cross_entropy(modelo(x.to(DEVICE)), y.to(DEVICE))
perda.backward()
otimizador.step()
perdas.append(perda.item())
historico.append(np.mean(perdas))
print(f"{nome:<32} final loss = {historico[-1]:.3f} ({time.time() - inicio:.0f} s)")
return modelo.eval(), historico
torch.manual_seed(0)
unet_zero, hist_zero = treina_segmentacao(UNet(), nome="U-Net do zero")U-Net do zero perda final = 0.679 (57 s)
We’ve seen that we can train a U-Net from scratch. But what if we used an already-trained network for the encoder and only trained the decoder’s parameters?
With only 70 images, learning everything from scratch is hard: the encoder has to figure out by itself what edges, textures and shapes are. The idea of transfer learning: replace the U-Net’s encoder with the pre-trained ResNet-50 from Part 3, which already knows how to extract these features, and train only the decoder.
timm provides the ready-made encoder with features_only=True: instead of classifying, ResNet-50 returns the maps at 5 depths, exactly the levels the U-Net needs for the skip connections.
image 256×256 mask 256×256 (5 classes)
│ ▲
┌───▼──────────── ENCODER (pre-trained ResNet-50, frozen) ────┐ ┌─── DECODER (trained) ────┴───┐
│ 64 channels, 128×128 ────────────── skip ───────────────────────► concat → conv → 32 ch │
│ 256 channels, 64×64 ────────────── skip ───────────────────────► concat → conv → 64 ch │
│ 512 channels, 32×32 ────────────── skip ───────────────────────► concat → conv → 128 ch │
│ 1024 channels, 16×16 ────────────── skip ───────────────────────► concat → conv → 256 ch │
│ 2048 channels, 8×8 ────────────── (bottom of the U) ──────────► upsample ×2 │
└─────────────────────────────────────────────────────────────┘ └──────────────────────────────┘
Notice the difference between the two kinds of skip connections we’ve seen in this class:
| ResNet | U-Net | |
|---|---|---|
| Distance | short: skips 2 or 3 layers | long: connects the encoder to the decoder |
| Operation | sum (F(x) + x) |
channel concatenation (torch.cat) |
| Goal | let the gradient flow in deep networks | recover the spatial details lost in pooling |
encoder_teste = timm.create_model("hf-hub:timm/resnet50.a1_in1k", pretrained=True, features_only=True)
with torch.no_grad():
for mapa, reducao in zip(encoder_teste(torch.zeros(1, 3, TAMANHO, TAMANHO)), encoder_teste.feature_info.reduction()):
print(f"{str(tuple(mapa.shape)):<22} (1/{reducao} of the size)")
del encoder_teste(1, 64, 128, 128) (1/2 do tamanho)
(1, 256, 64, 64) (1/4 do tamanho)
(1, 512, 32, 32) (1/8 do tamanho)
(1, 1024, 16, 16) (1/16 do tamanho)
(1, 2048, 8, 8) (1/32 do tamanho)
def bloco_decoder(entrada, saida):
return nn.Sequential(
nn.Conv2d(entrada, saida, 3, padding=1, bias=False), nn.BatchNorm2d(saida), nn.ReLU(inplace=True),
nn.Conv2d(saida, saida, 3, padding=1, bias=False), nn.BatchNorm2d(saida), nn.ReLU(inplace=True),
)
class UNetResNet50(nn.Module):
def __init__(self, pre_treinado=True, n_classes=5):
super().__init__()
self.encoder = timm.create_model("hf-hub:timm/resnet50.a1_in1k", pretrained=pre_treinado, features_only=True)
for p in self.encoder.parameters(): # FROZEN encoder: only the decoder learns
p.requires_grad = False # freeze the encoder
self.dec4 = bloco_decoder(2048 + 1024, 256)
self.dec3 = bloco_decoder(256 + 512, 128)
self.dec2 = bloco_decoder(128 + 256, 64)
self.dec1 = bloco_decoder(64 + 64, 32)
self.dec0 = bloco_decoder(32, 16)
self.cabeca = nn.Conv2d(16, n_classes, kernel_size=1) # 1 channel per class
def forward(self, x):
self.encoder.eval() # encoder BatchNorm in evaluation mode (frozen)
with torch.no_grad():
f1, f2, f3, f4, f5 = self.encoder(x) # 1/2, 1/4, 1/8, 1/16, 1/32
sobe = lambda t: F.interpolate(t, scale_factor=2, mode="bilinear", align_corners=False)
x = self.dec4(torch.cat([sobe(f5), f4], dim=1)) # skip connection = concatenation
x = self.dec3(torch.cat([sobe(x), f3], dim=1))
x = self.dec2(torch.cat([sobe(x), f2], dim=1))
x = self.dec1(torch.cat([sobe(x), f1], dim=1))
x = self.dec0(sobe(x))
return self.cabeca(x) # (batch, 5, 256, 256): one "logit" per class and per pixel
torch.manual_seed(0)
unet50 = UNetResNet50()
treinaveis = sum(p.numel() for p in unet50.parameters() if p.requires_grad)
congelados = sum(p.numel() for p in unet50.parameters() if not p.requires_grad)
print(f"frozen encoder: {congelados / 1e6:.1f} M parameters | trainable decoder: {treinaveis / 1e6:.1f} M parameters")
unet_pre, hist_pre = treina_segmentacao(unet50, nome="U-Net + ResNet-50 pré-treinada")encoder congelado: 23.5 M parâmetros | decoder treinável: 9.0 M parâmetros
U-Net + ResNet-50 pré-treinada perda final = 0.471 (48 s)
In segmentation, the most widely used metric is the IoU (Intersection over Union) of each class: the area where prediction and label agree, divided by the total area marked by either of them. The mIoU is the average across classes. Pixel accuracy is misleading: a model that guesses “background” everywhere already gets ~60% of the pixels right.
\[\text{IoU}_c = \frac{|\text{predicted}_c \cap \text{true}_c|}{|\text{predicted}_c \cup \text{true}_c|}\]
@torch.no_grad()
def prediz(modelo, X):
return torch.cat([modelo(normaliza(X[i:i + 5]).to(DEVICE)).argmax(dim=1).cpu() for i in range(0, len(X), 5)])
def iou_por_classe(pred, real):
return [((pred == c) & (real == c)).sum().item() / max(((pred == c) | (real == c)).sum().item(), 1) for c in range(5)]
modelos_seg = {"U-Net do zero": unet_zero, "U-Net + ResNet-50 pré-treinada": unet_pre}
predicoes = {nome: prediz(m, X_te) for nome, m in modelos_seg.items()}
avaliacao = pd.DataFrame({nome: iou_por_classe(p, Y_te) + [(p == Y_te).float().mean().item()] for nome, p in predicoes.items()},
index=[f"IoU {c}" for c in NOMES_LC] + ["pixel accuracy"])
avaliacao.loc["mIoU"] = avaliacao.iloc[:5].mean()
avaliacao.round(3)| U-Net do zero | U-Net + ResNet-50 pré-treinada | |
|---|---|---|
| IoU fundo | 0.775 | 0.906 |
| IoU edificação | 0.000 | 0.000 |
| IoU floresta | 0.437 | 0.870 |
| IoU água | 0.000 | 0.656 |
| IoU estrada | 0.000 | 0.091 |
| acurácia por pixel | 0.735 | 0.919 |
| mIoU | 0.242 | 0.505 |
cores_modelos = {"U-Net do zero": LARANJA, "U-Net + ResNet-50 pré-treinada": AZUL}
fig, axes = plt.subplots(1, 2, figsize=(14, 4), width_ratios=[1, 1.4])
for nome, hist in [("U-Net do zero", hist_zero), ("U-Net + ResNet-50 pré-treinada", hist_pre)]:
axes[0].plot(range(1, len(hist) + 1), hist, color=cores_modelos[nome], lw=2, marker="o", ms=3, label=nome)
axes[0].set(xlabel="epoch", ylabel="training loss", title="Training")
axes[0].legend(frameon=False)
ious = avaliacao.loc[[f"IoU {c}" for c in NOMES_LC]]
y = np.arange(5)
for desloc, nome in [(0.2, "U-Net + ResNet-50 pré-treinada"), (-0.2, "U-Net do zero")]:
axes[1].barh(y + desloc, ious[nome], height=0.38, color=cores_modelos[nome], label=nome)
for yy, v in enumerate(ious[nome]):
axes[1].text(v + 0.01, yy + desloc, f"{v:.2f}", va="center", fontsize=9, color=TINTA)
axes[1].set(yticks=y, yticklabels=NOMES_LC, xlim=(0, 1.08), xlabel="test IoU", title="IoU per class (15 test images)")
axes[1].invert_yaxis()
axes[1].grid(axis="y", visible=False)
axes[1].legend(frameon=False, loc="lower right")
plt.tight_layout()
plt.show()
fig, axes = plt.subplots(3, 4, figsize=(14, 10.5))
for linha, idx in enumerate([1, 6, 12]):
paineis = [(X_te[idx].permute(1, 2, 0), "imagem"), (Y_te[idx], "true label")] + \
[(predicoes[nome][idx], nome) for nome in modelos_seg]
for ax, (mapa, titulo) in zip(axes[linha], paineis):
if titulo == "imagem":
ax.imshow(mapa)
else:
ax.imshow(mapa, cmap=cmap_lc, vmin=0, vmax=4, interpolation="nearest")
ax.axis("off")
if linha == 0:
ax.set_title(titulo)
for nome, cor in zip(NOMES_LC, CORES_LC):
axes[0, 3].scatter([], [], marker="s", s=120, color=cor, label=nome)
axes[0, 3].legend(frameon=False, loc="upper left", bbox_to_anchor=(1.02, 1))
plt.tight_layout()
plt.show()
Reading the results:
| Architecture | Year | Era | Type of training | Key idea | Weak point |
|---|---|---|---|---|---|
| CNN / LeNet-5 | 1998 | old | supervised | learned filters, shared weights | local context |
| AlexNet | 2012 | old | supervised (ImageNet) | depth + GPU + ReLU | heavy, ad hoc |
| VGG | 2014 | old | supervised (ImageNet) | stack 3 × 3 convolutions | 138 M parameters, stops improving with more layers |
| ResNet | 2015 | classic, widely used | supervised (ImageNet) | skip connections (sum) | still local |
| U-Net | 2015 | classic, widely used | supervised (masks) | encoder-decoder + long skips (concatenation) | needs labeled masks |
F(x) + x enables networks with dozens or hundreds of layers.UNet from section 4.1, remove the skip connections (pass a tensor of zeros instead of skip). What happens to the class boundaries in the predictions?F.cross_entropy(..., weight=pesos) with larger weights for building and road. Does the IoU of those classes improve?Embeddings and dimensionality reduction (PCA, t-SNE, UMAP) are for class 8 (dl8_embeddings.ipynb).