AI voor Iedereen

Search

Search chapters and demos

👁️ Convolutional networks in Python

A network that has seen more than a million photos recognizes the photos from the demo. Then you teach a network to recognize ten kinds of food from only a hundred doodles per kind: first with a small CNN from scratch, with and without data augmentation, then by reusing the trained network, with its mistakes and a heatmap of where it looks.

Run in Google Colab

Colab requires a Google account, but you can also .

Reading mode. Below is the whole notebook, with the output of the code included. So you can simply read all of it here. To change the code and see what happens, you can go to Google Colab (external link).

In the chapter Convolutional Neural Networks, a network recognized photos with filters it had learned by itself. This notebook puts such networks to work in PyTorch (external link): one that has already seen more than a million photos, and a small one that you train yourself on doodles.

You will:

  1. 📷 let a trained network recognize the photos from the chapter's demo, and look at the filters of its first layer;
  2. 🧱 train a small CNN of your own on doodles from the game Quick, Draw!, with only 100 examples per kind, and 🔄 help it with randomly changed versions of those doodles;
  3. ♻️ reuse the trained network for the same doodles, and see how much that helps;
  4. 🔍 measure the result once on new doodles, look at the mistakes, and 🔥 see where the network looks.

Prior knowledge: the chapter Convolutional Neural Networks. The training function comes from the neural networks notebook. You can run the whole notebook without changing a single line.

Estimated time: about 40 minutes.

This notebook is part of AI voor Iedereen (KU Leuven). The latest version is always at ai.kuleuven.be/aivooriedereen/en/notebook/convolutional-networks, and you can open it directly in Google Colab (external link).

🚀 First time in a notebook?

Then the short introductory notebook explains everything step by step. The most important things:

  1. Make your own copy: File → Save a copy in Drive (in the menu at the top left), and work in that copy.
  2. Run a cell by clicking in it and pressing Shift+Enter, or with the ▶ button to its left. The result appears below the cell.
  3. Run the cells in order, from top to bottom, because a cell uses what the cells above it made. Does something behave strangely? Choose Runtime → Restart session and run everything again from the top.

Prefer not to use Google? Download the notebook file and open it in Jupyter (external link) or Visual Studio Code (external link), with PyTorch (torch and torchvision), scikit-learn and matplotlib installed.

🐍 Python in this notebook

New to Python? The introductory notebook explains the basics: variables, lists, loops and functions. The neural networks notebook explains tensors, nn.Sequential and training. On top of those, this notebook uses:

CodeMeaning
models.resnet18(weights=...)Builds the network ResNet-18 and downloads the weights it learned (about 45 MB).
model.eval()Puts a network in prediction mode: some layers behave differently while training.
Image.open(...), ImageDraw.Draw(image)Opens a photo, or makes an empty image to draw on, with the package Pillow.
nn.Conv2d(1, 16, 3, padding=1)A layer of 16 filters of 3 by 3 pixels that slide over the image. The 1 says how many maps come in: one for a gray drawing.
nn.MaxPool2d(2)Pooling: keeps the largest number of every block of 2 by 2, which halves the width and the height.
nn.Flatten()Lays all the maps out in one long row, for the layers at the end.
transforms.RandomAffine(...), transforms.RandomHorizontalFlip()Change an image at random: turn, shift and resize it a little, or mirror it half of the time. transforms.Compose([...]) does several in a row.
nn.Identity()A layer that does nothing. Put in the place of the last layer, it makes a network end with the numbers that went into that layer.
probabilities.topk(3)The three highest probabilities, with their positions.

📷 A network that already knows a thousand kinds

The demo in the chapter shows AlexNet at work. Here we use ResNet-18, a newer CNN with 18 layers and almost 12 million weights, which makes fewer mistakes. Both learned from ImageNet (external link): more than a million photos of 1,000 kinds of things, from "Persian cat" to "espresso". torchvision downloads the network with the weights it learned, so you don't have to train anything.

