Files
pytorch-deep-learning/07_pytorch_experiment_tracking.ipynb
T
2022-05-31 11:41:31 +10:00

50 KiB

(WIP) 07. PyTorch Experiment Tracking

This notebook tries several different models with different types of data augmentation and tracks the results to compare them.

TODO:

Start with one model + tracking experiments, then upgrade to more.

TK 0. Getting setup

In [2]:
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
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

Setup device

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

TK 1. Get data

In [4]:
import os
import zipfile

from pathlib import Path

import requests

def download_data(source: str, 
                  destination: str,
                  remove_source: bool = True) -> Path:
    """Downloads a zipped dataset from source and unzips to destination.

    Args:
        source (str): A link to a zipped file containing data.
        destination (str): A target directory to unzip data to.
        remove_source (bool): Whether to remove the source after downloading and extracting.
    
    Returns:
        pathlib.Path to downloaded data.
    
    Example usage:
        download_data(source="https://github.com/mrdbourke/pytorch-deep-learning/raw/main/data/pizza_steak_sushi.zip",
                      destination="pizza_steak_sushi")
    """
    # Setup path to data folder
    data_path = Path("data/")
    image_path = data_path / destination

    # If the image folder doesn't exist, download it and prepare it... 
    if image_path.is_dir():
        print(f"[INFO] {image_path} directory exists, skipping download.")
    else:
        print(f"[INFO] Did not find {image_path} directory, creating one...")
        image_path.mkdir(parents=True, exist_ok=True)
        
        # Download pizza, steak, sushi data
        target_file = Path(source).name
        with open(data_path / target_file, "wb") as f:
            request = requests.get(source)
            print(f"[INFO] Downloading {target_file} from {source}...")
            f.write(request.content)

        # Unzip pizza, steak, sushi data
        with zipfile.ZipFile(data_path / target_file, "r") as zip_ref:
            print(f"[INFO] Unzipping {target_file} data...") 
            zip_ref.extractall(image_path)

        # Remove .zip file
        if remove_source:
            os.remove(data_path / target_file)
    
    return image_path

image_path = download_data(source="https://github.com/mrdbourke/pytorch-deep-learning/raw/main/data/pizza_steak_sushi.zip",
                           destination="pizza_steak_sushi")
image_path
Out [4]:
[INFO] data/pizza_steak_sushi directory exists, skipping download.
PosixPath('data/pizza_steak_sushi')

TK 2. Create Datasets and DataLoaders

In [5]:
# Setup dirs
train_dir = image_path / "train"
test_dir = image_path / "test"

# Setup ImageNet normalization levels (turns all images into similar distribution as ImageNet)
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                 std=[0.229, 0.224, 0.225])

# Create starter transform
simple_transform = transforms.Compose([
    transforms.Resize((224, 224)),
    transforms.ToTensor(),
    normalize
])           

# Create data loaders
train_dataloader, test_dataloader, class_names = data_setup.create_dataloaders(
    train_dir=train_dir,
    test_dir=test_dir,
    transform=simple_transform,
    batch_size=32
)

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

TK 3. Getting a pretrained model, freezing the base layers and changing the classifier head

In [6]:
model = torchvision.models.efficientnet_b0(pretrained=True).to(device)
# model
In [7]:
torch.manual_seed(42)
torch.cuda.manual_seed(42)

# Update the classifier
model.classifier = torch.nn.Sequential(
    nn.Dropout(p=0.2),
    nn.Linear(1280, len(class_names)).to(device))

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

TK 4. Train model and track results

In [8]:
# Define loss and optimizer
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)

TK Adjust training function to track results with SummaryWriter

See SummaryWriter() here: https://pytorch.org/docs/stable/tensorboard.html

In [9]:
model.name = "EfficietNetB0"
model.name
Out [9]:
'EfficietNetB0'
In [10]:
from torch.utils.tensorboard import SummaryWriter
from going_modular.going_modular.engine import train_step, test_step

