Files
pytorch-deep-learning/06_pytorch_transfer_learning.ipynb
T
2022-05-19 07:16:32 +10:00

588 KiB

Open In Colab

(WIP) 06. PyTorch Transfer Learning

We've built a few models by hand so far.

But their performance has been poor.

You might be thinking, is there a well-performing model that already exists for our problem?

And in the world of deep learning, the answer is often yes.

We'll see how by using a powerful technique called transfer learning.

TK - What is transfer learning?

  • TK image - transfer learning overview

Transfer learning allows us to take the patterns (also called weights) another model has learned from another problem and use them for our own problem.

For example, we can take the patterns a computer vision model has learned from datasets such as ImageNet (millions of images of different objects) and use them to power our FoodVision Mini model.

Or we could take the patterns from a langauge model (a model that's been through large amounts of text to learn a representation of language) and use them as the basis of a model to classify different text samples.

The premise remains: find a well-performing existing model and apply it to your own problem.

TK - Why use transfer learning?

There are two main benefits to using transfer learning:

  1. Can leverage an existing model (usually a neural network architecture) proven to work on problems similar to our own.
  2. Can leverage a working model which has already learned patterns on similar data to our own. This often results in achieving great results with less custom data.
  • TK image - transfer learning applied to our problem

We'll be putting these to the test for our FoodVision Mini problem, trying to classify images of pizza, steak and sushi.

TK - Where to find pretrained models

The world of deep learning is an amazing place.

So amazing that many people around the world share their work.

Often, code and pretrained models for the latest state-of-the-art research is released within a few days of publishing.

And there are several places you can find pretrained models to use for your own problems.

Location What's there? Link(s)
PyTorch domain libraries Each of the PyTorch domain libraries (torchvision, torchtext) come with pretrained models of some form. The models there work right within PyTorch. torchvision.models, torchtext.models, torchaudio.models, torchrec.models
HuggingFace Hub A series of pretrained models on many different domains (vision, text, audio and more) from organizations around the world. There's plenty of different datasets too. https://huggingface.co/models, https://huggingface.co/datasets
timm (PyTorch Image Models) library Almost all of the latest and greatest computer vision models in PyTorch code as well as plenty of other helpful computer vision features. https://github.com/rwightman/pytorch-image-models
Paperswithcode A collection of the latest state-of-the-art machine learning papers with code implementations attached. You can also find benchmarks here of model performance on different tasks. https://paperswithcode.com/
  • TK image - different places to find pretrained models

Note: With access to such high-quality resources as above, it should be common practice at the start of every deep learning problem you take on to ask, "Does a pretrained model exist for my problem?"

TK links Exercise: Spend 5-minutes going through torchvision.models as well as the HuggingFace Hub Models page, what do you find? (there's no right answers here, it's just to practice exploring)

TK - What we're going to cover

  • TK - list this after completing the materials
  • TK - Using a pretrained model from torchvision.models and applying it to our problem
  • TK - transforming data to be used with a pretrained model from torchvision.models

TK - Where can you get help?

All of the materials for this course are available on GitHub.

If you run into trouble, you can ask a question on the course GitHub Discussions page.

And of course, there's the PyTorch documentation and PyTorch developer forums, a very helpful place for all things PyTorch.

TK - 0. Getting setup

Let's get started by importing/downloading the required modules for this section.

To save us writing extra code, we're going to be leveraging some of the Python scripts (such as data_setup.py and engine.py) we created in the previous section, 05. PyTorch Going Modular.

Specifically, we're going to download the going_modular directory from the pytorch-deep-learning repository (if we don't already have it).

We'll also get the torchinfo library if it's not available.

torchinfo will help later on to give us a visual representation of our model.

In [1]:
import torch
import torchvision
import numpy as np
import matplotlib.pyplot as plt

from torch import nn
from torchvision import transforms, datasets

# Try to get torchinfo, install it if it doesn't work
try:
    from torchinfo import summary
except:
    print("[INFO] Couldn't find torchinfo... installing it.")
    !pip install -q torchinfo
    from torchinfo import summary

# Try to import the going_modular directory, download it from GitHub if it doesn't work
try:
    from going_modular.going_modular import data_setup, engine