The network expects a photo of 224 by 224 pixels, with its colors scaled the way it saw them while learning; weights.transforms() does that. These are six photos from the demo in the chapter.

import io
import json
import urllib.request

import matplotlib.pyplot as plt
import numpy as np
import torch
from torch import nn
from PIL import Image, ImageDraw
from torchvision import models, transforms

weights = models.ResNet18_Weights.IMAGENET1K_V1
resnet = models.resnet18(weights=weights)     # downloads about 45 MB the first time
resnet.eval()
prepare = weights.transforms()                 # 224 by 224 pixels, colors scaled like the photos it learned from
imagenet_kinds = weights.meta["categories"]    # the names of its 1,000 kinds
print(sum(p.numel() for p in resnet.parameters()), "weights")

PHOTO_URL = "https://ai.kuleuven.be/aivooriedereen/demo-data/cnn/images/"
fig, axes = plt.subplots(2, 3, figsize=(10, 8.2))
for ax, name in zip(axes.flat, ["cat", "pizza", "espresso", "sunflower", "library", "kuleuven-logo"]):
    with urllib.request.urlopen(PHOTO_URL + name + ".webp") as response:
        photo = Image.open(io.BytesIO(response.read())).convert("RGB")
    with torch.no_grad():
        probabilities = torch.softmax(resnet(prepare(photo).unsqueeze(0)), dim=1)[0]
    top = probabilities.topk(3)
    ax.imshow(photo)
    ax.set_title("\n".join(f"{imagenet_kinds[i]}: {p:.0%}" for p, i in zip(top.values, top.indices)), fontsize=9)
    ax.axis("off")
plt.tight_layout()
plt.show()
Output
11689512 weights

Above every photo are the three kinds the network finds most likely. The cat and the pizza are easy. The sunflower becomes a daisy: ImageNet has no sunflowers, so the network picks the kind that looks most like one, just like AlexNet in the chapter. The university library of Leuven becomes a palace. And the KU Leuven logo is no photo of anything: the network still has to choose one of its 1,000 kinds, and it hardly knows which.

The first layer of ResNet-18 has 64 filters of 7 by 7 pixels, one for each color. Nobody designed them: the network learned them from the photos, just like AlexNet in the chapter.

filters = resnet.conv1.weight.detach()         # 64 filters, each 3 colors of 7 by 7 pixels
fig, axes = plt.subplots(8, 8, figsize=(6, 6))
for ax, f in zip(axes.flat, filters):
    f = (f - f.min()) / (f.max() - f.min())    # stretch every filter over the full range of colors, to see it
    ax.imshow(f.permute(1, 2, 0))              # the colors last, the way matplotlib wants them
    ax.axis("off")
plt.show()
Output

Edges in every direction, stripes, and spots of color: the building blocks that the next layers combine into corners, round shapes and, deep in the network, eyes and wheels.

✏️ Doodles from Quick, Draw!

In the game Quick, Draw! (external link), players get 20 seconds to draw something, while a neural network guesses what it is. We use 300 drawings of each of ten kinds of food that the game recognized. Every drawing is stored as lines: the positions the pen passed, from 0 to 255. So we can draw them at any size we like, as black lines on a white square, like a photo.

The first 100 drawings of each kind are for learning, the next 100 for checking while learning, and the last 100 for the very end. That is far less than the 50,000 handwritten digits in the neural networks notebook: only 1,000 drawings to learn ten kinds from.

The drawings come from the Quick, Draw! Dataset (external link) by Google (CC BY 4.0).

DATA_URL = "https://ai.kuleuven.be/aivooriedereen/notebooks/data/"
with urllib.request.urlopen(DATA_URL + "quickdraw-food.json") as response:
    doodles = json.load(response)
kinds = doodles["kinds"]                       # the ten kinds of food