writer = SummaryWriter()
In [11]:
from typing import Dict, List
from tqdm.auto import tqdm
def train(model: torch.nn.Module, 
          train_dataloader: torch.utils.data.DataLoader, 
          test_dataloader: torch.utils.data.DataLoader, 
          optimizer: torch.optim.Optimizer,
          loss_fn: torch.nn.Module,
          epochs: int,
          device: torch.device) -> Dict[str, List]:
    """Trains and tests a PyTorch model.
    Passes a target PyTorch models through train_step() and test_step()
    functions for a number of epochs, training and testing the model
    in the same epoch loop.
    Calculates, prints and stores evaluation metrics throughout.
    Args:
    model: A PyTorch model to be trained and tested.
    train_dataloader: A DataLoader instance for the model to be trained on.
    test_dataloader: A DataLoader instance for the model to be tested on.
    optimizer: A PyTorch optimizer to help minimize the loss function.
    loss_fn: A PyTorch loss function to calculate loss on both datasets.
    epochs: An integer indicating how many epochs to train for.
    device: A target device to compute on (e.g. "cuda" or "cpu").
    Returns:
    A dictionary of training and testing loss as well as training and
    testing accuracy metrics. Each metric has a value in a list for 
    each epoch.
    In the form: {train_loss: [...],
              train_acc: [...],
              test_loss: [...],
              test_acc: [...]} 
    For example if training for epochs=2: 
             {train_loss: [2.0616, 1.0537],
              train_acc: [0.3945, 0.3945],
              test_loss: [1.2641, 1.5706],
              test_acc: [0.3400, 0.2973]} 
    """
    # Create empty results dictionary
    results = {"train_loss": [],
               "train_acc": [],
               "test_loss": [],
               "test_acc": []
    }

    # Loop through training and testing steps for a number of epochs
    for epoch in tqdm(range(epochs)):
        train_loss, train_acc = train_step(model=model,
                                          dataloader=train_dataloader,
                                          loss_fn=loss_fn,
                                          optimizer=optimizer,
                                          device=device)
        test_loss, test_acc = test_step(model=model,
          dataloader=test_dataloader,
          loss_fn=loss_fn,
          device=device)

        # Print out what's happening
        print(
          f"Epoch: {epoch+1} | "
          f"train_loss: {train_loss:.4f} | "
          f"train_acc: {train_acc:.4f} | "
          f"test_loss: {test_loss:.4f} | "
          f"test_acc: {test_acc:.4f}"
        )

        # Update results dictionary
        results["train_loss"].append(train_loss)
        results["train_acc"].append(train_acc)
        results["test_loss"].append(test_loss)
        results["test_acc"].append(test_acc)

        # Add results to SummaryWriter
        writer.add_scalars(main_tag="Loss", 
                           tag_scalar_dict={"train_loss": train_loss,
                                            "test_loss": test_loss},
                           global_step=epoch)
        writer.add_scalars(main_tag="Accuracy", 
                           tag_scalar_dict={"train_acc": train_acc,
                                            "test_acc": test_acc}, 
                           global_step=epoch)
    
    # Close the writer
    writer.close()

    # Return the filled results at the end of the epochs
    return results
In [12]:
# Train model
# Note: Not using engine.train() since the original script isn't updated
results = train(model=model,
                train_dataloader=train_dataloader,
                test_dataloader=test_dataloader,
                optimizer=optimizer,
                loss_fn=loss_fn,
                epochs=5,
                device=device)
  0%|          | 0/5 [00:00<?, ?it/s]
Epoch: 1 | train_loss: 1.0520 | train_acc: 0.4961 | test_loss: 0.9212 | test_acc: 0.4782
Epoch: 2 | train_loss: 0.8743 | train_acc: 0.6875 | test_loss: 0.8136 | test_acc: 0.6203
Epoch: 3 | train_loss: 0.8097 | train_acc: 0.6523 | test_loss: 0.7196 | test_acc: 0.8258
Epoch: 4 | train_loss: 0.7096 | train_acc: 0.7578 | test_loss: 0.5920 | test_acc: 0.8864
Epoch: 5 | train_loss: 0.5999 | train_acc: 0.9062 | test_loss: 0.5689 | test_acc: 0.8864
In [16]:
# TK - view the above in TensorBoard...

TK Create a helper function to build SummaryWriter() instances

