Files
pytorch-deep-learning/09_pytorch_model_deployment.ipynb
T

370 KiB

Open In Colab

(WIP) 09. PyTorch Model Deployment

Welcome to Milestone Project 3: PyTorch Model Deployment!

Status: Work in progress.

Goal: Take FoodVision Mini model and make it publically accessible (deploy it to a usable app/interface), want it to be:

  • Fast (a slow app is a boring app)
  • Good (95%+ accuracy for 3 classes but this would be harder to achieve with more classes)

--

  • TK - What is model deployment?
    • TK - PyTorch workflow + model deployment... (another step)
  • TK - Why deploy a machine learning model?
  • TK - Batch vs real-time (online -> real-time vs offline -> batch)
    • Model deployment trade off: Do you pick a model that works at 95% of performance that has an inference time of 1 second or a model that works at 98% but takes 10 seconds per inference?
  • TK - On edge vs on cloud
  • TK - ways to deploy a machine learning model (discuss the different methods of deployment)
  • TK - What to do when your model is deployed? E.g. monitoring?
    • TK - Perhaps talk about this when the model is actually deployed
    • TK - What could go wrong when a model is deployed?
  • TK - Creating a demo (what are the inputs and outputs)...
    • TK - Describing a machine learning problem... one of the best ways is in inputs and outputs, "what are your ideal inputs and ideal outputs?"
  • TK - Even at the last project we're still experimenting... two model's have shined throughout on the FoodVision Mini project, now let's investigate further to see which is best
    • TK - fast & good

TK - What we're going to cover

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.

0. Getting setup

As we've done previously, let's make sure we've got all of the modules we'll need for this section.

We'll import the Python scripts (such as data_setup.py and engine.py) we created in 05. PyTorch Going Modular.

To do so, we'll download going_modular directory from the pytorch-deep-learning repository (if we don't already have it).

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

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

And since later on we'll be using torchvision v0.13 package (available as of July 2022), we'll make sure we've got the latest versions.

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 [1]:
# For this notebook to run with updated APIs, we need torch 1.12+ and torchvision 0.13+
try:
    import torch
    import torchvision
    assert int(torch.__version__.split(".")[1]) >= 12, "torch version should be 1.12+"
    assert int(torchvision.__version__.split(".")[1]) >= 13, "torchvision version should be 0.13+"
    print(f"torch version: {torch.__version__}")
    print(f"torchvision version: {torchvision.__version__}")
except:
    print(f"[INFO] torch/torchvision versions not as required, installing nightly versions.")
    !pip3 install -U --pre torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/nightly/cu113
    import torch
    import torchvision
    print(f"torch version: {torch.__version__}")
    print(f"torchvision version: {torchvision.__version__}")
torch version: 1.12.0+cu102
torchvision version: 0.13.0+cu102

Note: If you're using Google Colab and the cell above starts to install various software packages, you may have to restart your runtime after running the above cell. After restarting, you can run the cell again and verify you've got the right versions of torch and torchvision.

Now we'll continue with the regular imports, setting up device agnostic code and this time we'll also get the helper_functions.py script from GitHub.

The helper_functions.py script contains several functions we created in previous sections:

Note: It may be a better idea for many of the functions in the helper_functions.py script to be merged into going_modular/going_modular/utils.py, perhaps that's an extension you'd like to try.

In [2]:
# Continue with regular imports
import matplotlib.pyplot as plt
import torch
import torchvision

from torch import nn
from torchvision import transforms

# 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
    from helper_functions import download_data, set_seeds, plot_loss_curves
except:
    # Get the going_modular scripts
    print("[INFO] Couldn't find going_modular or helper_functions scripts... downloading them from GitHub.")
    !git clone https://github.com/mrdbourke/pytorch-deep-learning
    !mv pytorch-deep-learning/going_modular .
    !mv pytorch-deep-learning/helper_functions.py . # get the helper_functions.py script
    !rm -rf pytorch-deep-learning
    from going_modular.going_modular import data_setup, engine
    from helper_functions import download_data, set_seeds, plot_loss_curves

Finally, we'll setup device-agnostic code to make sure our models run on the GPU.

In [3]:
device = "cuda" if torch.cuda.is_available() else "cpu"
device
Out [3]:
'cuda'

TK - 1. Getting data

We left off in 08. PyTorch Paper Replicating comparing our own ViT (Vision Transformer) feature extractor model to the EfficientNetB2 (EffNetB2) feature extractor model we created in 07. PyTorch Experiment Tracking.

And we found that there was a slight difference in the comparison.

The EffNetB2 model was trained on 20% of the pizza, steak and sushi data from Food101 where as the ViT model was trained on 10%.

Since our goal is to deploy the best model for our FoodVision Mini problem, let's start by downloading the 20% pizza, steak and sushi dataset and train an EffNetB2 feature extractor and ViT feature extractor on it and then compare the two models.

This way we'll be comparing apples to apples.

Note: The dataset we're downloading is a sample of the entire Food101 dataset (101 food classes with 1,000 images each). More specifically, 20% refers to 20% of images from the pizza, steak and sushi classes selected at random. You can see how this dataset was created in extras/04_custom_data_creation.ipynb.

In [4]:
# Download pizza, steak, sushi images from GitHub
data_20_percent_path = download_data(source="https://github.com/mrdbourke/pytorch-deep-learning/raw/main/data/pizza_steak_sushi_20_percent.zip",
                                     destination="pizza_steak_sushi_20_percent")

data_20_percent_path
Out [4]:
[INFO] data/pizza_steak_sushi_20_percent directory exists, skipping download.
PosixPath('data/pizza_steak_sushi_20_percent')

Wonderful!

Now we've got a dataset, let's creat training and test paths.

In [5]:
# Setup directory paths to train and test images
train_dir = data_20_percent_path / "train"
test_dir = data_20_percent_path / "test"

TK - FoodVision Mini modelling experiment outline

The ideal deployed model FoodVision Mini performs well and fast.

Ideally, we'd like a model that performs as close to real-time as possible.

Real-time in this case being ~30FPS (frames per second) because that's about how fast the human eye can see (there is debate on this but let's just use ~30FPS as our benchmark).

And for classifying three different classes (pizza, steak and sushi), we'd like a model that performs at 95%+ accuracy.

Of course, higher accuracy would be nice but this might sacrifice speed.

So our goals are:

  1. Performance - A model that performs at 95%+ accuracy.
  2. Speed - A model that can classify an image at ~30FPS (0.03 seconds inference time per image).

We'll put an emphasis on speed, meaning, we'd prefer a model performing at 90%+ accuracy at ~30FPS than a model performing 95%+ accuracy at 10FPS.