def draw(strokes, size):
    # Draws one doodle as black lines on a white square of size by size pixels, centered with a small margin
    xs = [x for stroke in strokes for x in stroke[0]]
    ys = [y for stroke in strokes for y in stroke[1]]
    scale = 0.84 * size / max(max(xs) - min(xs), max(ys) - min(ys), 1)
    shift_x = (size - (max(xs) - min(xs)) * scale) / 2 - min(xs) * scale
    shift_y = (size - (max(ys) - min(ys)) * scale) / 2 - min(ys) * scale
    image = Image.new("L", (size, size), 255)
    pen = ImageDraw.Draw(image)
    for stroke_xs, stroke_ys in strokes:
        points = [(x * scale + shift_x, y * scale + shift_y) for x, y in zip(stroke_xs, stroke_ys)]
        pen.line(points * 2 if len(points) == 1 else points, fill=0, width=max(1, round(size / 40)), joint="curve")
    return image


def split(part):
    # The doodles of one part (learn, check or end) of every kind, with their kind as a number from 0 to 9
    first = {"learn": 0, "check": 100, "end": 200}[part]
    strokes = [s for kind in kinds for s in doodles["drawings"][kind][first:first + 100]]
    labels = torch.tensor([k for k in range(len(kinds)) for _ in range(100)])
    return strokes, labels


def to_tensor(strokes, size):
    # Doodles as a tensor, one per row: the ink of every pixel, from 0 (paper) to 1 (line)
    images = np.stack([np.asarray(draw(s, size)) for s in strokes])
    return 1 - torch.tensor(images, dtype=torch.float32).unsqueeze(1) / 255


learn_strokes, y_learn = split("learn")
check_strokes, y_check = split("check")

fig, axes = plt.subplots(len(kinds), 8, figsize=(8, 10.5))
for row, kind in zip(axes, kinds):
    for ax, strokes in zip(row, doodles["drawings"][kind]):
        ax.imshow(draw(strokes, 112), cmap="gray")
        ax.set_xticks([])
        ax.set_yticks([])
    row[0].set_ylabel(kind, rotation=0, ha="right", va="center")
plt.show()
Output

🧱 A small CNN of your own

First a CNN of our own, built like the architecture in the chapter: three times a convolutional layer with pooling, then two ordinary layers that turn the maps into a score for every kind. From scratch, it doesn't need the size of a photo: we draw the doodles at 64 by 64 pixels, which keeps training fast.

A CNN learns its filters the same way as any neural network, so train and plot_curves are the functions from the neural networks notebook: minibatches, the two learning curves, and a copy of the weights from the epoch with the lowest validation loss. Only the option augment is new; it comes back further on.

import copy
import time
from torch.utils.data import DataLoader, TensorDataset


def train(model, X, y, X_val, y_val, epochs, learning_rate=0.001, augment=None):
    # Trains on X and y in minibatches and measures both losses after every epoch;
    # at the end, the model gets the weights of the epoch with the lowest validation loss
    batches = DataLoader(TensorDataset(X, y), batch_size=128, shuffle=True)
    optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
    loss_function = nn.CrossEntropyLoss()        # softmax and cross-entropy in one
    history = {"training": [], "validation": [], "accuracy": [], "seconds": []}
    best_loss = float("inf")
    for epoch in range(epochs):
        start = time.perf_counter()
        for X_batch, y_batch in batches:
            if augment is not None:              # a new random version of every image, at every epoch
                X_batch = torch.stack([augment(x) for x in X_batch])
            loss = loss_function(model(X_batch), y_batch)
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
        history["seconds"].append(time.perf_counter() - start)
        with torch.no_grad():
            history["training"].append(loss_function(model(X), y).item())
            val_scores = model(X_val)
            history["validation"].append(loss_function(val_scores, y_val).item())
            history["accuracy"].append((val_scores.argmax(dim=1) == y_val).float().mean().item())
        # the best epoch so far: keep a copy of its weights
        if history["validation"][-1] < best_loss:
            best_loss = history["validation"][-1]
            best_weights = copy.deepcopy(model.state_dict())
            history["best_epoch"] = epoch + 1
    model.load_state_dict(best_weights)
    return history