In [13]:
from datetime import datetime
datetime.now().strftime("%Y-%m-%d")
Out [13]:
'2022-05-31'
In [14]:
def create_writer(experiment_name, model_name, extra=None):
    # assert experiment_name, "experiment_name can't be None"
    # assert model_name, "model_name can't be None"

    # Get timestamp of current date (all experiments on certain day live in same folder)
    timestamp = datetime.now().strftime("%Y-%m-%d")

    if extra:
        log_dir = os.path.join("runs", timestamp, experiment_name, model_name, extra)
    else:
        log_dir = os.path.join("runs", timestamp, experiment_name, model_name)
    print(f"Created SummaryWriter and saving to {log_dir}...")
    return SummaryWriter(log_dir=log_dir)
In [17]:
# Add create_writer() to train()
from typing import Dict, List
from tqdm.auto import tqdm
def train(model: torch.nn.Module, 
          train_dataloader: torch.utils.data.DataLoader, 
          test_dataloader: torch.utils.data.DataLoader, 
          optimizer: torch.optim.Optimizer,
          loss_fn: torch.nn.Module,
          epochs: int,
          device: torch.device, 
          writer: torch.utils.tensorboard.writer.SummaryWriter) -> Dict[str, List]:
    """Trains and tests a PyTorch model.
    Passes a target PyTorch models through train_step() and test_step()
    functions for a number of epochs, training and testing the model
    in the same epoch loop.

    Calculates, prints and stores evaluation metrics throughout.

    Args:
      model: A PyTorch model to be trained and tested.
      train_dataloader: A DataLoader instance for the model to be trained on.
      test_dataloader: A DataLoader instance for the model to be tested on.
      optimizer: A PyTorch optimizer to help minimize the loss function.
      loss_fn: A PyTorch loss function to calculate loss on both datasets.
      epochs: An integer indicating how many epochs to train for.
      device: A target device to compute on (e.g. "cuda" or "cpu").

    Returns:
      A dictionary of training and testing loss as well as training and
      testing accuracy metrics. Each metric has a value in a list for 
      each epoch.
      In the form: {train_loss: [...],
                train_acc: [...],
                test_loss: [...],
                test_acc: [...]} 
      For example if training for epochs=2: 
              {train_loss: [2.0616, 1.0537],
                train_acc: [0.3945, 0.3945],
                test_loss: [1.2641, 1.5706],
                test_acc: [0.3400, 0.2973]} 
    """
    # Create empty results dictionary
    results = {"train_loss": [],
               "train_acc": [],
               "test_loss": [],
               "test_acc": []
    }

    # Loop through training and testing steps for a number of epochs
    for epoch in tqdm(range(epochs)):
        train_loss, train_acc = train_step(model=model,
                                          dataloader=train_dataloader,
                                          loss_fn=loss_fn,
                                          optimizer=optimizer,
                                          device=device)
        test_loss, test_acc = test_step(model=model,
          dataloader=test_dataloader,
          loss_fn=loss_fn,
          device=device)

        # Print out what's happening
        print(
          f"Epoch: {epoch+1} | "
          f"train_loss: {train_loss:.4f} | "
          f"train_acc: {train_acc:.4f} | "
          f"test_loss: {test_loss:.4f} | "
          f"test_acc: {test_acc:.4f}"
        )

        # Update results dictionary
        results["train_loss"].append(train_loss)
        results["train_acc"].append(train_acc)
        results["test_loss"].append(test_loss)
        results["test_acc"].append(test_acc)

        if writer:
            # Add results to SummaryWriter
            writer.add_scalars(main_tag="Loss", 
                            tag_scalar_dict={"train_loss": train_loss,
                                                "test_loss": test_loss},
                            global_step=epoch)
            writer.add_scalars(main_tag="Accuracy", 
                            tag_scalar_dict={"train_acc": train_acc,
                                                "test_acc": test_acc}, 
                            global_step=epoch)

            # Close the writer
            writer.close()
        else:
            pass
    
    # Close the writer
    writer.close()

    # Return the filled results at the end of the epochs
    return results

TK - Experiment creation