To try and achieve these results, let's bring in our best performing models from the previous sections:

  1. EffNetB2 feature extractor (EffNetB2 for short) - originally created in 07. PyTorch Experiment Tracking section 7.5 using torchvision.models.efficientnet_b2() with adjusted classifier layers.
  2. ViT-B/16 feature extractor (ViT for short) - originally created in 08. PyTorch Paper Replicating section 10 using torchvision.models.vit_b_16() with adjusted head layers.
    • Note ViT-B/16 stands for "Vision Transformer Base, patch size 16".

TK image - experiment outline (2 models, same dataset, same training regime)

Note: A "feature extractor model" often starts with a model that has been pretrained on a dataset similar to your own problem. The pretrained model's base layers are often left frozen (the pretrained patterns/weights stay the same) whilst some of the top (or classifier/classification head) layers get customized to your own problem by training on your own data. We covered the concept of a feature extractor model in 06. PyTorch Transfer Learning section 3.4.

TK - Creating an EffNetB2 feature extractor

We first created an EffNetB2 feature extractor model in 07. PyTorch Experiment Tracking section 7.5.

And we saw by the end of that section it performed very well.

So let's now recreate it here so we can compare its results to a ViT feature extractor trained on the same data.

To do so we can:

  1. Setup the pretrained weights as torchvision.models.EfficientNet_B2_Weights.DEFAULT, where "DEFAULT" means "best currently available" (or could use weights="DEFAULT").
  2. Get the pretrained model image transforms from the weights with the transforms() method (we need these so we can convert our images into the same format as the pretrained EffNetB2 was trained on).
  3. Create a pretrained model instance by passing the weights to an instance of torchvision.models.efficientnet_b2.
  4. Freeze the base layers in the model.
  5. Update the classifier head to suit our own data.
In [6]:
# 1. Setup pretrained EffNetB2 weights
effnetb2_weights = torchvision.models.EfficientNet_B2_Weights.DEFAULT

# 2. Get EffNetB2 transforms
effnetb2_transforms = effnetb2_weights.transforms()

# 3. Setup pretrained model
effnetb2 = torchvision.models.efficientnet_b2(weights=effnetb2_weights) # could also use weights="DEFAULT"

# 4. Freeze the base layers in the model (this will freeze all layers to begin with)
for param in effnetb2.parameters():
    param.requires_grad = False

Now to change the classifier head, let's first inspect it using the classifier attribute of our model.

In [7]:
# Check out EffNetB2 classifier head
effnetb2.classifier
Out [7]:
Sequential(
  (0): Dropout(p=0.3, inplace=True)
  (1): Linear(in_features=1408, out_features=1000, bias=True)
)

Excellent! To change the classifier head to suit our own problem, let's replace the out_features variable with the same number of classes we have (in our case, out_features=3, one for pizza, steak, sushi).

Note: This process of changing the output layers/classifier head will be dependent on the problem you're working on. For example, if you wanted a different number of outputs or a different kind of ouput, you would have to change the output layers accordingly.

In [8]:
# 5. Update the classifier head
effnetb2.classifier = nn.Sequential(
    nn.Dropout(p=0.3, inplace=True), # keep dropout layer same
    nn.Linear(in_features=1408, # keep in_features same 
              out_features=3)) # change out_features to suit our number of classes

Beautiful!

Looks like our EffNetB2 feature extractor is ready to go, however, since there's quite a few steps involved here, how about we turn the code above into a function we can re-use later?

We'll call it create_effnetb2_model() and it'll take a customizable number of classes and a random seed parameter for reproducibility.

Ideally, it will return an EffNetB2 feature extractor along with its assosciated transforms.

In [9]:
def create_effnetb2_model(num_classes:int=3, 
                          seed:int=42):
    """Creates an EfficientNetB2 feature extractor model and transforms.

    Args:
        num_classes (int, optional): number of classes in the classifier head. 
            Defaults to 3.
        seed (int, optional): random seed value. Defaults to 42.

    Returns:
        model (torch.nn.Module): EffNetB2 feature extractor model. 
        transforms (torchvision.transforms): EffNetB2 image transforms.
    """
    # 1, 2, 3. Create EffNetB2 pretrained weights, transforms and model
    weights = torchvision.models.EfficientNet_B2_Weights.DEFAULT
    transforms = weights.transforms()
    model = torchvision.models.efficientnet_b2(weights=weights)

    # 4. Freeze all layers in base model
    for param in model.parameters():
        param.requires_grad = False

    # 5. Change classifier head with random seed for reproducibility
    torch.manual_seed(seed)
    model.classifier = nn.Sequential(
        nn.Dropout(p=0.3, inplace=True),
        nn.Linear(in_features=1408, out_features=num_classes),
    )
    
    return model, transforms

Woohoo! That's a nice looking function, let's try it out.

In [10]:
effnetb2, effnetb2_transforms = create_effnetb2_model(num_classes=3,
                                                      seed=42)

No errors, nice, now to really try it out, let's get a summary with torchinfo.summary().

In [11]:
from torchinfo import summary
summary(effnetb2, 
        input_size=(1, 3, 224, 224),
        col_names=["input_size", "output_size", "num_params", "trainable"],
        col_width=20,
        row_settings=["var_names"])