def plot_curves(history):
    # The two learning curves, with a dashed line at the epoch whose weights train kept
    epochs = range(1, len(history["training"]) + 1)
    plt.plot(epochs, history["training"], label="training doodles")
    plt.plot(epochs, history["validation"], label="validation doodles")
    plt.axvline(history["best_epoch"], color="grey", linestyle="--", label="lowest validation loss")
    plt.xlabel("epoch")
    plt.ylabel("loss (cross-entropy)")
    plt.legend()
    plt.show()
X_learn, X_check = to_tensor(learn_strokes, 64), to_tensor(check_strokes, 64)


def new_small_cnn():
    # A fresh, untrained small CNN for drawings of 64 by 64 pixels
    return nn.Sequential(
        nn.Conv2d(1, 16, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),     # 16 filters, then 32 by 32 pixels
        nn.Conv2d(16, 32, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),    # 32 filters, then 16 by 16
        nn.Conv2d(32, 64, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),    # 64 filters, then 8 by 8
        nn.Flatten(),                                                   # 64 maps of 8 by 8: 4,096 numbers
        nn.Linear(64 * 8 * 8, 64), nn.ReLU(),
        nn.Linear(64, 10),                                              # a score for every kind
    )


torch.manual_seed(0)
small_cnn = new_small_cnn()
history = train(small_cnn, X_learn, y_learn, X_check, y_check, epochs=30)
best = history["best_epoch"]
print(f"{sum(p.numel() for p in small_cnn.parameters())} weights; after epoch {best}, "
      f"{history['accuracy'][best - 1]:.0%} of the validation doodles right")
plot_curves(history)
Output
286154 weights; after epoch 21, 83% of the validation doodles right

With only 100 drawings per kind, the small CNN gets about 83% of the validation doodles right. The learning curves show the limit: after about twenty epochs, the training loss keeps going down while the validation loss goes up again. The network starts to learn its 1,000 drawings by heart, and train keeps the weights of the best epoch.

🔄 Augmenting the training doodles

A pizza that is mirrored, turned a little, shifted or drawn a bit bigger is still a pizza. Data augmentation makes use of that: augment changes a drawing at random, and train with augment gives the network a new version of every training doodle at every epoch. Those are much harder to learn by heart than the same 1,000 drawings every time. The validation doodles stay as they are: they have to show how the network does on real drawings. First eight random versions of the same pizza, then the same small CNN, trained again from scratch with augment.

augment = transforms.Compose([
    transforms.RandomHorizontalFlip(),                                               # mirror half of the time
    transforms.RandomAffine(degrees=15, translate=(0.1, 0.1), scale=(0.85, 1.15)),   # turn, shift and resize a little
])

pizza = to_tensor([doodles["drawings"]["pizza"][0]], 64)[0]     # one doodle, the way the small CNN sees it
fig, axes = plt.subplots(1, 8, figsize=(12, 1.8))
for ax in axes:
    ax.imshow(1 - augment(pizza)[0], cmap="gray")               # a new random version every time, black on white
    ax.axis("off")
plt.show()

torch.manual_seed(0)
augmented_cnn = new_small_cnn()                                 # the same network, trained again from scratch
history = train(augmented_cnn, X_learn, y_learn, X_check, y_check, epochs=30, augment=augment)
best = history["best_epoch"]
print(f"with augmentation: after epoch {best}, {history['accuracy'][best - 1]:.0%} of the validation doodles right")
plot_curves(history)
Output
with augmentation: after epoch 30, 87% of the validation doodles right

With augmentation, the same small CNN gets about 87% of the validation doodles right, against about 83% without. The learning curves show why: the validation loss now keeps going down until the last epoch, and the training loss stays close to it, so the network no longer learns its drawings by heart. The network could even learn for longer: with 60 epochs instead of 30, it got about 91% in our tests, in twice the time. Only choose changes that keep the kind the same: mirroring is fine for food, but it turns the letter b into a d.

