Files
pytorch-deep-learning/06_pytorch_transfer_learning.ipynb
T

1230 lines
578 KiB
Plaintext
Raw Normal View History

2021-11-24 15:56:58 +10:00
{
2022-05-17 16:21:57 +10:00
"cells": [
{
"cell_type": "markdown",
"id": "39355618-53c2-4f68-b6b2-076e0caa727e",
"metadata": {},
"source": [
"<a href=\"https://colab.research.google.com/github/mrdbourke/pytorch-deep-learning/blob/main/06_pytorch_transfer_learning.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
2022-05-18 09:26:01 +10:00
"id": "a283a60e-4ee4-4a02-a998-ca942a4d3e0d",
2022-05-17 16:21:57 +10:00
"metadata": {},
"source": [
"# (WIP) 06. PyTorch Transfer Learning\n",
"\n",
2022-05-18 09:26:01 +10:00
"We've built a few models by hand so far.\n",
2022-05-17 16:21:57 +10:00
"\n",
2022-05-18 09:26:01 +10:00
"But their performance has been poor.\n",
"\n",
2022-05-19 07:16:32 +10:00
"You might be thinking, **is there a well-performing model that already exists for our problem?**\n",
2022-05-18 09:26:01 +10:00
"\n",
"And in the world of deep learning, the answer is often *yes*.\n",
"\n",
"We'll see how by using a powerful technique called [**transfer learning**](https://developers.google.com/machine-learning/glossary#transfer-learning)."
]
},
{
"cell_type": "markdown",
"id": "bce1d5c7-8cb9-4f7f-8402-58f419ae9176",
"metadata": {},
"source": [
"## TK - What is transfer learning?\n",
"\n",
"* TK image - transfer learning overview\n",
"\n",
"**Transfer learning** allows us to take the patterns (also called weights) another model has learned from another problem and use them for our own problem.\n",
"\n",
"For example, we can take the patterns a computer vision model has learned from datasets such as [ImageNet](https://www.image-net.org/) (millions of images of different objects) and use them to power our FoodVision Mini model.\n",
"\n",
"Or we could take the patterns from a [langauge model](https://developers.google.com/machine-learning/glossary#masked-language-model) (a model that's been through large amounts of text to learn a representation of language) and use them as the basis of a model to classify different text samples.\n",
"\n",
"The premise remains: find a well-performing existing model and apply it to your own problem."
]
},
{
"cell_type": "markdown",
"id": "08cee0cd-4e6a-4faa-8027-c06e2dee4c7d",
"metadata": {},
"source": [
"## TK - Why use transfer learning?\n",
"\n",
"There are two main benefits to using transfer learning:\n",
"\n",
"1. Can leverage an existing model (usually a neural network architecture) proven to work on problems similar to our own.\n",
"2. Can leverage a working model which has **already learned** patterns on similar data to our own. This often results in achieving **great results with less custom data**.\n",
"\n",
"* TK image - transfer learning applied to our problem\n",
"\n",
"We'll be putting these to the test for our FoodVision Mini problem, trying to classify images of pizza, steak and sushi."
]
},
{
"cell_type": "markdown",
"id": "4ef09280-6222-4b64-bfe1-90fe6840c6ff",
"metadata": {},
"source": [
"## TK - Where to find pretrained models\n",
"\n",
"The world of deep learning is an amazing place.\n",
"\n",
"So amazing that many people around the world share their work.\n",
"\n",
"Often, code and pretrained models for the latest state-of-the-art research is released within a few days of publishing.\n",
"\n",
"And there are several places you can find pretrained models to use for your own problems.\n",
"\n",
"| **Location** | **What's there?** | **Link(s)** | \n",
"| ----- | ----- | ----- |\n",
"| **PyTorch domain libraries** | Each of the PyTorch domain libraries (`torchvision`, `torchtext`) come with pretrained models of some form. The models there work right within PyTorch. | [`torchvision.models`](https://pytorch.org/vision/stable/models.html), [`torchtext.models`](https://pytorch.org/text/main/models.html), [`torchaudio.models`](https://pytorch.org/audio/stable/models.html), [`torchrec.models`](https://pytorch.org/torchrec/torchrec.models.html) |\n",
"| **HuggingFace Hub** | A series of pretrained models on many different domains (vision, text, audio and more) from organizations around the world. There's plenty of different datasets too. | https://huggingface.co/models, https://huggingface.co/datasets | \n",
"| **`timm` (PyTorch Image Models) library** | Almost all of the latest and greatest computer vision models in PyTorch code as well as plenty of other helpful computer vision features. | https://github.com/rwightman/pytorch-image-models|\n",
"| **Paperswithcode** | A collection of the latest state-of-the-art machine learning papers with code implementations attached. You can also find benchmarks here of model performance on different tasks. | https://paperswithcode.com/ | \n",
"\n",
"* TK image - different places to find pretrained models\n",
"\n",
"> **Note:** With access to such high-quality resources as above, it should be common practice at the start of every deep learning problem you take on to ask, \"Does a pretrained model exist for my problem?\" \n",
"\n",
"> TK links **Exercise:** Spend 5-minutes going through [`torchvision.models`](https://pytorch.org/vision/stable/models.html) as well as the [HuggingFace Hub Models page](https://huggingface.co/models), what do you find? (there's no right answers here, it's just to practice exploring) "
]
},
{
"cell_type": "markdown",
"id": "047709a9-e17e-471d-ab4e-b01fd7bfdc40",
"metadata": {},
"source": [
"## TK - What we're going to cover\n",
"\n",
"* TK - list this after completing the materials\n",
"* TK - Using a pretrained model from `torchvision.models` and applying it to our problem\n",
"* TK - transforming data to be used with a pretrained model from `torchvision.models`"
]
},
{
"cell_type": "markdown",
"id": "41430fb1-466a-4b38-bfef-0479ca85baf1",
"metadata": {},
"source": [
"## TK - Where can you get help?\n",
"\n",
"All of the materials for this course [are available on GitHub](https://github.com/mrdbourke/pytorch-deep-learning).\n",
"\n",
"If you run into trouble, you can ask a question on the course [GitHub Discussions page](https://github.com/mrdbourke/pytorch-deep-learning/discussions).\n",
"\n",
"And of course, there's the [PyTorch documentation](https://pytorch.org/docs/stable/index.html) and [PyTorch developer forums](https://discuss.pytorch.org/), a very helpful place for all things PyTorch. "
2022-05-17 16:21:57 +10:00
]
},
{
"cell_type": "markdown",
"id": "590369df-00b6-491e-8feb-cb540ad257ec",
"metadata": {},
"source": [
"## TK - 0. Getting setup\n",
"\n",
2022-05-18 09:26:01 +10:00
"Let's get started by importing/downloading the required modules for this section.\n",
"\n",
"To save us writing extra code, we're going to be leveraging some of the Python scripts (such as `data_setup.py` and `engine.py`) we created in the previous section, [05. PyTorch Going Modular](https://www.learnpytorch.io/05_pytorch_going_modular/).\n",
"\n",
"Specifically, we're going to download the [`going_modular`](https://github.com/mrdbourke/pytorch-deep-learning/tree/main/going_modular) directory from the `pytorch-deep-learning` repository (if we don't already have it).\n",
"\n",
2022-05-20 09:03:45 +10:00
"We'll also get the [`torchinfo`](https://github.com/TylerYep/torchinfo) package if it's not available. \n",
2022-05-18 09:26:01 +10:00
"\n",
"`torchinfo` will help later on to give us a visual representation of our model."
2022-05-17 16:21:57 +10:00
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "0797a4ff-512e-4c46-a82a-e913e0db10a8",
"metadata": {},
"outputs": [],
"source": [
"import torch\n",
"import torchvision\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"\n",
"from torch import nn\n",
"from torchvision import transforms, datasets\n",
"\n",
2022-05-18 09:26:01 +10:00
"# Try to get torchinfo, install it if it doesn't work\n",
2022-05-17 16:21:57 +10:00
"try:\n",
" from torchinfo import summary\n",
"except:\n",
" print(\"[INFO] Couldn't find torchinfo... installing it.\")\n",
" !pip install -q torchinfo\n",
" from torchinfo import summary\n",
"\n",
2022-05-18 09:26:01 +10:00
"# Try to import the going_modular directory, download it from GitHub if it doesn't work\n",
2022-05-17 16:21:57 +10:00
"try:\n",
" from going_modular.going_modular import data_setup, engine\n",
"except:\n",
" # Get the going_modular scripts\n",
" print(\"[INFO] Couldn't find going_modular scripts... downloading them from GitHub.\")\n",
" !git clone https://github.com/mrdbourke/pytorch-deep-learning\n",
" !mv pytorch-deep-learning/going_modular .\n",
" !rm -rf pytorch-deep-learning\n",
" from going_modular.going_modular import data_setup, engine"
]
},
2022-05-18 09:26:01 +10:00
{
"cell_type": "markdown",
"id": "208107cc-a0d7-4d84-ad27-4b5120d6be02",
"metadata": {},
"source": [
"Now let's setup device agnostic code.\n",
"\n",
"> **Note:** If you're using Google Colab, and you don't have a GPU turned on yet, it's now time to turn one on via `Runtime -> Change runtime type -> Hardware accelerator -> GPU`."
]
},
2022-05-17 16:21:57 +10:00
{
"cell_type": "code",
2022-05-20 09:03:45 +10:00
"execution_count": 2,
2022-05-17 16:21:57 +10:00
"id": "b93a75c4-6e40-4575-8d60-d1d43be9220f",
"metadata": {},
"outputs": [
2021-11-24 15:56:58 +10:00
{
2022-05-17 16:21:57 +10:00
"data": {
"text/plain": [
"'cuda'"
2021-11-24 15:56:58 +10:00
]
2022-05-17 16:21:57 +10:00
},
2022-05-20 09:03:45 +10:00
"execution_count": 2,
2022-05-17 16:21:57 +10:00
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Setup device agnostic code\n",
"device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
"device"
]
},
{
"cell_type": "markdown",
"id": "afbfa2ba-bae1-406b-bed6-4d17250e5b97",
"metadata": {},
"source": [
2022-05-18 09:26:01 +10:00
"## TK 1. Get data\n",
"\n",
"Before we can start to use **transfer learning**, we'll need a dataset.\n",
"\n",
"To see how transfer learning compares to our previous attempts at model building, we'll download the same dataset we've been using for FoodVision Mini.\n",
"\n",
"Let's write some code to download the [`pizza_steak_sushi.zip`](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/data/pizza_steak_sushi.zip) dataset from the course GitHub and then unzip it.\n",
"\n",
"We can also make sure if we've already got the data, it doesn't redownload. "
2022-05-17 16:21:57 +10:00
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "8dfd6e3f-3f0d-4fca-9835-6a45a7c797c3",
"metadata": {},
"outputs": [
{
2022-05-17 16:21:57 +10:00
"name": "stdout",
"output_type": "stream",
"text": [
"data/pizza_steak_sushi directory exists.\n"
]
}
],
"source": [
"import os\n",
"import requests\n",
"import zipfile\n",
"\n",
"from pathlib import Path\n",
"\n",
"# Setup path to data folder\n",
"data_path = Path(\"data/\")\n",
"image_path = data_path / \"pizza_steak_sushi\"\n",
"\n",
"# If the image folder doesn't exist, download it and prepare it... \n",
"if image_path.is_dir():\n",
" print(f\"{image_path} directory exists.\")\n",
"else:\n",
" print(f\"Did not find {image_path} directory, creating one...\")\n",
" image_path.mkdir(parents=True, exist_ok=True)\n",
" \n",
" # Download pizza, steak, sushi data\n",
" with open(data_path / \"pizza_steak_sushi.zip\", \"wb\") as f:\n",
" request = requests.get(\"https://github.com/mrdbourke/pytorch-deep-learning/raw/main/data/pizza_steak_sushi.zip\")\n",
" print(\"Downloading pizza, steak, sushi data...\")\n",
" f.write(request.content)\n",
"\n",
" # Unzip pizza, steak, sushi data\n",
" with zipfile.ZipFile(data_path / \"pizza_steak_sushi.zip\", \"r\") as zip_ref:\n",
" print(\"Unzipping pizza, steak, sushi data...\") \n",
" zip_ref.extractall(image_path)\n",
"\n",
" # Remove .zip file\n",
" os.remove(data_path / \"pizza_steak_sushi.zip\")"
]
},
2022-05-18 09:26:01 +10:00
{
"cell_type": "markdown",
"id": "173ed0e2-bd8d-4b7e-8c17-2d2a64a2b886",
"metadata": {},
"source": [
"Excellent!\n",
"\n",
"Now we've got the same dataset we've been using previously, a series of images of pizza, steak and sushi in standard image classification format.\n",
"\n",
"Let's now create paths to our training and test directories."
]
},
2022-05-17 16:21:57 +10:00
{
"cell_type": "code",
"execution_count": 4,
"id": "e3e04e57-44e8-4c13-97db-ba9a21a1924c",
"metadata": {},
"outputs": [],
"source": [
"# Setup Dirs\n",
"train_dir = image_path / \"train\"\n",
"test_dir = image_path / \"test\""
]
},
{
"cell_type": "markdown",
"id": "80dde33f-ab14-41b7-a9f8-2cc0b8a512c0",
"metadata": {},
"source": [
2022-05-18 09:26:01 +10:00
"## TK 2. Create Datasets and DataLoaders\n",
"\n",
"Since we've downloaded the `going_modular` directory, we can use the [`data_setup.py`](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/going_modular/going_modular/data_setup.py) script we created in section [05. PyTorch Going Modular](https://www.learnpytorch.io/05_pytorch_going_modular/#2-create-datasets-and-dataloaders-data_setuppy) to prepare and setup our DataLoaders.\n",
"\n",
"But since we'll be using a pretrained model from [`torchvision.models`](https://pytorch.org/vision/stable/models.html), there's a specific transform we need to prepare our images first."
]
},
{
"cell_type": "markdown",
"id": "0db9c008-5432-4ad2-bad4-881ebe212a6c",
"metadata": {
"tags": []
},
"source": [
"### 2.1 Creating a transform for `torchvision.models`\n",
"\n",
"When using a pretrained model, it's important that **your custom data going into the model is prepared in the same way as the original training data that went into the model**.\n",
"\n",
"For the case of pretrained models in `torchvision.models`, the documentation states:\n",
"\n",
"> All pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB images of shape (3 x H x W), where H and W are expected to be at least 224. \n",
">\n",
"> The images have to be loaded in to a range of `[0, 1]` and then normalized using `mean = [0.485, 0.456, 0.406]` and `std = [0.229, 0.224, 0.225]`. \n",
">\n",
"> You can use the following transform to normalize:\n",
">\n",
"> ```\n",
"> normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n",
" std=[0.229, 0.224, 0.225])\n",
"> ```\n",
"\n",
"The good news is, we can achieve the above transformations with a combination of: \n",
"\n",
"| **Transform number** | **Transform required** | **Code to perform transform** | \n",
"| ----- | ----- | ----- |\n",
"| 1 | Mini-batches of size `[batch_size, 3, height, width]` where height and width are at least 224x224^. | `torchvision.transforms.Resize()` to resize images into `[3, 224, 224]`^ and `torch.utils.data.DataLoader()` to create batches of images. |\n",
"| 2 | Values between 0 & 1. | `torchvision.transforms.ToTensor()` |\n",
"| 3 | A mean of `[0.485, 0.456, 0.406]` (values across each colour channel). | `torchvision.transforms.Normalize(mean=...)` to adjust the mean of our images. |\n",
"| 4 | A standard deviation of `[0.229, 0.224, 0.225]` (values across each colour channel). | `torchvision.transforms.Normalize(std=...)` to adjust the standard deviation of our images. | \n",
"\n",
"> **Note:** ^some pretrained models from `torchvision.models` in different sizes to `[3, 224, 224]`, for example, some might take them in `[3, 240, 240]`. For specific input image sizes, see the documentation.\n",
"\n",
"> **Question:** *Where did the mean and standard deviation values come from? Why do we need to do this?*\n",
">\n",
"> These were calculated from the data. Specifically, the ImageNet dataset by taking the means and standard deviations across a subset of images.\n",
">\n",
"> We also don't *need* to do this. Neural networks are usually quite capable of figuring out appropriate data distributions (they'll calculate where the mean and standard deviations need to be on their own) but setting them at the start can help our networks achieve better performance quicker.\n",
"\n",
"Let's compose a series of `torchvision.transforms` to perform the above steps."
2022-05-17 16:21:57 +10:00
]
},
{
"cell_type": "code",
2022-05-20 09:03:45 +10:00
"execution_count": 5,
2022-05-18 09:26:01 +10:00
"id": "4e095ac1-af8e-4215-8028-de97cfb65c39",
"metadata": {},
"outputs": [],
"source": [
"# Create a transforms pipeline\n",
"simple_transform = transforms.Compose([\n",
" transforms.Resize((224, 224)), # 1. Reshape all images to 224x224 (though some models may require different sizes)\n",
" transforms.ToTensor(), # 2. Turn image values to between 0 & 1 \n",
" transforms.Normalize(mean=[0.485, 0.456, 0.406], # 3. A mean of [0.485, 0.456, 0.406] (across each colour channel)\n",
" std=[0.229, 0.224, 0.225]) # 4. A standard deviation of [0.229, 0.224, 0.225] (across each colour channel),\n",
"])"
]
},
{
"cell_type": "markdown",
"id": "cd676c4f-6f81-4bfb-a578-8f3d5cd2bd4a",
"metadata": {},
"source": [
"Wonderful!\n",
"\n",
"Now we've got a series of transforms ready to prepare our images, let's create training and testing DataLoaders.\n",
"\n",
"We can create these using the `create_dataloaders` function from the [`data_setup.py`](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/going_modular/going_modular/data_setup.py) script we created in [05. PyTorch Going Modular Part 2](https://www.learnpytorch.io/05_pytorch_going_modular/#2-create-datasets-and-dataloaders-data_setuppy).\n",
"\n",
"We'll set `batch_size=32` so our model see's mini-batches of 32 samples at a time.\n",
"\n",
"And we can transform our images using the transform pipeline we created above by setting `transform=simple_transform`."
]
},
{
"cell_type": "code",
2022-05-20 09:03:45 +10:00
"execution_count": 6,
2022-05-18 09:26:01 +10:00
"id": "f7d97a6f-50f8-4212-a777-3d2cfac2a4fe",
2022-05-17 16:21:57 +10:00
"metadata": {},
"outputs": [
{
2022-05-17 16:21:57 +10:00
"data": {
"text/plain": [
2022-05-20 09:03:45 +10:00
"(<torch.utils.data.dataloader.DataLoader at 0x7f1661b63ca0>,\n",
" <torch.utils.data.dataloader.DataLoader at 0x7f1661b635b0>,\n",
2022-05-17 16:21:57 +10:00
" ['pizza', 'steak', 'sushi'])"
]
2022-05-17 16:21:57 +10:00
},
2022-05-20 09:03:45 +10:00
"execution_count": 6,
2022-05-17 16:21:57 +10:00
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
2022-05-18 09:26:01 +10:00
"# Create training and testing DataLoader's as well as get a list of class names\n",
2022-05-17 16:21:57 +10:00
"train_dataloader, test_dataloader, class_names = data_setup.create_dataloaders(train_dir=train_dir,\n",
2022-05-18 09:26:01 +10:00
" test_dir=test_dir,\n",
" transform=simple_transform, # resize, convert images to between 0 & 1 and normalize them\n",
" batch_size=32) # set mini-batch size to 32\n",
2022-05-17 16:21:57 +10:00
"\n",
"train_dataloader, test_dataloader, class_names"
]
},
{
"cell_type": "markdown",
2022-05-18 09:26:01 +10:00
"id": "71a4f3eb-9349-472f-96b1-735fac55ba73",
"metadata": {},
"source": [
"## TK 3. Getting a pretrained model\n",
"\n",
"Alright, here comes the fun part!\n",
"\n",
"Over the past few notebooks we've been building PyTorch neural networks from scratch.\n",
"\n",
"And while that's a good skill to have, our models haven't been performing as well as we'd like. \n",
"\n",
"That's where **transfer learning** comes in.\n",
"\n",
"The whole idea of transfer learning is to **take an already well-performing model on a problem-space similar to yours and then customising it to your use case**.\n",
"\n",
"Since we're working on a computer vision problem (image classification with FoodVision Mini), we can find pretrained classification models in [`torchvision.models`](https://pytorch.org/vision/stable/models.html#classification).\n",
"\n",
"Exploring the documentation, you'll find plenty of common computer vision architecture backbones such as:\n",
"\n",
"| **Architecuture backbone** | **Code** |\n",
"| ----- | ----- |\n",
"| [ResNet](https://arxiv.org/abs/1512.03385)'s | `torchvision.models.resnet18()`, `torchvision.models.resnet50()`... | \n",
"| [VGG](https://arxiv.org/abs/1409.1556) (similar to what we used for TinyVGG) | `torchvision.models.vgg16()` | \n",
"| [EfficientNet](https://arxiv.org/abs/1905.11946)'s | `torchvision.models.efficientnet_b0()`, `torchvision.models.efficientnet_b1()`... | \n",
"| [VisionTransformer](https://arxiv.org/abs/2010.11929) (ViT's)| `torchvision.models.vit_b_16()`, `torchvision.models.vit_b_32()`... | \n",
"| [ConvNeXt](https://arxiv.org/abs/2201.03545) | `torchvision.models.convnext_tiny()`, `torchvision.models.convnext_small()`... |\n",
"| More available in `torchvision.models` | `torchvision.models...` | "
]
},
{
"cell_type": "markdown",
"id": "c570cca9-9dd6-4a88-a5ca-4237f7f94663",
2022-05-17 16:21:57 +10:00
"metadata": {},
"source": [
2022-05-18 09:26:01 +10:00
"### TK - 3.1 Which pretrained model should you use?\n",
"\n",
"It depends on your problem/the device you're working with.\n",
"\n",
"Generally, the higher number in the model name (e.g. `efficientnet_b0()` -> `efficientnet_b1()` -> `efficientnet_b7()`) means *better performance* but a *larger* model.\n",
"\n",
"You might think better performance is *always better*, right?\n",
"\n",
"That's true but **some better performaning models are too big for some devices**.\n",
"\n",
"For example, say you'd like to run your model on a mobile-device, you'll have to take into account the limited compute resources on the device, thus you'd be looking for a smaller model.\n",
"\n",
"But if you've got unlimited compute power, as [The Bitter Lesson](http://www.incompleteideas.net/IncIdeas/BitterLesson.html) states, you'd likely take the biggest, most compute hungry model you can.\n",
"\n",
"Understanding this **performance vs. speed vs. size tradeoff** will come with time and practice.\n",
"\n",
2022-05-19 07:16:32 +10:00
"For me, I've found a nice balance in the `efficientnet_bX` models. \n",
"\n",
2022-05-20 09:03:45 +10:00
"As of May 2022, [Nutrify](https://nutrify.app) (the machine learning powered app I'm working on) is powered by an `efficientnet_b0`.\n",
2022-05-19 07:16:32 +10:00
"\n",
"[Comma.ai](https://comma.ai/) (a company that makes open source self-driving car software) [uses an `efficientnet_b2`](https://geohot.github.io/blog/jekyll/update/2021/10/29/an-architecture-for-life.html) to learn a representation of the road.\n",
"\n",
"> **Note:** Even though we're using `efficientnet_bX`, it's important not to get too attached to any one architecture, as they are always changing as new research gets released. Best to experiment, experiment, experiment and see what works for your problem. "
]
},
{
"cell_type": "markdown",
"id": "5d2d5d0b-ba3c-4f6a-a7eb-ae8b3bbc5a34",
"metadata": {},
"source": [
"### 3.2 Setting up a pretrained model\n",
"\n",
"The pretrained model we're going to be using is [`torchvision.models.efficientnet_b0()`](https://pytorch.org/vision/stable/generated/torchvision.models.efficientnet_b0.html#torchvision.models.efficientnet_b0).\n",
"\n",
"The architecture is from the paper *[EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks](https://arxiv.org/abs/1905.11946)*.\n",
"\n",
"* TK image - efficientnet architecture\n",
"\n",
"To setup the model and make sure it comes with pretrained weights, we can set `pretrained=True`, doing so will download a set of model weights learned from the ImageNet dataset.\n",
"\n",
"This means the model has already been trained on millions of images and has a good base representation of image data.\n",
"\n",
2022-05-20 09:03:45 +10:00
"The PyTorch version of this pretrained model is capable of achieving ~77.7% accuracy across ImageNet's 1000 classes.\n",
"\n",
2022-05-19 07:16:32 +10:00
"> **Note:** As of December 2019, the PyTorch team announced a [new mutli-weight API for TorchVision](https://pytorch.org/blog/introducing-torchvision-new-multi-weight-support-api/), allowing different sets of model weights (e.g. weights learned from different datasets) to be used for pretrained models. Though as of May 2022, this new API is not released. But even with the new API, the idea still remains: take the weights/patterns from one model and apply it to your own.\n",
"\n",
"We'll also send it to the target device."
]
},
{
"cell_type": "code",
2022-05-20 09:03:45 +10:00
"execution_count": 7,
2022-05-19 07:16:32 +10:00
"id": "7593110c-0b32-47e6-9e29-f33d6c0ac840",
"metadata": {},
"outputs": [],
"source": [
"# Setup the model with pretrained weights and send it to the target device \n",
"model = torchvision.models.efficientnet_b0(pretrained=True).to(device)\n",
"#model # uncomment to output (it's very long)"
]
},
{
"cell_type": "markdown",
2022-05-20 09:03:45 +10:00
"id": "9a681f58-458a-47f0-a18a-cabe772df7b3",
2022-05-19 07:16:32 +10:00
"metadata": {},
"source": [
"If we print the model, we get something similar to the following:\n",
"\n",
"* TK image - turn the below into an image which describes each section\n",
"\n",
"```\n",
"EfficientNet(\n",
" (features): Sequential(\n",
" (0): ConvNormActivation(\n",
" (0): Conv2d(3, 32, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)\n",
" (1): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n",
" (2): SiLU(inplace=True)\n",
" )\n",
" (1): Sequential(\n",
" (0): MBConv(\n",
" (block): Sequential(\n",
" (0): ConvNormActivation(\n",
" (0): Conv2d(32, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=32, bias=False)\n",
" (1): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n",
" (2): SiLU(inplace=True)\n",
" ...\n",
" ...\n",
" ...\n",
" (avgpool): AdaptiveAvgPool2d(output_size=1)\n",
" (classifier): Sequential(\n",
" (0): Dropout(p=0.2, inplace=True)\n",
" (1): Linear(in_features=1280, out_features=1000, bias=True)\n",
" )\n",
")\n",
"```\n",
"\n",
"Lots and lots and lots of layers.\n",
"\n",
"This is one of the benefits of transfer learning, taking an existing model, that's been crafted by some of the best engineers in the world and applying to your own problem.\n",
2022-05-18 09:26:01 +10:00
"\n",
2022-05-19 07:16:32 +10:00
"Our `efficientnet_b0` comes in three main parts:\n",
2022-05-20 09:03:45 +10:00
"1. `features` - A collection of convolutional layers and other various activation layers to learn a base representation of vision data (this base representation/collection of layers is often referred to as **features** or **feature extractor**, \"the base layers of the model learn the different **features** of images\").\n",
"2. `avgpool` - Takes the average of the output of the `features` layer(s) and turns it into a **feature vector**.\n",
"3. `classifier` - Turns the **feature vector** into a vector with the same dimensionality as the number of required output classes (since `efficientnet_b0` is pretrained on ImageNet and because ImageNet has 1000 classes, `out_features=1000` is the default). "
]
},
{
"cell_type": "markdown",
"id": "29912dff-574a-47c7-b514-86841532dbe3",
"metadata": {},
"source": [
"### 3.3 Getting a summary of our model with `torchinfo.summary()`\n",
"\n",
"To learn more about our model, let's use `torchinfo`'s [`summary()` method](https://github.com/TylerYep/torchinfo#documentation).\n",
"\n",
"To do so, we'll pass in:\n",
" * `model` - the model we'd like to get a summary of.\n",
" * `input_size` - the shape of the data we'd like to pass to our model, for the case of `efficientnet_b0`, the input size is `(batch_size, 3, 224, 224)`, though [other variants of `efficientnet_bX` have different input sizes](https://github.com/pytorch/vision/blob/d2bfd639e46e1c5dc3c177f889dc7750c8d137c7/references/classification/train.py#L92-L93).\n",
" * `col_names` - the various information columns we'd like to see about our model. \n",
" * `col_width` - how wide the columns should be for the summary.\n",
" * `row_settings` - what features to show in a row."
2022-05-17 16:21:57 +10:00
]
},
{
"cell_type": "code",
2022-05-20 09:03:45 +10:00
"execution_count": 8,
"id": "524020c6-09d3-4ecf-b791-dbd71ed389e3",
2022-05-17 16:21:57 +10:00
"metadata": {},
"outputs": [
{
2022-05-17 16:21:57 +10:00
"data": {
"text/plain": [
2022-05-20 09:03:45 +10:00
"============================================================================================================================================\n",
"Layer (type (var_name)) Input Shape Output Shape Param # Trainable\n",
"============================================================================================================================================\n",
"EfficientNet -- -- -- True\n",
"├─Sequential (features) [32, 3, 224, 224] [32, 1280, 7, 7] -- True\n",
"│ └─ConvNormActivation (0) [32, 3, 224, 224] [32, 32, 112, 112] -- True\n",
"│ │ └─Conv2d (0) [32, 3, 224, 224] [32, 32, 112, 112] 864 True\n",
"│ │ └─BatchNorm2d (1) [32, 32, 112, 112] [32, 32, 112, 112] 64 True\n",
"│ │ └─SiLU (2) [32, 32, 112, 112] [32, 32, 112, 112] -- --\n",
"│ └─Sequential (1) [32, 32, 112, 112] [32, 16, 112, 112] -- True\n",
"│ │ └─MBConv (0) [32, 32, 112, 112] [32, 16, 112, 112] 1,448 True\n",
"│ └─Sequential (2) [32, 16, 112, 112] [32, 24, 56, 56] -- True\n",
"│ │ └─MBConv (0) [32, 16, 112, 112] [32, 24, 56, 56] 6,004 True\n",
"│ │ └─MBConv (1) [32, 24, 56, 56] [32, 24, 56, 56] 10,710 True\n",
"│ └─Sequential (3) [32, 24, 56, 56] [32, 40, 28, 28] -- True\n",
"│ │ └─MBConv (0) [32, 24, 56, 56] [32, 40, 28, 28] 15,350 True\n",
"│ │ └─MBConv (1) [32, 40, 28, 28] [32, 40, 28, 28] 31,290 True\n",
"│ └─Sequential (4) [32, 40, 28, 28] [32, 80, 14, 14] -- True\n",
"│ │ └─MBConv (0) [32, 40, 28, 28] [32, 80, 14, 14] 37,130 True\n",
"│ │ └─MBConv (1) [32, 80, 14, 14] [32, 80, 14, 14] 102,900 True\n",
"│ │ └─MBConv (2) [32, 80, 14, 14] [32, 80, 14, 14] 102,900 True\n",
"│ └─Sequential (5) [32, 80, 14, 14] [32, 112, 14, 14] -- True\n",
"│ │ └─MBConv (0) [32, 80, 14, 14] [32, 112, 14, 14] 126,004 True\n",
"│ │ └─MBConv (1) [32, 112, 14, 14] [32, 112, 14, 14] 208,572 True\n",
"│ │ └─MBConv (2) [32, 112, 14, 14] [32, 112, 14, 14] 208,572 True\n",
"│ └─Sequential (6) [32, 112, 14, 14] [32, 192, 7, 7] -- True\n",
"│ │ └─MBConv (0) [32, 112, 14, 14] [32, 192, 7, 7] 262,492 True\n",
"│ │ └─MBConv (1) [32, 192, 7, 7] [32, 192, 7, 7] 587,952 True\n",
"│ │ └─MBConv (2) [32, 192, 7, 7] [32, 192, 7, 7] 587,952 True\n",
"│ │ └─MBConv (3) [32, 192, 7, 7] [32, 192, 7, 7] 587,952 True\n",
"│ └─Sequential (7) [32, 192, 7, 7] [32, 320, 7, 7] -- True\n",
"│ │ └─MBConv (0) [32, 192, 7, 7] [32, 320, 7, 7] 717,232 True\n",
"│ └─ConvNormActivation (8) [32, 320, 7, 7] [32, 1280, 7, 7] -- True\n",
"│ │ └─Conv2d (0) [32, 320, 7, 7] [32, 1280, 7, 7] 409,600 True\n",
"│ │ └─BatchNorm2d (1) [32, 1280, 7, 7] [32, 1280, 7, 7] 2,560 True\n",
"│ │ └─SiLU (2) [32, 1280, 7, 7] [32, 1280, 7, 7] -- --\n",
"├─AdaptiveAvgPool2d (avgpool) [32, 1280, 7, 7] [32, 1280, 1, 1] -- --\n",
"├─Sequential (classifier) [32, 1280] [32, 1000] -- True\n",
"│ └─Dropout (0) [32, 1280] [32, 1280] -- --\n",
"│ └─Linear (1) [32, 1280] [32, 1000] 1,281,000 True\n",
"============================================================================================================================================\n",
2022-05-17 16:21:57 +10:00
"Total params: 5,288,548\n",
"Trainable params: 5,288,548\n",
"Non-trainable params: 0\n",
"Total mult-adds (G): 12.35\n",
2022-05-20 09:03:45 +10:00
"============================================================================================================================================\n",
2022-05-17 16:21:57 +10:00
"Input size (MB): 19.27\n",
"Forward/backward pass size (MB): 3452.35\n",
"Params size (MB): 21.15\n",
"Estimated Total Size (MB): 3492.77\n",
2022-05-20 09:03:45 +10:00
"============================================================================================================================================"
]
2022-05-17 16:21:57 +10:00
},
2022-05-20 09:03:45 +10:00
"execution_count": 8,
2022-05-17 16:21:57 +10:00
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
2022-05-20 09:03:45 +10:00
"# Print a summary using torchinfo\n",
"summary(model=model, \n",
2022-05-17 16:21:57 +10:00
" input_size=(32, 3, 224, 224), # make sure this is \"input_size\", not \"input_shape\"\n",
2022-05-20 09:03:45 +10:00
" # col_names=[\"input_size\"], # uncomment for smaller output\n",
" col_names=[\"input_size\", \"output_size\", \"num_params\", \"trainable\"],\n",
2022-05-19 07:16:32 +10:00
" col_width=20,\n",
2022-05-17 16:21:57 +10:00
" row_settings=[\"var_names\"]\n",
")"
]
},
{
2022-05-20 09:03:45 +10:00
"cell_type": "markdown",
"id": "d0ebecfb-1635-48b6-bd89-cbe710d8410f",
2022-05-17 16:21:57 +10:00
"metadata": {},
"source": [
2022-05-20 09:03:45 +10:00
"* TK image - get the torchinfo.summary() output but make it smaller so it's visible + add annotations \n",
"\n",
"Woah!\n",
"\n",
"Now that's a big model!\n",
"\n",
"From the output of the summary, we can see all of the various input and output shape changes as our image data goes through the model.\n",
"\n",
"And there are a whole bunch more total parameters (pretrained weights) to recognize different patterns in our data.\n",
"\n",
"For reference, our model from previous sections, **TinyVGG had 8,083 parameters vs. 5,288,548 parameters for `efficientnet_b0`, an increase of ~654x**!\n",
"\n",
"What do you think, will this mean better performance?"
2022-05-17 16:21:57 +10:00
]
},
{
"cell_type": "markdown",
"id": "24af9d91-7ddc-4eb7-b39e-7459b529fb38",
"metadata": {},
"source": [
2022-05-20 09:03:45 +10:00
"### TK - 3.4 Freezing the base model and changing the output layer to suit our needs\n",
"\n",
"The process of transfer learning usually goes: freeze some base layers of a pretrained model (typically the `features` section) and then adjust the output layers (also called head/classifier layers) to suit your needs.\n",
"\n",
"* TK image - changing the classifier head\n",
"\n",
"Let's freeze all of the layers/parameters in the `features` section of our `efficientnet_b0` model.\n",
"\n",
"> **Note:** To *freeze* layers means to keep them how they are during training. For example, if your model has pretrained layers, to *freeze* them would be to say, \"don't change any of the patterns in these layers during training, keep them how they are.\" In essence, we'd like to keep the pretrained weights/patterns our model has learned from ImageNet as a backbone and then only change the output layers.\n",
"\n",
"We can freeze all of the layers/parameters in the `features` section by setting the attribute `requires_grad=False`.\n",
"\n",
"For parameters with `requires_grad=False`, PyTorch doesn't track gradient updates and in turn, these parameters won't be changed by our optimizer during training.\n",
"\n",
"In essence, a parameter with `requires_grad=False` is \"untrainable\" or \"frozen\" in place."
2022-05-17 16:21:57 +10:00
]
},
{
"cell_type": "code",
2022-05-20 09:03:45 +10:00
"execution_count": 9,
2022-05-17 16:21:57 +10:00
"id": "d9cbf97f-5dbf-4283-b70f-91b49e3713e5",
"metadata": {},
"outputs": [],
"source": [
2022-05-20 09:03:45 +10:00
"# Freeze all base layers (the feature extractor in efficientnet_b0) by setting requires_grad=False\n",
"for param in model.features.parameters():\n",
" param.requires_grad = False"
]
},
{
"cell_type": "markdown",
"id": "e65359fc-116c-44a3-a2d0-42efd958aea1",
"metadata": {},
"source": [
"Feature extractor layers frozen!\n",
"\n",
"Let's now adjust the output layer or the `classifier` portion of our pretrained model to our needs.\n",
"\n",
"Right now our pretrained model has `out_features=1000` because there are 1000 classes in ImageNet. \n",
"\n",
"However, we don't have 1000 classes, we only have three, pizza, steak and sushi.\n",
"\n",
"We can change the `classifier` portion of our model by creating a new series of layers.\n",
"\n",
"The current `classifier` consists of:\n",
"\n",
"```\n",
"(classifier): Sequential(\n",
" (0): Dropout(p=0.2, inplace=True)\n",
" (1): Linear(in_features=1280, out_features=1000, bias=True)\n",
"```\n",
"\n",
"We'll keep the `Dropout` layer the same using [`torch.nn.Dropout(p=0.2, inplace=True)`](https://pytorch.org/docs/stable/generated/torch.nn.Dropout.html).\n",
"\n",
"> **Note:** [Dropout layers](https://developers.google.com/machine-learning/glossary#dropout_regularization) randomly remove connections between two neural network layers with a probability of `p`. For example, if `p=0.2`, 20% of connections between neural network layers will be removed at random each pass. This practice is meant to help to regularize (prevent overfitting) a model by making sure the connections that remain learn features to compensate for the removal of the other connections (hopefully these remaining features are *more general*). \n",
"\n",
"And we'll keep `in_features=1280` for our `Linear` output layer but we'll change the `out_features` value to the length of our `class_names` (`len(['pizza', 'steak', 'sushi']) = 3`).\n",
"\n",
"Our new `classifier` layer should be on the same device as our `model`. "
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "79e804bd-5ddd-470c-9c95-a4150cc1cc3c",
"metadata": {},
"outputs": [],
"source": [
"# Set the manual seeds\n",
2022-05-17 16:21:57 +10:00
"torch.manual_seed(42)\n",
"torch.cuda.manual_seed(42)\n",
"\n",
2022-05-20 09:03:45 +10:00
"# Get the length of class_names (one output unit for each class)\n",
2022-05-17 16:21:57 +10:00
"output_shape = len(class_names)\n",
"\n",
2022-05-20 09:03:45 +10:00
"# Recreate the classifier layer and seed it to the target device\n",
"model.classifier = torch.nn.Sequential(\n",
" torch.nn.Dropout(p=0.2, inplace=True), \n",
" torch.nn.Linear(in_features=1280, \n",
" out_features=output_shape, # same number of output units as our number of classes\n",
" bias=True)).to(device)"
2022-05-17 16:21:57 +10:00
]
},
{
"cell_type": "markdown",
"id": "cb8248ca-1599-45f5-8ca5-6bb2b760bb31",
"metadata": {},
"source": [
2022-05-20 09:03:45 +10:00
"Nice!\n",
"\n",
"Output layer updated, let's get another summary of our model and see what's changed."
2022-05-17 16:21:57 +10:00
]
},
{
"cell_type": "code",
2022-05-20 09:03:45 +10:00
"execution_count": 11,
2022-05-17 16:21:57 +10:00
"id": "d5370a8b-34cf-441f-925d-4120a929ed62",
"metadata": {},
"outputs": [
{
2022-05-17 16:21:57 +10:00
"data": {
"text/plain": [
2022-05-17 16:31:20 +10:00
"============================================================================================================================================\n",
"Layer (type (var_name)) Input Shape Output Shape Param # Trainable\n",
"============================================================================================================================================\n",
2022-05-20 09:03:45 +10:00
"EfficientNet -- -- -- Partial\n",
"├─Sequential (features) [32, 3, 224, 224] [32, 1280, 7, 7] -- False\n",
"│ └─ConvNormActivation (0) [32, 3, 224, 224] [32, 32, 112, 112] -- False\n",
"│ │ └─Conv2d (0) [32, 3, 224, 224] [32, 32, 112, 112] (864) False\n",
"│ │ └─BatchNorm2d (1) [32, 32, 112, 112] [32, 32, 112, 112] (64) False\n",
2022-05-17 16:31:20 +10:00
"│ │ └─SiLU (2) [32, 32, 112, 112] [32, 32, 112, 112] -- --\n",
2022-05-20 09:03:45 +10:00
"│ └─Sequential (1) [32, 32, 112, 112] [32, 16, 112, 112] -- False\n",
"│ │ └─MBConv (0) [32, 32, 112, 112] [32, 16, 112, 112] (1,448) False\n",
"│ └─Sequential (2) [32, 16, 112, 112] [32, 24, 56, 56] -- False\n",
"│ │ └─MBConv (0) [32, 16, 112, 112] [32, 24, 56, 56] (6,004) False\n",
"│ │ └─MBConv (1) [32, 24, 56, 56] [32, 24, 56, 56] (10,710) False\n",
"│ └─Sequential (3) [32, 24, 56, 56] [32, 40, 28, 28] -- False\n",
"│ │ └─MBConv (0) [32, 24, 56, 56] [32, 40, 28, 28] (15,350) False\n",
"│ │ └─MBConv (1) [32, 40, 28, 28] [32, 40, 28, 28] (31,290) False\n",
"│ └─Sequential (4) [32, 40, 28, 28] [32, 80, 14, 14] -- False\n",
"│ │ └─MBConv (0) [32, 40, 28, 28] [32, 80, 14, 14] (37,130) False\n",
"│ │ └─MBConv (1) [32, 80, 14, 14] [32, 80, 14, 14] (102,900) False\n",
"│ │ └─MBConv (2) [32, 80, 14, 14] [32, 80, 14, 14] (102,900) False\n",
"│ └─Sequential (5) [32, 80, 14, 14] [32, 112, 14, 14] -- False\n",
"│ │ └─MBConv (0) [32, 80, 14, 14] [32, 112, 14, 14] (126,004) False\n",
"│ │ └─MBConv (1) [32, 112, 14, 14] [32, 112, 14, 14] (208,572) False\n",
"│ │ └─MBConv (2) [32, 112, 14, 14] [32, 112, 14, 14] (208,572) False\n",
"│ └─Sequential (6) [32, 112, 14, 14] [32, 192, 7, 7] -- False\n",
"│ │ └─MBConv (0) [32, 112, 14, 14] [32, 192, 7, 7] (262,492) False\n",
"│ │ └─MBConv (1) [32, 192, 7, 7] [32, 192, 7, 7] (587,952) False\n",
"│ │ └─MBConv (2) [32, 192, 7, 7] [32, 192, 7, 7] (587,952) False\n",
"│ │ └─MBConv (3) [32, 192, 7, 7] [32, 192, 7, 7] (587,952) False\n",
"│ └─Sequential (7) [32, 192, 7, 7] [32, 320, 7, 7] -- False\n",
"│ │ └─MBConv (0) [32, 192, 7, 7] [32, 320, 7, 7] (717,232) False\n",
"│ └─ConvNormActivation (8) [32, 320, 7, 7] [32, 1280, 7, 7] -- False\n",
"│ │ └─Conv2d (0) [32, 320, 7, 7] [32, 1280, 7, 7] (409,600) False\n",
"│ │ └─BatchNorm2d (1) [32, 1280, 7, 7] [32, 1280, 7, 7] (2,560) False\n",
2022-05-17 16:31:20 +10:00
"│ │ └─SiLU (2) [32, 1280, 7, 7] [32, 1280, 7, 7] -- --\n",
"├─AdaptiveAvgPool2d (avgpool) [32, 1280, 7, 7] [32, 1280, 1, 1] -- --\n",
2022-05-20 09:03:45 +10:00
"├─Sequential (classifier) [32, 1280] [32, 3] -- True\n",
2022-05-17 16:31:20 +10:00
"│ └─Dropout (0) [32, 1280] [32, 1280] -- --\n",
2022-05-20 09:03:45 +10:00
"│ └─Linear (1) [32, 1280] [32, 3] 3,843 True\n",
2022-05-17 16:31:20 +10:00
"============================================================================================================================================\n",
2022-05-20 09:03:45 +10:00
"Total params: 4,011,391\n",
"Trainable params: 3,843\n",
"Non-trainable params: 4,007,548\n",
"Total mult-adds (G): 12.31\n",
2022-05-17 16:31:20 +10:00
"============================================================================================================================================\n",
2022-05-17 16:21:57 +10:00
"Input size (MB): 19.27\n",
2022-05-20 09:03:45 +10:00
"Forward/backward pass size (MB): 3452.09\n",
"Params size (MB): 16.05\n",
"Estimated Total Size (MB): 3487.41\n",
2022-05-17 16:31:20 +10:00
"============================================================================================================================================"
]
2022-05-17 16:21:57 +10:00
},
2022-05-20 09:03:45 +10:00
"execution_count": 11,
2022-05-17 16:21:57 +10:00
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
2022-05-20 09:03:45 +10:00
"# Do a summary *after* freezing the features and changing the output classifier layer\n",
2022-05-17 16:21:57 +10:00
"summary(model, \n",
2022-05-20 09:03:45 +10:00
" input_size=(32, 3, 224, 224), # make sure this is \"input_size\", not \"input_shape\" (batch_size, color_channels, height, width)\n",
2022-05-17 16:21:57 +10:00
" verbose=0,\n",
" col_names=[\"input_size\", \"output_size\", \"num_params\", \"trainable\"],\n",
2022-05-17 16:31:20 +10:00
" col_width=20,\n",
2022-05-17 16:21:57 +10:00
" row_settings=[\"var_names\"]\n",
")"
]
},
2022-05-20 09:03:45 +10:00
{
"cell_type": "markdown",
"id": "0604eef1-edc2-45c1-86a7-ebf20a147b59",
"metadata": {},
"source": [
"* TK image - annotate the above with what's going on\n",
"\n",
"Ho, ho! There's a fair few changes here!\n",
"\n",
"Let's go through them:\n",
"* **Trainable column** - You'll see that many of the base layers (the ones in the `features` portion) have their Trainable value as `False`. This is because we set their attribute `requires_grad=False`. Unless we change this, these layers won't be updated during furture training.\n",
"* **Output shape of `classifier`** - The `classifier` portion of the model now has an Output Shape value of `[32, 3]` instead of `[32, 1000]`. It's Trainable value is also `True`. This means its parameters will be updated during training. In essence, we're using the `features` portion to feed our `classifier` portion a base representation of an image and then our `classifier` layer is going to learn how to base representation aligns with our problem.\n",
"* **Less trainable parameters** - Previously there was 5,288,548 trainable parameters. But since we froze many of the layers of the model and only left the `classifier` as trainable, there's now only 3,843 trainable parameters (even less than our TinyVGG model). Though there's also 4,007,548 non-trainable parameters, these will create a base representation of our input images to feed into our `classifier` layer.\n",
"\n",
"> **Note:** The more trainable parameters a model has, the more compute power/longer it takes to train. Freezing the base layers of our model and leaving it with less trainable parameters means our model should train quite quickly. This is one huge benefit of transfer learning, taking the already learned parameters of a model trained on a problem similar to yours and only tweaking the outputs slightly to suit your problem."
]
},
2022-05-17 16:21:57 +10:00
{
"cell_type": "markdown",
"id": "dc075f8d-4394-49b3-83e6-5bf3500209f5",
"metadata": {},
"source": [
2022-05-20 09:03:45 +10:00
"## TK 4. Train model\n",
"\n",
"Now we've got a pretraiend model that's semi-frozen and has a customised `classifier`, how about we see transfer learning in action?\n",
"\n",
"To begin training, let's create a loss function and an optimizer.\n",
"\n",
"Because we're still working with multi-class classification, we'll use `nn.CrossEntropyLoss()` for the loss function.\n",
"\n",
"And we'll stick with `torch.optim.Adam()` as our optimizer with `lr=0.001`.\n",
"\n"
2022-05-17 16:21:57 +10:00
]
},
{
"cell_type": "code",
2022-05-20 09:03:45 +10:00
"execution_count": 12,
2022-05-17 16:21:57 +10:00
"id": "582200bb-c3f8-4044-ae59-007b921a2422",
"metadata": {},
"outputs": [],
"source": [
"# Define loss and optimizer\n",
"loss_fn = nn.CrossEntropyLoss()\n",
"optimizer = torch.optim.Adam(model.parameters(), lr=0.001)"
]
},
2022-05-20 09:03:45 +10:00
{
"cell_type": "markdown",
"id": "b94c81d7-e583-4171-9191-62b83d6e002e",
"metadata": {},
"source": [
"Wonderful! \n",
"\n",
"To train our model, we can use `train()` function we defined in the [05. PyTorch Going Modular section 04](https://www.learnpytorch.io/05_pytorch_going_modular/#4-creating-train_step-and-test_step-functions-and-train-to-combine-them).\n",
"\n",
"The `train()` function is in the [`engine.py`](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/going_modular/going_modular/engine.py) script inside the [`going_modular` directory](https://github.com/mrdbourke/pytorch-deep-learning/tree/main/going_modular/going_modular). \n",
"\n",
"Let's see how long it takes to train our model for 5 epochs.\n",
"\n",
"> **Note:** We're only going to be training the parameters `classifier` here as all of the other parameters in our model have been frozen."
]
},
2022-05-17 16:21:57 +10:00
{
"cell_type": "code",
2022-05-20 09:03:45 +10:00
"execution_count": 13,
2022-05-17 16:21:57 +10:00
"id": "0e698d13-dedf-48f7-bca3-b21cd969b2d2",
"metadata": {},
"outputs": [
{
2022-05-17 16:21:57 +10:00
"data": {
"application/vnd.jupyter.widget-view+json": {
2022-05-20 09:03:45 +10:00
"model_id": "8631bb4e365047e0ac9dc267d7321db4",
2022-05-17 16:21:57 +10:00
"version_major": 2,
"version_minor": 0
},
2022-05-17 16:21:57 +10:00
"text/plain": [
" 0%| | 0/5 [00:00<?, ?it/s]"
]
2022-05-17 16:21:57 +10:00
},
"metadata": {},
"output_type": "display_data"
},
{
2022-05-17 16:21:57 +10:00
"name": "stdout",
"output_type": "stream",
"text": [
2022-05-20 09:03:45 +10:00
"Epoch: 1 | train_loss: 1.0894 | train_acc: 0.4492 | test_loss: 0.9214 | test_acc: 0.5085\n",
"Epoch: 2 | train_loss: 0.8697 | train_acc: 0.7734 | test_loss: 0.8036 | test_acc: 0.7434\n",
"Epoch: 3 | train_loss: 0.7769 | train_acc: 0.7734 | test_loss: 0.7404 | test_acc: 0.7737\n",
"Epoch: 4 | train_loss: 0.7244 | train_acc: 0.7422 | test_loss: 0.6488 | test_acc: 0.8864\n",
"Epoch: 5 | train_loss: 0.6426 | train_acc: 0.7812 | test_loss: 0.6254 | test_acc: 0.8968\n",
"[INFO] Total training time: 5.065 seconds\n"
2022-05-17 16:21:57 +10:00
]
}
],
"source": [
2022-05-20 09:03:45 +10:00
"# Set the random seeds\n",
2022-05-17 16:21:57 +10:00
"torch.manual_seed(42)\n",
"torch.cuda.manual_seed(42)\n",
"\n",
"# Start the timer\n",
"from timeit import default_timer as timer \n",
"start_time = timer()\n",
"\n",
2022-05-20 09:03:45 +10:00
"# Setup training and save the results\n",
2022-05-17 16:21:57 +10:00
"results = engine.train(model=model,\n",
" train_dataloader=train_dataloader,\n",
" test_dataloader=test_dataloader,\n",
" optimizer=optimizer,\n",
" loss_fn=loss_fn,\n",
" epochs=5,\n",
" device=device)\n",
"\n",
"# End the timer and print out how long it took\n",
"end_time = timer()\n",
"print(f\"[INFO] Total training time: {end_time-start_time:.3f} seconds\")"
]
},
2022-05-20 09:03:45 +10:00
{
"cell_type": "markdown",
"id": "6ef14d56-d23a-4550-a19a-1a7cff1f3189",
"metadata": {},
"source": [
"Wow!\n",
"\n",
"Our model trained quite fast (~5 seconds on my local machine with a big GPU/about 10 seconds on Google Colab).\n",
"\n",
"And it looks like it got quite good results too, let's investigate them further."
]
},
2022-05-17 16:21:57 +10:00
{
"cell_type": "markdown",
"id": "1a5fb2e3-4e5a-4517-a5ab-409dbe92ad86",
"metadata": {},
"source": [
"## 5. TK - Evaluate model"
]
},
{
"cell_type": "code",
2022-05-20 09:03:45 +10:00
"execution_count": 14,
2022-05-17 16:21:57 +10:00
"id": "c3c0c6af-3685-4814-b4f6-bd7abeeda28f",
"metadata": {},
"outputs": [
{
2022-05-17 16:21:57 +10:00
"data": {
2022-05-20 09:03:45 +10:00
"image/png": "iVBORw0KGgoAAAANSUhEUgAAA2oAAAG5CAYAAAD/HsejAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjQuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8rg+JYAAAACXBIWXMAAAsTAAALEwEAmpwYAACERklEQVR4nOzdd3hUZcLG4d+bTkgoKUBC6BA6Cb0GBKRJEwuCoqIiYu+7+q1b3F13XXtD7Cio2BWCIIjSixRN6L2TAKETQkh7vz9OQEA6Sc5M8tzXlYvkzJnJkxCYefKWY6y1iIiIiIiIiOfwcTuAiIiIiIiInEpFTURERERExMOoqImIiIiIiHgYFTUREREREREPo6ImIiIiIiLiYVTUREREREREPIyKmoiIiIiIiIdRURO5DMaYzcaYK93OISIiUtiMMTOMMfuNMYFuZxEpCVTUREREROScjDHVgQTAAv2K8PP6FdXnEv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+vfvz0MPPcQHH3zAbbfddt7PJyJysbx2jZq1lkWb92GtdTuKiEiBKl269In3Z8yYwbRp05g/fz7Jyck0bdr0jBfRDQwMPPG+r68vOTk55/08Z/v/08/Pj4ULF3Lttdfy3Xff0bOncynNt956i3//+99s27aN+Ph49u7de7FfWnFzpgtlnf5NfRYob4xJAu4HfgPO+JfjbRtuFfbP6dChQ3njjTdYtmwZf//738958Whr7RmvW+bn50deXt6Jc7Kysi4q/9ket0qVKlSsWJGff/6ZX375hV69ep01m4gUQ8fSYe8G2L+5UD+
2022-05-17 16:21:57 +10:00
"text/plain": [
"<Figure size 1080x504 with 2 Axes>"
]
2022-05-17 16:21:57 +10:00
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"try:\n",
" from helper_functions import plot_loss_curves\n",
"except:\n",
" print(\"[INFO] Couldn't find helper_functions.py, downloading...\")\n",
" with open(\"helper_functions.py\", \"wb\") as f:\n",
" import requests\n",
" request = requests.get(\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/helper_functions.py\")\n",
" f.write(request.content)\n",
" from helper_functions import plot_loss_curves\n",
"\n",
"plot_loss_curves(results)"
]
},
{
"cell_type": "markdown",
"id": "88eff8af-9fee-4ef2-881c-ff811827b0f3",
"metadata": {},
"source": [
"## TK - Make predictions with custom images (could use/create `predict.py` from previous section)\n",
"\n",
"* TK - Things to remember: image has to be in *same* format model was trained on... e.g. same transforms"
]
},
{
"cell_type": "code",
2022-05-20 09:03:45 +10:00
"execution_count": 15,
2022-05-17 16:21:57 +10:00
"id": "3418ab5a-9cf7-47ce-bb9b-9f1c18132af3",
"metadata": {},
"outputs": [
{
2022-05-17 16:21:57 +10:00
"data": {
2022-05-20 09:03:45 +10:00
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAOcAAAD3CAYAAADmIkO7AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjQuMiwgaHR0cHM6Ly9tYXRwbG90bGliL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A8Vhb4KxlMp5wZA2d768noHH1fSKCM46yLECUzrdgAjFalDGbm89RDXdoInjvCSFAjKD5iWXFiRhQQaOiQbFiMMaRio/65xLT73kOEVlbfu9ci/Sq+wmjoIARh4hJc6qBGDuIHaoBSTOEIBhjsdYgKBpjugYN+SeCCEYsIiWmHFOWGxgpQVtiWNB1Z++6ruEbCCf5YfWWc3kj+aGnhfv4ahfphTRbTuk1Vb4defJ4eez33go9eUyvBGBNmBTErD7/bvGzLt+LKAbWFMJjxz2hNFbCCU9WUT2uBPgG72VhdwISCKFFgBg7uq5Gl0Kk2br1gpmUie8CxOR5iBpQk+/FIyJYq8ReAENIC1PWvIVeWYoQY3o2xpjHrj36gBIxIlgjGBNR6WjmJ4SoqLRgWoyBGBWNii0swUem5zM0RsJS6HvrFPM6SfNnrSUEjw8dajxQgrnEjRf+OXA7xEh2kbKSRhBjAcEHT1GUy2ceQySKgFqQEhGDqCYBISLE3l4tBUbzuVkKrS6/r1cioml9iHUYW0GEGDo01sTYIOJJS0FBBcnKsvdONEY0eDSELMSa5EMMYseU5Q5VsYmPlhg6uvacGL5N4UyTnb48avpZjcddPLLLIFnj9wIsS9vVW8bl2VGV1Twtrdfaoomsbl5XwimY1XtPCMjK8r3LDcl7C/KTwrq6ypWxXX7/UtOurl/ELM+R7sWsFBQRjZ7oO4z
2022-05-17 16:21:57 +10:00
"text/plain": [
"<Figure size 432x288 with 1 Axes>"
]
2022-05-17 16:21:57 +10:00
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
},
{
2022-05-17 16:21:57 +10:00
"data": {
2022-05-20 09:03:45 +10:00
"image/png": "iVBORw0KGgoAAAANSUhEUgAAALAAAAD3CAYAAAC96t6KAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjQuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8rg+JYAAAACXBIWXMAAAsTAAALEwEAmpwYAAEAAElEQVR4nOz9ebDtWZbfB33WHn6/35nu/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A3wdMKx/tJbatEYg6bHGdYYcylxikmQhYQQQ8KIUDlD6CJK0QSaNtdXVZJRWgKtUaKAFcEZw9ANJAIgxBSJmrULIiSjiAopKN56RMGIwZisti2WGCKIyRfKwghrbJa0mopKVYwVTAKNWWInjdjCIFnAr79TYaAtpnoW7bZfUwVTrruWwtu8tj5qWwhsnkGh7Ybmutai6xNcbjZkLWC4fG3rnmV74/wuLtpzGfhbb7/K2dkC6xwxtfTO0y0jTeNQZxhiJEZl3g3M+4SplBgHXCV463BqsSLElIiipBRwJnLQVOzXPW0fCZJIT3BntoNlYzooz/kiwkbSbgi9be9uq6RtUhYpoZoQI/Rty6jyrIIylDzc5kFsEbmLA60GUqFcjAFxFlLKUtEYSKlov7VGAGcdlXU4a0kaEKPEGEhJM0NLzAwbLx+uweCMJZEwKeUHa4QUlUS200UV1OSHv2EJ3VYdG5qshepjtJBL1b42lzIjmcck9PazWav8zXm3GPXStMva7fHDix2cPYxi58vGVGBz/cc3yfMCDc+3gT+7g2KxVYW4hKsrFGg7CGnFRRdJUVhiWZlIJYm2X9KpIK7CGZ8NfgFrDVpZzKDMouf6bMbx8SmDRqJIkUB
2022-05-17 16:21:57 +10:00
"text/plain": [
"<Figure size 432x288 with 1 Axes>"
]
2022-05-17 16:21:57 +10:00
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
},
{
2022-05-17 16:21:57 +10:00
"data": {
2022-05-20 09:03:45 +10:00
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAOcAAAD3CAYAAADmIkO7AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjQuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8rg+JYAAAACXBIWXMAAAsTAAALEwEAmpwYAAEAAElEQVR4nOz9eaxt+ZXfh33Wb9jDme745lev5mKRRTbJJnum2N1SS4rUCmRZHhBJVuwgQhInkYMEsZ1AgZ1ESvxPkACybBgGEjlOIssxFMWwpUiG2rLUaqmb7JHNJos1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UHVt7diHD/Mh6LHO2y3OCK0EbjLFcvnaddtkkLdit6JoVIThsWVONRzgpELGE3tO3c3yIaK0RJYBfP9zYt+ggWKMpjKZ3PYv5ObPZAX3nqCohilDXM47n71OUFiK0XYe2lkikbVqWqyWMLKow9M7jfUAbQYlglALvUMFTFipr+ZjFlkJIBKGUTvsjav1AYowMokzIRCWCiholIBITMyshEhCJ1AoaAu1yTrM6p/Ur+tDiQo9G0FFRKIMygtECxhB6zSJLcSQRqVeCENFReOONd2nmDaILnC5BwJYlZbdCRXBRCKKTADCW6AVtBJ813KC5YtY02y7MQDgD8SQ62wiojUYkEzeIKEQ0IoEQEkNoVOI/BLVWDRCCT3skaZ9dJmBiFosRtGRmAHyM+EzUojaEOwjLGEGTnq1EIAo6MyXDv5gEE6KJweP6DrIWTsJlYM5IiH59pFIqX4tADOma8/cpNTCT2tq/tG/bVkMIkSABpRKzeueygEv3YrJFud7nGEBA6Q9Vmt+ZObumoet6RpMZRV0wGk2
2022-05-17 16:21:57 +10:00
"text/plain": [
"<Figure size 432x288 with 1 Axes>"
]
2022-05-17 16:21:57 +10:00
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"# Get a random image path from test set\n",
"import random\n",
"test_image_path_list = list(Path(test_dir).glob(\"*/*.jpg\"))\n",
"test_image_path_sample = random.sample(test_image_path_list, k=3)\n",
"\n",
"# Open image\n",
"from PIL import Image\n",
"from typing import List, Tuple\n",
"\n",
"def pred_and_plot_image(model: torch.nn.Module, \n",
" image_path: str, \n",
" class_names: List[str], \n",
" image_size: Tuple[int, int]=(224, 224)):\n",
" # TK - similar to function from notebook 04\n",
" # See here for reference: https://www.learnpytorch.io/04_pytorch_custom_datasets/#113-putting-custom-image-prediction-together-building-a-function\n",
" # Open image\n",
" img = Image.open(image_path)\n",
"\n",
" # Create transformation for image\n",
" normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n",
" std=[0.229, 0.224, 0.225])\n",
"\n",
" simple_transform = transforms.Compose([\n",
" transforms.Resize(image_size),\n",
" transforms.ToTensor(),\n",
" normalize,\n",
" ])\n",
"\n",
" ### Predict on image\n",
"\n",
" # Make sure the model is on the target device\n",
" model.to(device)\n",
"\n",
" # Turn on model evaluation mode and inference mode\n",
" model.eval()\n",
" with torch.inference_mode():\n",
" # Transform and add an extra dimension to image (model requires samples in [batch_size, color_channels, height, width])\n",
" transformed_image = simple_transform(img).unsqueeze(dim=0)\n",
"\n",
" # Make a prediction on image with an extra dimension and send it to the target device\n",
" target_image_pred = model(transformed_image.to(device))\n",
"\n",
" # Convert logits -> prediction probabilities (using torch.softmax() for multi-class classification)\n",
" target_image_pred_probs = torch.softmax(target_image_pred, dim=1)\n",
"\n",
" # Convert prediction probabilities -> prediction labels\n",
" target_image_pred_label = torch.argmax(target_image_pred_probs, dim=1)\n",
"\n",
" # Plot image with predicted label and probability \n",
" plt.figure()\n",
" plt.imshow(img)\n",
" plt.title(f\"Pred: {class_names[target_image_pred_label]} | Prob: {target_image_pred_probs.max():.3f}\")\n",
" plt.axis(False);\n",
"\n",
"for image_path in test_image_path_sample:\n",
" pred_and_plot_image(model=model, \n",
" image_path=image_path,\n",
" class_names=class_names, \n",
" image_size=(224, 224))"
]
},
{
"cell_type": "markdown",
"id": "d56c914f-e653-454e-b14a-09f8e0f032e6",
"metadata": {},
"source": [
"### TK - Pred on custom image (pizza dad)"
]
},
{
"cell_type": "code",
2022-05-20 09:03:45 +10:00
"execution_count": 16,
2022-05-17 16:21:57 +10:00
"id": "db9f9b21-4b58-4394-8ed4-b4ba704812a3",
"metadata": {},
"outputs": [
{
2022-05-17 16:21:57 +10:00
"name": "stdout",
"output_type": "stream",
"text": [
"data/04-pizza-dad.jpeg already exists, skipping download.\n"
]
},
{
2022-05-17 16:21:57 +10:00
"data": {
2022-05-20 09:03:45 +10:00
"image/png": "iVBORw0KGgoAAAANSUhEUgAAALEAAAD3CAYAAABSKLW0AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZ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8H3v8Xae21WFm/xMrGBTTH5MrVHrqQXL/yHC+eP0l9u8Pb3vFO9u8/xB995t9g2QJig1q5BgKUSn9CCNY21ikXS1zbOM+l5y9hZw0OHz/MGx/8ESrVCucvP8+R/cc5e/oxtrdWiRKFbk3wK7/y/yKbz+J7Htlclk67TXNwiTPPLvHcc+d5z3vex2tf/ybGq6NEcUytMkWrt41lOuiaxsDvIOkzMqrx9PPX6bck46MTbOzsMT6RZbyWIfDbuF7M1Nw4nfUd7j/5Y6w3z2DZgvXNAM00MU3zpvDeaDe23QzaA8gEgcKyLcbGJuh2WuzubGEaBlPTMxSKBaIgwPd9NA3COCBJEjRNQwgNyzSRUqJpAjm8sOd67O7ssK82i6OZgLwpwEpJhNCQw/ccxxH3nrwdXdPoeQN000QTkEid6ekZBBoK8IOAUqWEYVmUSiW6vT6PPf4kjmPhWA591+PRb36LJIkxDJ1r166h6zq2ZZBEMaZp0o9cpJQYpkEUJ2iWjtD07yqnryjEv/Hrf5s4TNAMHYnAMjPouo7jOJQKRRzHJpfL49gWk5OTFApFdNNgtLSfrJPj/hMHsG0bKRNyI3lOHDvJSG2EybFxarURbDvLRG2eF556gcmZHN2ez7XLK9h2nicef4yZqSnuOvIIbXeH5ZXL5LIV/MClXm8OP4jGN574Gu99+/vo9z0OnzxItqRTK1eJxQCpcrz3be/nYx/7l7jdJtvbdZTM8KEP/QXK5RJSSRwnQxh4uMEmf/iRT7C7lfC
2022-05-17 16:21:57 +10:00
"text/plain": [
"<Figure size 432x288 with 1 Axes>"
]
2022-05-17 16:21:57 +10:00
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
2021-11-24 15:56:58 +10:00
}
2022-05-17 16:21:57 +10:00
],
"source": [
"# Download custom image\n",
"import requests\n",
"\n",
"# Setup custom image path\n",
"custom_image_path = data_path / \"04-pizza-dad.jpeg\"\n",
"\n",
"# Download the image if it doesn't already exist\n",
"if not custom_image_path.is_file():\n",
" with open(custom_image_path, \"wb\") as f:\n",
" # When downloading from GitHub, need to use the \"raw\" file link\n",
" request = requests.get(\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/04-pizza-dad.jpeg\")\n",
" print(f\"Downloading {custom_image_path}...\")\n",
" f.write(request.content)\n",
"else:\n",
" print(f\"{custom_image_path} already exists, skipping download.\")\n",
"\n",
"pred_and_plot_image(model=model,\n",
" image_path=custom_image_path,\n",
" class_names=class_names)"
]
},
{
"cell_type": "markdown",
"id": "15b7cd60-fe0f-4a74-b121-9525c82913b1",
"metadata": {},
"source": [
"## TK - Extensions + Exercises\n",
"* Try a different model from PyTorch pretrained models\n",
" * You'll have to change the size of the classifier layer\n",
" * See here for more models: https://pytorch.org/vision/stable/models.html\n",
" * Try ConvNext-Tiny, does it perform better than EfficientNetB0?\n",
" * `torchvision.models.convnext_tiny()` \n",
"* Train for longer, what happens?\n",
"* Train with more data, what happens?\n",
" * Double the images of pizza, steak, sushi\n",
" * Now introduce 10 classes (10 whole foods), see what happens\n",
"* Could you add in some data augmentation, what happens?\n",
"* Predict on your own image of pizza/steak/sushi - how does the model go?\n",
2022-05-20 09:03:45 +10:00
"* Get the \"most wrong\" of the predictions on the test dataset \n",
2022-05-17 16:21:57 +10:00
"\n",
"## TK - Extra-curriculum\n",
"* TK - Fine-tuning: if you have lots of data, this may be a good option...\n",
"* Check out the PyTorch multi-weights API (still in beta at time of writing, May 2022) - https://pytorch.org/blog/introducing-torchvision-new-multi-weight-support-api/"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
2021-11-24 15:56:58 +10:00
},
2022-05-17 16:21:57 +10:00
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.7"
}
},
"nbformat": 4,
"nbformat_minor": 5
}