{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "3c788ca0",
   "metadata": {},
   "source": [
    "# 👁️ Convolutional networks in Python\n",
    "\n",
    "In the chapter [Convolutional Neural Networks](https://ai.kuleuven.be/aivooriedereen/en/convolutional-neural-networks), a network recognized photos with filters it had learned by itself. This notebook puts such networks to work in [PyTorch](https://pytorch.org): one that has already seen more than a million photos, and a small one that you train yourself on doodles.\n",
    "\n",
    "You will:\n",
    "\n",
    "1. 📷 let a trained network recognize the photos from the chapter's demo, and look at the filters of its first layer;\n",
    "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;\n",
    "3. ♻️ reuse the trained network for the same doodles, and see how much that helps;\n",
    "4. 🔍 measure the result once on new doodles, look at the mistakes, and 🔥 see where the network looks.\n",
    "\n",
    "**Prior knowledge**: the chapter [Convolutional Neural Networks](https://ai.kuleuven.be/aivooriedereen/en/convolutional-neural-networks). The training function comes from the [neural networks notebook](https://ai.kuleuven.be/aivooriedereen/en/notebook/neural-networks). You can run the whole notebook without changing a single line.\n",
    "\n",
    "**Estimated time**: about 40 minutes.\n",
    "\n",
    "*This notebook is part of [AI voor Iedereen](https://ai.kuleuven.be/aivooriedereen/en) (KU Leuven). The latest version is always at [ai.kuleuven.be/aivooriedereen/en/notebook/convolutional-networks](https://ai.kuleuven.be/aivooriedereen/en/notebook/convolutional-networks), and you can open it directly in [Google Colab](https://colab.research.google.com/drive/1B84W9TpqWPKdVQ2h3TreeoNCAtmFNa-F?usp=sharing).*"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a37f4d0a",
   "metadata": {},
   "source": [
    "## 🚀 First time in a notebook?\n",
    "\n",
    "Then the short [introductory notebook](https://ai.kuleuven.be/aivooriedereen/en/notebook/python-basics) explains everything step by step. The most important things:\n",
    "\n",
    "1. **Make your own copy**: *File → Save a copy in Drive* (in the menu at the top left), and work in that copy.\n",
    "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.\n",
    "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.\n",
    "\n",
    "**Prefer not to use Google?** Download [the notebook file](https://ai.kuleuven.be/aivooriedereen/notebooks/convolutional-networks.ipynb) and open it in [Jupyter](https://jupyter.org/install) or [Visual Studio Code](https://code.visualstudio.com/docs/datascience/jupyter-notebooks), with PyTorch (`torch` and `torchvision`), scikit-learn and matplotlib installed."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bbffbf6a",
   "metadata": {},
   "source": [
    "## 🐍 Python in this notebook\n",
    "\n",
    "New to Python? The [introductory notebook](https://ai.kuleuven.be/aivooriedereen/en/notebook/python-basics) explains the basics: variables, lists, loops and functions. The [neural networks notebook](https://ai.kuleuven.be/aivooriedereen/en/notebook/neural-networks) explains tensors, `nn.Sequential` and training. On top of those, this notebook uses:\n",
    "\n",
    "| Code | Meaning |\n",
    "| --- | --- |\n",
    "| `models.resnet18(weights=...)` | Builds the network ResNet-18 and downloads the weights it learned (about 45 MB). |\n",
    "| `model.eval()` | Puts a network in prediction mode: some layers behave differently while training. |\n",
    "| `Image.open(...)`, `ImageDraw.Draw(image)` | Opens a photo, or makes an empty image to draw on, with the package Pillow. |\n",
    "| `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. |\n",
    "| `nn.MaxPool2d(2)` | Pooling: keeps the largest number of every block of 2 by 2, which halves the width and the height. |\n",
    "| `nn.Flatten()` | Lays all the maps out in one long row, for the layers at the end. |\n",
    "| `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. |\n",
    "| `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. |\n",
    "| `probabilities.topk(3)` | The three highest probabilities, with their positions. |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6d08df33",
   "metadata": {},
   "source": [
    "## 📷 A network that already knows a thousand kinds\n",
    "\n",
    "The [demo in the chapter](https://ai.kuleuven.be/aivooriedereen/en/convolutional-neural-networks#see-for-yourself) 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](https://en.wikipedia.org/wiki/ImageNet): 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.\n",
    "\n",
    "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."
   ]
  },
  {
   "cell_type": "code",
   "id": "1643531e",
   "metadata": {},
   "source": [
    "import io\n",
    "import json\n",
    "import urllib.request\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import torch\n",
    "from torch import nn\n",
    "from PIL import Image, ImageDraw\n",
    "from torchvision import models, transforms\n",
    "\n",
    "weights = models.ResNet18_Weights.IMAGENET1K_V1\n",
    "resnet = models.resnet18(weights=weights)     # downloads about 45 MB the first time\n",
    "resnet.eval()\n",
    "prepare = weights.transforms()                 # 224 by 224 pixels, colors scaled like the photos it learned from\n",
    "imagenet_kinds = weights.meta[\"categories\"]    # the names of its 1,000 kinds\n",
    "print(sum(p.numel() for p in resnet.parameters()), \"weights\")\n",
    "\n",
    "PHOTO_URL = \"https://ai.kuleuven.be/aivooriedereen/demo-data/cnn/images/\"\n",
    "fig, axes = plt.subplots(2, 3, figsize=(10, 8.2))\n",
    "for ax, name in zip(axes.flat, [\"cat\", \"pizza\", \"espresso\", \"sunflower\", \"library\", \"kuleuven-logo\"]):\n",
    "    with urllib.request.urlopen(PHOTO_URL + name + \".webp\") as response:\n",
    "        photo = Image.open(io.BytesIO(response.read())).convert(\"RGB\")\n",
    "    with torch.no_grad():\n",
    "        probabilities = torch.softmax(resnet(prepare(photo).unsqueeze(0)), dim=1)[0]\n",
    "    top = probabilities.topk(3)\n",
    "    ax.imshow(photo)\n",
    "    ax.set_title(\"\\n\".join(f\"{imagenet_kinds[i]}: {p:.0%}\" for p, i in zip(top.values, top.indices)), fontsize=9)\n",
    "    ax.axis(\"off\")\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "3621e9c0",
   "metadata": {},
   "source": [
    "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](https://ai.kuleuven.be/aivooriedereen/en/convolutional-neural-networks#surprising-insights). 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.\n",
    "\n",
    "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](https://ai.kuleuven.be/aivooriedereen/en/convolutional-neural-networks#who-designs-the-filters), just like AlexNet in the chapter."
   ]
  },
  {
   "cell_type": "code",
   "id": "bbd715a0",
   "metadata": {},
   "source": [
    "filters = resnet.conv1.weight.detach()         # 64 filters, each 3 colors of 7 by 7 pixels\n",
    "fig, axes = plt.subplots(8, 8, figsize=(6, 6))\n",
    "for ax, f in zip(axes.flat, filters):\n",
    "    f = (f - f.min()) / (f.max() - f.min())    # stretch every filter over the full range of colors, to see it\n",
    "    ax.imshow(f.permute(1, 2, 0))              # the colors last, the way matplotlib wants them\n",
    "    ax.axis(\"off\")\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "838a9f89",
   "metadata": {},
   "source": [
    "Edges in every direction, stripes, and spots of color: the building blocks that the [next layers combine](https://ai.kuleuven.be/aivooriedereen/en/convolutional-neural-networks#layer-upon-layer-from-edges-to-objects) into corners, round shapes and, deep in the network, eyes and wheels."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "633a38f8",
   "metadata": {},
   "source": [
    "## ✏️ Doodles from Quick, Draw!\n",
    "\n",
    "In the game [Quick, Draw!](https://quickdraw.withgoogle.com), 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.\n",
    "\n",
    "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](https://ai.kuleuven.be/aivooriedereen/en/notebook/neural-networks): only 1,000 drawings to learn ten kinds from.\n",
    "\n",
    "*The drawings come from the [Quick, Draw! Dataset](https://github.com/googlecreativelab/quickdraw-dataset) by Google (CC BY 4.0).*"
   ]
  },
  {
   "cell_type": "code",
   "id": "01065ec6",
   "metadata": {},
   "source": [
    "DATA_URL = \"https://ai.kuleuven.be/aivooriedereen/notebooks/data/\"\n",
    "with urllib.request.urlopen(DATA_URL + \"quickdraw-food.json\") as response:\n",
    "    doodles = json.load(response)\n",
    "kinds = doodles[\"kinds\"]                       # the ten kinds of food\n",
    "\n",
    "\n",
    "def draw(strokes, size):\n",
    "    # Draws one doodle as black lines on a white square of size by size pixels, centered with a small margin\n",
    "    xs = [x for stroke in strokes for x in stroke[0]]\n",
    "    ys = [y for stroke in strokes for y in stroke[1]]\n",
    "    scale = 0.84 * size / max(max(xs) - min(xs), max(ys) - min(ys), 1)\n",
    "    shift_x = (size - (max(xs) - min(xs)) * scale) / 2 - min(xs) * scale\n",
    "    shift_y = (size - (max(ys) - min(ys)) * scale) / 2 - min(ys) * scale\n",
    "    image = Image.new(\"L\", (size, size), 255)\n",
    "    pen = ImageDraw.Draw(image)\n",
    "    for stroke_xs, stroke_ys in strokes:\n",
    "        points = [(x * scale + shift_x, y * scale + shift_y) for x, y in zip(stroke_xs, stroke_ys)]\n",
    "        pen.line(points * 2 if len(points) == 1 else points, fill=0, width=max(1, round(size / 40)), joint=\"curve\")\n",
    "    return image\n",
    "\n",
    "\n",
    "def split(part):\n",
    "    # The doodles of one part (learn, check or end) of every kind, with their kind as a number from 0 to 9\n",
    "    first = {\"learn\": 0, \"check\": 100, \"end\": 200}[part]\n",
    "    strokes = [s for kind in kinds for s in doodles[\"drawings\"][kind][first:first + 100]]\n",
    "    labels = torch.tensor([k for k in range(len(kinds)) for _ in range(100)])\n",
    "    return strokes, labels\n",
    "\n",
    "\n",
    "def to_tensor(strokes, size):\n",
    "    # Doodles as a tensor, one per row: the ink of every pixel, from 0 (paper) to 1 (line)\n",
    "    images = np.stack([np.asarray(draw(s, size)) for s in strokes])\n",
    "    return 1 - torch.tensor(images, dtype=torch.float32).unsqueeze(1) / 255\n",
    "\n",
    "\n",
    "learn_strokes, y_learn = split(\"learn\")\n",
    "check_strokes, y_check = split(\"check\")\n",
    "\n",
    "fig, axes = plt.subplots(len(kinds), 8, figsize=(8, 10.5))\n",
    "for row, kind in zip(axes, kinds):\n",
    "    for ax, strokes in zip(row, doodles[\"drawings\"][kind]):\n",
    "        ax.imshow(draw(strokes, 112), cmap=\"gray\")\n",
    "        ax.set_xticks([])\n",
    "        ax.set_yticks([])\n",
    "    row[0].set_ylabel(kind, rotation=0, ha=\"right\", va=\"center\")\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "9376632a",
   "metadata": {},
   "source": [
    "### 🧱 A small CNN of your own\n",
    "\n",
    "First a CNN of our own, built like the [architecture in the chapter](https://ai.kuleuven.be/aivooriedereen/en/convolutional-neural-networks#the-complete-architecture): three times a convolutional layer with [pooling](https://ai.kuleuven.be/aivooriedereen/en/convolutional-neural-networks#summarizing-with-pooling), then two ordinary layers that [turn the maps into a score](https://ai.kuleuven.be/aivooriedereen/en/convolutional-neural-networks#from-feature-maps-to-one-answer) 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.\n",
    "\n",
    "A CNN [learns its filters](https://ai.kuleuven.be/aivooriedereen/en/convolutional-neural-networks#how-does-a-cnn-learn) 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."
   ]
  },
  {
   "cell_type": "code",
   "id": "439e1cdd",
   "metadata": {},
   "source": [
    "import copy\n",
    "import time\n",
    "from torch.utils.data import DataLoader, TensorDataset\n",
    "\n",
    "\n",
    "def train(model, X, y, X_val, y_val, epochs, learning_rate=0.001, augment=None):\n",
    "    # Trains on X and y in minibatches and measures both losses after every epoch;\n",
    "    # at the end, the model gets the weights of the epoch with the lowest validation loss\n",
    "    batches = DataLoader(TensorDataset(X, y), batch_size=128, shuffle=True)\n",
    "    optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n",
    "    loss_function = nn.CrossEntropyLoss()        # softmax and cross-entropy in one\n",
    "    history = {\"training\": [], \"validation\": [], \"accuracy\": [], \"seconds\": []}\n",
    "    best_loss = float(\"inf\")\n",
    "    for epoch in range(epochs):\n",
    "        start = time.perf_counter()\n",
    "        for X_batch, y_batch in batches:\n",
    "            if augment is not None:              # a new random version of every image, at every epoch\n",
    "                X_batch = torch.stack([augment(x) for x in X_batch])\n",
    "            loss = loss_function(model(X_batch), y_batch)\n",
    "            optimizer.zero_grad()\n",
    "            loss.backward()\n",
    "            optimizer.step()\n",
    "        history[\"seconds\"].append(time.perf_counter() - start)\n",
    "        with torch.no_grad():\n",
    "            history[\"training\"].append(loss_function(model(X), y).item())\n",
    "            val_scores = model(X_val)\n",
    "            history[\"validation\"].append(loss_function(val_scores, y_val).item())\n",
    "            history[\"accuracy\"].append((val_scores.argmax(dim=1) == y_val).float().mean().item())\n",
    "        # the best epoch so far: keep a copy of its weights\n",
    "        if history[\"validation\"][-1] < best_loss:\n",
    "            best_loss = history[\"validation\"][-1]\n",
    "            best_weights = copy.deepcopy(model.state_dict())\n",
    "            history[\"best_epoch\"] = epoch + 1\n",
    "    model.load_state_dict(best_weights)\n",
    "    return history\n",
    "\n",
    "\n",
    "def plot_curves(history):\n",
    "    # The two learning curves, with a dashed line at the epoch whose weights train kept\n",
    "    epochs = range(1, len(history[\"training\"]) + 1)\n",
    "    plt.plot(epochs, history[\"training\"], label=\"training doodles\")\n",
    "    plt.plot(epochs, history[\"validation\"], label=\"validation doodles\")\n",
    "    plt.axvline(history[\"best_epoch\"], color=\"grey\", linestyle=\"--\", label=\"lowest validation loss\")\n",
    "    plt.xlabel(\"epoch\")\n",
    "    plt.ylabel(\"loss (cross-entropy)\")\n",
    "    plt.legend()\n",
    "    plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "2cda905f",
   "metadata": {},
   "source": [
    "X_learn, X_check = to_tensor(learn_strokes, 64), to_tensor(check_strokes, 64)\n",
    "\n",
    "\n",
    "def new_small_cnn():\n",
    "    # A fresh, untrained small CNN for drawings of 64 by 64 pixels\n",
    "    return nn.Sequential(\n",
    "        nn.Conv2d(1, 16, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),     # 16 filters, then 32 by 32 pixels\n",
    "        nn.Conv2d(16, 32, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),    # 32 filters, then 16 by 16\n",
    "        nn.Conv2d(32, 64, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),    # 64 filters, then 8 by 8\n",
    "        nn.Flatten(),                                                   # 64 maps of 8 by 8: 4,096 numbers\n",
    "        nn.Linear(64 * 8 * 8, 64), nn.ReLU(),\n",
    "        nn.Linear(64, 10),                                              # a score for every kind\n",
    "    )\n",
    "\n",
    "\n",
    "torch.manual_seed(0)\n",
    "small_cnn = new_small_cnn()\n",
    "history = train(small_cnn, X_learn, y_learn, X_check, y_check, epochs=30)\n",
    "best = history[\"best_epoch\"]\n",
    "print(f\"{sum(p.numel() for p in small_cnn.parameters())} weights; after epoch {best}, \"\n",
    "      f\"{history['accuracy'][best - 1]:.0%} of the validation doodles right\")\n",
    "plot_curves(history)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "c0c84010",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 🔄 Augmenting the training doodles\n",
    "\n",
    "A pizza that is mirrored, turned a little, shifted or drawn a bit bigger is still a pizza. [Data augmentation](https://ai.kuleuven.be/aivooriedereen/en/convolutional-neural-networks#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`."
   ]
  },
  {
   "cell_type": "code",
   "id": "1aaeb530",
   "metadata": {},
   "source": [
    "augment = transforms.Compose([\n",
    "    transforms.RandomHorizontalFlip(),                                               # mirror half of the time\n",
    "    transforms.RandomAffine(degrees=15, translate=(0.1, 0.1), scale=(0.85, 1.15)),   # turn, shift and resize a little\n",
    "])\n",
    "\n",
    "pizza = to_tensor([doodles[\"drawings\"][\"pizza\"][0]], 64)[0]     # one doodle, the way the small CNN sees it\n",
    "fig, axes = plt.subplots(1, 8, figsize=(12, 1.8))\n",
    "for ax in axes:\n",
    "    ax.imshow(1 - augment(pizza)[0], cmap=\"gray\")               # a new random version every time, black on white\n",
    "    ax.axis(\"off\")\n",
    "plt.show()\n",
    "\n",
    "torch.manual_seed(0)\n",
    "augmented_cnn = new_small_cnn()                                 # the same network, trained again from scratch\n",
    "history = train(augmented_cnn, X_learn, y_learn, X_check, y_check, epochs=30, augment=augment)\n",
    "best = history[\"best_epoch\"]\n",
    "print(f\"with augmentation: after epoch {best}, {history['accuracy'][best - 1]:.0%} of the validation doodles right\")\n",
    "plot_curves(history)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "47ecff04",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### ♻️ Reusing a trained network\n",
    "\n",
    "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](https://ai.kuleuven.be/aivooriedereen/en/convolutional-neural-networks#reusing-trained-layers) 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."
   ]
  },
  {
   "cell_type": "code",
   "id": "68fc19b6",
   "metadata": {},
   "source": [
    "from matplotlib.patches import FancyBboxPatch, Rectangle\n",
    "\n",
    "\n",
    "def draw_reuse(network, example):\n",
    "    # A diagram of ResNet-18: the reused layers (frozen, blue) and the new last layer (orange) that replaces the old one\n",
    "    stages = [(\"conv1\", 64, 112), (\"layer1\", 64, 56), (\"layer2\", 128, 28), (\"layer3\", 256, 14), (\"layer4\", 512, 7)]\n",
    "    frozen = sum(p.numel() for name, p in network.named_parameters() if not name.startswith(\"fc.\"))\n",
    "    fig, ax = plt.subplots(figsize=(12, 4.4))\n",
    "    ax.axis(\"off\")\n",
    "    ax.imshow(np.asarray(example), cmap=\"gray\", extent=(-0.9, 0.3, -0.6, 0.6), zorder=2)\n",
    "    ax.text(-0.3, -0.8, \"a doodle\\n224 × 224\", ha=\"center\", va=\"top\", fontsize=9)\n",
    "    x = 1.0\n",
    "    for name, maps, size in stages:     # every block: its height shows the size of its maps, its width how many maps\n",
    "        height, width = 0.4 + 2.0 * (size / 112) ** 0.5, 0.25 + 0.55 * maps / 512\n",
    "        ax.add_patch(Rectangle((x, -height / 2), width, height, facecolor=\"#3b82f6\", edgecolor=\"#1e3a8a\", zorder=2))\n",
    "        ax.text(x + width / 2, -1.35, f\"{name}\\n{maps} maps\\n{size} × {size}\", ha=\"center\", va=\"top\", fontsize=8.5)\n",
    "        ax.annotate(\"\", xy=(x, 0), xytext=(x - 0.55, 0), arrowprops=dict(arrowstyle=\"->\", color=\"grey\"), zorder=1)\n",
    "        x += width + 0.9\n",
    "    ax.add_patch(Rectangle((x, -0.9), 0.18, 1.8, facecolor=\"#93c5fd\", edgecolor=\"#1e3a8a\", zorder=2))\n",
    "    ax.text(x + 0.09, -1.35, \"average\\n512\\nnumbers\", ha=\"center\", va=\"top\", fontsize=8.5)\n",
    "    ax.annotate(\"\", xy=(x, 0), xytext=(x - 0.55, 0), arrowprops=dict(arrowstyle=\"->\", color=\"grey\"), zorder=1)\n",
    "    ax.add_patch(FancyBboxPatch((0.7, -2.45), x - 0.2, 4.3, boxstyle=\"round,pad=0.05\", color=\"#dbeafe\", zorder=0))\n",
    "    ax.text(x / 2 + 0.6, 2.05, f\"reused from ImageNet and frozen: {frozen:,} weights stay as they are\",\n",
    "            ha=\"center\", fontsize=11, color=\"#1e3a8a\")\n",
    "    x += 1.1\n",
    "    ax.add_patch(Rectangle((x, 0.7), 1.9, 1.1, facecolor=\"white\", edgecolor=\"grey\", linestyle=\"--\", zorder=2))\n",
    "    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\")\n",
    "    ax.add_patch(Rectangle((x, -0.55), 1.9, 1.0, facecolor=\"#f97316\", edgecolor=\"#9a3412\", zorder=2))\n",
    "    ax.text(x + 0.95, -0.05, \"new last layer\\n512 → 10 kinds\", ha=\"center\", va=\"center\", fontsize=9, color=\"white\", weight=\"bold\")\n",
    "    ax.text(x + 0.95, -0.75, f\"learns: {512 * 10 + 10:,} weights\", ha=\"center\", va=\"top\", fontsize=9, color=\"#9a3412\")\n",
    "    ax.annotate(\"\", xy=(x, -0.05), xytext=(x - 0.75, 0), arrowprops=dict(arrowstyle=\"->\", color=\"grey\"), zorder=1)\n",
    "    for k, kind in enumerate(kinds):\n",
    "        y = 1.6 - k * 0.36\n",
    "        ax.text(x + 2.35, y, kind, fontsize=8.5, va=\"center\")\n",
    "        ax.plot([x + 1.9, x + 2.28], [-0.05, y], color=\"#fdba74\", lw=0.7, zorder=1)\n",
    "    ax.set_xlim(-1.0, x + 3.4)\n",
    "    ax.set_ylim(-2.6, 2.4)\n",
    "    plt.show()\n",
    "\n",
    "\n",
    "draw_reuse(resnet, draw(doodles[\"drawings\"][\"pizza\"][0], 112))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "191fd94c",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "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."
   ]
  },
  {
   "cell_type": "code",
   "id": "c0bfa371",
   "metadata": {},
   "source": [
    "backbone = models.resnet18(weights=weights)\n",
    "backbone.fc = nn.Identity()                    # leave out the last layer: the network now ends with 512 numbers\n",
    "backbone.eval()\n",
    "normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])   # like weights.transforms()\n",
    "\n",
    "\n",
    "def features(strokes):\n",
    "    # Runs doodles through the reused layers of ResNet-18, 100 at a time, and keeps the 512 numbers of every doodle\n",
    "    result = []\n",
    "    with torch.no_grad():\n",
    "        for start in range(0, len(strokes), 100):\n",
    "            ink = to_tensor(strokes[start:start + 100], 224)\n",
    "            photos = (1 - ink).repeat(1, 3, 1, 1)                 # black lines on white, in 3 colors\n",
    "            result.append(backbone(normalize(photos)))\n",
    "    return torch.cat(result)\n",
    "\n",
    "\n",
    "start = time.perf_counter()\n",
    "F_learn, F_check = features(learn_strokes), features(check_strokes)\n",
    "print(f\"{len(F_learn) + len(F_check)} doodles through ResNet-18 in {time.perf_counter() - start:.0f} seconds, \"\n",
    "      f\"{F_learn.shape[1]} numbers each\")\n",
    "\n",
    "torch.manual_seed(0)\n",
    "new_layer = nn.Linear(512, 10)                 # the only layer that learns: 512 weights and a bias per kind\n",
    "history = train(new_layer, F_learn, y_learn, F_check, y_check, epochs=40, learning_rate=0.01)\n",
    "best = history[\"best_epoch\"]\n",
    "print(f\"after epoch {best}, {history['accuracy'][best - 1]:.0%} of the validation doodles right\")\n",
    "plot_curves(history)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "97d797c3",
   "metadata": {},
   "source": [
    "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](https://ai.kuleuven.be/aivooriedereen/en/convolutional-neural-networks#train-an-image-recognizer-yourself) from the chapter learns from a few pictures of your webcam in seconds.\n",
    "\n",
    "### 🔍 Looking at the mistakes\n",
    "\n",
    "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."
   ]
  },
  {
   "cell_type": "code",
   "id": "4de58364",
   "metadata": {},
   "source": [
    "from sklearn.metrics import ConfusionMatrixDisplay\n",
    "\n",
    "end_strokes, y_end = split(\"end\")\n",
    "with torch.no_grad():\n",
    "    probabilities = torch.softmax(new_layer(features(end_strokes)), dim=1)\n",
    "confidence, guess = probabilities.max(dim=1)\n",
    "print(f\"test accuracy: {(guess == y_end).float().mean():.0%} of {len(y_end)} doodles\")\n",
    "\n",
    "ConfusionMatrixDisplay.from_predictions(y_end, guess, display_labels=kinds, xticks_rotation=45, colorbar=False)\n",
    "plt.show()\n",
    "\n",
    "wrong = (guess != y_end).nonzero().squeeze(1)\n",
    "most_sure = wrong[confidence[wrong].argsort(descending=True)][:8]\n",
    "fig, axes = plt.subplots(1, 8, figsize=(12, 2.2))\n",
    "for ax, i in zip(axes, most_sure):\n",
    "    ax.imshow(draw(end_strokes[i], 112), cmap=\"gray\")\n",
    "    ax.set_title(f\"{kinds[y_end[i]]} →\\n{kinds[guess[i]]} {confidence[i]:.0%}\", fontsize=9)\n",
    "    ax.axis(\"off\")\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "d2f7ccce",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 🔥 Where does it look?\n",
    "\n",
    "Which lines made the network choose its kind? **Grad-CAM**, the [heat map from the chapter](https://ai.kuleuven.be/aivooriedereen/en/convolutional-neural-networks#a-heatmap-of-attention), 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."
   ]
  },
  {
   "cell_type": "code",
   "id": "a0b6e3c6",
   "metadata": {},
   "source": [
    "import torch.nn.functional as F\n",
    "\n",
    "\n",
    "def grad_cam(strokes):\n",
    "    # The kind the network chooses for one doodle, and a heat map of where that choice came from\n",
    "    photo = normalize((1 - to_tensor([strokes], 224)).repeat(1, 3, 1, 1))\n",
    "    maps = {}\n",
    "    hook = backbone.layer4.register_forward_hook(lambda module, inputs, output: maps.update(last=output))\n",
    "    scores = new_layer(backbone(photo))\n",
    "    hook.remove()\n",
    "    kind = scores.argmax().item()\n",
    "    gradients = torch.autograd.grad(scores[0, kind], maps[\"last\"])[0]      # how much each spot pushes that score\n",
    "    heat = torch.relu((gradients.mean(dim=(2, 3), keepdim=True) * maps[\"last\"]).sum(dim=1, keepdim=True))\n",
    "    heat = F.interpolate(heat, size=224, mode=\"bilinear\")[0, 0]\n",
    "    return kind, (heat / heat.max()).detach()\n",
    "\n",
    "\n",
    "fig, axes = plt.subplots(2, 5, figsize=(12, 5.4))\n",
    "for ax, kind in zip(axes.flat, range(len(kinds))):\n",
    "    strokes = end_strokes[kind * 100]                                   # the first test doodle of every kind\n",
    "    chosen, heat = grad_cam(strokes)\n",
    "    ax.imshow(draw(strokes, 224), cmap=\"gray\")\n",
    "    ax.imshow(heat, cmap=\"jet\", alpha=0.45)\n",
    "    ax.set_title(f\"{kinds[kind]} → {kinds[chosen]}\", fontsize=10)\n",
    "    ax.axis(\"off\")\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "c5299210",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f7829aa1",
   "metadata": {},
   "source": [
    "## 🧰 Image recognition for your own problem\n",
    "\n",
    "The recipe for your own photos:\n",
    "\n",
    "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.\n",
    "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](https://docs.pytorch.org/vision/stable/models.html), such as MobileNet, which is smaller and fast enough for a phone.\n",
    "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.\n",
    "\n",
    "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](https://ai.kuleuven.be/aivooriedereen/en/convolutional-neural-networks#feature-extraction-or-fine-tuning). 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**."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ad8b4955",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "*By [Thomas Winters](https://thomaswinters.be) for [AI voor Iedereen](https://ai.kuleuven.be/aivooriedereen/en), KU Leuven. The latest version of this notebook: [ai.kuleuven.be/aivooriedereen/en/notebook/convolutional-networks](https://ai.kuleuven.be/aivooriedereen/en/notebook/convolutional-networks).*"
   ]
  }
 ],
 "metadata": {
  "aivi": {
   "chapters": [
    "convolutionele-neurale-netwerken"
   ],
   "language": "en",
   "title": "Convolutional networks in Python"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