♻️ Reusing a trained network

ResNet-18 has learned from more than a million photos which edges, corners and round shapes are worth looking for. Those layers are useful for doodles too, so we reuse them and only replace the last layer: instead of a score for each of the 1,000 kinds of ImageNet, a new layer gives a score for each of our ten kinds of food. The diagram shows what that means for ResNet-18; you don't need to read how draw_reuse works.

from matplotlib.patches import FancyBboxPatch, Rectangle


def draw_reuse(network, example):
    # A diagram of ResNet-18: the reused layers (frozen, blue) and the new last layer (orange) that replaces the old one
    stages = [("conv1", 64, 112), ("layer1", 64, 56), ("layer2", 128, 28), ("layer3", 256, 14), ("layer4", 512, 7)]
    frozen = sum(p.numel() for name, p in network.named_parameters() if not name.startswith("fc."))
    fig, ax = plt.subplots(figsize=(12, 4.4))
    ax.axis("off")
    ax.imshow(np.asarray(example), cmap="gray", extent=(-0.9, 0.3, -0.6, 0.6), zorder=2)
    ax.text(-0.3, -0.8, "a doodle\n224 × 224", ha="center", va="top", fontsize=9)
    x = 1.0
    for name, maps, size in stages:     # every block: its height shows the size of its maps, its width how many maps
        height, width = 0.4 + 2.0 * (size / 112) ** 0.5, 0.25 + 0.55 * maps / 512
        ax.add_patch(Rectangle((x, -height / 2), width, height, facecolor="#3b82f6", edgecolor="#1e3a8a", zorder=2))
        ax.text(x + width / 2, -1.35, f"{name}\n{maps} maps\n{size} × {size}", ha="center", va="top", fontsize=8.5)
        ax.annotate("", xy=(x, 0), xytext=(x - 0.55, 0), arrowprops=dict(arrowstyle="->", color="grey"), zorder=1)
        x += width + 0.9
    ax.add_patch(Rectangle((x, -0.9), 0.18, 1.8, facecolor="#93c5fd", edgecolor="#1e3a8a", zorder=2))
    ax.text(x + 0.09, -1.35, "average\n512\nnumbers", ha="center", va="top", fontsize=8.5)
    ax.annotate("", xy=(x, 0), xytext=(x - 0.55, 0), arrowprops=dict(arrowstyle="->", color="grey"), zorder=1)
    ax.add_patch(FancyBboxPatch((0.7, -2.45), x - 0.2, 4.3, boxstyle="round,pad=0.05", color="#dbeafe", zorder=0))
    ax.text(x / 2 + 0.6, 2.05, f"reused from ImageNet and frozen: {frozen:,} weights stay as they are",
            ha="center", fontsize=11, color="#1e3a8a")
    x += 1.1
    ax.add_patch(Rectangle((x, 0.7), 1.9, 1.1, facecolor="white", edgecolor="grey", linestyle="--", zorder=2))
    ax.text(x + 0.95, 1.25, "old last layer\n512 → 1,000 kinds\n(removed)", ha="center", va="center", fontsize=8.5, color="grey")
    ax.add_patch(Rectangle((x, -0.55), 1.9, 1.0, facecolor="#f97316", edgecolor="#9a3412", zorder=2))
    ax.text(x + 0.95, -0.05, "new last layer\n512 → 10 kinds", ha="center", va="center", fontsize=9, color="white", weight="bold")
    ax.text(x + 0.95, -0.75, f"learns: {512 * 10 + 10:,} weights", ha="center", va="top", fontsize=9, color="#9a3412")
    ax.annotate("", xy=(x, -0.05), xytext=(x - 0.75, 0), arrowprops=dict(arrowstyle="->", color="grey"), zorder=1)
    for k, kind in enumerate(kinds):
        y = 1.6 - k * 0.36
        ax.text(x + 2.35, y, kind, fontsize=8.5, va="center")
        ax.plot([x + 1.9, x + 2.28], [-0.05, y], color="#fdba74", lw=0.7, zorder=1)
    ax.set_xlim(-1.0, x + 3.4)
    ax.set_ylim(-2.6, 2.4)
    plt.show()


