"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",
"| **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. "
"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",
"> **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."
]
},
{
"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",
"| 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."
" 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`."
"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",
"### 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",
"[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",
"> **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",
"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",
" * `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."
"* 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?"
"### 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."
"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`. "
"* 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."
"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."
" # See here for reference: https://www.learnpytorch.io/04_pytorch_custom_datasets/#113-putting-custom-image-prediction-together-building-a-function\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/"