except:
    # Get the going_modular scripts
    print("[INFO] Couldn't find going_modular scripts... downloading them from GitHub.")
    !git clone https://github.com/mrdbourke/pytorch-deep-learning
    !mv pytorch-deep-learning/going_modular .
    !rm -rf pytorch-deep-learning
    from going_modular.going_modular import data_setup, engine

Now let's setup 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.

In [24]:
# Setup device agnostic code
device = "cuda" if torch.cuda.is_available() else "cpu"
device
Out [24]:
'cuda'

TK 1. Get data

Before we can start to use transfer learning, we'll need a dataset.

To see how transfer learning compares to our previous attempts at model building, we'll download the same dataset we've been using for FoodVision Mini.

Let's write some code to download the pizza_steak_sushi.zip dataset from the course GitHub and then unzip it.

We can also make sure if we've already got the data, it doesn't redownload.

In [3]:
import os
import requests
import zipfile

from pathlib import Path

# Setup path to data folder
data_path = Path("data/")
image_path = data_path / "pizza_steak_sushi"

# If the image folder doesn't exist, download it and prepare it... 
if image_path.is_dir():
    print(f"{image_path} directory exists.")
else:
    print(f"Did not find {image_path} directory, creating one...")
    image_path.mkdir(parents=True, exist_ok=True)
    
    # Download pizza, steak, sushi data
    with open(data_path / "pizza_steak_sushi.zip", "wb") as f:
        request = requests.get("https://github.com/mrdbourke/pytorch-deep-learning/raw/main/data/pizza_steak_sushi.zip")
        print("Downloading pizza, steak, sushi data...")
        f.write(request.content)

    # Unzip pizza, steak, sushi data
    with zipfile.ZipFile(data_path / "pizza_steak_sushi.zip", "r") as zip_ref:
        print("Unzipping pizza, steak, sushi data...") 
        zip_ref.extractall(image_path)

    # Remove .zip file
    os.remove(data_path / "pizza_steak_sushi.zip")
data/pizza_steak_sushi directory exists.

Excellent!

Now we've got the same dataset we've been using previously, a series of images of pizza, steak and sushi in standard image classification format.

Let's now create paths to our training and test directories.

In [4]:
# Setup Dirs
train_dir = image_path / "train"
test_dir = image_path / "test"

TK 2. Create Datasets and DataLoaders

Since we've downloaded the going_modular directory, we can use the data_setup.py script we created in section 05. PyTorch Going Modular to prepare and setup our DataLoaders.

But since we'll be using a pretrained model from torchvision.models, there's a specific transform we need to prepare our images first.

2.1 Creating a transform for torchvision.models

When using a pretrained model, it's important that your custom data going into the model is prepared in the same way as the original training data that went into the model.

For the case of pretrained models in torchvision.models, the documentation states:

All pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB images of shape (3 x H x W), where H and W are expected to be at least 224.

The images have to be loaded in to a range of [0, 1] and then normalized using mean = [0.485, 0.456, 0.406] and std = [0.229, 0.224, 0.225].

You can use the following transform to normalize:

normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
                             std=[0.229, 0.224, 0.225])

The good news is, we can achieve the above transformations with a combination of:

Transform number Transform required Code to perform transform
1 Mini-batches of size [batch_size, 3, height, width] where height and width are at least 224x224^. torchvision.transforms.Resize() to resize images into [3, 224, 224]^ and torch.utils.data.DataLoader() to create batches of images.
2 Values between 0 & 1. torchvision.transforms.ToTensor()
3 A mean of [0.485, 0.456, 0.406] (values across each colour channel). torchvision.transforms.Normalize(mean=...) to adjust the mean of our images.
4 A standard deviation of [0.229, 0.224, 0.225] (values across each colour channel). torchvision.transforms.Normalize(std=...) to adjust the standard deviation of our images.

Note: ^some pretrained models from torchvision.models in different sizes to [3, 224, 224], for example, some might take them in [3, 240, 240]. For specific input image sizes, see the documentation.

Question: Where did the mean and standard deviation values come from? Why do we need to do this?

These were calculated from the data. Specifically, the ImageNet dataset by taking the means and standard deviations across a subset of images.

