"[Computer vision](https://en.wikipedia.org/wiki/Computer_vision) is the art of teaching a computer to see.\n",
"\n",
"For example, it could involve building a model to classify whether a photo is of a cat or a dog ([binary classification](https://developers.google.com/machine-learning/glossary#binary-classification)).\n",
"\n",
"Or whether a photo is of a cat, dog or chicken ([multi-class classification](https://developers.google.com/machine-learning/glossary#multi-class-classification)).\n",
"\n",
"Or identifying where a car appears in a video frame ([object detection](https://en.wikipedia.org/wiki/Object_detection)).\n",
"\n",
"Or figuring out where different objects in an image can be separated ([panoptic segmentation](https://arxiv.org/abs/1801.00868)).\n",
"*Example computer vision problems for binary classification, multiclass classification, object detection and segmentation.*"
]
},
{
"cell_type": "markdown",
"id": "19179a39-0c6c-40f7-9891-09e17d107ecf",
"metadata": {
"id": "19179a39-0c6c-40f7-9891-09e17d107ecf"
},
"source": [
"## Where does computer vision get used?\n",
"\n",
"If you use a smartphone, you've already used computer vision.\n",
"\n",
"Camera and photo apps use [computer vision to enhance](https://machinelearning.apple.com/research/panoptic-segmentation) and sort images.\n",
"\n",
"Modern cars use [computer vision](https://youtu.be/j0z4FweCy4M?t=2989) to avoid other cars and stay within lane lines.\n",
"\n",
"Manufacturers use computer vision to identify defects in various products.\n",
"\n",
"Security cameras use computer vision to detect potential intruders.\n",
"\n",
"In essence, anything that can described in a visual sense can be a potential computer vision problem."
]
},
{
"cell_type": "markdown",
"id": "412e8bd1-0e6b-4ad6-8506-b28a8f669dc1",
"metadata": {
"id": "412e8bd1-0e6b-4ad6-8506-b28a8f669dc1"
},
"source": [
"## What we're going to cover\n",
"\n",
"We're going to apply the PyTorch Workflow we've been learning in the past couple of sections to computer vision.\n",
"\n",
"\n",
"\n",
"Specifically, we're going to cover:\n",
"\n",
"| **Topic** | **Contents** |\n",
"| ----- | ----- |\n",
"| **0. Computer vision libraries in PyTorch** | PyTorch has a bunch of built-in helpful computer vision libraries, let's check them out. |\n",
"| **1. Load data** | To practice computer vision, we'll start with some images of different pieces of clothing from [FashionMNIST](https://github.com/zalandoresearch/fashion-mnist). |\n",
"| **2. Prepare data** | We've got some images, let's load them in with a [PyTorch `DataLoader`](https://pytorch.org/docs/stable/data.html) so we can use them with our training loop. |\n",
"| **3. Model 0: Building a baseline model** | Here we'll create a multi-class classification model to learn patterns in the data, we'll also choose a **loss function**, **optimizer** and build a **training loop**. | \n",
"| **4. Making predictions and evaluting model 0** | Let's make some predictions with our baseline model and evaluate them. |\n",
"| **5. Setup device agnostic code for future models** | It's best practice to write device-agnostic code, so let's set it up. |\n",
"| **6. Model 1: Adding non-linearity** | Experimenting is a large part of machine learning, let's try and improve upon our baseline model by adding non-linear layers. |\n",
"| **7. Model 2: Convolutional Neural Network (CNN)** | Time to get computer vision specific and introduce the powerful convolutional neural network architecture. |\n",
"| **8. Comparing our models** | We've built three different models, let's compare them. |\n",
"| **9. Evaluating our best model** | Let's make some predictons on random images and evaluate our best model. |\n",
"| **10. Making a confusion matrix** | A confusion matrix is a great way to evaluate a classification model, let's see how we can make one. |\n",
"| **11. Saving and loading the best performing model** | Since we might want to use our model for later, let's save it and make sure it loads back in correctly. |"
]
},
{
"cell_type": "markdown",
"id": "cddf62c3-f5e5-4f7e-852a-2ad6d38b7399",
"metadata": {
"id": "cddf62c3-f5e5-4f7e-852a-2ad6d38b7399"
},
"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",
"id": "a0bedcfc-e12a-4a81-9913-84c6a888742a",
"metadata": {
"id": "a0bedcfc-e12a-4a81-9913-84c6a888742a"
},
"source": [
"## 0. Computer vision libraries in PyTorch\n",
"\n",
"Before we get started writing code, let's talk about some PyTorch computer vision libraries you should be aware of.\n",
"\n",
"| PyTorch module | What does it do? |\n",
"| ----- | ----- |\n",
"| [`torchvision`](https://pytorch.org/vision/stable/index.html) | Contains datasets, model architectures and image transformations often used for computer vision problems. |\n",
"| [`torchvision.datasets`](https://pytorch.org/vision/stable/datasets.html) | Here you'll find many example computer vision datasets for a range of problems from image classification, object detection, image captioning, video classification and more. It also contains [a series of base classes for making custom datasets](https://pytorch.org/vision/stable/datasets.html#base-classes-for-custom-datasets). |\n",
"| [`torchvision.models`](https://pytorch.org/vision/stable/models.html) | This module contains well-performing and commonly used computer vision model architectures implemented in PyTorch, you can use these with your own problems. | \n",
"| [`torchvision.transforms`](https://pytorch.org/vision/stable/transforms.html) | Often images need to be transformed (turned into numbers/processed/augmented) before being used with a model, common image transformations are found here. | \n",
"| [`torch.utils.data.Dataset`](https://pytorch.org/docs/stable/data.html#torch.utils.data.Dataset) | Base dataset class for PyTorch. | \n",
"| [`torch.utils.data.DataLoader`](https://pytorch.org/docs/stable/data.html#module-torch.utils.data) | Creates a Python iterable over a dataset (created with `torch.utils.data.Dataset`). |\n",
"> **Note:** The `torch.utils.data.Dataset` and `torch.utils.data.DataLoader` classes aren't only for computer vision in PyTorch, they are capable of dealing with many different types of data.\n",
"\n",
"Now we've covered some of the most important PyTorch computer vision libraries, let's import the relevant dependencies.\n"
"To begin working on a computer vision problem, let's get a computer vision dataset.\n",
"\n",
"We're going to start with FashionMNIST.\n",
"\n",
"MNIST stands for Modified National Institute of Standards and Technology.\n",
"\n",
"The [original MNIST dataset](https://en.wikipedia.org/wiki/MNIST_database) contains thousands of examples of handwritten digits (from 0 to 9) and was used to build computer vision models to identify numbers for postal services.\n",
"\n",
"[FashionMNIST](https://github.com/zalandoresearch/fashion-mnist), made by Zalando Research, is a similar setup. \n",
"\n",
"Except it contains grayscale images of 10 different kinds of clothing.\n",
"\n",
"\n",
"*`torchvision.datasets` contains a lot of example datasets you can use to practice writing computer vision code on. FashionMNIST is one of those datasets. And since it has 10 different image classes (different types of clothing), it's a multi-class classification problem.*\n",
"\n",
"Later, we'll be building a computer vision neural network to identify the different styles of clothing in these images.\n",
"\n",
"PyTorch has a bunch of common computer vision datasets stored in `torchvision.datasets`.\n",
"\n",
"Including FashionMNIST in [`torchvision.datasets.FashionMNIST()`](https://pytorch.org/vision/main/generated/torchvision.datasets.FashionMNIST.html).\n",
"\n",
"To download it, we provide the following parameters:\n",
"* `root: str` - which folder do you want to download the data to?\n",
"* `train: Bool` - do you want the training or test split?\n",
"* `download: Bool` - should the data be downloaded?\n",
"* `transform: torchvision.transforms` - what transformations would you like to do on the data?\n",
"* `target_transform` - you can transform the targets (labels) if you like too.\n",
"\n",
"Many other datasets in `torchvision` have these parameter options."
"Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-images-idx3-ubyte.gz to data/FashionMNIST/raw/train-images-idx3-ubyte.gz\n"
"Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-labels-idx1-ubyte.gz to data/FashionMNIST/raw/train-labels-idx1-ubyte.gz\n"
"Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-images-idx3-ubyte.gz to data/FashionMNIST/raw/t10k-images-idx3-ubyte.gz\n"
"Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-labels-idx1-ubyte.gz to data/FashionMNIST/raw/t10k-labels-idx1-ubyte.gz\n"
"The shape of the image tensor is `[1, 28, 28]` or more specifically:\n",
"\n",
"```\n",
"[color_channels=1, height=28, width=28]\n",
"```\n",
"\n",
"Having `color_channels=1` means the image is grayscale.\n",
"\n",
"\n",
"*Various problems will have various input and output shapes. But the premise remains: encode data into numbers, build a model to find patterns in those numbers, convert those patterns into something meaningful.*\n",
"\n",
"If `color_channels=3`, the image comes in pixel values for red, green and blue (this is also known a the [RGB color model](https://en.wikipedia.org/wiki/RGB_color_model)).\n",
"\n",
"The order of our current tensor is often referred to as `CHW` (Color Channels, Height, Width).\n",
"\n",
"There's debate on whether images should be represented as `CHW` (color channels first) or `HWC` (color channels last).\n",
"\n",
"> **Note:** You'll also see `NCHW` and `NHWC` formats where `N` stands for *number of images*. For example if you have a `batch_size=32`, your tensor shape may be `[32, 1, 28, 28]`. We'll cover batch sizes later.\n",
"\n",
"PyTorch generally accepts `NCHW` (channels first) as the default for many operators.\n",
"\n",
"However, PyTorch also explains that `NHWC` (channels last) performs better and is [considered best practice](https://pytorch.org/blog/tensor-memory-format-matters/#pytorch-best-practice). \n",
"\n",
"For now, since our dataset and models are relatively small, this won't make too much of a difference.\n",
"\n",
"But keep it in mind for when you're working on larger image datasets and using convolutional neural networks (we'll see these later).\n",
"Hmmm, this dataset doesn't look too aesthetic.\n",
"\n",
"But the principles we're going to learn on how to build a model for it will be similar across a wide range of computer vision problems.\n",
"\n",
"In essence, taking pixel values and building a model to find patterns in them to use on future pixel values.\n",
"\n",
"Plus, even for this small dataset (yes, even 60,000 images in deep learning is considered quite small), could you write a program to classify each one of them?\n",
"\n",
"You probably could.\n",
"\n",
"But I think coding a model in PyTorch would be faster.\n",
"\n",
"> **Question:** Do you think the above data can be model with only straight (linear) lines? Or do you think you'd also need non-straight (non-linear) lines?"
]
},
{
"cell_type": "markdown",
"id": "43cdd23d-bd1f-4e8c-ba20-22d2b6ac14b1",
"metadata": {
"id": "43cdd23d-bd1f-4e8c-ba20-22d2b6ac14b1"
},
"source": [
"## 2. Prepare DataLoader\n",
"\n",
"Now we've got a dataset ready to go.\n",
"\n",
"The next step is to prepare it with a [`torch.utils.data.DataLoader`](https://pytorch.org/docs/stable/data.html#torch.utils.data.Dataset) or `DataLoader` for short.\n",
"\n",
"The `DataLoader` does what you think it might do.\n",
"\n",
"It helps load data into a model.\n",
"\n",
"For training and for inference.\n",
"\n",
"It turns a large `Dataset` into a Python iterable of smaller chunks.\n",
"\n",
"These smaller chunks are called **batches** or **mini-batches** and can be set by the `batch_size` parameter.\n",
"\n",
"Why do this?\n",
"\n",
"Because it's more computationally efficient.\n",
"\n",
"In an ideal world you could do the forward pass and backward pass across all of your data at once.\n",
"\n",
"But once you start using really large datasets, unless you've got infinite computing power, it's easier to break them up into batches.\n",
"\n",
"It also gives your model more opportunities to improve.\n",
"\n",
"With **mini-batches** (small portions of the data), gradient descent is performed more often per epoch (once per mini-batch rather than once per epoch).\n",
"\n",
"What's a good batch size?\n",
"\n",
"[32 is a good place to start](https://twitter.com/ylecun/status/989610208497360896?s=20&t=N96J_jotN--PYuJk2WcjMw) for a fair amount of problems.\n",
"\n",
"But since this is a value you can set (a **hyperparameter**) you can try all different kinds of values, though generally powers of 2 are used most often (e.g. 32, 64, 128, 256, 512).\n",
"\n",
"\n",
"*Batching FashionMNIST with a batch size of 32 and shuffle turned on. A similar batching process will occur for other datasets but will differ depending on the batch size.*\n",
"\n",
"Let's create `DataLoader`'s for our training and test sets. "
"Dataloaders: (<torch.utils.data.dataloader.DataLoader object at 0x7fc991463cd0>, <torch.utils.data.dataloader.DataLoader object at 0x7fc991475120>)\n",
"Length of train dataloader: 1875 batches of 32\n",
"Length of test dataloader: 313 batches of 32\n"
]
}
],
"source": [
"from torch.utils.data import DataLoader\n",
"\n",
"# Setup the batch size hyperparameter\n",
"BATCH_SIZE = 32\n",
"\n",
"# Turn datasets into iterables (batches)\n",
"train_dataloader = DataLoader(train_data, # dataset to turn into iterable\n",
" batch_size=BATCH_SIZE, # how many samples per batch? \n",
" shuffle=True # shuffle data every epoch?\n",
")\n",
"\n",
"test_dataloader = DataLoader(test_data,\n",
" batch_size=BATCH_SIZE,\n",
" shuffle=False # don't necessarily have to shuffle the testing data\n",
"We've got a baseline model class we can use, now let's instantiate a model.\n",
"\n",
"We'll need to set the following parameters:\n",
"* `input_shape=784` - this is how many features you've got going in the model, in our case, it's one for every pixel in the target image (28 pixels high by 28 pixels wide = 784 features).\n",
"* `hidden_units=10` - number of units/neurons in the hidden layer(s), this number could be whatever you want but to keep the model small we'll start with `10`.\n",
"* `output_shape=len(class_names)` - since we're working with a multi-class classification problem, we need an output neuron per class in our dataset.\n",
"\n",
"Let's create an instance of our model and send to the CPU for now (we'll run a small test for running `model_0` on CPU vs. a similar model on GPU soon)."
"model_0 = FashionMNISTModelV0(input_shape=784, # one for every pixel (28x28)\n",
" hidden_units=10, # how many units in the hiden layer\n",
" output_shape=len(class_names) # one for every class\n",
")\n",
"model_0.to(\"cpu\") # keep model on CPU to begin with "
]
},
{
"cell_type": "markdown",
"id": "03243179-1cdc-45d9-8b8c-82538ac02e9c",
"metadata": {
"id": "03243179-1cdc-45d9-8b8c-82538ac02e9c"
},
"source": [
"### 3.1 Setup loss, optimizer and evaluation metrics\n",
"\n",
"Since we're working on a classification problem, let's bring in our [`helper_functions.py` script](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/helper_functions.py) and subsequently the `accuracy_fn()` we defined in [notebook 02](https://www.learnpytorch.io/02_pytorch_classification/).\n",
"\n",
"> **Note:** Rather than importing and using our own accuracy function or evaluation metric(s), you could import various evaluation metrics from the [TorchMetrics package](https://torchmetrics.readthedocs.io/en/latest/)."
" with open(\"helper_functions.py\", \"wb\") as f:\n",
" f.write(request.content)"
]
},
{
"cell_type": "code",
"execution_count": 17,
"id": "ce3d13b8-f018-4b44-8bba-375074dc4c5f",
"metadata": {
"id": "ce3d13b8-f018-4b44-8bba-375074dc4c5f"
},
"outputs": [],
"source": [
"# Import accuracy metric\n",
"from helper_functions import accuracy_fn # Note: could also use torchmetrics.Accuracy(task = 'multiclass', num_classes=len(class_names)).to(device)\n",
"\n",
"# Setup loss function and optimizer\n",
"loss_fn = nn.CrossEntropyLoss() # this is also called \"criterion\"/\"cost function\" in some places\n",
"### 3.2 Creating a function to time our experiments\n",
"\n",
"Loss function and optimizer ready!\n",
"\n",
"It's time to start training a model.\n",
"\n",
"But how about we do a little experiment while we train.\n",
"\n",
"I mean, let's make a timing function to measure the time it takes our model to train on CPU versus using a GPU.\n",
"\n",
"We'll train this model on the CPU but the next one on the GPU and see what happens.\n",
"\n",
"Our timing function will import the [`timeit.default_timer()` function](https://docs.python.org/3/library/timeit.html#timeit.default_timer) from the Python [`timeit` module](https://docs.python.org/3/library/timeit.html)."
" \"\"\"Prints difference between start and end time.\n",
"\n",
" Args:\n",
" start (float): Start time of computation (preferred in timeit format). \n",
" end (float): End time of computation.\n",
" device ([type], optional): Device that compute is running on. Defaults to None.\n",
"\n",
" Returns:\n",
" float: time between start and end in seconds (higher is longer).\n",
" \"\"\"\n",
" total_time = end - start\n",
" print(f\"Train time on {device}: {total_time:.3f} seconds\")\n",
" return total_time"
]
},
{
"cell_type": "markdown",
"id": "07b9560e-f5dc-45d6-b3b2-ddae17a71b34",
"metadata": {
"id": "07b9560e-f5dc-45d6-b3b2-ddae17a71b34"
},
"source": [
"### 3.3 Creating a training loop and training a model on batches of data\n",
"\n",
"Beautiful!\n",
"\n",
"Looks like we've got all of the pieces of the puzzle ready to go, a timer, a loss function, an optimizer, a model and most importantly, some data.\n",
"\n",
"Let's now create a training loop and a testing loop to train and evaluate our model.\n",
"\n",
"We'll be using the same steps as the previous notebook(s), though since our data is now in batch form, we'll add another loop to loop through our data batches.\n",
"\n",
"Our data batches are contained within our `DataLoader`s, `train_dataloader` and `test_dataloader` for the training and test data splits respectively.\n",
"\n",
"A batch is `BATCH_SIZE` samples of `X` (features) and `y` (labels), since we're using `BATCH_SIZE=32`, our batches have 32 samples of images and targets.\n",
"\n",
"And since we're computing on batches of data, our loss and evaluation metrics will be calculated **per batch** rather than across the whole dataset.\n",
"\n",
"This means we'll have to divide our loss and accuracy values by the number of batches in each dataset's respective dataloader. \n",
"\n",
"Let's step through it: \n",
"1. Loop through epochs.\n",
"2. Loop through training batches, perform training steps, calculate the train loss *per batch*.\n",
"3. Loop through testing batches, perform testing steps, calculate the test loss *per batch*.\n",
"Nice! Looks like our baseline model did fairly well.\n",
"\n",
"It didn't take too long to train either, even just on the CPU, I wonder if it'll speed up on the GPU?\n",
"\n",
"Let's write some code to evaluate our model."
]
},
{
"cell_type": "markdown",
"id": "7442511b-bfe9-4ec7-9f5b-9c808f8e560b",
"metadata": {
"id": "7442511b-bfe9-4ec7-9f5b-9c808f8e560b"
},
"source": [
"## 4. Make predictions and get Model 0 results\n",
"\n",
"Since we're going to be building a few models, it's a good idea to write some code to evaluate them all in similar ways.\n",
"\n",
"Namely, let's create a function that takes in a trained model, a `DataLoader`, a loss function and an accuracy function.\n",
"\n",
"The function will use the model to make predictions on the data in the `DataLoader` and then we can evaluate those predictions using the loss function and accuracy function."
"We can use this dictionary to compare the baseline model results to other models later on."
]
},
{
"cell_type": "markdown",
"id": "3b76784d-4cdb-43d2-a6da-8e4da9a812a9",
"metadata": {
"id": "3b76784d-4cdb-43d2-a6da-8e4da9a812a9"
},
"source": [
"## 5. Setup device agnostic-code (for using a GPU if there is one)\n",
"We've seen how long it takes to train ma PyTorch model on 60,000 samples on CPU.\n",
"\n",
"> **Note:** Model training time is dependent on hardware used. Generally, more processors means faster training and smaller models on smaller datasets will often train faster than large models and large datasets.\n",
"\n",
"Now let's setup some [device-agnostic code](https://pytorch.org/docs/stable/notes/cuda.html#best-practices) for our models and data to run on GPU if it's available.\n",
"\n",
"If you're running this notebook on Google Colab, and you don't 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`."
"device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
"device"
]
},
{
"cell_type": "markdown",
"id": "514021a8-d6f2-47f3-ab50-55f844e42310",
"metadata": {
"id": "514021a8-d6f2-47f3-ab50-55f844e42310"
},
"source": [
"Beautiful!\n",
"\n",
"Let's build another model."
]
},
{
"cell_type": "markdown",
"id": "d7893907-5f82-4c5e-8fde-fa542a9f25af",
"metadata": {
"id": "d7893907-5f82-4c5e-8fde-fa542a9f25af"
},
"source": [
"## 6. Model 1: Building a better model with non-linearity\n",
"\n",
"We learned about [the power of non-linearity in notebook 02](https://www.learnpytorch.io/02_pytorch_classification/#6-the-missing-piece-non-linearity).\n",
"\n",
"Seeing the data we've been working with, do you think it needs non-linear functions?\n",
"\n",
"And remember, linear means straight and non-linear means non-straight.\n",
"\n",
"Let's find out.\n",
"\n",
"We'll do so by recreating a similar model to before, except this time we'll put non-linear functions (`nn.ReLU()`) in between each linear layer."
]
},
{
"cell_type": "code",
"execution_count": 22,
"id": "2ccce5f2-b1e5-47a6-a7f3-6bc096b35ffb",
"metadata": {
"id": "2ccce5f2-b1e5-47a6-a7f3-6bc096b35ffb"
},
"outputs": [],
"source": [
"# Create a model with non-linear and linear layers\n",
"Now let's instantiate it with the same settings we used before.\n",
"\n",
"We'll need `input_shape=784` (equal to the number of features of our image data), `hidden_units=10` (starting small and the same as our baseline model) and `output_shape=len(class_names)` (one output unit per class).\n",
"\n",
"> **Note:** Notice how we kept most of the settings of our model the same except for one change: adding non-linear layers. This is a standard practice for running a series of machine learning experiments, change one thing and see what happens, then do it again, again, again."
"model_1 = FashionMNISTModelV1(input_shape=784, # number of input features\n",
" hidden_units=10,\n",
" output_shape=len(class_names) # number of output classes desired\n",
").to(device) # send model to GPU if it's available\n",
"next(model_1.parameters()).device # check model device"
]
},
{
"cell_type": "markdown",
"id": "b54a4e9d-a7ad-404c-920f-485fcff18a92",
"metadata": {
"id": "b54a4e9d-a7ad-404c-920f-485fcff18a92"
},
"source": [
"### 6.1 Setup loss, optimizer and evaluation metrics\n",
"\n",
"As usual, we'll setup a loss function, an optimizer and an evaluation metric (we could do multiple evaluation metrics but we'll stick with accuracy for now)."
"### 6.2 Functionizing training and test loops\n",
"\n",
"So far we've been writing train and test loops over and over. \n",
"\n",
"Let's write them again but this time we'll put them in functions so they can be called again and again.\n",
"\n",
"And because we're using device-agnostic code now, we'll be sure to call `.to(device)` on our feature (`X`) and target (`y`) tensors.\n",
"\n",
"For the training loop we'll create a function called `train_step()` which takes in a model, a `DataLoader` a loss function and an optimizer.\n",
"\n",
"The testing loop will be similar but it'll be called `test_step()` and it'll take in a model, a `DataLoader`, a loss function and an evaluation function.\n",
"\n",
"> **Note:** Since these are functions, you can customize them in any way you like. What we're making here can be considered barebones training and testing functions for our specific classification use case."
]
},
{
"cell_type": "code",
"execution_count": 25,
"id": "3d239ed2-4028-4603-8db3-ffca2b727819",
"metadata": {
"id": "3d239ed2-4028-4603-8db3-ffca2b727819"
},
"outputs": [],
"source": [
"def train_step(model: torch.nn.Module,\n",
" data_loader: torch.utils.data.DataLoader,\n",
" loss_fn: torch.nn.Module,\n",
" optimizer: torch.optim.Optimizer,\n",
" accuracy_fn,\n",
" device: torch.device = device):\n",
" train_loss, train_acc = 0, 0\n",
" model.to(device)\n",
" for batch, (X, y) in enumerate(data_loader):\n",
" # Send data to GPU\n",
" X, y = X.to(device), y.to(device)\n",
"\n",
" # 1. Forward pass\n",
" y_pred = model(X)\n",
"\n",
" # 2. Calculate loss\n",
" loss = loss_fn(y_pred, y)\n",
" train_loss += loss\n",
" train_acc += accuracy_fn(y_true=y,\n",
" y_pred=y_pred.argmax(dim=1)) # Go from logits -> pred labels\n",
"\n",
" # 3. Optimizer zero grad\n",
" optimizer.zero_grad()\n",
"\n",
" # 4. Loss backward\n",
" loss.backward()\n",
"\n",
" # 5. Optimizer step\n",
" optimizer.step()\n",
"\n",
" # Calculate loss and accuracy per epoch and print out what's happening\n",
" y_pred=test_pred.argmax(dim=1) # Go from logits -> pred labels\n",
" )\n",
" \n",
" # Adjust metrics and print out\n",
" test_loss /= len(data_loader)\n",
" test_acc /= len(data_loader)\n",
" print(f\"Test loss: {test_loss:.5f} | Test accuracy: {test_acc:.2f}%\\n\")"
]
},
{
"cell_type": "markdown",
"id": "e44121b6-c4be-4909-9175-dc9bd8dc6273",
"metadata": {
"id": "e44121b6-c4be-4909-9175-dc9bd8dc6273"
},
"source": [
"Woohoo!\n",
"\n",
"Now we've got some functions for training and testing our model, let's run them.\n",
"\n",
"We'll do so inside another loop for each epoch.\n",
"\n",
"That way for each epoch we're going a training and a testing step.\n",
"\n",
"> **Note:** You can customize how often you do a testing step. Sometimes people do them every five epochs or 10 epochs or in our case, every epoch.\n",
"\n",
"Let's also time things to see how long our code takes to run on the GPU."
"Our model trained but the training time took longer?\n",
"\n",
"> **Note:** The training time on CUDA vs CPU will depend largely on the quality of the CPU/GPU you're using. Read on for a more explained answer.\n",
"\n",
"> **Question:** \"I used a a GPU but my model didn't train faster, why might that be?\"\n",
">\n",
"> **Answer:** Well, one reason could be because your dataset and model are both so small (like the dataset and model we're working with) the benefits of using a GPU are outweighed by the time it actually takes to transfer the data there.\n",
"> \n",
"> There's a small bottleneck between copying data from the CPU memory (default) to the GPU memory.\n",
">\n",
"> So for smaller models and datasets, the CPU might actually be the optimal place to compute on.\n",
">\n",
"> But for larger datasets and models, the speed of computing the GPU can offer usually far outweighs the cost of getting the data there.\n",
">\n",
"> However, this is largely dependant on the hardware you're using. With practice, you will get used to where the best place to train your models is. \n",
"\n",
"Let's evaluate our trained `model_1` using our `eval_model()` function and see how it went."
"\u001b[0;32m<ipython-input-27-93fed76e63a5>\u001b[0m in \u001b[0;36m<cell line: 4>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;31m# Note: This will error due to `eval_model()` not using device agnostic code\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m model_1_results = eval_model(model=model_1, \n\u001b[0m\u001b[1;32m 5\u001b[0m \u001b[0mdata_loader\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mtest_dataloader\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0mloss_fn\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mloss_fn\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m<ipython-input-20-885bc9be9cde>\u001b[0m in \u001b[0;36meval_model\u001b[0;34m(model, data_loader, loss_fn, accuracy_fn)\u001b[0m\n\u001b[1;32m 20\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mX\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0my\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mdata_loader\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 21\u001b[0m \u001b[0;31m# Make predictions with the model\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 22\u001b[0;31m \u001b[0my_pred\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mmodel\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mX\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 23\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 24\u001b[0m \u001b[0;31m# Accumulate the loss and accuracy values per batch\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py\u001b[0m in \u001b[0;36m_call_impl\u001b[0;34m(self, *args, **kwargs)\u001b[0m\n\u001b[1;32m 1499\u001b[0m \u001b[0;32mor\u001b[0m \u001b[0m_global_backward_pre_hooks\u001b[0m \u001b[0;32mor\u001b[0m \u001b[0m_global_backward_hooks\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1500\u001b[0m or _global_forward_hooks or _global_forward_pre_hooks):\n\u001b[0;32m-> 1501\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mforward_call\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 1502\u001b[0m \u001b[0;31m# Do not call functions when jit is used\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1503\u001b[0m \u001b[0mfull_backward_hooks\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mnon_full_backward_hooks\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py\u001b[0m in \u001b[0;36m_call_impl\u001b[0;34m(self, *args, **kwargs)\u001b[0m\n\u001b[1;32m 1499\u001b[0m \u001b[0;32mor\u001b[0m \u001b[0m_global_backward_pre_hooks\u001b[0m \u001b[0;32mor\u001b[0m \u001b[0m_global_backward_hooks\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1500\u001b[0m or _global_forward_hooks or _global_forward_pre_hooks):\n\u001b[0;32m-> 1501\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mforward_call\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 1502\u001b[0m \u001b[0;31m# Do not call functions when jit is used\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1503\u001b[0m \u001b[0mfull_backward_hooks\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mnon_full_backward_hooks\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py\u001b[0m in \u001b[0;36m_call_impl\u001b[0;34m(self, *args, **kwargs)\u001b[0m\n\u001b[1;32m 1499\u001b[0m \u001b[0;32mor\u001b[0m \u001b[0m_global_backward_pre_hooks\u001b[0m \u001b[0;32mor\u001b[0m \u001b[0m_global_backward_hooks\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1500\u001b[0m or _global_forward_hooks or _global_forward_pre_hooks):\n\u001b[0;32m-> 1501\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mforward_call\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 1502\u001b[0m \u001b[0;31m# Do not call functions when jit is used\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1503\u001b[0m \u001b[0mfull_backward_hooks\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mnon_full_backward_hooks\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;31mRuntimeError\u001b[0m: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! (when checking argument for argument mat1 in method wrapper_CUDA_addmm)"
]
}
],
"source": [
"torch.manual_seed(42)\n",
"\n",
"# Note: This will error due to `eval_model()` not using device agnostic code \n",
"model_1_results = eval_model(model=model_1, \n",
" data_loader=test_dataloader,\n",
" loss_fn=loss_fn, \n",
" accuracy_fn=accuracy_fn) \n",
"model_1_results "
]
},
{
"cell_type": "markdown",
"id": "6a3481a5-489d-4db9-ac95-c3ce385978b7",
"metadata": {
"id": "6a3481a5-489d-4db9-ac95-c3ce385978b7"
},
"source": [
"Oh no! \n",
"\n",
"It looks like our `eval_model()` function errors out with:\n",
"\n",
"> `RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! (when checking argument for argument mat1 in method wrapper_addmm)`\n",
"\n",
"It's because we've setup our data and model to use device-agnostic code but not our evaluation function.\n",
"\n",
"How about we fix that by passing a target `device` parameter to our `eval_model()` function?\n",
"Where the contents of `[Convolutional layer -> activation layer -> pooling layer]` can be upscaled and repeated multiple times, depending on requirements. "
]
},
{
"cell_type": "markdown",
"id": "9c358955-1d20-4903-b872-a239d2753d88",
"metadata": {
"id": "9c358955-1d20-4903-b872-a239d2753d88"
},
"source": [
"### What model should I use?\n",
"\n",
"> **Question:** Wait, you say CNN's are good for images, are there any other model types I should be aware of?\n",
"\n",
"Good question.\n",
"\n",
"This table is a good general guide for which model to use (though there are exceptions).\n",
"\n",
"| **Problem type** | **Model to use (generally)** | **Code example** |\n",
"| ----- | ----- | ----- |\n",
"| Structured data (Excel spreadsheets, row and column data) | Gradient boosted models, Random Forests, XGBoost | [`sklearn.ensemble`](https://scikit-learn.org/stable/modules/classes.html#module-sklearn.ensemble), [XGBoost library](https://xgboost.readthedocs.io/en/stable/) |\n",
"> **Note:** The table above is only for reference, the model you end up using will be highly dependant on the problem you're working on and the constraints you have (amount of data, latency requirements).\n",
"\n",
"Enough talking about models, let's now build a CNN that replicates the model on the [CNN Explainer website](https://poloclub.github.io/cnn-explainer/).\n",
"\n",
"\n",
"\n",
"To do so, we'll leverage the [`nn.Conv2d()`](https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html) and [`nn.MaxPool2d()`](https://pytorch.org/docs/stable/generated/torch.nn.MaxPool2d.html) layers from `torch.nn`.\n"
"What we've done is a common practice in machine learning.\n",
"\n",
"Find a model architecture somewhere and replicate it with code. "
]
},
{
"cell_type": "markdown",
"id": "6478cc5a-7b33-425d-9ab3-6d40168a1aee",
"metadata": {
"id": "6478cc5a-7b33-425d-9ab3-6d40168a1aee"
},
"source": [
"### 7.1 Stepping through `nn.Conv2d()`\n",
"\n",
"We could start using our model above and see what happens but let's first step through the two new layers we've added:\n",
"* [`nn.Conv2d()`](https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html), also known as a convolutional layer.\n",
"* [`nn.MaxPool2d()`](https://pytorch.org/docs/stable/generated/torch.nn.MaxPool2d.html), also known as a max pooling layer.\n",
"\n",
"> **Question:** What does the \"2d\" in `nn.Conv2d()` stand for?\n",
">\n",
"> The 2d is for 2-dimensional data. As in, our images have two dimensions: height and width. Yes, there's color channel dimension but each of the color channel dimensions have two dimensions too: height and width.\n",
">\n",
"> For other dimensional data (such as 1D for text or 3D for 3D objects) there's also `nn.Conv1d()` and `nn.Conv3d()`. \n",
"\n",
"To test the layers out, let's create some toy data just like the data used on CNN Explainer."
"Let's create an example `nn.Conv2d()` with various parameters:\n",
"* `in_channels` (int) - Number of channels in the input image.\n",
"* `out_channels` (int) - Number of channels produced by the convolution.\n",
"* `kernel_size` (int or tuple) - Size of the convolving kernel/filter.\n",
"* `stride` (int or tuple, optional) - How big of a step the convolving kernel takes at a time. Default: 1.\n",
"* `padding` (int, tuple, str) - Padding added to all four sides of input. Default: 0.\n",
"\n",
"\n",
"\n",
"*Example of what happens when you change the hyperparameters of a `nn.Conv2d()` layer.*"
"# Create a convolutional layer with same dimensions as TinyVGG \n",
"# (try changing any of the parameters and see what happens)\n",
"conv_layer = nn.Conv2d(in_channels=3,\n",
" out_channels=10,\n",
" kernel_size=3,\n",
" stride=1,\n",
" padding=0) # also try using \"valid\" or \"same\" here \n",
"\n",
"# Pass the data through the convolutional layer\n",
"conv_layer(test_image) # Note: If running PyTorch <1.11.0, this will error because of shape issues (nn.Conv.2d() expects a 4d tensor as input) "
]
},
{
"cell_type": "markdown",
"id": "cb0184ad-5c16-4e1c-bcfa-70ecf15377da",
"metadata": {
"id": "cb0184ad-5c16-4e1c-bcfa-70ecf15377da"
},
"source": [
"If we try to pass a single image in, we get a shape mismatch error:\n",
"\n",
"> `RuntimeError: Expected 4-dimensional input for 4-dimensional weight [10, 3, 3, 3], but got 3-dimensional input of size [3, 64, 64] instead`\n",
">\n",
"> **Note:** If you're running PyTorch 1.11.0+, this error won't occur.\n",
"\n",
"This is because our `nn.Conv2d()` layer expects a 4-dimensional tensor as input with size `(N, C, H, W)` or `[batch_size, color_channels, height, width]`.\n",
"\n",
"Right now our single image `test_image` only has a shape of `[color_channels, height, width]` or `[3, 64, 64]`.\n",
"\n",
"We can fix this for a single image using `test_image.unsqueeze(dim=0)` to add an extra dimension for `N`."
"# Pass test image with extra dimension through conv_layer\n",
"conv_layer(test_image.unsqueeze(dim=0)).shape"
]
},
{
"cell_type": "markdown",
"id": "181df81b-7c5a-46cc-b8d5-a592bf755a13",
"metadata": {
"id": "181df81b-7c5a-46cc-b8d5-a592bf755a13"
},
"source": [
"Hmm, notice what happens to our shape (the same shape as the first layer of TinyVGG on [CNN Explainer](https://poloclub.github.io/cnn-explainer/)), we get different channel sizes as well as different pixel sizes.\n",
"# Create a new conv_layer with different values (try setting these to whatever you like)\n",
"conv_layer_2 = nn.Conv2d(in_channels=3, # same number of color channels as our input image\n",
" out_channels=10,\n",
" kernel_size=(5, 5), # kernel is usually a square so a tuple also works\n",
" stride=2,\n",
" padding=0)\n",
"\n",
"# Pass single image through new conv_layer_2 (this calls nn.Conv2d()'s forward() method on the input)\n",
"conv_layer_2(test_image.unsqueeze(dim=0)).shape"
]
},
{
"cell_type": "markdown",
"id": "b27dbdbb-3e32-4ffa-803e-cf943d96c72b",
"metadata": {
"id": "b27dbdbb-3e32-4ffa-803e-cf943d96c72b"
},
"source": [
"Woah, we get another shape change.\n",
"\n",
"Now our image is of shape `[1, 10, 30, 30]` (it will be different if you use different values) or `[batch_size=1, color_channels=10, height=30, width=30]`.\n",
"\n",
"What's going on here?\n",
"\n",
"Behind the scenes, our `nn.Conv2d()` is compressing the information stored in the image.\n",
"\n",
"It does this by performing operations on the input (our test image) against its internal parameters.\n",
"\n",
"The goal of this is similar to all of the other neural networks we've been building.\n",
"\n",
"Data goes in and the layers try to update their internal parameters (patterns) to lower the loss function thanks to some help of the optimizer.\n",
"\n",
"The only difference is *how* the different layers calculate their parameter updates or in PyTorch terms, the operation present in the layer `forward()` method.\n",
"\n",
"If we check out our `conv_layer_2.state_dict()` we'll find a similar weight and bias setup as we've seen before."
"> **Question:** What should we set the parameters of our `nn.Conv2d()` layers?\n",
">\n",
"> That's a good one. But similar to many other things in machine learning, the values of these aren't set in stone (and recall, because these values are ones we can set ourselves, they're referred to as \"**hyperparameters**\"). \n",
">\n",
"> The best way to find out is to try out different values and see how they effect your model's performance.\n",
">\n",
"> Or even better, find a working example on a problem similar to yours (like we've done with TinyVGG) and copy it. \n",
"\n",
"We're working with a different of layer here to what we've seen before.\n",
"\n",
"But the premise remains the same: start with random numbers and update them to better represent the data."
]
},
{
"cell_type": "markdown",
"id": "6370d45d-ca44-4fa0-a2d7-efaf0a207b91",
"metadata": {
"id": "6370d45d-ca44-4fa0-a2d7-efaf0a207b91"
},
"source": [
"### 7.2 Stepping through `nn.MaxPool2d()`\n",
"Now let's check out what happens when we move data through `nn.MaxPool2d()`."
"print(f\"\\nMax pool tensor:\\n{max_pool_tensor} <- this is the maximum value from random_tensor\")\n",
"print(f\"Max pool tensor shape: {max_pool_tensor.shape}\")"
]
},
{
"cell_type": "markdown",
"id": "002e586e-dcb3-40fe-a7dd-a1c18a3b8da0",
"metadata": {
"id": "002e586e-dcb3-40fe-a7dd-a1c18a3b8da0"
},
"source": [
"Notice the final two dimensions between `random_tensor` and `max_pool_tensor`, they go from `[2, 2]` to `[1, 1]`.\n",
"\n",
"In essence, they get halved.\n",
"\n",
"And the change would be different for different values of `kernel_size` for `nn.MaxPool2d()`.\n",
"\n",
"Also notice the value leftover in `max_pool_tensor` is the **maximum** value from `random_tensor`.\n",
"\n",
"What's happening here?\n",
"\n",
"This is another important piece of the puzzle of neural networks.\n",
"\n",
"Essentially, **every layer in a neural network is trying to compress data from higher dimensional space to lower dimensional space**. \n",
"\n",
"In other words, take a lot of numbers (raw data) and learn patterns in those numbers, patterns that are predictive whilst also being *smaller* in size than the original values.\n",
"\n",
"From an artificial intelligence perspective, you could consider the whole goal of a neural network to *compress* information.\n",
"\n",
"\n",
"\n",
"This means, that from the point of view of a neural network, intelligence is compression.\n",
"\n",
"This is the idea of the use of a `nn.MaxPool2d()` layer: take the maximum value from a portion of a tensor and disregard the rest.\n",
"\n",
"In essence, lowering the dimensionality of a tensor whilst still retaining a (hopefully) significant portion of the information.\n",
"\n",
"It is the same story for a `nn.Conv2d()` layer.\n",
"\n",
"Except instead of just taking the maximum, the `nn.Conv2d()` performs a convolutional operation on the data (see this in action on the [CNN Explainer webpage](https://poloclub.github.io/cnn-explainer/)).\n",
"\n",
"> **Exercise:** What do you think the [`nn.AvgPool2d()`](https://pytorch.org/docs/stable/generated/torch.nn.AvgPool2d.html) layer does? Try making a random tensor like we did above and passing it through. Check the input and output shapes as well as the input and output values.\n",
"\n",
"> **Extra-curriculum:** Lookup \"most common convolutional neural networks\", what architectures do you find? Are any of them contained within the [`torchvision.models`](https://pytorch.org/vision/stable/models.html) library? What do you think you could do with these?"
]
},
{
"cell_type": "markdown",
"id": "39a3c646-52f0-4f4b-8527-2fc33d0dfb13",
"metadata": {
"id": "39a3c646-52f0-4f4b-8527-2fc33d0dfb13"
},
"source": [
"### 7.3 Setup a loss function and optimizer for `model_2`\n",
"\n",
"We've stepped through the layers in our first CNN enough.\n",
"\n",
"But remember, if something still isn't clear, try starting small.\n",
"\n",
"Pick a single layer of a model, pass some data through it and see what happens.\n",
"\n",
"Now it's time to move forward and get to training!\n",
"\n",
"Let's setup a loss function and an optimizer.\n",
"\n",
"We'll use the functions as before, `nn.CrossEntropyLoss()` as the loss function (since we're working with multi-class classification data).\n",
"\n",
"And `torch.optim.SGD()` as the optimizer to optimize `model_2.parameters()` with a learning rate of `0.1`."
" sample = torch.unsqueeze(sample, dim=0).to(device) # Add an extra dimension and send sample to device\n",
"\n",
" # Forward pass (model outputs raw logit)\n",
" pred_logit = model(sample)\n",
"\n",
" # Get prediction probability (logit -> prediction probability)\n",
" pred_prob = torch.softmax(pred_logit.squeeze(), dim=0) # note: perform softmax on the \"logits\" dimension, not \"batch\" dimension (in this case we have a batch size of 1, so can perform on dim=0)\n",
"\n",
" # Get pred_prob off GPU for further calculations\n",
" pred_probs.append(pred_prob.cpu())\n",
" \n",
" # Stack the pred_probs to turn list into a tensor\n",
"# Make predictions on test samples with model 2\n",
"pred_probs= make_predictions(model=model_2, \n",
" data=test_samples)\n",
"\n",
"# View first two prediction probabilities list\n",
"pred_probs[:2]"
]
},
{
"cell_type": "markdown",
"id": "22d3c080-4eb6-4b5d-a5c4-2319e78228af",
"metadata": {
"id": "22d3c080-4eb6-4b5d-a5c4-2319e78228af"
},
"source": [
"Excellent!\n",
"\n",
"And now we can go from prediction probabilities to prediction labels by taking the `torch.argmax()` of the output of the `torch.softmax()` activation function."
" # Check for equality and change title colour accordingly\n",
" if pred_label == truth_label:\n",
" plt.title(title_text, fontsize=10, c=\"g\") # green text if correct\n",
" else:\n",
" plt.title(title_text, fontsize=10, c=\"r\") # red text if wrong\n",
" plt.axis(False);"
]
},
{
"cell_type": "markdown",
"id": "5ce6dc44-90a5-48c3-91a5-810fa084d98b",
"metadata": {
"id": "5ce6dc44-90a5-48c3-91a5-810fa084d98b"
},
"source": [
"Well, well, well, doesn't that look good!\n",
"\n",
"Not bad for a couple dozen lines of PyTorch code!"
]
},
{
"cell_type": "markdown",
"id": "ab108078-6770-4cb9-ac62-a761ff159aba",
"metadata": {
"id": "ab108078-6770-4cb9-ac62-a761ff159aba"
},
"source": [
"## 10. Making a confusion matrix for further prediction evaluation\n",
"\n",
"There are many [different evaluation metrics](https://www.learnpytorch.io/02_pytorch_classification/#9-more-classification-evaluation-metrics) we can use for classification problems. \n",
"\n",
"One of the most visual is a [confusion matrix](https://www.dataschool.io/simple-guide-to-confusion-matrix-terminology/).\n",
"\n",
"A confusion matrix shows you where your classification model got confused between predicitons and true labels.\n",
"\n",
"To make a confusion matrix, we'll go through three steps:\n",
"1. Make predictions with our trained model, `model_2` (a confusion matrix compares predictions to true labels).\n",
"2. Make a confusion matrix using [`torchmetrics.ConfusionMatrix`](https://torchmetrics.readthedocs.io/en/latest/references/modules.html?highlight=confusion#confusionmatrix).\n",
"3. Plot the confusion matrix using [`mlxtend.plotting.plot_confusion_matrix()`](http://rasbt.github.io/mlxtend/user_guide/plotting/plot_confusion_matrix/).\n",
"\n",
"Let's start by making predictions with our trained model."
" y_pred = torch.softmax(y_logit, dim=1).argmax(dim=1) # note: perform softmax on the \"logits\" dimension, not \"batch\" dimension (in this case we have a batch size of 32, so can perform on dim=1)\n",
" # Put predictions on CPU for evaluation\n",
" y_preds.append(y_pred.cpu())\n",
"# Concatenate list of predictions into a tensor\n",
"y_pred_tensor = torch.cat(y_preds)"
]
},
{
"cell_type": "markdown",
"id": "362002d9-ec41-4c74-a210-b5d4f53410c4",
"metadata": {
"id": "362002d9-ec41-4c74-a210-b5d4f53410c4"
},
"source": [
"Wonderful!\n",
"\n",
"Now we've got predictions, let's go through steps 2 & 3:\n",
"2. Make a confusion matrix using [`torchmetrics.ConfusionMatrix`](https://torchmetrics.readthedocs.io/en/latest/references/modules.html?highlight=confusion#confusionmatrix).\n",
"3. Plot the confusion matrix using [`mlxtend.plotting.plot_confusion_matrix()`](http://rasbt.github.io/mlxtend/user_guide/plotting/plot_confusion_matrix/).\n",
"\n",
"First we'll need to make sure we've got `torchmetrics` and `mlxtend` installed (these two libraries will help us make and visual a confusion matrix).\n",
"\n",
"> **Note:** If you're using Google Colab, the default version of `mlxtend` installed is 0.14.0 (as of March 2022), however, for the parameters of the `plot_confusion_matrix()` function we'd like use, we need 0.19.0 or higher. "
"assert int(mlxtend.__version__.split(\".\")[1]) >= 19 # should be version 0.19.0 or higher"
]
},
{
"cell_type": "markdown",
"id": "c91b9346-e25f-48ab-967e-425649331dc6",
"metadata": {
"id": "c91b9346-e25f-48ab-967e-425649331dc6"
},
"source": [
"`torchmetrics` and `mlxtend` installed, let's make a confusion matrix!\n",
"\n",
"First we'll create a `torchmetrics.ConfusionMatrix` instance telling it how many classes we're dealing with by setting `num_classes=len(class_names)`.\n",
"\n",
"Then we'll create a confusion matrix (in tensor format) by passing our instance our model's predictions (`preds=y_pred_tensor`) and targets (`target=test_data.targets`).\n",
"\n",
"Finally we can plot our confision matrix using the `plot_confusion_matrix()` function from `mlxtend.plotting`."
" conf_mat=confmat_tensor.numpy(), # matplotlib likes working with NumPy \n",
" class_names=class_names, # turn the row and column labels into class names\n",
" figsize=(10, 7)\n",
");"
]
},
{
"cell_type": "markdown",
"id": "381c1c93-df30-451c-b65e-5d4c1680dc30",
"metadata": {
"id": "381c1c93-df30-451c-b65e-5d4c1680dc30"
},
"source": [
"Woah! Doesn't that look good?\n",
"\n",
"We can see our model does fairly well since most of the dark squares are down the diagonal from top left to bottom right (and ideal model will have only values in these squares and 0 everywhere else).\n",
"\n",
"The model gets most \"confused\" on classes that are similar, for example predicting \"Pullover\" for images that are actually labelled \"Shirt\".\n",
"\n",
"And the same for predicting \"Shirt\" for classes that are actually labelled \"T-shirt/top\".\n",
"\n",
"This kind of information is often more helpful than a single accuracy metric because it tells use *where* a model is getting things wrong.\n",
"\n",
"It also hints at *why* the model may be getting certain things wrong.\n",
"\n",
"It's understandable the model sometimes predicts \"Shirt\" for images labelled \"T-shirt/top\".\n",
"\n",
"We can use this kind of information to further inspect our models and data to see how it could be improved.\n",
"\n",
"> **Exercise:** Use the trained `model_2` to make predictions on the test FashionMNIST dataset. Then plot some predictions where the model was wrong alongside what the label of the image should've been. After visualing these predictions do you think it's more of a modelling error or a data error? As in, could the model do better or are the labels of the data too close to each other (e.g. a \"Shirt\" label is too close to \"T-shirt/top\")?"
]
},
{
"cell_type": "markdown",
"id": "25818e83-89de-496d-8b56-af4fc9f2acc5",
"metadata": {
"id": "25818e83-89de-496d-8b56-af4fc9f2acc5"
},
"source": [
"## 11. Save and load best performing model\n",
"\n",
"Let's finish this section off by saving and loading in our best performing model.\n",
"\n",
"Recall from [notebook 01](https://www.learnpytorch.io/01_pytorch_workflow/#5-saving-and-loading-a-pytorch-model) we can save and load a PyTorch model using a combination of:\n",
"* `torch.save` - a function to save a whole PyTorch model or a model's `state_dict()`. \n",
"* `torch.load` - a function to load in a saved PyTorch object.\n",
"* `torch.nn.Module.load_state_dict()` - a function to load a saved `state_dict()` into an existing model instance.\n",
"\n",
"You can see more of these three in the [PyTorch saving and loading models documentation](https://pytorch.org/tutorials/beginner/saving_loading_models.html).\n",
"\n",
"For now, let's save our `model_2`'s `state_dict()` then load it back in and evaluate it to make sure the save and load went correctly. "
"print(f\"Saving model to: {MODEL_SAVE_PATH}\")\n",
"torch.save(obj=model_2.state_dict(), # only saving the state_dict() only saves the learned parameters\n",
" f=MODEL_SAVE_PATH)"
]
},
{
"cell_type": "markdown",
"id": "a1542284-8132-42ba-b00d-57e9b9037e4e",
"metadata": {
"id": "a1542284-8132-42ba-b00d-57e9b9037e4e"
},
"source": [
"Now we've got a saved model `state_dict()` we can load it back in using a combination of `load_state_dict()` and `torch.load()`.\n",
"\n",
"Since we're using `load_state_dict()`, we'll need to create a new instance of `FashionMNISTModelV2()` with the same input parameters as our saved model `state_dict()`."
]
},
{
"cell_type": "code",
"execution_count": 58,
"id": "634a8f7a-3013-4b45-b365-49b286d3c478",
"metadata": {
"id": "634a8f7a-3013-4b45-b365-49b286d3c478"
},
"outputs": [],
"source": [
"# Create a new instance of FashionMNISTModelV2 (the same class as our saved state_dict())\n",
"# Note: loading model will error if the shapes here aren't the same as the saved version\n",
"We can find out if two tensors are close to each other using `torch.isclose()` and passing in a tolerance level of closeness via the parameters `atol` (absolute tolerance) and `rtol` (relative tolerance).\n",
"\n",
"If our model's results are close, the output of `torch.isclose()` should be true."
"All of the exercises are focused on practicing the code in the sections above.\n",
"\n",
"You should be able to complete them by referencing each section or by following the resource(s) linked.\n",
"\n",
"All exercises should be completed using [device-agnostic code](https://pytorch.org/docs/stable/notes/cuda.html#device-agnostic-code).\n",
"\n",
"**Resources:**\n",
"* [Exercise template notebook for 03](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/extras/exercises/03_pytorch_computer_vision_exercises.ipynb)\n",
"* [Example solutions notebook for 03](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/extras/solutions/03_pytorch_computer_vision_exercise_solutions.ipynb) (try the exercises *before* looking at this)\n",
"\n",
"1. What are 3 areas in industry where computer vision is currently being used?\n",
"2. Search \"what is overfitting in machine learning\" and write down a sentence about what you find. \n",
"3. Search \"ways to prevent overfitting in machine learning\", write down 3 of the things you find and a sentence about each. **Note:** there are lots of these, so don't worry too much about all of them, just pick 3 and start with those.\n",
"4. Spend 20-minutes reading and clicking through the [CNN Explainer website](https://poloclub.github.io/cnn-explainer/).\n",
" * Upload your own example image using the \"upload\" button and see what happens in each layer of a CNN as your image passes through it.\n",
"5. Load the [`torchvision.datasets.MNIST()`](https://pytorch.org/vision/stable/generated/torchvision.datasets.MNIST.html#torchvision.datasets.MNIST) train and test datasets.\n",
"6. Visualize at least 5 different samples of the MNIST training dataset.\n",
"7. Turn the MNIST train and test datasets into dataloaders using `torch.utils.data.DataLoader`, set the `batch_size=32`.\n",
"8. Recreate `model_2` used in this notebook (the same model from the [CNN Explainer website](https://poloclub.github.io/cnn-explainer/), also known as TinyVGG) capable of fitting on the MNIST dataset.\n",
"9. Train the model you built in exercise 8. on CPU and GPU and see how long it takes on each.\n",
"10. Make predictions using your trained model and visualize at least 5 of them comparing the prediciton to the target label.\n",
"11. Plot a confusion matrix comparing your model's predictions to the truth labels.\n",
"12. Create a random tensor of shape `[1, 3, 64, 64]` and pass it through a `nn.Conv2d()` layer with various hyperparameter settings (these can be any settings you choose), what do you notice if the `kernel_size` parameter goes up and down?\n",
"13. Use a model similar to the trained `model_2` from this notebook to make predictions on the test [`torchvision.datasets.FashionMNIST`](https://pytorch.org/vision/main/generated/torchvision.datasets.FashionMNIST.html) dataset. \n",
" * Then plot some predictions where the model was wrong alongside what the label of the image should've been. \n",
" * After visualing these predictions do you think it's more of a modelling error or a data error? \n",
" * As in, could the model do better or are the labels of the data too close to each other (e.g. a \"Shirt\" label is too close to \"T-shirt/top\")?\n",
"\n",
"## Extra-curriculum\n",
"* **Watch:** [MIT's Introduction to Deep Computer Vision](https://www.youtube.com/watch?v=iaSUYvmCekI&list=PLtBw6njQRU-rwp5__7C0oIVt26ZgjG9NI&index=3) lecture. This will give you a great intuition behind convolutional neural networks.\n",
"* Spend 10-minutes clicking thorugh the different options of the [PyTorch vision library](https://pytorch.org/vision/stable/index.html), what different modules are available?\n",
"* Lookup \"most common convolutional neural networks\", what architectures do you find? Are any of them contained within the [`torchvision.models`](https://pytorch.org/vision/stable/models.html) library? What do you think you could do with these?\n",
"* For a large number of pretrained PyTorch computer vision models as well as many different extensions to PyTorch's computer vision functionalities check out the [PyTorch Image Models library `timm`](https://github.com/rwightman/pytorch-image-models/) (Torch Image Models) by Ross Wightman."