draw_reuse(resnet, draw(doodles["drawings"]["pizza"][0], 112))
Output

The blue layers are reused as they are: they stay frozen, so their weights don't change. The old last layer, with a score for each of the 1,000 kinds of ImageNet, is removed. In its place comes the orange layer, the only one that learns: a weight for each of the 512 numbers and a bias, for each of the ten kinds.

Because the frozen layers don't change, every doodle only has to go through them once. features draws the doodles at the size of the photos (224 by 224 pixels, black on white) and keeps the 512 numbers that ResNet-18 ends with, just before its last layer. The new last layer then learns from those numbers, with the same train as before. Running the doodles through ResNet-18 takes a minute or two on the free processor of Colab.

backbone = models.resnet18(weights=weights)
backbone.fc = nn.Identity()                    # leave out the last layer: the network now ends with 512 numbers
backbone.eval()
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])   # like weights.transforms()


def features(strokes):
    # Runs doodles through the reused layers of ResNet-18, 100 at a time, and keeps the 512 numbers of every doodle
    result = []
    with torch.no_grad():
        for start in range(0, len(strokes), 100):
            ink = to_tensor(strokes[start:start + 100], 224)
            photos = (1 - ink).repeat(1, 3, 1, 1)                 # black lines on white, in 3 colors
            result.append(backbone(normalize(photos)))
    return torch.cat(result)


start = time.perf_counter()
F_learn, F_check = features(learn_strokes), features(check_strokes)
print(f"{len(F_learn) + len(F_check)} doodles through ResNet-18 in {time.perf_counter() - start:.0f} seconds, "
      f"{F_learn.shape[1]} numbers each")

torch.manual_seed(0)
new_layer = nn.Linear(512, 10)                 # the only layer that learns: 512 weights and a bias per kind
history = train(new_layer, F_learn, y_learn, F_check, y_check, epochs=40, learning_rate=0.01)
best = history["best_epoch"]
print(f"after epoch {best}, {history['accuracy'][best - 1]:.0%} of the validation doodles right")
plot_curves(history)
Output
2000 doodles through ResNet-18 in 87 seconds, 512 numbers each
after epoch 30, 93% of the validation doodles right

With the same 100 drawings per kind, reusing ResNet-18 gets about 93% right, against about 83% for the small CNN, or 87% with augmentation. And only 5,130 weights had to learn anything: the rest came from the photos. This is how Teachable Machine from the chapter learns from a few pictures of your webcam in seconds.

🔍 Looking at the mistakes

Now the last 100 drawings of every kind, which neither network has seen, measured once. The confusion matrix counts, for every real kind (the rows), how often the network chose each kind (the columns): the diagonal is right, everything else is a mistake. Below it are the mistakes the network was most sure about.

from sklearn.metrics import ConfusionMatrixDisplay

end_strokes, y_end = split("end")
with torch.no_grad():
    probabilities = torch.softmax(new_layer(features(end_strokes)), dim=1)
confidence, guess = probabilities.max(dim=1)
print(f"test accuracy: {(guess == y_end).float().mean():.0%} of {len(y_end)} doodles")

ConfusionMatrixDisplay.from_predictions(y_end, guess, display_labels=kinds, xticks_rotation=45, colorbar=False)
plt.show()

wrong = (guess != y_end).nonzero().squeeze(1)
most_sure = wrong[confidence[wrong].argsort(descending=True)][:8]
fig, axes = plt.subplots(1, 8, figsize=(12, 2.2))
for ax, i in zip(axes, most_sure):
    ax.imshow(draw(end_strokes[i], 112), cmap="gray")
    ax.set_title(f"{kinds[y_end[i]]} →\n{kinds[guess[i]]} {confidence[i]:.0%}", fontsize=9)
    ax.axis("off")