Out [11]:
============================================================================================================================================
Layer (type (var_name))                                      Input Shape          Output Shape         Param #              Trainable
============================================================================================================================================
EfficientNet (EfficientNet)                                  [1, 3, 224, 224]     [1, 3]               --                   Partial
├─Sequential (features)                                      [1, 3, 224, 224]     [1, 1408, 7, 7]      --                   False
│    └─Conv2dNormActivation (0)                              [1, 3, 224, 224]     [1, 32, 112, 112]    --                   False
│    │    └─Conv2d (0)                                       [1, 3, 224, 224]     [1, 32, 112, 112]    (864)                False
│    │    └─BatchNorm2d (1)                                  [1, 32, 112, 112]    [1, 32, 112, 112]    (64)                 False
│    │    └─SiLU (2)                                         [1, 32, 112, 112]    [1, 32, 112, 112]    --                   --
│    └─Sequential (1)                                        [1, 32, 112, 112]    [1, 16, 112, 112]    --                   False
│    │    └─MBConv (0)                                       [1, 32, 112, 112]    [1, 16, 112, 112]    (1,448)              False
│    │    └─MBConv (1)                                       [1, 16, 112, 112]    [1, 16, 112, 112]    (612)                False
│    └─Sequential (2)                                        [1, 16, 112, 112]    [1, 24, 56, 56]      --                   False
│    │    └─MBConv (0)                                       [1, 16, 112, 112]    [1, 24, 56, 56]      (6,004)              False
│    │    └─MBConv (1)                                       [1, 24, 56, 56]      [1, 24, 56, 56]      (10,710)             False
│    │    └─MBConv (2)                                       [1, 24, 56, 56]      [1, 24, 56, 56]      (10,710)             False
│    └─Sequential (3)                                        [1, 24, 56, 56]      [1, 48, 28, 28]      --                   False
│    │    └─MBConv (0)                                       [1, 24, 56, 56]      [1, 48, 28, 28]      (16,518)             False
│    │    └─MBConv (1)                                       [1, 48, 28, 28]      [1, 48, 28, 28]      (43,308)             False
│    │    └─MBConv (2)                                       [1, 48, 28, 28]      [1, 48, 28, 28]      (43,308)             False
│    └─Sequential (4)                                        [1, 48, 28, 28]      [1, 88, 14, 14]      --                   False
│    │    └─MBConv (0)                                       [1, 48, 28, 28]      [1, 88, 14, 14]      (50,300)             False
│    │    └─MBConv (1)                                       [1, 88, 14, 14]      [1, 88, 14, 14]      (123,750)            False
│    │    └─MBConv (2)                                       [1, 88, 14, 14]      [1, 88, 14, 14]      (123,750)            False
│    │    └─MBConv (3)                                       [1, 88, 14, 14]      [1, 88, 14, 14]      (123,750)            False
│    └─Sequential (5)                                        [1, 88, 14, 14]      [1, 120, 14, 14]     --                   False
│    │    └─MBConv (0)                                       [1, 88, 14, 14]      [1, 120, 14, 14]     (149,158)            False
│    │    └─MBConv (1)                                       [1, 120, 14, 14]     [1, 120, 14, 14]     (237,870)            False
│    │    └─MBConv (2)                                       [1, 120, 14, 14]     [1, 120, 14, 14]     (237,870)            False
│    │    └─MBConv (3)                                       [1, 120, 14, 14]     [1, 120, 14, 14]     (237,870)            False
│    └─Sequential (6)                                        [1, 120, 14, 14]     [1, 208, 7, 7]       --                   False
│    │    └─MBConv (0)                                       [1, 120, 14, 14]     [1, 208, 7, 7]       (301,406)            False
│    │    └─MBConv (1)                                       [1, 208, 7, 7]       [1, 208, 7, 7]       (686,868)            False
│    │    └─MBConv (2)                                       [1, 208, 7, 7]       [1, 208, 7, 7]       (686,868)            False
│    │    └─MBConv (3)                                       [1, 208, 7, 7]       [1, 208, 7, 7]       (686,868)            False
│    │    └─MBConv (4)                                       [1, 208, 7, 7]       [1, 208, 7, 7]       (686,868)            False
│    └─Sequential (7)                                        [1, 208, 7, 7]       [1, 352, 7, 7]       --                   False
│    │    └─MBConv (0)                                       [1, 208, 7, 7]       [1, 352, 7, 7]       (846,900)            False
│    │    └─MBConv (1)                                       [1, 352, 7, 7]       [1, 352, 7, 7]       (1,888,920)          False
│    └─Conv2dNormActivation (8)                              [1, 352, 7, 7]       [1, 1408, 7, 7]      --                   False
│    │    └─Conv2d (0)                                       [1, 352, 7, 7]       [1, 1408, 7, 7]      (495,616)            False
│    │    └─BatchNorm2d (1)                                  [1, 1408, 7, 7]      [1, 1408, 7, 7]      (2,816)              False
│    │    └─SiLU (2)                                         [1, 1408, 7, 7]      [1, 1408, 7, 7]      --                   --
├─AdaptiveAvgPool2d (avgpool)                                [1, 1408, 7, 7]      [1, 1408, 1, 1]      --                   --
├─Sequential (classifier)                                    [1, 1408]            [1, 3]               --                   True
│    └─Dropout (0)                                           [1, 1408]            [1, 1408]            --                   --
│    └─Linear (1)                                            [1, 1408]            [1, 3]               4,227                True
============================================================================================================================================
Total params: 7,705,221
Trainable params: 4,227
Non-trainable params: 7,700,994
Total mult-adds (M): 657.64
============================================================================================================================================
Input size (MB): 0.60
Forward/backward pass size (MB): 156.80
Params size (MB): 30.82
Estimated Total Size (MB): 188.22
============================================================================================================================================

Base layers frozen, top layers trainable and customized!

TK image - turn model summary into image

TK - Creating DataLoaders for EffNetB2

Our EffNetB2 feature extractor is ready, time to create some DataLoaders.

We can do this by using the data_setup.create_dataloaders() function we created in 05. PyTorch Going Modular section 2.

We'll use a batch_size of 32 and transform our images using the effnetb2_transforms so they're in the same format that our effnetb2 model was trained on.

In [12]:
# Setup DataLoaders
from going_modular.going_modular import data_setup
train_dataloader_effnetb2, test_dataloader_effnetb2, class_names = data_setup.create_dataloaders(train_dir=train_dir,
                                                                                                 test_dir=test_dir,
                                                                                                 transform=effnetb2_transforms,
                                                                                                 batch_size=32)

TK - Training EffNetB2

Model ready, DataLoaders ready, let's train!

Just like in 07. PyTorch Experiment Tracking section 7.6, ten epochs should be enough to get good results.

We can do so by creating an optimizer (we'll use torch.optim.Adam() with a learning rate of 1e-3), a loss function (we'll use torch.nn.CrossEntropyLoss() for multi-class classification) and then passing everything to the engine.train() function we created in 05. PyTorch Going Modular section 4.

In [13]:
from going_modular.going_modular import engine

# Setup optimizer
optimizer = torch.optim.Adam(params=effnetb2.parameters(),
                             lr=1e-3)
# Setup loss function
loss_fn = torch.nn.CrossEntropyLoss()

# Set seeds for reproducibility and train the model
set_seeds()
effnetb2_results = engine.train(model=effnetb2,
                                train_dataloader=train_dataloader_effnetb2,
                                test_dataloader=test_dataloader_effnetb2,
                                epochs=10,
                                optimizer=optimizer,
                                loss_fn=loss_fn,
                                device=device)
  0%|          | 0/10 [00:00<?, ?it/s]