We also don't need to do this. Neural networks are usually quite capable of figuring out appropriate data distributions (they'll calculate where the mean and standard deviations need to be on their own) but setting them at the start can help our networks achieve better performance quicker.

Let's compose a series of torchvision.transforms to perform the above steps.

In [25]:
# Create a transforms pipeline
simple_transform = transforms.Compose([
    transforms.Resize((224, 224)), # 1. Reshape all images to 224x224 (though some models may require different sizes)
    transforms.ToTensor(), # 2. Turn image values to between 0 & 1 
    transforms.Normalize(mean=[0.485, 0.456, 0.406], # 3. A mean of [0.485, 0.456, 0.406] (across each colour channel)
                         std=[0.229, 0.224, 0.225]) # 4. A standard deviation of [0.229, 0.224, 0.225] (across each colour channel),
])

Wonderful!

Now we've got a series of transforms ready to prepare our images, let's create training and testing DataLoaders.

We can create these using the create_dataloaders function from the data_setup.py script we created in 05. PyTorch Going Modular Part 2.

We'll set batch_size=32 so our model see's mini-batches of 32 samples at a time.

And we can transform our images using the transform pipeline we created above by setting transform=simple_transform.

In [29]:
# Create training and testing DataLoader's as well as get a list of class names
train_dataloader, test_dataloader, class_names = data_setup.create_dataloaders(train_dir=train_dir,
                                                                               test_dir=test_dir,
                                                                               transform=simple_transform, # resize, convert images to between 0 & 1 and normalize them
                                                                               batch_size=32) # set mini-batch size to 32

train_dataloader, test_dataloader, class_names
Out [29]:
(<torch.utils.data.dataloader.DataLoader at 0x7fe4d7704bb0>,
 <torch.utils.data.dataloader.DataLoader at 0x7fe4d7a30f70>,
 ['pizza', 'steak', 'sushi'])

TK 3. Getting a pretrained model

Alright, here comes the fun part!

Over the past few notebooks we've been building PyTorch neural networks from scratch.

And while that's a good skill to have, our models haven't been performing as well as we'd like.

That's where transfer learning comes in.

The whole idea of transfer learning is to take an already well-performing model on a problem-space similar to yours and then customising it to your use case.

Since we're working on a computer vision problem (image classification with FoodVision Mini), we can find pretrained classification models in torchvision.models.

Exploring the documentation, you'll find plenty of common computer vision architecture backbones such as:

