"> **Note:** This notebook uses `torchvision`'s upcoming [multi-weight support API (coming in `torchvision` v0.13)](https://pytorch.org/blog/introducing-torchvision-new-multi-weight-support-api/). \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)."
"**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",
"Or we could take the patterns from a [language 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",
"The premise remains: find a well-performing existing model and apply it to your own problem.\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/06-transfer-learning-example-overview.png\" alt=\"transfer learning overview on different problems\" width=900/>\n",
"\n",
"*Example of transfer learning being applied to computer vision and natural language processing (NLP). In the case of computer vision, a computer vision model might learn patterns on millions of images in ImageNet and then use those patterns to infer on another problem. And for NLP, a language model may learn the structure of language by reading all of Wikipedia (and perhaps more) and then apply that knowledge to a different problem.*"
"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",
"*We'll be putting these to the test for our FoodVision Mini problem, we'll take a computer vision model pretrained on ImageNet and try to leverage its underlying learned representations for classifying images of pizza, steak and sushi.*\n",
"\n",
"Both research and practice support the use of transfer learning too.\n",
"\n",
"A finding from a recent machine learning research paper recommended practioner's use transfer learning wherever possible.\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/06-how-to-train-your-vit-section-6-transfer-learning-highlight.png\" width=900 alt=\"how to train your vision transformer paper section 6, advising to use transfer learning if you can\"/>\n",
"\n",
"*A study into the effects of whether training from scratch or using transfer learning was better from a practioner's point of view, found transfer learning to be far more beneficial in terms of cost and time. **Source:** [How to train your ViT? Data, Augmentation, and Regularization in Vision Transformers](https://arxiv.org/abs/2106.10270) paper section 6 (conclusion).*\n",
"\n",
"And Jeremy Howard (founder of [fastai](https://www.fast.ai/)) is a big proponent of transfer learning.\n",
"\n",
"> The things that really make a difference (transfer learning), if we can do better at transfer learning, it’s this world changing thing. Suddenly lots more people can do world-class work with less resources and less data. — [Jeremy Howard on the Lex Fridman Podcast](https://youtu.be/Bi7f1JSSlh8?t=72)\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",
"*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",
"> **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) "
"We're going to take a pretrained model from `torchvision.models` and customise it to work on (and hopefully improve) our FoodVision Mini problem.\n",
"\n",
"| **Topic** | **Contents** |\n",
"| ----- | ----- |\n",
"| **0. Getting setup** | We've written a fair bit of useful code over the past few sections, let's download it and make sure we can use it again. |\n",
"| **1. Get data** | Let's get the pizza, steak and sushi image classification dataset we've been using to try and improve our model's results. |\n",
"| **2. Create Datasets and DataLoaders** | We'll use the `data_setup.py` script we wrote in chapter 05. PyTorch Going Modular to setup our DataLoaders. |\n",
"| **3. Get and customise a pretrained model** | Here we'll download a pretrained model from `torchvision.models` and customise it to our own problem. | \n",
"| **4. Train model** | Let's see how the new pretrained model goes on our pizza, steak, sushi dataset. We'll use the training functions we created in the previous chapter. |\n",
"| **5. Evaluate the model by plotting loss curves** | How did our first transfer learning model go? Did it overfit or underfit? |\n",
"| **6. Make predictions on images from the test set** | It's one thing to check out a model's evaluation metrics but it's another thing to view its predictions on test samples, let's *visualize, visualize, visualize*! |"
"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. "
"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",
"`torchinfo` will help later on to give us a visual representation of our model.\n",
"\n",
"> **Note:** As of June 2022, this notebook uses the nightly versions of `torch` and `torchvision` as `torchvision` v0.13+ is required for using the updated multi-weights API. You can install these using the command below."
"> **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`."
"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. "
"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."
"### 2.1 Creating a transform for `torchvision.models` (manual creation)\n",
"\n",
"> **Note:** As of `torchvision` v0.13+, there's an update to how data transforms can be created using `torchvision.models`. I've called the previous method \"manual creation\" and the new method \"auto creation\". This notebook showcases both.\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",
"> 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",
"| 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",
"| 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."
"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",
"And we can transform our images using the transform pipeline we created above by setting `transform=simple_transform`.\n",
"\n",
"> **Note:** I've included this manual creation of transforms in this notebook because you may come across resources that use this style. It's also important to note that because these transforms are manually created, they're also infinitely customizable. So if you wanted to included data augmentation techniques in your transforms pipeline, you could."
" transform=manual_transforms, # resize, convert images to between 0 & 1 and normalize them\n",
" batch_size=32) # set mini-batch size to 32\n",
"\n",
"train_dataloader, test_dataloader, class_names"
]
},
{
"cell_type": "markdown",
"id": "7cbd7821-21c0-44e7-a3a0-0682e241ea27",
"metadata": {},
"source": [
"### 2.2 Creating a transform for `torchvision.models` (auto creation)\n",
"\n",
"As previously stated, 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",
"Above we saw how to manually create a transform for a pretrained model.\n",
"\n",
"But as of `torchvision` v0.13+, an automatic transform creation feature has been added.\n",
"\n",
"When you setup a model from `torchvision.models` and select the pretrained model weights you'd like to use, for example, say we'd like to use:\n",
"* `EfficientNet_B0_Weights` is the model architecture weights we'd like to use (there are many differnt model architecture options in `torchvision.models`).\n",
"* `DEFAULT` means the *best available* weights (the best performance in ImageNet).\n",
" * **Note:** Depending on the model architecture you choose, you may also see other options such as `IMAGENET_V1` and `IMAGENET_V2` where generally the higher version number the better. Though if you want the best available, `DEFAULT` is the easiest option. See the [`torchvision.models` documentation](https://pytorch.org/vision/main/models.html) for more.\n",
" \n",
"Let's try it out."
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "d3f4bd4c-7b7a-41fb-8d1c-ae96ee88f024",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"EfficientNet_B0_Weights.IMAGENET1K_V1"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Get a set of pretrained model weights\n",
"weights = torchvision.models.EfficientNet_B0_Weights.DEFAULT # .DEFAULT = best available weights from pretraining on ImageNet\n",
"weights"
]
},
{
"cell_type": "markdown",
"id": "cebcdf20-4ab7-40ba-8691-9d9af8962dab",
"metadata": {},
"source": [
"And now to access the transforms assosciated with our `weights`, we can use the `transforms()` method.\n",
"\n",
"This is essentially saying \"get the data transforms that were used to train the `EfficientNet_B0_Weights` on ImageNet\"."
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "29924062-a233-4926-a77a-9052d1956938",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"ImageClassification(\n",
" crop_size=[224]\n",
" resize_size=[256]\n",
" mean=[0.485, 0.456, 0.406]\n",
" std=[0.229, 0.224, 0.225]\n",
" interpolation=InterpolationMode.BICUBIC\n",
")"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Get the transforms used to create our pretrained weights\n",
"auto_transforms = weights.transforms()\n",
"auto_transforms"
]
},
{
"cell_type": "markdown",
"id": "243ecdc5-e2c7-46d5-9bb5-6a07606ce93e",
"metadata": {},
"source": [
"Notice how `auto_transforms` is very similar to `manual_transforms`, the only difference is that `auto_transforms` came with the model architecture we chose, where as we had to create `manual_transforms` by hand.\n",
"\n",
"The benefit of automatically creating a transform through `weights.transforms()` is that you ensure you're using the same data transformation as the pretrained model used when it was trained.\n",
"\n",
"However, the tradeoff of using automatically created transforms is a lack of customization.\n",
"\n",
"We can use `auto_transforms` to create DataLoaders with `create_dataloaders()` just as before."
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "7c21ffb5-a6d9-40d5-b0d0-47828612d282",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(<torch.utils.data.dataloader.DataLoader at 0x7fa942951460>,\n",
" <torch.utils.data.dataloader.DataLoader at 0x7fa942951550>,\n",
" ['pizza', 'steak', 'sushi'])"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Create training and testing DataLoaders as well as get a list of class names\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",
"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",
"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",
"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",
"[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",
"*Example of what we're going to create, a pretrained [`EfficientNet_B0` model](https://ai.googleblog.com/2019/05/efficientnet-improving-accuracy-and.html) from `torchvision.models` with the output layer adjusted for our use case of classifying pizza, steak and sushi images.*\n",
"> However, running this using `torchvision` v0.13+ will result in errors such as the following:\n",
"> \n",
"> `UserWarning: The parameter 'pretrained' is deprecated since 0.13 and will be removed in 0.15, please use 'weights' instead.`\n",
">\n",
"> And...\n",
"> \n",
"> `UserWarning: Arguments other than a weight enum or None for weights are deprecated since 0.13 and will be removed in 0.15. The current behavior is equivalent to passing weights=EfficientNet_B0_Weights.IMAGENET1K_V1. You can also use weights=EfficientNet_B0_Weights.DEFAULT to get the most up-to-date weights.`"
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/06-v2-effnetb0-model-print-out.png\" alt=\"output of printing the efficientnet_b0 model from torchvision.models\" width=900/>\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",
"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",
" * **Note:** Many modern models can handle input images of varying sizes thanks to [`torch.nn.AdaptiveAvgPool2d()`](https://pytorch.org/docs/stable/generated/torch.nn.AdaptiveAvgPool2d.html), this layer adaptively adjusts the `output_size` of a given input as required. You can try this out by passing different size input images to `summary()` or your models.\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/06-torchinfo-summary-unfrozen-layers.png\" alt=\"output of torchinfo.summary() when passed our model with all layers as trainable\" width=900/>\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?"
"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",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/06-v2-effnet-changing-the-classifier-head.png\" alt=\"changing the efficientnet classifier head to a custom number of outputs\" width=900/>\n",
"*You can customise the outputs of a pretrained model by changing the output layer(s) to suit your problem. The original `torchvision.models.efficientnet_b0()` comes with `out_features=1000` because there are 1000 classes in ImageNet, the dataset it was trained on. However, for our problem, classifying images of pizza, steak and sushi we only need `out_features=3`.*\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."
"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",
"> **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 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",
"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`. "
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/06-torchinfo-summary-frozen-layers.png\" alt=\"output of torchinfo.summary() after freezing multiple layers in our model and changing the classifier head\" width=900/>\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."
"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."
"Our model trained quite fast (~5 seconds on my local machine with a [NVIDIA TITAN RTX GPU](https://www.nvidia.com/en-au/deep-learning-ai/products/titan-rtx/)/about 15 seconds on Google Colab with a [NVIDIA P100 GPU](https://www.nvidia.com/en-au/data-center/tesla-p100/)).\n",
"With an `efficientnet_b0` backbone, our model achieves almost 85%+ accuracy on the test dataset, almost *double* what we were able to achieve with TinyVGG.\n",
"Our model looks like it's performing pretty well.\n",
"\n",
"Let's plot it's loss curves to see what the training looks like over time. \n",
"\n",
"We can plot the loss curves using the function `plot_loss_curves()` we created in [04. PyTorch Custom Datasets section 7.8](https://www.learnpytorch.io/04_pytorch_custom_datasets/#78-plot-the-loss-curves-of-model-0).\n",
"\n",
"The function is stored in the [`helper_functions.py`](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/helper_functions.py) script so we'll try to import it and download the script if we don't have it."
"Those are some excellent looking loss curves! \n",
"\n",
"It looks like the loss for both datasets (train and test) is heading in the right direction.\n",
"\n",
"The same with the accuracy values, trending upwards.\n",
"\n",
"That goes to show the power of **transfer learning**. Using a pretrained model often leads to pretty good results with a small amount of data in less time.\n",
"I wonder what would happen if you tried to train the model for longer? Or if we added more data?\n",
"\n",
"> **Question:** Looking at the loss curves, does our model look like it's overfitting or underfitting? Or perhaps neither? Hint: Check out notebook [04. PyTorch Custom Datasets part 8. What should an ideal loss curve look like?](https://www.learnpytorch.io/04_pytorch_custom_datasets/#8-what-should-an-ideal-loss-curve-look-like) for ideas."
"One thing we'll have to remember is that for our model to make predictions on an image, the image has to be in *same* format as the images our model was trained on.\n",
"\n",
"This means we'll need to make sure our images have:\n",
"* **Same shape** - If our images are different shapes to what our model was trained on, we'll get shape errors.\n",
"* **Same datatype** - If our images are a different datatype (e.g. `torch.int8` vs. `torch.float32`) we'll get datatype errors.\n",
"* **Same device** - If our images are on a different device to our model, we'll get device errors.\n",
"* **Same transformations** - If our model is trained on images that have been transformed in certain way (e.g. normalized with a specific mean and standard deviation) and we try and make preidctions on images transformed in a different way, these predictions may be off.\n",
"\n",
"> **Note:** These requirements go for all kinds of data if you're trying to make predictions with a trained model. Data you'd like to predict on should be in the same format as your model was trained on.\n",
"\n",
"To do all of this, we'll create a function `pred_and_plot_image()` to:\n",
"\n",
"1. Take in a trained model, a list of class names, a filepath to a target image, an image size, a transform and a target device.\n",
"2. Open an image with [`PIL.Image.open()`](https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.open).\n",
"3. Create a transform for the image (this will default to the `manual_transforms` we created above or it could use a transform generated from `weights.transforms()`).\n",
"4. Make sure the model is on the target device.\n",
"5. Turn on model eval mode with `model.eval()` (this turns off layers like `nn.Dropout()`, so they aren't used for inference) and the inference mode context manager.\n",
"6. Transform the target image with the transform made in step 3 and add an extra batch dimension with `torch.unsqueeze(dim=0)` so our input image has shape `[batch_size, color_channels, height, width]`.\n",
"7. Make a prediction on the image by passing it to the model ensuring it's on the target device.\n",
"8. Convert the model's output logits to prediction probabilities with `torch.softmax()`.\n",
"9. Convert model's prediction probabilities to prediction labels with `torch.argmax()`.\n",
"10. Plot the image with `matplotlib` and set the title to the prediction label from step 9 and prediction probability from step 8.\n",
"\n",
"> **Note:** This is a similar function to [04. PyTorch Custom Datasets section 11.3's](https://www.learnpytorch.io/04_pytorch_custom_datasets/#113-putting-custom-image-prediction-together-building-a-function) `pred_and_plot_image()` with a few tweaked steps. "
"Let's test it out by making predictions on a few random images from the test set.\n",
"\n",
"We can get a list of all the test image paths using `list(Path(test_dir).glob(\"*/*.jpg\"))`, the stars in the `glob()` method say \"any file matching this pattern\", in other words, any file ending in `.jpg` (all of our images).\n",
"\n",
"And then we can randomly sample a number of these using Python's [`random.sample(populuation, k)`](https://docs.python.org/3/library/random.html#random.sample) where `population` is the sequence to sample and `k` is the number of samples to retrieve."
"But this time the prediction probability is higher than the one from TinyVGG (`0.373`) in [04. PyTorch Custom Datasets section 11.3](https://www.learnpytorch.io/04_pytorch_custom_datasets/#113-putting-custom-image-prediction-together-building-a-function).\n",
"* **Transfer learning** often allows to you get good results with a relatively small amount of custom data.\n",
"* Knowing the power of transfer learning, it's a good idea to ask at the start of every problem, \"does an existing well-performing model exist for my problem?\"\n",
"* When using a pretrained model, it's important that your custom data be formatted/preprocessed in the same way that the original model was trained on, otherwise you may get degraded performance.\n",
"* The same goes for predicting on custom data, ensure your custom data is in the same format as the data your model was trained on.\n",
"* There are [several different places to find pretrained models](https://www.learnpytorch.io/06_pytorch_transfer_learning/#where-to-find-pretrained-models) from the PyTorch domain libraries, HuggingFace Hub and libraries such as `timm` (PyTorch Image Models)."
"* [Exercise template notebook for 06](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/extras/exercises/06_pytorch_transfer_learning_exercises.ipynb)\n",
"* [Example solutions notebook for 06](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/extras/solutions/06_pytorch_transfer_learning_exercise_solutions.ipynb) (try the exercises *before* looking at this)\n",
" * See a live [video walkthrough of the solutions on YouTube](https://youtu.be/ueLolShyFqs) (errors and all)\n",
"1. Make predictions on the entire test dataset and plot a confusion matrix for the results of our model compared to the truth labels. Check out [03. PyTorch Computer Vision section 10](https://www.learnpytorch.io/03_pytorch_computer_vision/#10-making-a-confusion-matrix-for-further-prediction-evaluation) for ideas.\n",
"2. Get the \"most wrong\" of the predictions on the test dataset and plot the 5 \"most wrong\" images. You can do this by:\n",
" * Predicting across all of the test dataset, storing the labels and predicted probabilities.\n",
" * Sort the predictions by *wrong prediction* and then *descending predicted probabilities*, this will give you the wrong predictions with the *highest* prediction probabilities, in other words, the \"most wrong\".\n",
" * Plot the top 5 \"most wrong\" images, why do you think the model got these wrong? \n",
"3. Predict on your own image of pizza/steak/sushi - how does the model go? What happens if you predict on an image that isn't pizza/steak/sushi?\n",
"4. Train the model from section 4 above for longer (10 epochs should do), what happens to the performance?\n",
" * You can find the [20% Pizza, Steak, Sushi dataset](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/data/pizza_steak_sushi_20_percent.zip) on the course GitHub. It was created with the notebook [`extras/04_custom_data_creation.ipynb`](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/extras/04_custom_data_creation.ipynb). \n",
"6. Try a different model from [`torchvision.models`](https://pytorch.org/vision/stable/models.html) on the Pizza, Steak, Sushi data, how does this model perform?\n",
"* Look up what \"model fine-tuning\" is and spend 30-minutes researching different methods to perform it with PyTorch. How would we change our code to fine-tine? Tip: fine-tuning usually works best if you have *lots* of custom data, where as, feature extraction is typically better if you have less custom data.\n",
"* Check out the new/upcoming [PyTorch multi-weights API](https://pytorch.org/blog/introducing-torchvision-new-multi-weight-support-api/) (still in beta at time of writing, May 2022), it's a new way to perform transfer learning in PyTorch. What changes to our code would need to made to use the new API?\n",
"* Try to create your own classifier on two classes of images, for example, you could collect 10 photos of your dog and your friends dog and train a model to classify the two dogs. This would be a good way to practice creating a dataset as well as building a model on that dataset."