Epoch: 1 | train_loss: 0.9856 | train_acc: 0.5604 | test_loss: 0.7408 | test_acc: 0.9347
Epoch: 2 | train_loss: 0.7175 | train_acc: 0.8438 | test_loss: 0.5869 | test_acc: 0.9409
Epoch: 3 | train_loss: 0.5876 | train_acc: 0.8917 | test_loss: 0.4909 | test_acc: 0.9500
Epoch: 4 | train_loss: 0.4474 | train_acc: 0.9062 | test_loss: 0.4355 | test_acc: 0.9409
Epoch: 5 | train_loss: 0.4290 | train_acc: 0.9104 | test_loss: 0.3915 | test_acc: 0.9443
Epoch: 6 | train_loss: 0.4381 | train_acc: 0.8896 | test_loss: 0.3512 | test_acc: 0.9688
Epoch: 7 | train_loss: 0.4245 | train_acc: 0.8771 | test_loss: 0.3268 | test_acc: 0.9563
Epoch: 8 | train_loss: 0.3897 | train_acc: 0.8958 | test_loss: 0.3457 | test_acc: 0.9381
Epoch: 9 | train_loss: 0.3749 | train_acc: 0.8812 | test_loss: 0.3129 | test_acc: 0.9131
Epoch: 10 | train_loss: 0.3757 | train_acc: 0.8604 | test_loss: 0.2813 | test_acc: 0.9688

TK - Inspecting EffNetB2 loss curves

Nice!

As we saw in 07. PyTorch Experiment Tracking, the EffNetB2 feature extractor model works quite well on our data.

Let's turn its results into loss curves to inspect them further.

Note: Loss curves are one of the best ways to visualize how your model's performing. For more on loss curves, check out 04. PyTorch Custom Datasets section 8: What should an ideal loss curve look like?

In [14]:
from helper_functions import plot_loss_curves

plot_loss_curves(effnetb2_results)

Woah!

Those are some nice looking loss curves.

It looks like our model is performing quite well and perhaps would benefit from a little longer training and potentially some data augmentation (to help prevent overfitting occurring from longer training).

TK - Saving EffNetB2

Now we've got a well-performing trained model, let's save it to file so we can import and use it later.

To save our model we can use the utils.save_model() function we created in 05. PyTorch Going Modular section 5.

We'll set the target_dir to "models" and the model_name to "09_pretrained_effnetb2_feature_extractor_pizza_steak_sushi_20_percent.pth" (a little comprehensive but at least we know what's going on).

In [15]:
from going_modular.going_modular import utils

# Save the model
utils.save_model(model=effnetb2,
                 target_dir="models",
                 model_name="09_pretrained_effnetb2_feature_extractor_pizza_steak_sushi_20_percent.pth")
[INFO] Saving model to: models/09_pretrained_effnetb2_feature_extractor_pizza_steak_sushi_20_percent.pth

TK - Checking the size of EffNetB2

Since one of our criteria for deploying a model to power FoodVision Mini is speed (~30FPS or better), let's check the size of our model.

Why check the size?

Well, while not always the case, the size of a model can influence its inference speed.

As in, if a model has more parameters, it generally performs more operations and each one of these operations requires some computing power.

And because we'd like our model to work on devices with limited computing power (e.g. on a mobile device or in a web browser), generally, the smaller the size the better (as long as it still performs well in terms of accuracy).

To check our model's size in bytes, we can use pathlib.Path.stat("path_to_model").st_size and then we can convert it (roughly) to megabytes by dividing it by (1024*1024).

In [16]:
from pathlib import Path

# Get the model size in bytes then convert to megabytes
pretrained_effnetb2_model_size = Path("models/09_pretrained_effnetb2_feature_extractor_pizza_steak_sushi_20_percent.pth").stat().st_size // (1024*1024) # division converts bytes to megabytes (roughly) 
print(f"Pretrained EffNetB2 feature extractor model size: {pretrained_effnetb2_model_size} MB")
Pretrained EffNetB2 feature extractor model size: 29 MB

TK - Collecting EffNetB2 stats

We've got a few statistics about our EffNetB2 model such as test loss, test accuracy and model size, how about we collect them all in a dictionary so we can compare them to the upcoming ViT feature extractor.

And we'll calculate an extra one for fun, total number of parameters.

We can do so by counting the number of elements (or patterns/weights) in effnetb2.parameters(). We'll access the number of elements in each parameter using the torch.numel() (short for "number of elements") method.

In [17]:
# Count number of parameters in EffNetB2
effnetb2_total_params = sum(torch.numel(param) for param in effnetb2.parameters())
effnetb2_total_params
Out [17]:
7705221

Excellent!

Now let's put everything in a dictionary so we can make comparisons later on.

In [18]:
# Create a dictionary with EffNetB2 statistics
effnetb2_stats = {"test_loss": effnetb2_results["test_loss"][-1],
                  "test_acc": effnetb2_results["test_acc"][-1],
                  "number_of_parameters": effnetb2_total_params,
                  "model_size (MB)": pretrained_effnetb2_model_size}
effnetb2_stats
Out [18]:
{'test_loss': 0.281286683678627,
 'test_acc': 0.96875,
 'number_of_parameters': 7705221,
 'model_size (MB)': 29}

Epic! Looks like our EffNetB2 model is performing at over 95% accuracy! Criteria number 1: perform at 95%+ accuracy, tick!

TK - Creating a ViT feature extractor

Time to continue with our FoodVision Mini modelling experiments.

This time we're going to create a ViT feature extractor.

And we'll do it in much the same way as the EffNetB2 feature extractor except this time with torchvision.models.vit_b_16() instead of torchvision.models.efficientnet_b2().

We'll start by creating a function called create_vit_model() which will be very similar to create_effnetb2_model() except of course returning a ViT feature extractor model and transforms rather than EffNetB2.

Another slight difference is that torchvision.models.vit_b_16()'s output layer is called heads rather than classifier.

In [19]:
# Check out ViT heads layer
vit = torchvision.models.vit_b_16()
vit.heads
Out [19]:
Sequential(
  (head): Linear(in_features=768, out_features=1000, bias=True)
)

Knowing this, we've got all the pieces of the puzzle we need.

In [20]:
def create_vit_model(num_classes:int=3, 
                     seed:int=42):
    """Creates a ViT-B/16 feature extractor model and transforms.

    Args:
        num_classes (int, optional): number of target classes. Defaults to 3.
        seed (int, optional): random seed value for output layer. Defaults to 42.

    Returns:
        model (torch.nn.Module): ViT-B/16 feature extractor model. 
        transforms (torchvision.transforms): ViT-B/16 image transforms.
    """
    # Create EffNetB2 pretrained weights, transforms and model
    weights = torchvision.models.ViT_B_16_Weights.DEFAULT
    transforms = weights.transforms()
    model = torchvision.models.vit_b_16(weights=weights)

    # Freeze all layers in model
    for param in model.parameters():
        param.requires_grad = False

    # Change classifier head to suit our needs (this will be trainable)
    torch.manual_seed(seed)
    model.heads = nn.Sequential(nn.Linear(in_features=768, # keep this the same as original model
                                          out_features=num_classes)) # update to reflect target number of classes
    
    return model, transforms

