"In the last notebook, [notebook 03](https://www.learnpytorch.io/03_pytorch_computer_vision/), we looked at how to build computer vision models on an in-built dataset in PyTorch (FashionMNIST).\n",
"\n",
"The steps we took are similar across many different problems in machine learning.\n",
"Find a dataset, turn the dataset into numbers, build a model (or find an existing model) to find patterns in those numbers that can be used for prediction.\n",
"PyTorch has many built-in datasets used for a wide number of machine learning benchmarks, however, you'll often want to use your own **custom dataset**."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## What is a custom dataset?\n",
"\n",
"A **custom dataset** is a collection of data relating to a specific problem you're working on.\n",
"\n",
"In essence, a **custom dataset** can be comprised of almost anything.\n",
"\n",
"For example, if we were building a food image classification app like [Nutrify](https://nutrify.app), our custom dataset might be images of food.\n",
"\n",
"Or if we were trying to build a model to classify whether or not a text-based review on a website was positive or negative, our custom dataset might be examples of existing customer reviews and their ratings.\n",
"\n",
"Or if we were trying to build a sound classification app, our custom dataset might be sound samples alongside their sample labels.\n",
"\n",
"Or if we were trying to build a recommendation system for customers purchasing things on our website, our custom dataset might be examples of products other people have bought.\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/04-pytorch-domain-libraries.png\" alt=\"different pytorch domain libraries can be used for specific PyTorch problems\" width=1000/>\n",
"\n",
"*PyTorch includes many existing functions to load in various custom datasets in the [`TorchVision`](https://pytorch.org/vision/stable/index.html), [`TorchText`](https://pytorch.org/text/stable/index.html), [`TorchAudio`](https://pytorch.org/audio/stable/index.html) and [`TorchRec`](https://pytorch.org/torchrec/) domain libraries.*\n",
"\n",
"But sometimes these existing functions may not be enough.\n",
"\n",
"In that case, we can always subclass `torch.utils.data.Dataset` and customize it to our liking."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## What we're going to cover\n",
"\n",
"We're going to be applying the PyTorch Workflow we covered in [notebook 01](https://www.learnpytorch.io/01_pytorch_workflow/) and [notebook 02](https://www.learnpytorch.io/02_pytorch_classification/) to a computer vision problem.\n",
"\n",
"But instead of using an in-built PyTorch dataset, we're going to be using our own dataset of pizza, steak and sushi images.\n",
"\n",
"The goal will be to load these images and then build a model to train and predict on them.\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/04-pytorch-food-vision-layout.png\" alt=\"building a pipeline to load in food images and then building a pytorch model to classify those food images\" width=800 />\n",
"\n",
"*What we're going to build. We'll use `torchvision.datasets` as well as our own custom `Dataset` class to load in images of food and then we'll build a PyTorch computer vision model to hopefully be able to classify them.*\n",
"\n",
"Specifically, we're going to cover:\n",
"\n",
"| **Topic** | **Contents** |\n",
"| ----- | ----- |\n",
"| **0. Importing PyTorch and setting up device-agnostic code** | Let's get PyTorch loaded and then follow best practice to setup our code to be device-agnostic. |\n",
"| **1. Get data** | We're going to be using our own **custom dataset** of pizza, steak and sushi images. |\n",
"| **2. Become one with the data (data preparation)** | At the beginning of any new machine learning problem, it's paramount to understand the data you're working with. Here we'll take some steps to figure out what data we have. |\n",
"| **3. Transforming data** |Often, the data you get won't be 100% ready to use with a machine learning model, here we'll look at some steps we can take to *transform* our images so they're ready to be used with a model. | \n",
"| **4. Loading data with `ImageFolder` (option 1)** | PyTorch has many in-built data loading functions for common types of data. `ImageFolder` is helpful if our images are in standard image classification format. |\n",
"| **5. Loading image data with a custom `Dataset`** | What if PyTorch didn't have an in-built function to load data with? This is where we can build our own custom subclass of `torch.utils.data.Dataset`. |\n",
"| **6. Other forms of transforms (data augmentation)** | Data augmentation is a common technique for expanding the diversity of your training data. Here we'll explore some of `torchvision`'s in-built data augmentation functions. |\n",
"| **7. Model 0: TinyVGG without data augmentation** | By this stage, we'll have our data ready, let's build a model capable of fitting it. We'll also create some training and testing functions for training and evaluating our model. |\n",
"| **8. Exploring loss curves** | Loss curves are a great way to see how your model is training/improving over time. They're also a good way to see if your model is **underfitting** or **overfitting**. |\n",
"| **9. Model 1: TinyVGG with data augmentation** | By now, we've tried a model *without*, how about we try one *with* data augmentation? |\n",
"| **10. Compare model results** | Let's compare our different models' loss curves and see which performed better and discuss some options for improving performance. |\n",
"| **11. Making a prediction on a custom image** | Our model is trained to on a dataset of pizza, steak and sushi images. In this section we'll cover how to use our trained model to predict on an image *outside* of our existing dataset. |"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Where can can you get help?\n",
"\n",
"All of the materials for this course [live 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) there too.\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. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 0. Importing PyTorch and setting up device-agnostic code"
"> **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`. If you do this, your runtime will likely reset and you'll have to run all of the cells above by going `Runtime -> Run before`."
"And like any good cooking show, some data has already been prepared for us.\n",
"\n",
"We're going to start small.\n",
"\n",
"Because we're not looking to train the biggest model or use the biggest dataset yet.\n",
"\n",
"Machine learning is an iterative process, start small, get something working and increase when necessary.\n",
"\n",
"The data we're going to be using is a subset of the [Food101 dataset](https://data.vision.ee.ethz.ch/cvl/datasets_extra/food-101/).\n",
"\n",
"Food101 is popular computer vision benchmark as it contains 1000 images of 101 different kinds of foods, totaling 101,000 images (75,750 train and 25,250 test).\n",
"\n",
"Can you think of 101 different foods?\n",
"\n",
"Can you think of a computer program to classify 101 foods?\n",
"\n",
"I can.\n",
"\n",
"A machine learning model! \n",
"\n",
"Specifically, a PyTorch computer vision model like we covered in [notebook 03](https://www.learnpytorch.io/03_pytorch_computer_vision/).\n",
"\n",
"Instead of 101 food classes though, we're going to start with 3: pizza, steak and sushi.\n",
"\n",
"And instead of 1,000 images per class, we're going to start with a random 10% (start small, increase when necessary).\n",
"\n",
"If you'd like to see where the data came from you see the following resources:\n",
"* Original [Food101 dataset and paper website](https://data.vision.ee.ethz.ch/cvl/datasets_extra/food-101/).\n",
"* [`torchvision.datasets.Food101`](https://pytorch.org/vision/main/generated/torchvision.datasets.Food101.html) - the version of the data I downloaded for this notebook.\n",
"* [`extras/04_custom_data_creation.ipynb`](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/extras/04_custom_data_creation.ipynb) - a notebook I used to format the Food101 dataset to use for this notebook.\n",
"* [`data/pizza_steak_sushi.zip`](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/data/pizza_steak_sushi.zip) - the zip archive of pizza, steak and sushi images from Food101, created with the notebook linked above.\n",
"\n",
"Let's write some code to download the formatted data from GitHub.\n",
"\n",
"> **Note:** The dataset we're about to use has been pre-formatted for what we'd like to use it for. However, you'll often have to format your own datasets for whatever problem you're working on. This is a regular practice in the machine learning world."
"## 2. Become one with the data (data preparation)\n",
"\n",
"Dataset downloaded!\n",
"\n",
"Time to become one with it.\n",
"\n",
"This is another important step before building a model.\n",
"\n",
"As Abraham Lossfunction said...\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/04-abraham-lossfunction.png\" alt=\"tweet by mrdbourke, if I had eight hours to build a machine learning model, I'd spend the first 6 hours preparing my dataset\" width=800/>\n",
"\n",
"*Data preparation is paramount. Before building a model, become one with the data. Ask: What am I trying to do here? Source: [@mrdbourke Twitter](https://twitter.com/mrdbourke).*\n",
"\n",
"What's inspecting the data and becoming one with it? \n",
"\n",
"Before starting a project or building any kind of model, it's important to know what data you're working with.\n",
"\n",
"In our case, we have images of pizza, steak and sushi in standard image classification format.\n",
"For example, all images of `pizza` are contained in the `pizza/` directory.\n",
"\n",
"This format is popular across many different image classification benchmarks, including [ImageNet](https://www.image-net.org/) (of the most popular computer vision benchmark datasets).\n",
"\n",
"You can see an example of the storage format below, the images numbers are arbitrary.\n",
"\n",
"```\n",
"pizza_steak_sushi/ <- overall dataset folder\n",
" train/ <- training images\n",
" pizza/ <- class name as folder name\n",
" image01.jpeg\n",
" image02.jpeg\n",
" ...\n",
" steak/\n",
" image24.jpeg\n",
" image25.jpeg\n",
" ...\n",
" sushi/\n",
" image37.jpeg\n",
" ...\n",
" test/ <- testing images\n",
" pizza/\n",
" image101.jpeg\n",
" image102.jpeg\n",
" ...\n",
" steak/\n",
" image154.jpeg\n",
" image155.jpeg\n",
" ...\n",
" sushi/\n",
" image167.jpeg\n",
" ...\n",
"```\n",
"\n",
"The goal will be to **take this data storage structure and turn it into a dataset usable with PyTorch**.\n",
"\n",
"> **Note:** The structure of the data you work with will vary depending on the problem you're working on. But the premise still remains: become one with the data, then find a way to best turn it into a dataset compatible with PyTorch.\n",
"\n",
"We can inspect what's in our data directory by writing a small helper function to walk through each of the subdirectories and count the files present.\n",
"\n",
"To do so, we'll use Python's in-built [`os.walk()`](https://docs.python.org/3/library/os.html#os.walk). "
"It looks like we've got about 75 images per training class and 25 images per testing class.\n",
"\n",
"That should be enough to get started.\n",
"\n",
"Remember, these images are subsets of the original Food101 dataset.\n",
"\n",
"You can see how they were created in the [data creation notebook](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/extras/04_custom_data_creation.ipynb).\n",
"\n",
"While we're at it, let's setup our training and testing paths."
"Okay, we've seen how our directory structure is formatted.\n",
"\n",
"Now in the spirit of the data explorer, it's time to *visualize, visualize, visualize!*\n",
"\n",
"Let's write some code to:\n",
"1. Get all of the image paths using [`pathlib.Path.glob()`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.glob) to find all of the files ending in `.jpg`. \n",
"2. Pick a random image path using Python's [`random.choice()`](https://docs.python.org/3/library/random.html#random.choice).\n",
"3. Get the image class name using [`pathlib.Path.parent.stem`](https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.parent).\n",
"4. And since we're working with images, we'll open the random image path using [`PIL.Image.open()`](https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.open) (PIL stands for Python Image Library).\n",
"5. We'll then show the image and print some metadata."
"We can do the same with [`matplotlib.pyplot.imshow()`](https://matplotlib.org/3.5.0/api/_as_gen/matplotlib.pyplot.imshow.html), except we have to convert the image to a NumPy array first."
"Now what if we wanted to load our image data into PyTorch?\n",
"\n",
"Before we can use our image data with PyTorch we need to:\n",
"\n",
"1. Turn it into tensors (numerical representations of our images).\n",
"2. Turn it into a `torch.utils.data.Dataset` and subsequently a `torch.utils.data.DataLoader`, we'll call these `Dataset` and `DataLoader` for short.\n",
"\n",
"There are several different kinds of pre-built datasets and dataset loaders for PyTorch, depending on the problem you're working on. \n",
"\n",
"| **Problem space** | **Pre-built Datasets and Functions** |\n",
"Since we're working with a vision problem, we'll be looking at `torchvision.datasets` for our data loading functions as well as [`torchvision.transforms`](https://pytorch.org/vision/stable/transforms.html) for preparing our data.\n",
"### 3.1 Transforming data with `torchvision.transforms`\n",
"\n",
"We've got folders of images but before we can use them with PyTorch, we need to convert them into tensors.\n",
"\n",
"One of the ways we can do this is by using the `torchvision.transforms` module.\n",
"\n",
"`torchvision.transforms` contains many pre-built methods for formatting images, turning them into tensors and even manipulating them for **data augmentation** (the practice of altering data to make it harder for a model to learn, we'll see this later on) purposes . \n",
"\n",
"To get experience with `torchvision.transforms`, let's write a series of transform steps that:\n",
"1. Resize the images using [`transforms.Resize()`](https://pytorch.org/vision/stable/generated/torchvision.transforms.Resize.html#torchvision.transforms.Resize) (from about 512x512 to 64x64, the same shape as the images on the [CNN Explainer website](https://poloclub.github.io/cnn-explainer/)).\n",
"2. Flip our images randomly on the horizontal using [`transforms.RandomHorizontalFlip()`](https://pytorch.org/vision/stable/generated/torchvision.transforms.RandomHorizontalFlip.html#torchvision.transforms.RandomHorizontalFlip) (this could be considered a form of data augmentation because it will artificially change our image data).\n",
"3. Turn our images from a PIL image to a PyTorch tensor using [`transforms.ToTensor()`](https://pytorch.org/vision/stable/generated/torchvision.transforms.ToTensor.html#torchvision.transforms.ToTensor).\n",
"\n",
"We can compile all of these steps using [`torchvision.transforms.Compose()`](https://pytorch.org/vision/stable/generated/torchvision.transforms.Compose.html#torchvision.transforms.Compose)."
"We've now got a way to convert our images to tensors using `torchvision.transforms`.\n",
"\n",
"We also manipulate their size and orientation if needed (some models prefer images of different sizes and shapes).\n",
"\n",
"Generally, the larger the shape of the image, the more information a model can recover.\n",
"\n",
"For example, an image of size `[256, 256, 3]` will have 16x more pixels than an image of size `[64, 64, 3]` (`(256*256*3)/(64*64*3)=16`).\n",
"\n",
"However, the tradeoff is that more pixels requires more computations.\n",
"\n",
"> **Exercise:** Try commenting out one of the transforms in `data_transform` and running the plotting function `plot_transformed_images()` again, what happens?"
]
},
{
"cell_type": "markdown",
"metadata": {
"tags": []
},
"source": [
"## 4. Option 1: Loading Image Data Using [`ImageFolder`](https://pytorch.org/vision/stable/generated/torchvision.datasets.ImageFolder.html#torchvision.datasets.ImageFolder)\n",
"\n",
"Alright, time to turn our image data into a `Dataset` capable of being used with PyTorch.\n",
"\n",
"Since our data is in standard image classification format, we can use the class [`torchvision.datasets.ImageFolder`](https://pytorch.org/vision/stable/generated/torchvision.datasets.ImageFolder.html#torchvision.datasets.ImageFolder).\n",
"\n",
"Where we can pass it the file path of a target image directory as well as a series of transforms we'd like to perform on our images.\n",
"\n",
"Let's test it out on our data folders `train_dir` and `test_dir` passing in `transform=data_transform` to turn our images into tensors."
"Our images are now in the form of a tensor (with shape `[3, 64, 64]`) and the labels are in the form of an integer relating to a specific class (as referenced by the `class_to_idx` attribute).\n",
"\n",
"How about we plot a single image tensor using `matplotlib`?\n",
"\n",
"We'll first have to to permute (rearrange the order of its dimensions) so it's compatible.\n",
"\n",
"Right now our image dimensions are in the format `CHW` (color channels, height, width) but `matplotlib` prefers `HWC` (height, width, color channels)."
"Turning our `Dataset`'s into `DataLoader`'s makes them iterable so a model can go through and learn the relationships between samples and targets (features and labels).\n",
"To keep things simple, we'll use a `batch_size=1` and `num_workers=1`.\n",
"\n",
"What's `num_workers`?\n",
"\n",
"Good question.\n",
"\n",
"It defines how many subprocesses will be created to load your data.\n",
"\n",
"Think of it like this, the higher value `num_workers` is set to, the more compute power PyTorch will use to load your data.\n",
"\n",
"Personally, I usually set it to the total number of CPUs on my machine via Python's [`os.cpu_count()`](https://docs.python.org/3/library/os.html#os.cpu_count).\n",
"\n",
"This ensures the `DataLoader` recruits as many cores as possible to load data.\n",
"\n",
"> **Note:** There are more parameters you can get familiar with using `torch.utils.data.DataLoader` in the [PyTorch documentation](https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader)."
"We could now use these `DataLoader`'s with a training and testing loop to train a model.\n",
"\n",
"But before we do, let's look at another option to load images (or almost any other kind of data)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 5. Option 2: Loading Image Data with a Custom `Dataset`\n",
"\n",
"What if a pre-built `Dataset` creator like [`torchvision.datasets.ImageFolder()`](https://pytorch.org/vision/stable/datasets.html#torchvision.datasets.ImageFolder) didn't exist?\n",
"\n",
"Or one for your specific problem didn't exist?\n",
"\n",
"Well, you could build your own.\n",
"\n",
"But wait, what are the pros and cons of creating your own custom way to load `Dataset`'s?\n",
"\n",
"| Pros of creating a custom `Dataset` | Cons of creating a custom `Dataset` |\n",
"| ----- | ----- |\n",
"| Can create a `Dataset` out of almost anything. | Even though you *could* create a `Dataset` out of almost anything, it doesn't mean it will work. | \n",
"| Not limited to PyTorch pre-built `Dataset` functions. | Using a custom `Dataset` often results in writing more code, which could be prone to errors or performance issues. |\n",
"To see this in action, let's work towards replicating `torchvision.datasets.ImageFolder()` by subclassing `torch.utils.data.Dataset` (the base class for all `Dataset`'s in PyTorch). \n",
"* Various types from Python's `typing` module to add type hints to our code.\n",
"\n",
"> **Note:** You can customize the following steps for your own dataset. The premise remains: write code to load your data in the format you'd like it."
"2. Initialize our subclass with a `targ_dir` parameter (the target data directory) and `transform` parameter (so we have the option to transform our data if needed).\n",
"3. Create several attributes for `paths` (the paths of our target images), `transform` (the transforms we might like to use, this can be `None`), `classes` and `class_to_idx` (from our `find_classes()` function).\n",
"4. Create a function to load images from file and return them, this could be using `PIL` or [`torchvision.io`](https://pytorch.org/vision/stable/io.html#image) (for input/output of vision data). \n",
"5. Overwrite the `__len__` method of `torch.utils.data.Dataset` to return the number of samples in the `Dataset`, this is recommended but not required. This is so you can call `len(Dataset)`.\n",
"6. Overwrite the `__getitem__` method of `torch.utils.data.Dataset` to return a single sample from the `Dataset`, this is required.\n",
"Woah! A whole bunch of code to load in our images.\n",
"\n",
"This is one of the downsides of creating your own custom `Dataset`'s.\n",
"\n",
"However, now we've written it once, we could move it into a `.py` file such as `data_loader.py` along with some other helpful data functions and reuse it later on. \n",
"\n",
"Before we test out our new `ImageFolderCustom` class, let's create some transforms to prepare our images."
"Let's turn our training images (contained in `train_dir`) and our testing images (contained in `test_dir`) into `Dataset`'s using our own `ImageFolderCustom` class."
"Time to put on our data explorer's hat and *visualize, visualize, visualize!*\n",
"\n",
"Let's create a helper function called `display_random_images()` that helps us visualize images in our `Dataset'`s.\n",
"\n",
"Specifically, it'll:\n",
"1. Take in a `Dataset` and a number of other parameters such as `classes` (the names of our target classes), the number of images to display (`n`) and a random seed. \n",
"2. To prevent the display getting out of hand, we'll cap `n` at 10 images.\n",
"3. Set the random seed for reproducible plots (if `seed` is set). \n",
"4. Get a list of random sample indexes (we can use Python's `random.sample()` for this) to plot.\n",
"5. Setup a `matplotlib` plot.\n",
"6. Loop through the random sample indexes found in step 4 and plot them with `matplotlib`.\n",
"7. Make sure the sample images are of shape `HWC` (height, width, color channels) so we can plot them."
"We've got a way to turn our raw images into `Dataset`'s (features mapped to labels or `X`'s mapped to `y`'s) through our `ImageFolderCustom` class.\n",
"\n",
"Now how could we turn our custom `Dataset`'s into `DataLoader`'s?\n",
"\n",
"If you guessed by using `torch.utils.data.DataLoader()`, you'd be right!\n",
"**Data augmentation** is the process of altering your data in such a way that you *artificially* increase the diversity of your training set.\n",
"\n",
"Training a model on this *artificially* altered dataset hopefully results in a model that is capable of better *generalization* (the patterns it learns are more robust to future unseen examples).\n",
"You can see many different examples of data augmentation performed on images using `torchvision.transforms` in PyTorch's [Illustration of Transforms example](https://pytorch.org/vision/main/auto_examples/transforms/plot_transforms_illustrations.html).\n",
"Machine learning is all about harnessing the power of randomness and research shows that random transforms (like [`transforms.RandAugment()`](https://pytorch.org/vision/stable/auto_examples/plot_transforms.html#randaugment) and [`transforms.TrivialAugmentWide()`](https://pytorch.org/vision/stable/auto_examples/plot_transforms.html#trivialaugmentwide)) generally perform better than hand-picked transforms.\n",
"\n",
"The idea behind [TrivialAugment](https://arxiv.org/abs/2103.10158) is... well, trivial. \n",
"\n",
"You have a set of transforms and you randomly pick a number of them to perform on an image and at a random magnitude between a given range (a higher magnitude means more instense).\n",
"\n",
"The PyTorch team even [used TrivialAugment it to train their latest state-of-the-art vision models](https://pytorch.org/blog/how-to-train-state-of-the-art-models-using-torchvision-latest-primitives/#break-down-of-key-accuracy-improvements).\n",
"\n",
"\n",
"\n",
"*TrivialAugment was one of the ingredients used in a recent state of the art training upgrade to various PyTorch vision models.*\n",
"\n",
"How about we test it out on some of our own images?\n",
"\n",
"The main parameter to pay attention to in `transforms.TrivialAugmentWide()` is `num_magnitude_bins=31`.\n",
"\n",
"It defines how much of a range an intensity value will be picked to apply a certain transform, `0` being no range and `31` being maximum range (highest chance for highest intensity). \n",
"\n",
"We can incorporate `transforms.TrivialAugmentWide()` into `transforms.Compose()`."
" transforms.TrivialAugmentWide(num_magnitude_bins=31), # how intense \n",
" transforms.ToTensor() # use ToTensor() last to get everything between 0 & 1\n",
"])\n",
"\n",
"# Don't need to perform augmentation on the test data\n",
"test_transforms = transforms.Compose([\n",
" transforms.Resize((224, 224)), \n",
" transforms.ToTensor()\n",
"])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"> **Note:** You usually don't perform data augmentation on the test set. The idea of data augmentation is to to *artificially* increase the diversity of the training set to better predict on the testing set. \n",
">\n",
"> However, you do need to make sure your test set images are transformed to tensors. We size the test images to the same size as our training images too, however, inference can be done on different size images if necessary (though this may alter performance).\n",
"\n",
"Beautiful, now we've got a training transform (with data augmentation) and test transform (without data augmentation).\n",
"In [notebook 03](https://www.learnpytorch.io/03_pytorch_computer_vision/#7-model-2-building-a-convolutional-neural-network-cnn), we used the TinyVGG model from the [CNN Explainer website](https://poloclub.github.io/cnn-explainer/).\n",
"\n",
"Let's recreate the same model, except this time we'll be using color images instead of grayscale (`in_channels=3` instead of `in_channels=1` for RGB pixels). "
"> **Note:** One of the ways to speed up deep learning models computing on a GPU is to leverage **operator fusion**.\n",
">\n",
"> This means in the `forward()` method in our model above, instead of calling a layer block and reassigning `x` every time, we call each block in succession (see the final line of the `forward()` method in the model above for an example).\n",
">\n",
"> This saves the time spent reassigning `x` (memory heavy) and focuses on only computing on `x`.\n",
"> \n",
"> See [*Making Deep Learning Go Brrrr From First Principles*](https://horace.io/brrr_intro.html) by Horace He for more ways on how to speed up machine learning models.\n",
"A good way to test a model is to do a forward pass on a single piece of data.\n",
"\n",
"It's also handy way to test the input and output shapes of our different layers.\n",
"\n",
"To do a forward pass on a single image, let's:\n",
"1. Get a batch of images and labels from the `DataLoader`.\n",
"2. Get a single image from the batch and `unsqueeze()` the image so it has a batch size of `1` (so its shape fits the model).\n",
"3. Perform inference on a single image (making sure to send the image to the target `device`).\n",
"4. Print out what's happening and convert the model's raw output logits to prediction probabilities with `torch.softmax()` (since we're working with multi-class data) and convert the prediction probabilities to prediction labels with `torch.argmax()`."
"Printing out our model with `print(model)` gives us an idea of what's going on with our model.\n",
"\n",
"And we can print out the shapes of our data throughout the `forward()` method.\n",
"\n",
"However, a helpful way to get information from our model is to use [`torchinfo`](https://github.com/TylerYep/torchinfo).\n",
"\n",
"`torchinfo` comes with a `summary()` method that takes a PyTorch model as well as an `input_shape` and returns what happens as a tensor moves through your model.\n",
"\n",
"> **Note:** If you're using Google Colab, you'll need to install `torchinfo`."
"Now let's make some training and test loop functions to train our model on the training data and evaluate our model on the testing data.\n",
"\n",
"And to make sure we can use these the training and testing loops again, we'll functionize them.\n",
"\n",
"Specifically, we're going to make three functions:\n",
"1. `train_step()` - takes in a model, a `DataLoader`, a loss function and an optimizer and trains the model on the `DataLoader`.\n",
"2. `test_step()` - takes in a model, a `DataLoader` and a loss function and evaluates the model on the `DataLoader`.\n",
"3. `train()` - performs 1. and 2. together for a given number of epochs and returns a results dictionary.\n",
"\n",
"> **Note:** We covered the steps in a PyTorch opimization loop in [notebook 01](https://www.learnpytorch.io/01_pytorch_workflow/#creating-an-optimization-loop-in-pytorch), as well as the[ Unofficial PyTorch Optimization Loop Song](https://youtu.be/Nutpusq_AFw) and we've built similar functions in [notebook 03](https://www.learnpytorch.io/03_pytorch_computer_vision/#62-functionizing-training-and-test-loops).\n",
"\n",
"Let's start by building `train_step()`.\n",
"\n",
"Because we're dealing with batches in the `DataLoader`'s, we'll accumulate the model loss and accuracy values during training (by adding them up for each batch) and then adjust them at the end before we return them."
"Now we need a way to put our `train_step()` and `test_step()` functions together.\n",
"\n",
"To do so, we'll package them up in a `train()` function.\n",
"\n",
"This function will train the model as well as evaluate it.\n",
"\n",
"Specificially, it'll:\n",
"1. Take in a model, a `DataLoader` for training and test sets, an optimizer, a loss function and how many epochs to perform each train and test step for.\n",
"2. Create an empty results dictionary for `train_loss`, `train_acc`, `test_loss` and `test_acc` values (we can fill this up as training goes on).\n",
"3. Loop through the training and test step functions for a number of epochs.\n",
"4. Print out what's happening at the end of each epoch.\n",
"5. Update the empty results dictionary with the updated metrics each epoch.\n",
"6. Return the filled\n",
"\n",
"To keep track of the number of epochs we've been through, let's import `tqdm` from `tqdm.auto` ([`tqdm`](https://github.com/tqdm/tqdm) is one of the most popular progress bar libraries for Python and `tqdm.auto` automatically decides what kind of progress bar is best for your computing environment, e.g. Jupyter Notebook vs. Python script)."
"Alright, alright, alright we've got all of the ingredients we need to train and evaluate our model.\n",
"\n",
"Time to put our `TinyVGG` model, `DataLoader`'s and `train()` function together to see if we can build a model capable of discerning between pizza, steak and sushi!\n",
"\n",
"Let's recreate `model_0` (we don't need to but we will for completeness) then call our `train()` function passing in the necessary parameters.\n",
"\n",
"To keep our experiments quick, we'll train our model for **5 epochs** (though you could increase this if you want).\n",
"As for an **optimizer** and **loss function**, we'll use `torch.nn.CrossEntropyLoss()` (since we're working with multi-class classification data) and `torch.optim.Adam()` with a learning rate of `1e-3` respectively.\n",
"To see how long things take, we'll import Python's [`timeit.default_timer()`](https://docs.python.org/3/library/timeit.html#timeit.default_timer) method to calculate the training time."
"# End the timer and print out how long it took\n",
"end_time = timer()\n",
"print(f\"Total training time: {end_time-start_time:.3f} seconds\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Hmm...\n",
"\n",
"It looks like our model performed pretty poorly.\n",
"\n",
"But that's okay for now, we'll keep persevering.\n",
"\n",
"What are some ways you could potentially improve it?\n",
"\n",
"> **Note:** Check out the [*Improving a model (from a model perspective)* section in notebook 02](https://www.learnpytorch.io/02_pytorch_classification/#5-improving-a-model-from-a-model-perspective) for ideas on improving our TinyVGG model."
"But we kind of knew that because our model's print out results during training didn't show much promise.\n",
"\n",
"You could try training the model for longer and see what happens when you plot a loss curve over a longer time horizon."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 8. What should an ideal loss curve look like?\n",
"\n",
"Looking at training and test loss curves is a great way to see if your model is **overfitting**.\n",
"\n",
"An overfitting model is one that performs better (often by a considerable margin) on the training set than the validation/test set.\n",
"\n",
"If your training loss is far lower than your test loss, your model is **overfitting**.\n",
"\n",
"As in, it's learning the patterns in the training too well and those patterns aren't generalizing to the test data.\n",
"\n",
"The other side is when your training and test loss are not as low as you'd like, this is considered **underfitting**.\n",
"\n",
"The ideal position for a training and test loss curve is for them to line up closely with each other.\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/04-loss-curves-overfitting-underfitting-ideal.jpg\" alt=\"different training and test loss curves illustrating overfitting, underfitting and the ideal loss curves\" width=\"800\"/>\n",
"\n",
"*Left: If your training and test loss curves aren't as low as you'd like, this is considered **underfitting**. *Middle:* When your test/validation loss is higher than your training loss this is considered **overfitting**. *Right:* The ideal scenario is when your training and test loss curves line up over time. This means your model is generalizing well. There are more combinations and different things loss curves can do, for more on these, see Google's [Interpreting Loss Curves guide](https://developers.google.com/machine-learning/testing-debugging/metrics/interpretic).*"
"Since the main problem with overfitting is that your model is fitting the training data *too well*, you'll want to use techniques to \"reign it in\".\n",
"A common technique of preventing overfitting is known as [**regularization**](https://ml-cheatsheet.readthedocs.io/en/latest/regularization.html).\n",
"\n",
"I like to think of this as \"making our models more regular\", as in, capable of fitting *more* kinds of data.\n",
"\n",
"Let's discuss a few methods to prevent overfitting.\n",
"\n",
"| **Method to prevent overfitting** | **What is it?** |\n",
"| ----- | ----- |\n",
"| **Get more data** | Having more data gives the model more opportunities to learn patterns, patterns which may be more generalizable to new examples. | \n",
"| **Simplify your model** | If the current model is already overfitting the training data, it may be too complicated of a model. This means it's learning the patterns of the data too well and isn't able to generalize well to unseen data. One way to simplify a model is to reduce the number of layers it uses or to reduce the number of hidden units in each layer. | \n",
"| **Use data augmentation** | [**Data augmentation**](https://developers.google.com/machine-learning/glossary#data-augmentation) manipulates the training data in a way so that's harder for the model to learn as it artificially adds more variety to the data. If a model is able to learn patterns in augmented data, the model may be able to generalize better to unseen data. |\n",
"| **Use transfer learning** | [**Transfer learning**](https://developers.google.com/machine-learning/glossary#transfer-learning) involves leveraging the patterns (also called pretrained weights) one model has learned to use as the foundation for your own task. In our case, we could use one computer vision model pretrained on a large variety of images and then tweak it slightly to be more specialized for food images. |\n",
"| **Use dropout layers** | Dropout layers randomly remove connections between hidden layers in neural networks, effectively simplifying a model but also making the remaining connections better. See [`torch.nn.Dropout()`](https://pytorch.org/docs/stable/generated/torch.nn.Dropout.html) for more. | \n",
"| **Use learning rate decay** | The idea here is to slowly decrease the learning rate as a model trains. This is akin to reaching for a coin at the back of a couch. The closer you get, the smaller your steps. The same with the learning rate, the closer you get to [**convergence**](https://developers.google.com/machine-learning/glossary#convergence), the smaller you'll want your weight updates to be. |\n",
"| **Use early stopping** | [**Early stopping**](https://developers.google.com/machine-learning/glossary#early_stopping) stops model training *before* it begins to overfit. As in, say the model's loss has stopped decreasing for the past 10 epochs (this number is arbitrary), you may want to stop the model training here and go with the model weights that had the lowest loss (10 epochs prior). |\n",
"There are more methods for dealing with overfitting but these are some of the main ones.\n",
"\n",
"As you start to build more and more deep models, you'll find because deep learnings are *so good* at learning patterns in data, dealing with overfitting is one of the primary problems of deep learning."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 8.2 How to deal with underfitting \n",
"\n",
"When a model is [**underfitting**](https://developers.google.com/machine-learning/glossary#underfitting) it is considered to have poor predictive power on the training and test sets.\n",
"\n",
"In essence, an underfitting model will fail to reduce the loss values to a desired level.\n",
"\n",
"Right now, looking at our current loss curves, I'd considered our `TinyVGG` model, `model_0`, to be underfitting the data.\n",
"\n",
"The main idea behind dealing with underfitting is to *increase* your model's predictive power.\n",
"\n",
"There are several ways to do this.\n",
"\n",
"| **Method to prevent underfitting** | **What is it?** |\n",
"| ----- | ----- |\n",
"| **Add more layers/units to your model** | If your model is underfitting, it may not have enough capability to *learn* the required patterns/weights/representations of the data to be predictive. One way to add more predictive power to your model is to increase the number of hidden layers/units within those layers. | \n",
"| **Tweak the learning rate** | Perhaps your model's learning rate is too high to begin with. And it's trying to update its weights each epoch too much, in turn not learning anything. In this case, you might lower the learning rate and see what happens. |\n",
"| **Use transfer learning** | Transfer learning is capable of preventing overfitting and underfitting. It involves using the patterns from a previously working model and adjusting them to your own problem. |\n",
"| **Train for longer** | Sometimes a model just needs more time to learn representations of data. If you find in your smaller experiments your model isn't learning anything, perhaps leaving it train for a more epochs may result in better performance. |\n",
"| **Use less regularization** | Perhaps your model is underfitting because you're trying to prevent overfitting too much. Holding back on regularization techniques can help your model fit the data better. |"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 8.3 The balance between overfitting and underfitting\n",
"\n",
"None of the methods discussed above are silver bullets, meaning, they don't always work.\n",
"\n",
"And preventing overfitting and underfitting is possibly the most active area of machine learning research.\n",
"Since everyone wants their models to fit better (less underfitting) but not so good they don't generalize well and perform in the real world (less overfitting).\n",
"There's a fine line between overfitting and underfitting.\n",
"\n",
"Because too much of each can cause the other.\n",
"\n",
"Transfer learning is perhaps one of the most powerful techniques when it comes to dealing with both overfitting and underfitting on your own problems.\n",
"\n",
"Rather than handcraft different overfitting and underfitting techniques, transfer learning enables you to take an already working model in a similar problem space to yours (say one from [paperswithcode.com/sota](https://paperswithcode.com/sota) or [Hugging Face models](https://huggingface.co/models)) and apply it to your own dataset.\n",
"\n",
"We'll see the power of transfer learning in a later notebook."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 9. Model 1: TinyVGG with Data Augmentation\n",
"\n",
"Time to try out another model!\n",
"\n",
"This time, let's load in the data and use **data augmentation** to see if it improves our results in anyway.\n",
"\n",
"First, we'll compose a training transform to include `transforms.TrivialAugmentWide()` as well as resize and turn our images into tensors.\n",
"\n",
"We'll do the same for a testing transform except without the data augmentation.\n",
"# Create testing transform (no data augmentation)\n",
"test_transform = transforms.Compose([\n",
" transforms.Resize((64, 64)),\n",
" transforms.ToTensor()\n",
"])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Wonderful!\n",
"\n",
"Now let's turn our images into `Dataset`'s using `torchvision.datasets.ImageFolder()` and then into `DataLoader`'s with `torch.utils.data.DataLoader()`.\n",
"\n",
"### 9.2 Create train and test `Dataset`'s and `DataLoader`'s\n",
"\n",
"We'll make sure the train `Dataset` uses the `train_transform_trivial_augment` and the test `Dataset` uses the `test_transform`."
"And we'll make `DataLoader`'s with a `batch_size=32` and with `num_workers` set to the number of CPUs available on our machine (we can get this using Python's `os.cpu_count()`)."
"Since we've already got functions for the training loop (`train_step()`) and testing loop (`test_step()`) and a function to put them together in `train()`, let's reuse those.\n",
"\n",
"We'll use the same setup as `model_0` with only the `train_dataloader` parameter varying:\n",
"* Train for 5 epochs.\n",
"* Use `train_dataloader=train_dataloader_augmented` as the training data in `train()`.\n",
"* Use `torch.nn.CrossEntropyLoss()` as the loss function (since we're working with multi-class classification).\n",
"* Use `torch.optim.Adam()` with `lr=0.001` as the learning rate as the optimizer. "
"In our case, since we've trained a model on pizza, steak and sushi images, how could we use our model to make a prediction on one of our own images?\n",
"\n",
"To do so, we can load an image and then **preprocess it in a way that matches the type of data our model was trained on**.\n",
"\n",
"In other words, we'll have to convert our own custom image to a tensor and make sure it's in the right datatype before passing it to our model.\n",
"\n",
"Let's start by downloading a custom image.\n",
"\n",
"Since our model predicts whether an image contains pizza, steak or sushi, let's download a photo of [my Dad giving two thumbs up to a big pizza from the Learn PyTorch for Deep Learning GitHub](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/images/04-pizza-dad.jpeg).\n",
"\n",
"We download the image using Python's `requests` module.\n",
"\n",
"> **Note:** If you're using Google Colab, you can also upload an image to the current session by going to the left hand side menu -> Files -> Upload to session storage. Beware though, this image will delete when your Google Colab session ends.\n"
"### 11.1 Loading in a custom image with PyTorch\n",
"\n",
"Excellent!\n",
"\n",
"Looks like we've got a custom image downloaded and ready to go at `data/04-pizza-dad.jpeg`. \n",
"\n",
"Time to load it in.\n",
"\n",
"PyTorch's `torchvision` has several input and output (\"IO\" or \"io\" for short) methods for reading and writing images and video in [`torchvision.io`](https://pytorch.org/vision/stable/io.html).\n",
"\n",
"Since we want to load in an image, we'll use [`torchvision.io.read_image()`](https://pytorch.org/vision/stable/generated/torchvision.io.read_image.html#torchvision.io.read_image).\n",
"\n",
"This method will read a JPEG or PNG image and turn it into a 3 dimensional RGB or grayscale `torch.Tensor` with values of datatype `uint8` in range `[0, 255]`.\n",
"File \u001b[0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/module.py:1130\u001b[0m, in \u001b[0;36mModule._call_impl\u001b[0;34m(self, *input, **kwargs)\u001b[0m\n\u001b[1;32m 1126\u001b[0m \u001b[38;5;66;03m# If we don't have any hooks, we want to skip the rest of the logic in\u001b[39;00m\n\u001b[1;32m 1127\u001b[0m \u001b[38;5;66;03m# this function, and just call forward.\u001b[39;00m\n\u001b[1;32m 1128\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m (\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_backward_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_forward_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_forward_pre_hooks \u001b[38;5;129;01mor\u001b[39;00m _global_backward_hooks\n\u001b[1;32m 1129\u001b[0m \u001b[38;5;129;01mor\u001b[39;00m _global_forward_hooks \u001b[38;5;129;01mor\u001b[39;00m _global_forward_pre_hooks):\n\u001b[0;32m-> 1130\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mforward_call\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 1131\u001b[0m \u001b[38;5;66;03m# Do not call functions when jit is used\u001b[39;00m\n\u001b[1;32m 1132\u001b[0m full_backward_hooks, non_full_backward_hooks \u001b[38;5;241m=\u001b[39m [], []\n",
"Input \u001b[0;32mIn [41]\u001b[0m, in \u001b[0;36mTinyVGG.forward\u001b[0;34m(self, x)\u001b[0m\n\u001b[1;32m 39\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mforward\u001b[39m(\u001b[38;5;28mself\u001b[39m, x: torch\u001b[38;5;241m.\u001b[39mTensor):\n\u001b[0;32m---> 40\u001b[0m x \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mconv_block_1\u001b[49m\u001b[43m(\u001b[49m\u001b[43mx\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 41\u001b[0m \u001b[38;5;66;03m# print(x.shape)\u001b[39;00m\n\u001b[1;32m 42\u001b[0m x \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mconv_block_2(x)\n",
"File \u001b[0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/module.py:1130\u001b[0m, in \u001b[0;36mModule._call_impl\u001b[0;34m(self, *input, **kwargs)\u001b[0m\n\u001b[1;32m 1126\u001b[0m \u001b[38;5;66;03m# If we don't have any hooks, we want to skip the rest of the logic in\u001b[39;00m\n\u001b[1;32m 1127\u001b[0m \u001b[38;5;66;03m# this function, and just call forward.\u001b[39;00m\n\u001b[1;32m 1128\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m (\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_backward_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_forward_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_forward_pre_hooks \u001b[38;5;129;01mor\u001b[39;00m _global_backward_hooks\n\u001b[1;32m 1129\u001b[0m \u001b[38;5;129;01mor\u001b[39;00m _global_forward_hooks \u001b[38;5;129;01mor\u001b[39;00m _global_forward_pre_hooks):\n\u001b[0;32m-> 1130\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mforward_call\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 1131\u001b[0m \u001b[38;5;66;03m# Do not call functions when jit is used\u001b[39;00m\n\u001b[1;32m 1132\u001b[0m full_backward_hooks, non_full_backward_hooks \u001b[38;5;241m=\u001b[39m [], []\n",
"File \u001b[0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/module.py:1130\u001b[0m, in \u001b[0;36mModule._call_impl\u001b[0;34m(self, *input, **kwargs)\u001b[0m\n\u001b[1;32m 1126\u001b[0m \u001b[38;5;66;03m# If we don't have any hooks, we want to skip the rest of the logic in\u001b[39;00m\n\u001b[1;32m 1127\u001b[0m \u001b[38;5;66;03m# this function, and just call forward.\u001b[39;00m\n\u001b[1;32m 1128\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m (\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_backward_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_forward_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_forward_pre_hooks \u001b[38;5;129;01mor\u001b[39;00m _global_backward_hooks\n\u001b[1;32m 1129\u001b[0m \u001b[38;5;129;01mor\u001b[39;00m _global_forward_hooks \u001b[38;5;129;01mor\u001b[39;00m _global_forward_pre_hooks):\n\u001b[0;32m-> 1130\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mforward_call\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 1131\u001b[0m \u001b[38;5;66;03m# Do not call functions when jit is used\u001b[39;00m\n\u001b[1;32m 1132\u001b[0m full_backward_hooks, non_full_backward_hooks \u001b[38;5;241m=\u001b[39m [], []\n",
"Beautiful, it looks like our image data is now in the same format our model was trained on.\n",
"\n",
"Except for one thing...\n",
"\n",
"It's `shape`.\n",
"\n",
"Our model was trained on images with shape `[3, 64, 64]`, whereas our custom image is currently `[3, 4032, 3024]`. \n",
"\n",
"How could we make sure our custom image is the same shape as the images our model was trained on?\n",
"\n",
"Are there any `torchvision.transforms` that could help?\n",
"\n",
"Before we answer that question, let's plot the image with `matplotlib` to make sure it looks okay, remember we'll have to permute the dimensions from `CHW` to `HWC` to suit `matplotlib`'s requirements."
"evalue": "Expected all tensors to be on the same device, but found at least two devices, cpu and cuda:0! (when checking argument for argument weight in method wrapper___slow_conv2d_forward)",
"File \u001b[0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/module.py:1130\u001b[0m, in \u001b[0;36mModule._call_impl\u001b[0;34m(self, *input, **kwargs)\u001b[0m\n\u001b[1;32m 1126\u001b[0m \u001b[38;5;66;03m# If we don't have any hooks, we want to skip the rest of the logic in\u001b[39;00m\n\u001b[1;32m 1127\u001b[0m \u001b[38;5;66;03m# this function, and just call forward.\u001b[39;00m\n\u001b[1;32m 1128\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m (\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_backward_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_forward_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_forward_pre_hooks \u001b[38;5;129;01mor\u001b[39;00m _global_backward_hooks\n\u001b[1;32m 1129\u001b[0m \u001b[38;5;129;01mor\u001b[39;00m _global_forward_hooks \u001b[38;5;129;01mor\u001b[39;00m _global_forward_pre_hooks):\n\u001b[0;32m-> 1130\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mforward_call\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 1131\u001b[0m \u001b[38;5;66;03m# Do not call functions when jit is used\u001b[39;00m\n\u001b[1;32m 1132\u001b[0m full_backward_hooks, non_full_backward_hooks \u001b[38;5;241m=\u001b[39m [], []\n",
"Input \u001b[0;32mIn [41]\u001b[0m, in \u001b[0;36mTinyVGG.forward\u001b[0;34m(self, x)\u001b[0m\n\u001b[1;32m 39\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mforward\u001b[39m(\u001b[38;5;28mself\u001b[39m, x: torch\u001b[38;5;241m.\u001b[39mTensor):\n\u001b[0;32m---> 40\u001b[0m x \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mconv_block_1\u001b[49m\u001b[43m(\u001b[49m\u001b[43mx\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 41\u001b[0m \u001b[38;5;66;03m# print(x.shape)\u001b[39;00m\n\u001b[1;32m 42\u001b[0m x \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mconv_block_2(x)\n",
"File \u001b[0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/module.py:1130\u001b[0m, in \u001b[0;36mModule._call_impl\u001b[0;34m(self, *input, **kwargs)\u001b[0m\n\u001b[1;32m 1126\u001b[0m \u001b[38;5;66;03m# If we don't have any hooks, we want to skip the rest of the logic in\u001b[39;00m\n\u001b[1;32m 1127\u001b[0m \u001b[38;5;66;03m# this function, and just call forward.\u001b[39;00m\n\u001b[1;32m 1128\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m (\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_backward_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_forward_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_forward_pre_hooks \u001b[38;5;129;01mor\u001b[39;00m _global_backward_hooks\n\u001b[1;32m 1129\u001b[0m \u001b[38;5;129;01mor\u001b[39;00m _global_forward_hooks \u001b[38;5;129;01mor\u001b[39;00m _global_forward_pre_hooks):\n\u001b[0;32m-> 1130\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mforward_call\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 1131\u001b[0m \u001b[38;5;66;03m# Do not call functions when jit is used\u001b[39;00m\n\u001b[1;32m 1132\u001b[0m full_backward_hooks, non_full_backward_hooks \u001b[38;5;241m=\u001b[39m [], []\n",
"File \u001b[0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/module.py:1130\u001b[0m, in \u001b[0;36mModule._call_impl\u001b[0;34m(self, *input, **kwargs)\u001b[0m\n\u001b[1;32m 1126\u001b[0m \u001b[38;5;66;03m# If we don't have any hooks, we want to skip the rest of the logic in\u001b[39;00m\n\u001b[1;32m 1127\u001b[0m \u001b[38;5;66;03m# this function, and just call forward.\u001b[39;00m\n\u001b[1;32m 1128\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m (\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_backward_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_forward_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_forward_pre_hooks \u001b[38;5;129;01mor\u001b[39;00m _global_backward_hooks\n\u001b[1;32m 1129\u001b[0m \u001b[38;5;129;01mor\u001b[39;00m _global_forward_hooks \u001b[38;5;129;01mor\u001b[39;00m _global_forward_pre_hooks):\n\u001b[0;32m-> 1130\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mforward_call\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 1131\u001b[0m \u001b[38;5;66;03m# Do not call functions when jit is used\u001b[39;00m\n\u001b[1;32m 1132\u001b[0m full_backward_hooks, non_full_backward_hooks \u001b[38;5;241m=\u001b[39m [], []\n",
"\u001b[0;31mRuntimeError\u001b[0m: Expected all tensors to be on the same device, but found at least two devices, cpu and cuda:0! (when checking argument for argument weight in method wrapper___slow_conv2d_forward)"
"Despite our preparations our custom image and model are on different devices.\n",
"\n",
"And we get the error:\n",
"\n",
"> `RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cpu and cuda:0! (when checking argument for argument weight in method wrapper___slow_conv2d_forward)`\n",
"\n",
"Let's fix that by putting our `custom_image_transformed` on the target device."
"File \u001b[0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/module.py:1130\u001b[0m, in \u001b[0;36mModule._call_impl\u001b[0;34m(self, *input, **kwargs)\u001b[0m\n\u001b[1;32m 1126\u001b[0m \u001b[38;5;66;03m# If we don't have any hooks, we want to skip the rest of the logic in\u001b[39;00m\n\u001b[1;32m 1127\u001b[0m \u001b[38;5;66;03m# this function, and just call forward.\u001b[39;00m\n\u001b[1;32m 1128\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m (\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_backward_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_forward_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_forward_pre_hooks \u001b[38;5;129;01mor\u001b[39;00m _global_backward_hooks\n\u001b[1;32m 1129\u001b[0m \u001b[38;5;129;01mor\u001b[39;00m _global_forward_hooks \u001b[38;5;129;01mor\u001b[39;00m _global_forward_pre_hooks):\n\u001b[0;32m-> 1130\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mforward_call\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 1131\u001b[0m \u001b[38;5;66;03m# Do not call functions when jit is used\u001b[39;00m\n\u001b[1;32m 1132\u001b[0m full_backward_hooks, non_full_backward_hooks \u001b[38;5;241m=\u001b[39m [], []\n",
"Input \u001b[0;32mIn [41]\u001b[0m, in \u001b[0;36mTinyVGG.forward\u001b[0;34m(self, x)\u001b[0m\n\u001b[1;32m 42\u001b[0m x \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mconv_block_2(x)\n\u001b[1;32m 43\u001b[0m \u001b[38;5;66;03m# print(x.shape)\u001b[39;00m\n\u001b[0;32m---> 44\u001b[0m x \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mclassifier\u001b[49m\u001b[43m(\u001b[49m\u001b[43mx\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 45\u001b[0m \u001b[38;5;66;03m# print(x.shape)\u001b[39;00m\n\u001b[1;32m 46\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m x\n",
"File \u001b[0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/module.py:1130\u001b[0m, in \u001b[0;36mModule._call_impl\u001b[0;34m(self, *input, **kwargs)\u001b[0m\n\u001b[1;32m 1126\u001b[0m \u001b[38;5;66;03m# If we don't have any hooks, we want to skip the rest of the logic in\u001b[39;00m\n\u001b[1;32m 1127\u001b[0m \u001b[38;5;66;03m# this function, and just call forward.\u001b[39;00m\n\u001b[1;32m 1128\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m (\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_backward_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_forward_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_forward_pre_hooks \u001b[38;5;129;01mor\u001b[39;00m _global_backward_hooks\n\u001b[1;32m 1129\u001b[0m \u001b[38;5;129;01mor\u001b[39;00m _global_forward_hooks \u001b[38;5;129;01mor\u001b[39;00m _global_forward_pre_hooks):\n\u001b[0;32m-> 1130\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mforward_call\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 1131\u001b[0m \u001b[38;5;66;03m# Do not call functions when jit is used\u001b[39;00m\n\u001b[1;32m 1132\u001b[0m full_backward_hooks, non_full_backward_hooks \u001b[38;5;241m=\u001b[39m [], []\n",
"File \u001b[0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/module.py:1130\u001b[0m, in \u001b[0;36mModule._call_impl\u001b[0;34m(self, *input, **kwargs)\u001b[0m\n\u001b[1;32m 1126\u001b[0m \u001b[38;5;66;03m# If we don't have any hooks, we want to skip the rest of the logic in\u001b[39;00m\n\u001b[1;32m 1127\u001b[0m \u001b[38;5;66;03m# this function, and just call forward.\u001b[39;00m\n\u001b[1;32m 1128\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m (\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_backward_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_forward_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_forward_pre_hooks \u001b[38;5;129;01mor\u001b[39;00m _global_backward_hooks\n\u001b[1;32m 1129\u001b[0m \u001b[38;5;129;01mor\u001b[39;00m _global_forward_hooks \u001b[38;5;129;01mor\u001b[39;00m _global_forward_pre_hooks):\n\u001b[0;32m-> 1130\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mforward_call\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 1131\u001b[0m \u001b[38;5;66;03m# Do not call functions when jit is used\u001b[39;00m\n\u001b[1;32m 1132\u001b[0m full_backward_hooks, non_full_backward_hooks \u001b[38;5;241m=\u001b[39m [], []\n",
"> **Note:** What we've just gone through are three of the classical and most common deep learning and PyTorch issues:\n",
"> 1. **Wrong datatypes** - our model expects `torch.float32` where our original custom image was `uint8`.\n",
"> 2. **Wrong device** - our model was on the target `device` (in our case, the GPU) whereas our target data hadn't been moved to the target `device` yet.\n",
"> 3. **Wrong shapes** - our model expected an input image of shape `[N, C, H, W]` or `[batch_size, color_channels, height, width]` whereas our custom image tensor was of shape `[color_channels, height, width]`.\n",
">\n",
"> Keep in mind, these errors aren't just for predicting on custom images. \n",
">\n",
"> They will be present with almost every kind of data type (text, audio, structured data) and problem you work with.\n",
"\n",
"Now let's take a look at our model's predictions."
"custom_image_pred_class = class_names[custom_image_pred_label.cpu()] # put pred label to CPU, otherwise will error\n",
"custom_image_pred_class"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Wow.\n",
"\n",
"It looks like the model gets the prediction right, even though it was performing poorly based on our evaluation metrics.\n",
"\n",
"> **Note:** The model in its current form will predict \"pizza\", \"steak\" or \"sushi\" no matter what image it's given. If you wanted your model to predict on a different class, you'd have to train it to do so.\n",
"\n",
"But if we check the `custom_image_pred_probs`, we'll notice that the model gives almost equal weight (the values are similar) to every class."
"Looks like our model got the prediction right just by guessing.\n",
"\n",
"This won't always be the case with other images though...\n",
"\n",
"The image is pixelated too because we resized it to `[64, 64]` using `custom_image_transform`.\n",
"\n",
"> **Exercise:** Try making a prediction with one of your own images of pizza, steak or sushi and see what happens."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Main takeaways\n",
"\n",
"We've covered a fair bit in this module.\n",
"\n",
"Let's summarise it with a few dot points.\n",
"\n",
"* PyTorch has many in-built functions to deal with all kinds of data, from vision to text to audio to recommendation systems.\n",
"* If PyTorch's built-in data loading functions don't suit your requirements, you can write code to create your own custom datasets by subclassing `torch.utils.data.Dataset`.\n",
"* `torch.utils.data.DataLoader`'s in PyTorch help turn your `Dataset`'s into iterables that can be used when training and testing a model.\n",
"* A lot of machine learning is dealing with the balance between **overfitting** and **underfitting** (we discussed different methods for each above, so a good exercise would be to research more and writing code to try out the different techniques).\n",
"* Predicting on your own custom data with a trained model is possible, as long as you format the data into a similar format to what the model was trained on. Make sure you take care of the three big PyTorch and deep learning errors:\n",
" 1. **Wrong datatypes** - Your model expected `torch.float32` when your data is `torch.uint8`.\n",
" 2. **Wrong data shapes** - Your model expected `[batch_size, color_channels, height, width]` when your data is `[color_channels, height, width]`.\n",
" 3. **Wrong devices** - Your model is on the GPU but your data is on the CPU. "
"* [Exercise template notebook for 04](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/extras/exercises/04_pytorch_custom_datasets_exercises.ipynb)\n",
"* [Example solutions notebook for 04](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/extras/solutions/04_pytorch_custom_datasets_exercise_solutions.ipynb) (try the exercises *before* looking at this)\n",
"1. Our models are underperforming (not fitting the data well). What are 3 methods for preventing underfitting? Write them down and explain each with a sentence.\n",
"2. Recreate the data loading functions we built in sections 1, 2, 3 and 4. You should have train and test `DataLoader`'s ready to use.\n",
"3. Recreate `model_0` we built in section 7.\n",
"4. Create training and testing functions for `model_0`.\n",
"5. Try training the model you made in exercise 3 for 5, 20 and 50 epochs, what happens to the results?\n",
" * Use `torch.optim.Adam()` with a learning rate of 0.001 as the optimizer. \n",
"6. Double the number of hidden units in your model and train it for 20 epochs, what happens to the results?\n",
"7. Double the data you're using with your model and train it for 20 epochs, what happens to the results?\n",
" * **Note:** You can use the [custom data creation notebook](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/extras/04_custom_data_creation.ipynb) to scale up your Food101 dataset.\n",
" * You can also find the [already formatted double data (20% instead of 10% subset) dataset on GitHub](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/data/pizza_steak_sushi_20_percent.zip), you will need to write download code like in exercise 2 to get it into this notebook.\n",
"* To practice your knowledge of PyTorch `Dataset`'s and `DataLoader`'s through PyTorch [datasets and dataloaders tutorial notebook](https://pytorch.org/tutorials/beginner/basics/data_tutorial.html).\n",
"* Spend 10-minutes reading the [PyTorch `torchvision.transforms` documentation](https://pytorch.org/vision/stable/transforms.html).\n",
" * You can see demos of transforms in action in the [illustrations of transforms tutorial](https://pytorch.org/vision/main/auto_examples/transforms/plot_transforms_illustrations.html). \n",
"* Spend 10-minutes reading the PyTorch [`torchvision.datasets` documentation](https://pytorch.org/vision/stable/datasets.html).\n",
" * What are some datasets that stand out to you?\n",
" * How could you try building a model on these?\n",
"* [TorchData is currently in beta](https://pytorch.org/data/beta/index.html) (as of April 2022), it'll be a future way of loading data in PyTorch, but you can start to check it out now. \n",
"* To speed up deep learning models, you can do a few tricks to improve compute, memory and overhead computations, for more read the post [*Making Deep Learning Go Brrrr From First Principles*](https://horace.io/brrr_intro.html) by Horace He. "