plt.show()
Output
test accuracy: 93% of 1000 doodles

On these new doodles, the network also gets 93% right. The mistakes are mostly the ones a person could make too: kinds with the same outline, such as round cookies and donuts, apples and pears, or a slice of pizza and a carrot. Some drawings in the row above are hard to recognize for anyone.

🔥 Where does it look?

Which lines made the network choose its kind? Grad-CAM, the heat map from the chapter, answers that. It takes the maps of the last convolutional layer, and weighs each map by how much it pushes up the score of the chosen kind. Where the result is warm (red), the drawing counted most. You don't need to read how grad_cam works.

import torch.nn.functional as F


def grad_cam(strokes):
    # The kind the network chooses for one doodle, and a heat map of where that choice came from
    photo = normalize((1 - to_tensor([strokes], 224)).repeat(1, 3, 1, 1))
    maps = {}
    hook = backbone.layer4.register_forward_hook(lambda module, inputs, output: maps.update(last=output))
    scores = new_layer(backbone(photo))
    hook.remove()
    kind = scores.argmax().item()
    gradients = torch.autograd.grad(scores[0, kind], maps["last"])[0]      # how much each spot pushes that score
    heat = torch.relu((gradients.mean(dim=(2, 3), keepdim=True) * maps["last"]).sum(dim=1, keepdim=True))
    heat = F.interpolate(heat, size=224, mode="bilinear")[0, 0]
    return kind, (heat / heat.max()).detach()


fig, axes = plt.subplots(2, 5, figsize=(12, 5.4))
for ax, kind in zip(axes.flat, range(len(kinds))):
    strokes = end_strokes[kind * 100]                                   # the first test doodle of every kind
    chosen, heat = grad_cam(strokes)
    ax.imshow(draw(strokes, 224), cmap="gray")
    ax.imshow(heat, cmap="jet", alpha=0.45)
    ax.set_title(f"{kinds[kind]} → {kinds[chosen]}", fontsize=10)
    ax.axis("off")
plt.tight_layout()
plt.show()
Output

The heat maps are coarse: the last convolutional layer of ResNet-18 only has 7 by 7 spots for a whole image. Still, they show which part of a drawing decided the choice, such as the chips of a cookie or the hole of a donut. And not every drawing deserves a right answer: the first test apple is a single line, which the network calls a banana. Grad-CAM is how you check whether a network looks at the right thing, and not at something that happens to come with it, like the light in the photos of the chapter.

🧰 Image recognition for your own problem

The recipe for your own photos:

  1. Put your photos in a folder per kind, and load them with datasets.ImageFolder("my_photos", transform=weights.transforms()) from torchvision. Keep some photos of every kind apart for checking, and some for the very end.
  2. Run them once through a trained network without its last layer, like features does, and train a new last layer with train on those numbers. ResNet-18 is a good start; torchvision has many more (external link), such as MobileNet, which is smaller and fast enough for a phone.
  3. Measure once on the photos you kept for the end, with a confusion matrix and the most confident mistakes, and look with grad_cam at where the network looks.

With a few hundred photos per kind, you can also let the last layers of the network itself learn a little (fine-tuning); the chapter explains when that pays off. The images then go through the whole network at every epoch, so freeze the layers that should stay as they are: for weight in backbone.parameters(): weight.requires_grad = False before you unfreeze the ones that may learn. Make your photos a little more varied while learning, by turning, cropping and mirroring them at random (transforms.RandomResizedCrop, transforms.RandomHorizontalFlip), like augment did for the doodles: that helps most when the network itself learns. The small CNN gained four points from it, but for the new last layer on top of the frozen layers of ResNet-18, three extra turned, shifted and mirrored copies of every doodle raised the accuracy by less than half a percent.


By Thomas Winters (external link) for AI voor Iedereen, KU Leuven. The latest version of this notebook: ai.kuleuven.be/aivooriedereen/en/notebook/convolutional-networks.