ViT feature extraction model creation function ready!

Let's test it out.

In [21]:
# Create ViT model and transforms
vit, vit_transforms = create_vit_model(num_classes=3,
                                       seed=42)

No errors, lovely to see!

Now let's get a nice-looking summary of our ViT model using torchinfo.summary().

In [22]:
from torchinfo import summary
summary(vit, 
        input_size=(1, 3, 224, 224),
        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
======================================================================================================================================================
VisionTransformer (VisionTransformer)                                  [1, 3, 224, 224]     [1, 3]               768                  Partial
├─Conv2d (conv_proj)                                                   [1, 3, 224, 224]     [1, 768, 14, 14]     (590,592)            False
├─Encoder (encoder)                                                    [1, 197, 768]        [1, 197, 768]        151,296              False
│    └─Dropout (dropout)                                               [1, 197, 768]        [1, 197, 768]        --                   --
│    └─Sequential (layers)                                             [1, 197, 768]        [1, 197, 768]        --                   False
│    │    └─EncoderBlock (encoder_layer_0)                             [1, 197, 768]        [1, 197, 768]        (7,087,872)          False
│    │    └─EncoderBlock (encoder_layer_1)                             [1, 197, 768]        [1, 197, 768]        (7,087,872)          False
│    │    └─EncoderBlock (encoder_layer_2)                             [1, 197, 768]        [1, 197, 768]        (7,087,872)          False
│    │    └─EncoderBlock (encoder_layer_3)                             [1, 197, 768]        [1, 197, 768]        (7,087,872)          False
│    │    └─EncoderBlock (encoder_layer_4)                             [1, 197, 768]        [1, 197, 768]        (7,087,872)          False
│    │    └─EncoderBlock (encoder_layer_5)                             [1, 197, 768]        [1, 197, 768]        (7,087,872)          False
│    │    └─EncoderBlock (encoder_layer_6)                             [1, 197, 768]        [1, 197, 768]        (7,087,872)          False
│    │    └─EncoderBlock (encoder_layer_7)                             [1, 197, 768]        [1, 197, 768]        (7,087,872)          False
│    │    └─EncoderBlock (encoder_layer_8)                             [1, 197, 768]        [1, 197, 768]        (7,087,872)          False
│    │    └─EncoderBlock (encoder_layer_9)                             [1, 197, 768]        [1, 197, 768]        (7,087,872)          False
│    │    └─EncoderBlock (encoder_layer_10)                            [1, 197, 768]        [1, 197, 768]        (7,087,872)          False
│    │    └─EncoderBlock (encoder_layer_11)                            [1, 197, 768]        [1, 197, 768]        (7,087,872)          False
│    └─LayerNorm (ln)                                                  [1, 197, 768]        [1, 197, 768]        (1,536)              False
├─Sequential (heads)                                                   [1, 768]             [1, 3]               --                   True
│    └─Linear (0)                                                      [1, 768]             [1, 3]               2,307                True
======================================================================================================================================================
Total params: 85,800,963
Trainable params: 2,307
Non-trainable params: 85,798,656
Total mult-adds (M): 172.47
======================================================================================================================================================
Input size (MB): 0.60
Forward/backward pass size (MB): 104.09
Params size (MB): 257.55
Estimated Total Size (MB): 362.24
======================================================================================================================================================

TK image - summary output

Just like our EffNetB2 feature extractor model, our ViT model's base layers are frozen and the output layer is customized to our needs!

Do you notice the big difference though?

Our ViT model has far more parameters than our EffNetB2 model. Perhaps this will come into play when we compare are our models across speed and performance later on.

TK - Create DataLoaders for ViT

We've got our ViT model ready, now let's create some DataLoaders for it.

We'll do this in the same way we did for EffNetB2 except we'll use vit_transforms to transform our images into the same format the ViT model was trained on.

In [23]:
# Setup ViT DataLoaders
from going_modular.going_modular import data_setup
train_dataloader_vit, test_dataloader_vit, class_names = data_setup.create_dataloaders(train_dir=train_dir,
                                                                                       test_dir=test_dir,
                                                                                       transform=vit_transforms,
                                                                                       batch_size=32)

TK - Training ViT

You know what time it is...

...it's traininggggggg time (sung in the same tune as the song Closing Time).

Let's train our ViT feature extractor model for 10 epochs using our engine.train() function with torch.optim.Adam() and a learning rate of 1e-3 as our optimizer and torch.nn.CrossEntropyLoss() as our loss function.

We'll use our set_seeds() function before training to try and make our results as reproducible as possible.

In [24]:
from going_modular.going_modular import engine

# Setup optimizer
optimizer = torch.optim.Adam(params=vit.parameters(),
                             lr=1e-3)
# Setup loss function
loss_fn = torch.nn.CrossEntropyLoss()

# Train ViT model with seeds set for reproducibility
set_seeds()
vit_results = engine.train(model=vit,
                           train_dataloader=train_dataloader_vit,
                           test_dataloader=test_dataloader_vit,
                           epochs=10,
                           optimizer=optimizer,
                           loss_fn=loss_fn,
                           device=device)
  0%|          | 0/10 [00:00<?, ?it/s]
Epoch: 1 | train_loss: 0.7023 | train_acc: 0.7500 | test_loss: 0.2714 | test_acc: 0.9290
Epoch: 2 | train_loss: 0.2531 | train_acc: 0.9104 | test_loss: 0.1669 | test_acc: 0.9602
Epoch: 3 | train_loss: 0.1766 | train_acc: 0.9542 | test_loss: 0.1270 | test_acc: 0.9693
Epoch: 4 | train_loss: 0.1277 | train_acc: 0.9625 | test_loss: 0.1072 | test_acc: 0.9722
Epoch: 5 | train_loss: 0.1163 | train_acc: 0.9646 | test_loss: 0.0950 | test_acc: 0.9784
Epoch: 6 | train_loss: 0.1270 | train_acc: 0.9375 | test_loss: 0.0830 | test_acc: 0.9722
Epoch: 7 | train_loss: 0.0899 | train_acc: 0.9771 | test_loss: 0.0844 | test_acc: 0.9784
Epoch: 8 | train_loss: 0.0928 | train_acc: 0.9812 | test_loss: 0.0759 | test_acc: 0.9722
Epoch: 9 | train_loss: 0.0933 | train_acc: 0.9792 | test_loss: 0.0729 | test_acc: 0.9784
Epoch: 10 | train_loss: 0.0662 | train_acc: 0.9833 | test_loss: 0.0642 | test_acc: 0.9847

TK - Inspecting ViT loss curves

Alright, alright, alright, ViT model trained, let's get visual and see some loss curves.

Note: Don't forget you can see what an ideal set of loss curves should look like in 04. PyTorch Custom Datasets section 8.

In [25]:
from helper_functions import plot_loss_curves

plot_loss_curves(vit_results)

Ohh yeah!

Those are some nice looking loss curves. Just like our EffNetB2 feature extractor model, it looks our ViT model might benefit from a little longer training time and perhaps some data augmentation (to help prevent overfitting).

TK - Saving ViT

Our ViT model is performing outstanding!

So let's save it to file so we can import it and use it later if we wish.

We can do so using the utils.save_model() function we created in 05. PyTorch Going Modular section 5.

In [26]:
# Save the model
from going_modular.going_modular import utils

utils.save_model(model=vit,
                 target_dir="models",
                 model_name="09_pretrained_vit_feature_extractor_pizza_steak_sushi_20_percent.pth")
[INFO] Saving model to: models/09_pretrained_vit_feature_extractor_pizza_steak_sushi_20_percent.pth

TK - Checking the size of ViT

And since we want to compare our EffNetB2 model to our ViT model across a number of characteristics, let's find out its size.

To check our model's size in bytes, we can use Python's pathlib.Path.stat("path_to_model").st_size and then we can convert it (roughly) to megabytes by dividing it by (1024*1024).

In [27]:
from pathlib import Path

# Get the model size in bytes then convert to megabytes
pretrained_vit_model_size = Path("models/09_pretrained_vit_feature_extractor_pizza_steak_sushi_20_percent.pth").stat().st_size // (1024*1024) # division converts bytes to megabytes (roughly) 
print(f"Pretrained ViT feature extractor model size: {pretrained_vit_model_size} MB")
Pretrained ViT feature extractor model size: 327 MB

Hmm, how does the ViT feature extractor model size compare to our EffNetB2 model size?

We'll find this out shortly when we compare all of our model's characteristics.

TK - Collecting ViT stats

Let's put together all of our ViT model statistics.

We saw it in the summary output above but we'll calculate its total number of parameters.

In [28]:
# Count number of parameters in ViT
vit_total_params = sum(torch.numel(param) for param in vit.parameters())
vit_total_params
Out [28]:
85800963

Woah, that looks like a fair bit more than our EffNetB2!

Note: A larger number of parameters (or weights/patterns) generally means a model has a higher capacity to learn, whether it actually uses this extra capacity is another story. In light of this, our EffNetB2 model has 7,705,221 parameters where as our ViT model has 85,800,963 (11.1x more) so we could assume that our ViT model has more of a capacity to learn, if given more data (more opportunities to learn). However, this larger capacity to learn ofen comes with an increased model filesize and a longer time to perform inference.

Now let's create a dictionary with some important characteristics of our ViT model.

In [29]:
# Create ViT statistics dictionary
vit_stats = {"test_loss": vit_results["test_loss"][-1],
             "test_acc": vit_results["test_acc"][-1],
             "number_of_parameters": vit_total_params,
             "model_size (MB)": pretrained_vit_model_size}

vit_stats
Out [29]:
{'test_loss': 0.06418213145807386,
 'test_acc': 0.984659090909091,
 'number_of_parameters': 85800963,
 'model_size (MB)': 327}

Nice! Looks like our ViT model achieves over 95% accuracy too.

TK - Making predictions with our trained models and timing them

We've got a couple of trained models, both performing pretty well.

Now how about we test them out doing what we'd like them to do?

As in, let's see how they go making predictions (performing inference).

We know both of our models are performing at over 95% accuracy, but how fast are they?

Ideally, if we're deploying our FoodVision Mini model to a mobile device so people can take photos of their food and identify it, we'd like the predictions to happen at real-time (~30 frames per second).

That's why our second criteria is: a fast model.

To find out how long each of our models take to performance inference, let's create a function called pred_and_store() to iterate over each of the test dataset images one by one and perform a prediction.

We'll time each of the predictions as well as store the results in a common prediction format: a list of dictionaries (where each single prediction is its own dictionary).

Note: We time the predictions one by one rather than by batch because when our model is deployed, it will likely only be making a prediction on one image at a time. As in, someone takes a photo and our model predicts on that single image.

Since we'd like to make predictions across all the images in the test set, let's first get a list of all of the test image paths so we can iterate over them.

To do so, we'll use Python's pathlib.Path("target_dir").glob("*/*.jpg")) to find all of the filepaths in a target directory with the extension .jpg (all of our test images).