Architecuture backbone Code
ResNet's torchvision.models.resnet18(), torchvision.models.resnet50()...
VGG (similar to what we used for TinyVGG) torchvision.models.vgg16()
EfficientNet's torchvision.models.efficientnet_b0(), torchvision.models.efficientnet_b1()...
VisionTransformer (ViT's) torchvision.models.vit_b_16(), torchvision.models.vit_b_32()...
ConvNeXt torchvision.models.convnext_tiny(), torchvision.models.convnext_small()...
More available in torchvision.models torchvision.models...

TK - 3.1 Which pretrained model should you use?

It depends on your problem/the device you're working with.

Generally, the higher number in the model name (e.g. efficientnet_b0() -> efficientnet_b1() -> efficientnet_b7()) means better performance but a larger model.

You might think better performance is always better, right?

That's true but some better performaning models are too big for some devices.

For example, say you'd like to run your model on a mobile-device, you'll have to take into account the limited compute resources on the device, thus you'd be looking for a smaller model.

But if you've got unlimited compute power, as The Bitter Lesson states, you'd likely take the biggest, most compute hungry model you can.

Understanding this performance vs. speed vs. size tradeoff will come with time and practice.

For me, I've found a nice balance in the efficientnet_bX models.

As of May 2022, Nutrify (the machine learning powered app I'm working on) is powered by an efficientnet_b0.

Comma.ai (a company that makes open source self-driving car software) uses an efficientnet_b2 to learn a representation of the road.

Note: Even though we're using efficientnet_bX, it's important not to get too attached to any one architecture, as they are always changing as new research gets released. Best to experiment, experiment, experiment and see what works for your problem.

3.2 Setting up a pretrained model

The pretrained model we're going to be using is torchvision.models.efficientnet_b0().

The architecture is from the paper EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks.

  • TK image - efficientnet architecture

To setup the model and make sure it comes with pretrained weights, we can set pretrained=True, doing so will download a set of model weights learned from the ImageNet dataset.

This means the model has already been trained on millions of images and has a good base representation of image data.

Note: As of December 2019, the PyTorch team announced a new mutli-weight API for TorchVision, allowing different sets of model weights (e.g. weights learned from different datasets) to be used for pretrained models. Though as of May 2022, this new API is not released. But even with the new API, the idea still remains: take the weights/patterns from one model and apply it to your own.

We'll also send it to the target device.

In [33]:
# Setup the model with pretrained weights and send it to the target device 
model = torchvision.models.efficientnet_b0(pretrained=True).to(device)
#model # uncomment to output (it's very long)

If we print the model, we get something similar to the following:

  • TK image - turn the below into an image which describes each section
EfficientNet(
  (features): Sequential(
    (0): ConvNormActivation(
      (0): Conv2d(3, 32, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)
      (1): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (2): SiLU(inplace=True)
    )
    (1): Sequential(
      (0): MBConv(
        (block): Sequential(
          (0): ConvNormActivation(
            (0): Conv2d(32, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=32, bias=False)
            (1): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
            (2): SiLU(inplace=True)
  ...
  ...
  ...
  (avgpool): AdaptiveAvgPool2d(output_size=1)
  (classifier): Sequential(
    (0): Dropout(p=0.2, inplace=True)
    (1): Linear(in_features=1280, out_features=1000, bias=True)
  )
)

Lots and lots and lots of layers.

This is one of the benefits of transfer learning, taking an existing model, that's been crafted by some of the best engineers in the world and applying to your own problem.

UPTOHERE...

Our efficientnet_b0 comes in three main parts:

  1. features -
  2. avgpool -
  3. classifier -
In [39]:
# Print a summary
summary(model, 
        input_size=(32, 3, 224, 224), # make sure this is "input_size", not "input_shape"
        verbose=0,
        col_names=["input_size", "trainable"],
        # col_names=["input_size", "output_size", "num_params", "trainable"],
        col_width=20,
        row_settings=["var_names"]
)
Out [39]:
====================================================================================================
Layer (type (var_name))                                      Input Shape          Trainable
====================================================================================================
EfficientNet                                                 --                   True
├─Sequential (features)                                      [32, 3, 224, 224]    True
│    └─ConvNormActivation (0)                                [32, 3, 224, 224]    True
│    │    └─Conv2d (0)                                       [32, 3, 224, 224]    True
│    │    └─BatchNorm2d (1)                                  [32, 32, 112, 112]   True
│    │    └─SiLU (2)                                         [32, 32, 112, 112]   --
│    └─Sequential (1)                                        [32, 32, 112, 112]   True
│    │    └─MBConv (0)                                       [32, 32, 112, 112]   True
│    └─Sequential (2)                                        [32, 16, 112, 112]   True
│    │    └─MBConv (0)                                       [32, 16, 112, 112]   True
│    │    └─MBConv (1)                                       [32, 24, 56, 56]     True
│    └─Sequential (3)                                        [32, 24, 56, 56]     True
│    │    └─MBConv (0)                                       [32, 24, 56, 56]     True
│    │    └─MBConv (1)                                       [32, 40, 28, 28]     True
│    └─Sequential (4)                                        [32, 40, 28, 28]     True
│    │    └─MBConv (0)                                       [32, 40, 28, 28]     True
│    │    └─MBConv (1)                                       [32, 80, 14, 14]     True
│    │    └─MBConv (2)                                       [32, 80, 14, 14]     True
│    └─Sequential (5)                                        [32, 80, 14, 14]     True
│    │    └─MBConv (0)                                       [32, 80, 14, 14]     True
│    │    └─MBConv (1)                                       [32, 112, 14, 14]    True
│    │    └─MBConv (2)                                       [32, 112, 14, 14]    True
│    └─Sequential (6)                                        [32, 112, 14, 14]    True
│    │    └─MBConv (0)                                       [32, 112, 14, 14]    True
│    │    └─MBConv (1)                                       [32, 192, 7, 7]      True
│    │    └─MBConv (2)                                       [32, 192, 7, 7]      True
│    │    └─MBConv (3)                                       [32, 192, 7, 7]      True
│    └─Sequential (7)                                        [32, 192, 7, 7]      True
│    │    └─MBConv (0)                                       [32, 192, 7, 7]      True
│    └─ConvNormActivation (8)                                [32, 320, 7, 7]      True
│    │    └─Conv2d (0)                                       [32, 320, 7, 7]      True
│    │    └─BatchNorm2d (1)                                  [32, 1280, 7, 7]     True
│    │    └─SiLU (2)                                         [32, 1280, 7, 7]     --
├─AdaptiveAvgPool2d (avgpool)                                [32, 1280, 7, 7]     --
├─Sequential (classifier)                                    [32, 1280]           True
│    └─Dropout (0)                                           [32, 1280]           --
│    └─Linear (1)                                            [32, 1280]           True
====================================================================================================
Total params: 5,288,548
Trainable params: 5,288,548
Non-trainable params: 0
Total mult-adds (G): 12.35
====================================================================================================
Input size (MB): 19.27
Forward/backward pass size (MB): 3452.35
Params size (MB): 21.15
Estimated Total Size (MB): 3492.77
====================================================================================================
In [7]:
# TK - view the model
len(list(iter(model.parameters())))
# model.state_dict()
Out [7]:
213

TK - Freezing the base model and changing the output layer to suit our needs

In [8]:
# TK - Update the classifier - how is this done?
torch.manual_seed(42)
torch.cuda.manual_seed(42)

output_shape = len(class_names)
model.classifier = torch.nn.Linear(1280, output_shape).to(device)

# Freeze all base layers (the feature extractor in EfficientNet)
for param in model.features.parameters():
    param.requires_grad = False

# Print a summary
# model
  • TK image - before and after model frozen, show the summary + the change in the different layer shapes + outputs
In [22]:
# TK - do a summary *after* freezing the layers
summary(model, 
        input_size=(32, 3, 224, 224), # make sure this is "input_size", not "input_shape"
        verbose=0,
        col_names=["input_size", "output_size", "num_params", "trainable"],
        col_width=20,
        row_settings=["var_names"]
)
Out [22]:
============================================================================================================================================
Layer (type (var_name))                                      Input Shape          Output Shape         Param #              Trainable
============================================================================================================================================
EfficientNet                                                 --                   --                   --                   True
├─Sequential (features)                                      [32, 3, 224, 224]    [32, 1280, 7, 7]     --                   True
│    └─ConvNormActivation (0)                                [32, 3, 224, 224]    [32, 32, 112, 112]   --                   True
│    │    └─Conv2d (0)                                       [32, 3, 224, 224]    [32, 32, 112, 112]   864                  True
│    │    └─BatchNorm2d (1)                                  [32, 32, 112, 112]   [32, 32, 112, 112]   64                   True
│    │    └─SiLU (2)                                         [32, 32, 112, 112]   [32, 32, 112, 112]   --                   --
│    └─Sequential (1)                                        [32, 32, 112, 112]   [32, 16, 112, 112]   --                   True
│    │    └─MBConv (0)                                       [32, 32, 112, 112]   [32, 16, 112, 112]   1,448                True
│    └─Sequential (2)                                        [32, 16, 112, 112]   [32, 24, 56, 56]     --                   True
│    │    └─MBConv (0)                                       [32, 16, 112, 112]   [32, 24, 56, 56]     6,004                True
│    │    └─MBConv (1)                                       [32, 24, 56, 56]     [32, 24, 56, 56]     10,710               True
│    └─Sequential (3)                                        [32, 24, 56, 56]     [32, 40, 28, 28]     --                   True
│    │    └─MBConv (0)                                       [32, 24, 56, 56]     [32, 40, 28, 28]     15,350               True
│    │    └─MBConv (1)                                       [32, 40, 28, 28]     [32, 40, 28, 28]     31,290               True
│    └─Sequential (4)                                        [32, 40, 28, 28]     [32, 80, 14, 14]     --                   True
│    │    └─MBConv (0)                                       [32, 40, 28, 28]     [32, 80, 14, 14]     37,130               True
│    │    └─MBConv (1)                                       [32, 80, 14, 14]     [32, 80, 14, 14]     102,900              True
│    │    └─MBConv (2)                                       [32, 80, 14, 14]     [32, 80, 14, 14]     102,900              True
│    └─Sequential (5)                                        [32, 80, 14, 14]     [32, 112, 14, 14]    --                   True
│    │    └─MBConv (0)                                       [32, 80, 14, 14]     [32, 112, 14, 14]    126,004              True
│    │    └─MBConv (1)                                       [32, 112, 14, 14]    [32, 112, 14, 14]    208,572              True
│    │    └─MBConv (2)                                       [32, 112, 14, 14]    [32, 112, 14, 14]    208,572              True
│    └─Sequential (6)                                        [32, 112, 14, 14]    [32, 192, 7, 7]      --                   True
│    │    └─MBConv (0)                                       [32, 112, 14, 14]    [32, 192, 7, 7]      262,492              True
│    │    └─MBConv (1)                                       [32, 192, 7, 7]      [32, 192, 7, 7]      587,952              True
│    │    └─MBConv (2)                                       [32, 192, 7, 7]      [32, 192, 7, 7]      587,952              True
│    │    └─MBConv (3)                                       [32, 192, 7, 7]      [32, 192, 7, 7]      587,952              True
│    └─Sequential (7)                                        [32, 192, 7, 7]      [32, 320, 7, 7]      --                   True
│    │    └─MBConv (0)                                       [32, 192, 7, 7]      [32, 320, 7, 7]      717,232              True
│    └─ConvNormActivation (8)                                [32, 320, 7, 7]      [32, 1280, 7, 7]     --                   True
│    │    └─Conv2d (0)                                       [32, 320, 7, 7]      [32, 1280, 7, 7]     409,600              True
│    │    └─BatchNorm2d (1)                                  [32, 1280, 7, 7]     [32, 1280, 7, 7]     2,560                True
│    │    └─SiLU (2)                                         [32, 1280, 7, 7]     [32, 1280, 7, 7]     --                   --
├─AdaptiveAvgPool2d (avgpool)                                [32, 1280, 7, 7]     [32, 1280, 1, 1]     --                   --
├─Sequential (classifier)                                    [32, 1280]           [32, 1000]           --                   True
│    └─Dropout (0)                                           [32, 1280]           [32, 1280]           --                   --
│    └─Linear (1)                                            [32, 1280]           [32, 1000]           1,281,000            True
============================================================================================================================================
Total params: 5,288,548
Trainable params: 5,288,548
Non-trainable params: 0
Total mult-adds (G): 12.35
============================================================================================================================================
Input size (MB): 19.27
Forward/backward pass size (MB): 3452.35
Params size (MB): 21.15
Estimated Total Size (MB): 3492.77
============================================================================================================================================

TK 4. Train model

In [10]:
# Define loss and optimizer
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
In [11]:
# Train model
torch.manual_seed(42)
torch.cuda.manual_seed(42)

# Start the timer
from timeit import default_timer as timer 
start_time = timer()

results = engine.train(model=model,
                       train_dataloader=train_dataloader,
                       test_dataloader=test_dataloader,
                       optimizer=optimizer,
                       loss_fn=loss_fn,
                       epochs=5,
                       device=device)

# End the timer and print out how long it took
end_time = timer()
print(f"[INFO] Total training time: {end_time-start_time:.3f} seconds")
  0%|          | 0/5 [00:00<?, ?it/s]
Epoch: 1 | train_loss: 1.0906 | train_acc: 0.4062 | test_loss: 0.9001 | test_acc: 0.5388
Epoch: 2 | train_loss: 0.8596 | train_acc: 0.8047 | test_loss: 0.7819 | test_acc: 0.7841
Epoch: 3 | train_loss: 0.7651 | train_acc: 0.8125 | test_loss: 0.7106 | test_acc: 0.8352
Epoch: 4 | train_loss: 0.7062 | train_acc: 0.7695 | test_loss: 0.6235 | test_acc: 0.9072
Epoch: 5 | train_loss: 0.6237 | train_acc: 0.8008 | test_loss: 0.6045 | test_acc: 0.8864
[INFO] Total training time: 5.147 seconds

5. TK - Evaluate model

In [12]:
try:
    from helper_functions import plot_loss_curves
except:
    print("[INFO] Couldn't find helper_functions.py, downloading...")
    with open("helper_functions.py", "wb") as f:
        import requests
        request = requests.get("https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/helper_functions.py")
        f.write(request.content)
    from helper_functions import plot_loss_curves

plot_loss_curves(results)

TK - Make predictions with custom images (could use/create predict.py from previous section)

  • TK - Things to remember: image has to be in same format model was trained on... e.g. same transforms
In [13]:
# Get a random image path from test set
import random
test_image_path_list = list(Path(test_dir).glob("*/*.jpg"))
test_image_path_sample = random.sample(test_image_path_list, k=3)

# Open image
from PIL import Image
from typing import List, Tuple

def pred_and_plot_image(model: torch.nn.Module, 
                        image_path: str, 
                        class_names: List[str], 
                        image_size: Tuple[int, int]=(224, 224)):
    # TK - similar to function from notebook 04
    # See here for reference: https://www.learnpytorch.io/04_pytorch_custom_datasets/#113-putting-custom-image-prediction-together-building-a-function
    # Open image
    img = Image.open(image_path)

    # Create transformation for image
    normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                   std=[0.229, 0.224, 0.225])

    simple_transform = transforms.Compose([
    transforms.Resize(image_size),
    transforms.ToTensor(),
    normalize,
    ])

    ### Predict on image

    # Make sure the model is on the target device
    model.to(device)

    # Turn on model evaluation mode and inference mode
    model.eval()
    with torch.inference_mode():
      # Transform and add an extra dimension to image (model requires samples in [batch_size, color_channels, height, width])
      transformed_image = simple_transform(img).unsqueeze(dim=0)

      # Make a prediction on image with an extra dimension and send it to the target device
      target_image_pred = model(transformed_image.to(device))

    # Convert logits -> prediction probabilities (using torch.softmax() for multi-class classification)
    target_image_pred_probs = torch.softmax(target_image_pred, dim=1)

    # Convert prediction probabilities -> prediction labels
    target_image_pred_label = torch.argmax(target_image_pred_probs, dim=1)

    # Plot image with predicted label and probability 
    plt.figure()
    plt.imshow(img)
    plt.title(f"Pred: {class_names[target_image_pred_label]} | Prob: {target_image_pred_probs.max():.3f}")
    plt.axis(False);

for image_path in test_image_path_sample:
    pred_and_plot_image(model=model, 
                        image_path=image_path,
                        class_names=class_names, 
                        image_size=(224, 224))

TK - Pred on custom image (pizza dad)

In [14]:
# Download custom image
import requests

# Setup custom image path
custom_image_path = data_path / "04-pizza-dad.jpeg"

# Download the image if it doesn't already exist
if not custom_image_path.is_file():
    with open(custom_image_path, "wb") as f:
        # When downloading from GitHub, need to use the "raw" file link
        request = requests.get("https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/04-pizza-dad.jpeg")
        print(f"Downloading {custom_image_path}...")
        f.write(request.content)
else:
    print(f"{custom_image_path} already exists, skipping download.")

pred_and_plot_image(model=model,
                    image_path=custom_image_path,
                    class_names=class_names)
data/04-pizza-dad.jpeg already exists, skipping download.

TK - Extensions + Exercises

  • Try a different model from PyTorch pretrained models
    • You'll have to change the size of the classifier layer
    • See here for more models: https://pytorch.org/vision/stable/models.html
    • Try ConvNext-Tiny, does it perform better than EfficientNetB0?
      • torchvision.models.convnext_tiny()
  • Train for longer, what happens?
  • Train with more data, what happens?
    • Double the images of pizza, steak, sushi
    • Now introduce 10 classes (10 whole foods), see what happens
  • Could you add in some data augmentation, what happens?
  • Predict on your own image of pizza/steak/sushi - how does the model go?

TK - Extra-curriculum