TK - exerpiments to track:

  • model_0 = 10% data, effnet_b0, 5 epochs
  • model_1 = 10% data, effnet_b0, 10 epochs (double training time)
  • model_2 = 20% data, effnet_b0, 5 epochs (double data)
  • model_3 = 10% data, effnet_b2, 5 epochs (double model parameters)

Want:

  • A list or dict of different models and experiments to run
  • Each experiment should run only changing the model or augmentation type
    • e.g. Experiment 1: model = EffNetB0, aug = None
    • Experiment 2: model = EffNetB4, aug = None

See a list of Torch pretrained models here: https://pytorch.org/vision/stable/models.html, all pretrained models are expected to have data inputs that are normalized with the following:

normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                 std=[0.229, 0.224, 0.225])
In [18]:
from torchvision import transforms

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

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

TK - Load data

In [19]:
data_10_percent_path = download_data(source="https://github.com/mrdbourke/pytorch-deep-learning/raw/main/data/pizza_steak_sushi.zip",
                                     destination="pizza_steak_sushi")

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")
[INFO] data/pizza_steak_sushi directory exists, skipping download.
[INFO] data/pizza_steak_sushi_20_percent directory exists, skipping download.
In [20]:
# Setup training directory paths
train_dir_10_percent = data_10_percent_path / "train"
train_dir_20_percent = data_20_percent_path / "train"

# Setup testing directory paths (note: use the same test dataset for both to compare the results)
test_dir = data_10_percent_path / "test"
In [21]:
# Create 10% dataloaders
train_dataloader_10_percent, test_dataloader, class_names = data_setup.create_dataloaders(train_dir=train_dir_10_percent,
    test_dir=test_dir,
    transform=simple_transform,
    batch_size=32
)

# Create 20% dataloaders
train_dataloader_20_percent, test_dataloader, class_names = data_setup.create_dataloaders(train_dir=train_dir_20_percent,
    test_dir=test_dir,
    transform=simple_transform,
    batch_size=32
)

# TK - number of samples/batches per dataloader (using the same test_dataloader for both experiments)
len(train_dataloader_10_percent), len(train_dataloader_20_percent), len(test_dataloader), len(class_names)
Out [21]:
(8, 15, 3, 3)

TK Setup models

  • Note: Many modern models can handle input images of varying sizes thanks to torch.nn.AdaptiveAvgPool2d(), this layer adaptively adjusts the output_size of a given input as required. You can try this out by passing different size input images to summary() or your models.