In [30]:
from pathlib import Path

# Get all test data paths
print(f"[INFO] Finding all filepaths ending with '.jpg' in directory: {test_dir}")
test_data_paths = list(Path(test_dir).glob("*/*.jpg"))
test_data_paths[:5]
Out [30]:
[INFO] Finding all filepaths ending with '.jpg' in directory: data/pizza_steak_sushi_20_percent/test
[PosixPath('data/pizza_steak_sushi_20_percent/test/steak/831681.jpg'),
 PosixPath('data/pizza_steak_sushi_20_percent/test/steak/3100563.jpg'),
 PosixPath('data/pizza_steak_sushi_20_percent/test/steak/2752603.jpg'),
 PosixPath('data/pizza_steak_sushi_20_percent/test/steak/39461.jpg'),
 PosixPath('data/pizza_steak_sushi_20_percent/test/steak/730464.jpg')]

TK - Creating a function to make predictions across the test dataset

Now we've got a list of our test image paths, let's get to work on our pred_and_store() function:

  1. Create a function that takes a list of paths, a trained PyTorch model, a series of transforms (to prepare images), a list of target class names and a target device.
  2. Create an empty list to store prediction dictionaries (we want the function to return a list of dictionaries, one for each prediction).
  3. Loop through the target input paths (steps 4-14 will happen inside the loop).
  4. Create an empty dictionary for each iteration in the loop to store prediction values per sample.
  5. Get the sample path and ground truth class name (we can do this by infering the class from the path).
  6. Start the prediction timer using Python's timeit.default_timer.
  7. Open the image using PIL.Image.open(path).
  8. Transform the image so it's capable of being using with the target model as well as add a batch dimension and send the image to the target device.
  9. Prepare the model for inference by sending it to the target device and turning on eval() mode.
  10. Turn on torch.inference_mode() and pass the target transformed image to the model and calculate the prediction probability using torch.softmax() and the target label using torch.argmax().
  11. Add the prediction probability and prediction class to the prediction dictionary created in step 4. Also make sure the prediction probability is on the CPU so it can be used with non-GPU libraries such as NumPy and pandas for later inspection.
  12. End the prediction timer started in step 6 and add the time to the prediction dictionary created in step 4.
  13. See if the predicted class matches the ground truth class from step 5 and add the result to the prediction dictionary created in step 4.
  14. Append the updated prediction dictionary to the empty list of predictions created in step 2.
  15. Return the list of prediction dictionaries.

A bunch of steps, but nothing we can't handle!

Let's do it.

In [31]:
import pathlib
import torch

from PIL import Image
from timeit import default_timer as timer 
from tqdm.auto import tqdm
from typing import List, Dict

# 1. Create a function to return a list of dictionaries with sample, truth label, prediction, prediction probability and prediction time
def pred_and_store(paths: List[pathlib.Path], 
                   model: torch.nn.Module,
                   transform: torchvision.transforms, 
                   class_names: List[str], 
                   device: str = "cuda" if torch.cuda.is_available() else "cpu") -> List[Dict]:
    
    # 2. Create an empty list to store prediction dictionaires
    pred_list = []
    
    # 3. Loop through target paths
    for path in tqdm(paths):
        
        # 4. Create empty dictionary to store prediction information for each sample
        pred_dict = {}

        # 5. Get the sample path and ground truth class name
        pred_dict["image_path"] = path
        class_name = path.parent.stem
        pred_dict["class_name"] = class_name
        
        # 6. Start the prediction timer
        start_time = timer()
        
        # 7. Open image path
        img = Image.open(path)
        
        # 8. Transform the image, add batch dimension and put image on target device
        transformed_image = transform(img).unsqueeze(0).to(device) 
        
        # 9. Prepare model for inference by sending it to target device and turning on eval() mode
        model.to(device)
        model.eval()
        
        # 10. Get prediction probability, predicition label and prediction class
        with torch.inference_mode():
            pred_logit = model(transformed_image) # perform inference on target sample 
            pred_prob = torch.softmax(pred_logit, dim=1) # turn logits into prediction probabilities
            pred_label = torch.argmax(pred_prob, dim=1) # turn prediction probabilities into prediction label
            pred_class = class_names[pred_label.cpu()] # hardcode prediction class to be on CPU

            # 11. Make sure things in the dictionary are on CPU (required for inspecting predictions later on) 
            pred_dict["pred_prob"] = round(pred_prob.unsqueeze(0).max().cpu().item(), 4)
            pred_dict["pred_class"] = pred_class
            
            # 12. End the timer and calculate time per pred
            end_time = timer()
            pred_dict["time_for_pred"] = round(end_time-start_time, 4)

        # 13. Does the pred match the true label?
        pred_dict["correct"] = class_name == pred_class

        # 14. Add the dictionary to the list of preds
        pred_list.append(pred_dict)
    
    # 15. Return list of prediction dictionaries
    return pred_list

Ho, ho!

What a good looking function!

And you know what, since our pred_and_store() is a pretty good utility function for making and storing predictions, it could be stored to going_modular.going_modular.predictions.py for later use. That might be an extension you'd like to try, check out 05. PyTorch Going Modular for ideas.

TK - Making and timing predictions with EffNetB2

Time to test out our pred_and_store() function!

Let's start by using it to make predictions across the test dataset with our EffNetB2 model, paying attention to two details:

  1. Device - We'll hard code the device parameter to use "cpu" because when we deploy our model, we won't always have access to a "cuda" (GPU) device.
    • Making the predictions on CPU will be a good indicator of speed of inference too because generally predictions on CPU devices are slower than GPU devices.
  2. Transforms - We'll also be sure to set the transform parameter to effnetb2_transforms to make sure the images are opened and transformed in the same way our effnetb2 model has been trained on.
In [32]:
# Make predictions across test dataset with EffNetB2
effnetb2_test_pred_dicts = pred_and_store(paths=test_data_paths,
                                          model=effnetb2,
                                          transform=effnetb2_transforms,
                                          class_names=class_names,
                                          device="cpu") # make predictions on CPU 
  0%|          | 0/150 [00:00<?, ?it/s]

Nice! Look at those predictions fly!

Let's inspect the first couple and see what they look like.

In [33]:
# Inspect the first 2 prediction dictionaries
effnetb2_test_pred_dicts[:2]
Out [33]:
[{'image_path': PosixPath('data/pizza_steak_sushi_20_percent/test/steak/831681.jpg'),
  'class_name': 'steak',
  'pred_prob': 0.9293,
  'pred_class': 'steak',
  'time_for_pred': 0.0575,
  'correct': True},
 {'image_path': PosixPath('data/pizza_steak_sushi_20_percent/test/steak/3100563.jpg'),
  'class_name': 'steak',
  'pred_prob': 0.9534,
  'pred_class': 'steak',
  'time_for_pred': 0.0381,
  'correct': True}]

Woohoo!

It looks like our pred_and_store() function worked nicely.

Thanks to our list of dictionaries data structure, we've got plenty of useful information we can further inspect.

To do so, let's turn our list of dictionaries into a pandas DataFrame.

In [34]:
# Turn the test_pred_dicts into a DataFrame
import pandas as pd
effnetb2_test_pred_df = pd.DataFrame(effnetb2_test_pred_dicts)
effnetb2_test_pred_df.head()
Out [34]:
image_path class_name pred_prob pred_class time_for_pred correct
0 data/pizza_steak_sushi_20_percent/test/steak/8... steak 0.9293 steak 0.0575 True
1 data/pizza_steak_sushi_20_percent/test/steak/3... steak 0.9534 steak 0.0381 True
2 data/pizza_steak_sushi_20_percent/test/steak/2... steak 0.7531 steak 0.0370 True
3 data/pizza_steak_sushi_20_percent/test/steak/3... steak 0.5935 steak 0.0311 True
4 data/pizza_steak_sushi_20_percent/test/steak/7... steak 0.8959 steak 0.0317 True

Beautiful!

Look how easily those prediction dictionaries turn into a structured format we can perform analysis on.

Such as finding how many predictions our EffNetB2 model got wrong...

In [35]:
# Check number of correct predictions
effnetb2_test_pred_df.correct.value_counts()
Out [35]:
True     145
False      5
Name: correct, dtype: int64