In [22]:
effnetb2 = torchvision.models.efficientnet_b2(pretrained=True).to(device)
summary(model=effnetb2, 
        input_size=(32, 3, 224, 224), # make sure this is "input_size", not "input_shape"
        # col_names=["input_size"], # uncomment for smaller output
        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, 1408, 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
│    │    └─MBConv (1)                                       [32, 16, 112, 112]   [32, 16, 112, 112]   612                  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
│    │    └─MBConv (2)                                       [32, 24, 56, 56]     [32, 24, 56, 56]     10,710               True
│    └─Sequential (3)                                        [32, 24, 56, 56]     [32, 48, 28, 28]     --                   True
│    │    └─MBConv (0)                                       [32, 24, 56, 56]     [32, 48, 28, 28]     16,518               True
│    │    └─MBConv (1)                                       [32, 48, 28, 28]     [32, 48, 28, 28]     43,308               True
│    │    └─MBConv (2)                                       [32, 48, 28, 28]     [32, 48, 28, 28]     43,308               True
│    └─Sequential (4)                                        [32, 48, 28, 28]     [32, 88, 14, 14]     --                   True
│    │    └─MBConv (0)                                       [32, 48, 28, 28]     [32, 88, 14, 14]     50,300               True
│    │    └─MBConv (1)                                       [32, 88, 14, 14]     [32, 88, 14, 14]     123,750              True
│    │    └─MBConv (2)                                       [32, 88, 14, 14]     [32, 88, 14, 14]     123,750              True
│    │    └─MBConv (3)                                       [32, 88, 14, 14]     [32, 88, 14, 14]     123,750              True
│    └─Sequential (5)                                        [32, 88, 14, 14]     [32, 120, 14, 14]    --                   True
│    │    └─MBConv (0)                                       [32, 88, 14, 14]     [32, 120, 14, 14]    149,158              True
│    │    └─MBConv (1)                                       [32, 120, 14, 14]    [32, 120, 14, 14]    237,870              True
│    │    └─MBConv (2)                                       [32, 120, 14, 14]    [32, 120, 14, 14]    237,870              True
│    │    └─MBConv (3)                                       [32, 120, 14, 14]    [32, 120, 14, 14]    237,870              True
│    └─Sequential (6)                                        [32, 120, 14, 14]    [32, 208, 7, 7]      --                   True
│    │    └─MBConv (0)                                       [32, 120, 14, 14]    [32, 208, 7, 7]      301,406              True
│    │    └─MBConv (1)                                       [32, 208, 7, 7]      [32, 208, 7, 7]      686,868              True
│    │    └─MBConv (2)                                       [32, 208, 7, 7]      [32, 208, 7, 7]      686,868              True
│    │    └─MBConv (3)                                       [32, 208, 7, 7]      [32, 208, 7, 7]      686,868              True
│    │    └─MBConv (4)                                       [32, 208, 7, 7]      [32, 208, 7, 7]      686,868              True
│    └─Sequential (7)                                        [32, 208, 7, 7]      [32, 352, 7, 7]      --                   True
│    │    └─MBConv (0)                                       [32, 208, 7, 7]      [32, 352, 7, 7]      846,900              True
│    │    └─MBConv (1)                                       [32, 352, 7, 7]      [32, 352, 7, 7]      1,888,920            True
│    └─ConvNormActivation (8)                                [32, 352, 7, 7]      [32, 1408, 7, 7]     --                   True
│    │    └─Conv2d (0)                                       [32, 352, 7, 7]      [32, 1408, 7, 7]     495,616              True
│    │    └─BatchNorm2d (1)                                  [32, 1408, 7, 7]     [32, 1408, 7, 7]     2,816                True
│    │    └─SiLU (2)                                         [32, 1408, 7, 7]     [32, 1408, 7, 7]     --                   --
├─AdaptiveAvgPool2d (avgpool)                                [32, 1408, 7, 7]     [32, 1408, 1, 1]     --                   --
├─Sequential (classifier)                                    [32, 1408]           [32, 1000]           --                   True
│    └─Dropout (0)                                           [32, 1408]           [32, 1408]           --                   --
│    └─Linear (1)                                            [32, 1408]           [32, 1000]           1,409,000            True
============================================================================================================================================
Total params: 9,109,994
Trainable params: 9,109,994
Non-trainable params: 0
Total mult-adds (G): 21.09
============================================================================================================================================
Input size (MB): 19.27
Forward/backward pass size (MB): 5017.79
Params size (MB): 36.44
Estimated Total Size (MB): 5073.49
============================================================================================================================================
In [23]:
len(effnetb2.classifier.state_dict()["1.weight"][0])
Out [23]:
1408
In [24]:
import torchvision
from torch import nn

# Set seeds
def set_seeds(seed=42):
    torch.manual_seed(seed)
    torch.cuda.manual_seed(seed)

# Get num out features
OUT_FEATURES = len(class_names)

# EfficientNetB0
def create_effnetb0():
    set_seeds()
    model = torchvision.models.efficientnet_b0(pretrained=True).to(device)
    model.classifier = nn.Sequential(
        nn.Dropout(p=0.2),
        nn.Linear(in_features=1280, out_features=OUT_FEATURES)
    ).to(device)
    for param in model.features.parameters():
        param.requires_grad = False
    model.name = "effnetb0"
    print(f"[INFO] Creating new {model.name} model.")
    return model

# EfficientNetB2
def create_effnetb2():
    set_seeds()
    model = torchvision.models.efficientnet_b2(pretrained=True).to(device)
    model.classifier = nn.Sequential(
        nn.Dropout(p=0.3),
        nn.Linear(in_features=1408, out_features=OUT_FEATURES)
    ).to(device)
    for param in model.features.parameters():
        param.requires_grad = False
    model.name = "effnetb2"
    print(f"[INFO] Creating new {model.name} model.")
    return model

Create experiments

In [25]:
# Create models list (need to create a new model for each experiment)
models = ["effnetb0", "effnetb2"]

# Create dataloaders dictionary for various dataloaders
train_dataloaders = {"data_10_percent": train_dataloader_10_percent,
                     "data_20_percent": train_dataloader_20_percent}
In [26]:
set_seeds()

# TK - make sure model is training from scratch each time, e.g. don't retrain the same model, a new one has to be created 
# TK - Loop through the dataloaders first to train a new model on each dataloader 
for dataloader_name, train_dataloader in train_dataloaders.items():
    for model_name in models:
        # Select the model
        if model_name == "effnetb0":
            model = create_effnetb0()
        else:
            model = create_effnetb2()
        
        # Create information print outs
        print(f"[INFO] Model: {model_name}")
        print(f"[INFO] DataLoader: {dataloader_name}")
        print(f"----------")        
        
        # Create a new loss and optimizer for every model
        loss_fn = nn.CrossEntropyLoss()
        optimizer = torch.optim.Adam(params=model.parameters(), lr=0.001)

        # Train target model with target dataloaders and track experiments
        train(model=model,
              train_dataloader=train_dataloader,
              test_dataloader=test_dataloader, 
              optimizer=optimizer,
              loss_fn=loss_fn,
              epochs=5,
              device=device,
              writer=create_writer(experiment_name=dataloader_name,
                                   model_name=model_name
             ))
        
        # TK - add functionality to save the best model / save all models and then get the best one?
        print("----------\n")
[INFO] Creating new effnetb0 model.
[INFO] Model: effnetb0
[INFO] DataLoader: data_10_percent
----------
Created SummaryWriter and saving to runs/2022-05-31/data_10_percent/effnetb0...
  0%|          | 0/5 [00:00<?, ?it/s]
Epoch: 1 | train_loss: 1.0302 | train_acc: 0.4375 | test_loss: 0.8725 | test_acc: 0.6629
Epoch: 2 | train_loss: 0.9131 | train_acc: 0.6484 | test_loss: 0.6730 | test_acc: 0.9062
Epoch: 3 | train_loss: 0.7303 | train_acc: 0.8516 | test_loss: 0.6539 | test_acc: 0.8655
Epoch: 4 | train_loss: 0.6947 | train_acc: 0.7578 | test_loss: 0.6534 | test_acc: 0.8456
Epoch: 5 | train_loss: 0.6930 | train_acc: 0.7695 | test_loss: 0.6130 | test_acc: 0.8665
----------

[INFO] Creating new effnetb2 model.
[INFO] Model: effnetb2
[INFO] DataLoader: data_10_percent
----------
Created SummaryWriter and saving to runs/2022-05-31/data_10_percent/effnetb2...
  0%|          | 0/5 [00:00<?, ?it/s]
Epoch: 1 | train_loss: 0.9841 | train_acc: 0.5391 | test_loss: 0.9598 | test_acc: 0.6610
Epoch: 2 | train_loss: 0.8143 | train_acc: 0.7109 | test_loss: 0.8642 | test_acc: 0.7330
Epoch: 3 | train_loss: 0.7728 | train_acc: 0.6719 | test_loss: 0.8046 | test_acc: 0.8163
Epoch: 4 | train_loss: 0.6622 | train_acc: 0.7773 | test_loss: 0.6918 | test_acc: 0.8665
Epoch: 5 | train_loss: 0.5634 | train_acc: 0.9258 | test_loss: 0.6887 | test_acc: 0.8570
----------

[INFO] Creating new effnetb0 model.
[INFO] Model: effnetb0
[INFO] DataLoader: data_20_percent
----------
Created SummaryWriter and saving to runs/2022-05-31/data_20_percent/effnetb0...
  0%|          | 0/5 [00:00<?, ?it/s]
Epoch: 1 | train_loss: 0.9477 | train_acc: 0.5938 | test_loss: 0.7064 | test_acc: 0.8864
Epoch: 2 | train_loss: 0.7019 | train_acc: 0.8208 | test_loss: 0.5432 | test_acc: 0.8968
Epoch: 3 | train_loss: 0.5844 | train_acc: 0.8521 | test_loss: 0.4946 | test_acc: 0.8873
Epoch: 4 | train_loss: 0.4977 | train_acc: 0.8479 | test_loss: 0.3916 | test_acc: 0.9176
Epoch: 5 | train_loss: 0.4637 | train_acc: 0.8292 | test_loss: 0.3895 | test_acc: 0.9384
----------

[INFO] Creating new effnetb2 model.
[INFO] Model: effnetb2
[INFO] DataLoader: data_20_percent
----------
Created SummaryWriter and saving to runs/2022-05-31/data_20_percent/effnetb2...
  0%|          | 0/5 [00:00<?, ?it/s]
Epoch: 1 | train_loss: 0.9870 | train_acc: 0.4896 | test_loss: 0.8395 | test_acc: 0.8466
Epoch: 2 | train_loss: 0.7037 | train_acc: 0.8396 | test_loss: 0.6912 | test_acc: 0.8674
Epoch: 3 | train_loss: 0.5997 | train_acc: 0.8562 | test_loss: 0.5892 | test_acc: 0.9186
Epoch: 4 | train_loss: 0.4890 | train_acc: 0.8875 | test_loss: 0.5617 | test_acc: 0.8873
Epoch: 5 | train_loss: 0.4489 | train_acc: 0.9125 | test_loss: 0.4787 | test_acc: 0.8977
----------

View experiments in TensorBoard

In VSCode:

  • Press Shift + Cmd + P (to open the Command Palette)
  • Search "Launch TensorBoard"
  • Press Enter
In [ ]:
# # Viewing TensorBoard in Google Colab
# %load_ext tensorboard
# %tensorboard --logdir runs

Exercises

  • Add functionality to save the best model?
  • Scale up the dataset (e.g. could use all of Food101 + track experiment)
  • Introduce data augmentation to the list of experiments, does this change anything?
  • Could use the following for data augmentation:
# Note: Data augmentation transform like this should only be performed on training data
train_transform_data_aug = transforms.Compose([
    transforms.Resize((224, 224)),
    transforms.TrivialAugmentWide(),
    transforms.ToTensor(),
    normalize
])

# And to view images...
def view_dataloader_images(dataloader, n=10):
    if n > 10:
        print(f"Having n higher than 10 will create messy plots, lowering to 10.")
        n = 10
    imgs, labels = next(iter(train_dataloader_aug))
    plt.figure(figsize=(16, 8))
    for i in range(n):
        # Min max scale the image for display purposes
        targ_image = imgs[i]
        sample_min, sample_max = targ_image.min(), targ_image.max()
        sample_scaled = (targ_image - sample_min)/(sample_max - sample_min)

        # Plot images with appropriate axes information
        plt.subplot(1, 10, i+1)
        plt.imshow(sample_scaled.permute(1, 2, 0)) # resize for Matplotlib requirements
        plt.title(class_names[labels[i]])
        plt.axis(False)

# Have to update `create_dataloaders()` to handle different augmentations
import os
from torch.utils.data import DataLoader
from torchvision import datasets

NUM_WORKERS = os.cpu_count() # use maximum number of CPUs for workers to load data 

# Note: this is an update version of data_setup.create_dataloaders to handle
# differnt train and test transforms.
def create_dataloaders(
    train_dir, 
    test_dir, 
    train_transform, # add parameter for train transform (transforms on train dataset)
    test_transform,  # add parameter for test transform (transforms on test dataset)
    batch_size=32, num_workers=NUM_WORKERS
):
    # Use ImageFolder to create dataset(s)
    train_data = datasets.ImageFolder(train_dir, transform=train_transform)
    test_data = datasets.ImageFolder(test_dir, transform=test_transform)

    # Get class names
    class_names = train_data.classes

    # Turn images into data loaders
    train_dataloader = DataLoader(
        train_data,
        batch_size=batch_size,
        shuffle=True,
        num_workers=num_workers,
        pin_memory=True,
    )
    test_dataloader = DataLoader(
        test_data,
        batch_size=batch_size,
        shuffle=True,
        num_workers=num_workers,
        pin_memory=True,
    )

    return train_dataloader, test_dataloader, class_names

Extra-curriculum

Example: Use yellow boxes for examples that are not inside code cells, or use for mathematical formulas if needed.