Five wrong predictions out of 150 total, not bad!

And how about the average prediction time?

In [36]:
# Find the average time per prediction 
effnetb2_average_time_per_pred = round(effnetb2_test_pred_df.time_for_pred.mean(), 4)
print(f"EffNetB2 average time per prediction: {effnetb2_average_time_per_pred} seconds")
EffNetB2 average time per prediction: 0.0311 seconds

Hmm, how does that average prediction time live up to our criteria of our model performing at real-time (~30FPS or 0.03 seconds per prediction)?

Note: Prediction times will be different across different hardware types (e.g. a local Intel i9 vs Google Colab CPU). The better and faster the hardware, generally, the faster the prediction. For example, on my local deep learning PC with an Intel i9 chip, my average prediction time with EffNetB2 is around 0.031 seconds (just under real-time). However, on Google Colab (I'm not sure what CPU hardware Colab uses but it looks like it might be an Intel(R) Xeon(R)), my average prediction time with EffNetB2 is about 0.1396 seconds (3-4x slower).

Let's add our EffNetB2 average time per prediction to our effnetb2_stats dictionary.

In [37]:
# Add EffNetB2 average prediction time to stats dictionary 
effnetb2_stats["time_per_pred_cpu"] = effnetb2_average_time_per_pred
effnetb2_stats
Out [37]:
{'test_loss': 0.281286683678627,
 'test_acc': 0.96875,
 'number_of_parameters': 7705221,
 'model_size (MB)': 29,
 'time_per_pred_cpu': 0.0311}

TK - Making and timing predictions with ViT

We've made predictions with our EffNetB2 model, now let's do the same for our ViT model.

To do so, we can use the pred_and_store() function we created above except this time we'll pass in our vit model as well as the vit_transforms.

And we'll keep the predictions on the CPU via device="cpu" (a natural extension here would be to test the prediction times on CPU and on GPU).

In [38]:
# Make list of prediction dictionaries with ViT feature extractor model on test images
vit_test_pred_dicts = pred_and_store(paths=test_data_paths,
                                     model=vit,
                                     transform=vit_transforms,
                                     class_names=class_names,
                                     device="cpu")
  0%|          | 0/150 [00:00<?, ?it/s]

Predictions made!

Now let's check out the first couple.

In [39]:
# Check the first couple of ViT predictions on the test dataset
vit_test_pred_dicts[:2]
Out [39]:
[{'image_path': PosixPath('data/pizza_steak_sushi_20_percent/test/steak/831681.jpg'),
  'class_name': 'steak',
  'pred_prob': 0.9933,
  'pred_class': 'steak',
  'time_for_pred': 0.1643,
  'correct': True},
 {'image_path': PosixPath('data/pizza_steak_sushi_20_percent/test/steak/3100563.jpg'),
  'class_name': 'steak',
  'pred_prob': 0.9893,
  'pred_class': 'steak',
  'time_for_pred': 0.099,
  'correct': True}]

Wonderful!

And just like before, since our ViT model's predictions are in the form of a list of dictionaries, we can easily turn them into a pandas DataFrame for further inspection.

In [40]:
# Turn vit_test_pred_dicts into a DataFrame
import pandas as pd
vit_test_pred_df = pd.DataFrame(vit_test_pred_dicts)
vit_test_pred_df.head()
Out [40]:
image_path class_name pred_prob pred_class time_for_pred correct
0 data/pizza_steak_sushi_20_percent/test/steak/8... steak 0.9933 steak 0.1643 True
1 data/pizza_steak_sushi_20_percent/test/steak/3... steak 0.9893 steak 0.0990 True
2 data/pizza_steak_sushi_20_percent/test/steak/2... steak 0.9971 steak 0.0637 True
3 data/pizza_steak_sushi_20_percent/test/steak/3... steak 0.7685 steak 0.0645 True
4 data/pizza_steak_sushi_20_percent/test/steak/7... steak 0.9499 steak 0.0649 True

How many predictions did our ViT model get correct?

In [41]:
# Count the number of correct predictions
vit_test_pred_df.correct.value_counts()
Out [41]:
True     148
False      2
Name: correct, dtype: int64

Woah!

Our ViT model did a little better than our EffNetB2 model in terms of correct predictions, only two samples wrong across the whole test dataset.

As an extension you might want to visualize the ViT model's wrong predictions and see if there's any reason why it might've got them wrong.

How about we calculate how long the ViT model took per prediction?

In [42]:
# Calculate average time per prediction for ViT model
vit_average_time_per_pred = round(vit_test_pred_df.time_for_pred.mean(), 4)
print(f"ViT average time per prediction: {vit_average_time_per_pred} seconds")
ViT average time per prediction: 0.0661 seconds

Well, that looks a little slower than our EffNetB2 model's average time per prediction but how does it look in terms of our second criteria: speed?

For now, let's add the value to our vit_stats dictionary so we can compare it to our EffNetB2 model's stats.

Note: The average time per prediction values will be highly dependent on the hardware you make them on. For example, for the ViT model, my average time per prediction (on the CPU) was 0.0693-0.0777 seconds on my local deep learning PC with an Intel i9 CPU. Where as on Google Colab, my average time per prediction with the ViT model was 0.6766-0.7113 seconds.

In [43]:
# Add average prediction time for ViT model on CPU
vit_stats["time_per_pred_cpu"] = vit_average_time_per_pred
vit_stats
Out [43]:
{'test_loss': 0.06418213145807386,
 'test_acc': 0.984659090909091,
 'number_of_parameters': 85800963,
 'model_size (MB)': 327,
 'time_per_pred_cpu': 0.0661}

TK - Comparing model results, prediction times and size

Our two best model contenders have been trained and evaluated.

Now let's put them head to head and compare across their different statistics.

To do so, let's turn our effnetb2_stats and vit_stats dictionaries into a pandas DataFrame.

We'll add a column to view the model names as well as the convert the test accuracy to a whole percentage rather than decimal.

In [44]:
# Turn stat dictionaries into DataFrame
df = pd.DataFrame([effnetb2_stats, vit_stats])

# Add column for model names
df["model"] = ["EffNetB2", "ViT"]

# Convert accuracy to percentages
df["test_acc"] = round(df["test_acc"] * 100, 2)

df
Out [44]:
test_loss test_acc number_of_parameters model_size (MB) time_per_pred_cpu model
0 0.281287 96.88 7705221 29 0.0311 EffNetB2
1 0.064182 98.47 85800963 327 0.0661 ViT
Warning:
Output truncated. This notebook contains too many cells to display efficiently.