Files
pytorch-deep-learning/03_pytorch_computer_vision.ipynb
T
2022-03-14 14:03:42 +10:00

168 KiB

(WIP) 03. PyTorch computer vision

Computer vision is the art of teaching a computer to see.

For example, it could involve building a model to classify whether a photo is of a cat or a dog (binary classification).

Or whether a photo is of a cat, dog or chicken (multi-class classification).

Or where a car appears in a video frame (object detection).

Or where different objects in an image can be separated (panoptic segmentation).

Where does computer vision get used?

If you use a smartphone, you've already used computer vision.

Camera and photo apps use computer vision to enhance and sort images - TK Link: https://machinelearning.apple.com/research/panoptic-segmentation.

Modern cars use computer vision to avoid other cars and stay within lane lines.

Manufacturers use computer vision to identify defects in various products.

Security cameras use computer vision to detect potential intruders.

In essence, anything that can described in a visual sense can be a potential computer vision problem.

TK image - put above into computer vision use cases

What we're going to cover

TK image: pytorch workflow + classes? (could link to this image in a previous notebook?)

We're going to apply the PyTorch Workflow we've been learning in the past couple of sections to computer vision.

Specifically, we're going to cover:

Topic Contents
0. Computer vision libraries in PyTorch PyTorch has a bunch of built-in helpful computer vision libraries, let's check them out.
1. Load data To practice computer vision, we'll start with some images of different pieces of clothing from FashionMNIST.
2. Prepare data We've got some images, let's load them in with a PyTorch DataLoader so we can use them with our training loop.
3. Model 0: Building a baseline model Here we'll create a multi-class classification model to learn patterns in the data, we'll also choose a loss function, optimizer and build a training loop.
4. Making predictions and evaluting model 0 Let's make some predictions with our baseline model and evaluate them.
5. Setup device agnostic code for future models It's best practice to write device-agnostic code, so let's set it up.
6. Model 1: Adding non-linearity Experimenting is a large part of machine learning, let's try and improve upon our baseline model by adding non-linear layers.
7. Model 2: Convolutional Neural Network (CNN) Time to get computer vision specific and introduce the powerful convolutional neural network architecture.
8. Evaluating our best model Let's make some predictons on random images and evaluate our best model.
9. Making a confusion matrix A confusion matrix is a great way to evaluate a classification model, let's see how we can make one.
10. Saving and loading the best performing model Since we might want to use our model for later, let's save it and make sure it loads back in correctly.

Workflow:

TK - image for the workflow

  1. Data (prepare and load)
  2. Build model
  3. Fitting model to data (training)
  4. Making predictions and evaluating a model (inference)
    • Improving a model through experimentations (optional)
  5. Saving and loading model
  6. Putting it all together

Where can can you get help?

All of the materials for this course live on GitHub.

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

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

TK - 0. Computer vision libraries in PyTorch

Before we get started writing code, let's talk about some PyTorch computer vision libraries you should be aware of.

PyTorch module What does it do?
torchvision Contains datasets, model architectures and image transformations often used for computer vision problems.
torchvision.datasets Here you'll find many example computer vision datasets for a range of problems from image classification, object detection, image captioning, video classification and more. It also contains a series of base classes for making custom datasets.
torchvision.models This module contains well-performing and commonly used computer vision model architectures implemented in PyTorch, you can use these with your own problems.
torchvision.transforms Often images need to be transformed (turned into numbers/processed/augmented) before being used with a model, common image transformations are found here.
torch.utils.data.Dataset Base dataset class for PyTorch, all custom dataset classes should inherit from this and override __getitem()__ and __len()__.
torch.utils.data.DataLoader Creates a Python iteralbe over a dataset (created with torch.utils.data.Dataset).

Note: The torch.utils.data.Dataset and torch.utils.data.DataLoader classes aren't only for computer vision in PyTorch, they are capable of dealing with many different types of data.

Now we've covered some of the most important PyTorch computer vision libraries, let's import the relevant dependencies.

In [123]:
# Import PyTorch
import torch
from torch import nn

# Import torchvision 
import torchvision
from torchvision import datasets
from torchvision.transforms import ToTensor

# Import matplotlib for visualization
import matplotlib.pyplot as plt

# Check versions
# Note: your PyTorch version shouldn't be lower than 1.10.0 and torchvision version shouldn't be lower than 0.11)
print(f"PyTorch version: {torch.__version__}\ntorchvision version: {torchvision.__version__}")
PyTorch version: 1.10.0
torchvision version: 0.11.1

TK - 1. Data

UPTOHERE: explaining what downloading images is doing, what everything going on below is doing

In [120]:
train_data = datasets.FashionMNIST(
    root="data", # where to download data to?
    train=True, # get training data
    download=True, # download data if it doesn't exist on disk
    transform=ToTensor(), # images come as PIL format, we want to turn into Torch tensors
    target_transform=None # you can transform labels as well
)

test_data = datasets.FashionMNIST(
    root="data",
    train=False, # get test data
    download=True,
    transform=ToTensor()
)
In [95]:
# See labels
train_data.targets
Out [95]:
tensor([9, 0, 0,  ..., 3, 0, 5])
In [96]:
# See classes
class_names = train_data.classes
class_names
Out [96]:
['T-shirt/top',
 'Trouser',
 'Pullover',
 'Dress',
 'Coat',
 'Sandal',
 'Shirt',
 'Sneaker',
 'Bag',
 'Ankle boot']
In [97]:
# Check out the data shapes
img, label = train_data[0]
img.shape, label # image is [1, 28, 28] and has int label
Out [97]:
(torch.Size([1, 28, 28]), 9)
In [98]:
import matplotlib.pyplot as plt
img, label = train_data[0]
plt.imshow(img.squeeze()) # image shape is [1, 28, 28] (batch, height, width)
plt.title(label);
In [99]:
img, label = train_data[0]
plt.imshow(img.squeeze(), cmap="gray")
plt.title(class_names[label]);
In [100]:
# Plot more images
torch.manual_seed(42)
fig = plt.figure(figsize=(9, 9))
rows, cols = 4, 4
for i in range(1, rows * cols + 1):
    random_idx = torch.randint(0, len(train_data), size=[1]).item()
    img, label = train_data[random_idx]
    fig.add_subplot(rows, cols, i)
    plt.imshow(img.squeeze(), cmap="gray")
    plt.title(class_names[label])
    plt.axis(False);

TK question - Can these be modelled with straight lines? Let's try.

TK - 2. Prepare DataLoader

In [101]:
from torch.utils.data import DataLoader

# Turn datasets into iterables (batches)
train_dataloader = DataLoader(train_data, # dataset to turn into iterable
    batch_size=32, # how many samples per batch? 
    shuffle=True # shuffle data every epoch?
)

test_dataloader = DataLoader(test_data,
    batch_size=32,
    shuffle=True
)

# TK - these lengths are of the number of batch sizes...
train_dataloader, test_dataloader, len(train_dataloader), len(test_dataloader)
Out [101]:
(<torch.utils.data.dataloader.DataLoader at 0x7f423501bdf0>,
 <torch.utils.data.dataloader.DataLoader at 0x7f4228649970>,
 1875,
 313)
In [102]:
# Check out dataloader
# TK - If using VSCode, be sure to check these out in the Data Viewer (go to Variables -> pick the variable you want to inspect)
train_features_batch, train_labels_batch = next(iter(train_dataloader))
train_features_batch.shape, train_labels_batch.shape
Out [102]:
(torch.Size([32, 1, 28, 28]), torch.Size([32]))
In [103]:
# Show a sample
torch.manual_seed(42)
random_idx = torch.randint(0, len(train_features_batch), size=[1]).item()
img, label = train_features_batch[random_idx], train_labels_batch[random_idx]
plt.imshow(img.squeeze(), cmap="gray")
plt.title(class_names[label])
plt.axis("Off");
print(f"Image size: {img.shape}")
print(f"Label: {label}, label size: {label.shape}")
Image size: torch.Size([1, 28, 28])
Label: 6, label size: torch.Size([])

TK - 3. Model 0: Build a baseline model

Now our features and labels are prepared, let's build a model.

  • TK - Use flatten to turn the pixels (height x width) into one long feature vector
  • TK - What's a baseline?
In [104]:
flatten_model = nn.Flatten() # all nn modules function as a model (can do a forward pass)
x = train_features_batch[0]
output = flatten_model(x) # perform forward pass
x.shape, output.size()
Out [104]:
(torch.Size([1, 28, 28]), torch.Size([1, 784]))
In [105]:
from torch import nn
class FashionMNISTModelV0(nn.Module):
    def __init__(self, input_shape, hidden_units, output_shape):
        super().__init__()
        self.layer_stack = nn.Sequential(
            nn.Flatten(), # neural networks like their inputs in vector form
            nn.Linear(in_features=input_shape, out_features=hidden_units), # TK - explain in and out features (could use TF playground for this)
            nn.Linear(in_features=hidden_units, out_features=output_shape)
        )
    
    def forward(self, x):
        return self.layer_stack(x)
In [106]:
torch.manual_seed(42)

# Need to setup model with input parameters
model_0 = FashionMNISTModelV0(input_shape=784, # one for every pixel (28x28)
    hidden_units=128, # how many units in the hiden layer
    output_shape=len(class_names) # one for every class
)
model_0.to("cpu") # keep model on CPU to begin wtih 
Out [106]:
FashionMNISTModelV0(
  (layer_stack): Sequential(
    (0): Flatten(start_dim=1, end_dim=-1)
    (1): Linear(in_features=784, out_features=128, bias=True)
    (2): Linear(in_features=128, out_features=10, bias=True)
  )
)

TK - 3.1 Setup loss, optimizer and evaluation metrics for Model 1

In [107]:
# TK - Write code here to download helper functions
import requests
from pathlib import Path 

# Download helper functions from Learn PyTorch repo (if not already downloaded)
if Path("helper_functions.py").is_file():
  print("helper_functions.py already exists, skipping download")
else:
  print("Downloading helper_functions.py")
  request = requests.get("https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/helper_functions.py")
  with open("helper_functions.py", "wb") as f:
    f.write(request.content)
helper_functions.py already exists, skipping download
In [108]:
# Setup loss, optimizer and accuracy metric
from helper_functions import accuracy_fn
loss_fn = nn.CrossEntropyLoss() # this is also called "criterion"/"cost function" in some places
optimizer = torch.optim.SGD(model_0.parameters(), lr=0.1)
In [109]:
from timeit import default_timer as timer 
def print_train_time(start, end, device=None):
    """Prints difference between start and end time.

    Args:
        start (float): Start time of computation (preferred in timeit format). 
        end (float): End time of computation.
        device ([type], optional): Device that compute is running on. Defaults to None.

    Returns:
        float: time between start and end in seconds (higher is longer).
    """
    total_time = end - start
    print(f"\nTrain time on {device}: {total_time:.3f} seconds")
    return total_time
In [110]:
torch.manual_seed(42)
train_time_start_on_cpu = timer()

# Create training loop
epochs = 5
for epoch in range(epochs):
    print(f"\nEpoch {epoch+1}\n----------")
    for batch, (X, y) in enumerate(train_dataloader):
        # Training
        # 1. Forward pass
        y_pred = model_0(X)

        # 2. Calculate loss
        loss = loss_fn(y_pred, y)

        # 3. Optimizer zero grad
        optimizer.zero_grad()

        # 4. Loss backward
        loss.backward()

        # 5. Optimizer step
        optimizer.step()

        # Print out what's happening
        if batch % 250 == 0:
            batch_number = batch * len(X)
            print(f"Loss: {loss:.5f} | Looked at {batch_number}/{len(train_dataloader.dataset)} samples")
    
    # Testing
    test_loss, test_acc = 0, 0
    model_0.eval()
    with torch.inference_mode():
        
        for X, y in test_dataloader:
            # 1. Forward pass
            test_pred = model_0(X)
            # print(test_pred)
            # 2. Calculate loss (accumatively)
            test_loss += loss_fn(test_pred, y)
            # 3. Calculate accuracy (preds need to be same as y_true)
            test_acc += accuracy_fn(y_true=y, y_pred=test_pred.argmax(dim=1))
            # print(test_acc)
    
        # Divide total loss by length of test dataloader (per batch)
        test_loss /= len(test_dataloader)

        # Divide total accuracy by length of test dataloader (per batch)
        test_acc /= len(test_dataloader)
        print(f"\nTesting for Epoch: {epoch}\n----------")
        print(f"Test loss: {test_loss:.5f} | Test accuracy: {test_acc:.2f}%\n")

# Calculate training time      
train_time_end_on_cpu = timer()
total_train_time_on_cpu = print_train_time(start=train_time_start_on_cpu, 
                                           end=train_time_end_on_cpu,
                                           device=str(next(model_0.parameters()).device))
Epoch 1
----------
Loss: 2.34053 | Looked at 0/60000 samples
Loss: 0.63385 | Looked at 8000/60000 samples
Loss: 0.49907 | Looked at 16000/60000 samples
Loss: 0.26303 | Looked at 24000/60000 samples
Loss: 0.53534 | Looked at 32000/60000 samples
Loss: 0.36563 | Looked at 40000/60000 samples
Loss: 0.68232 | Looked at 48000/60000 samples
Loss: 0.18253 | Looked at 56000/60000 samples

Testing for Epoch: 0
----------
Test loss: 0.50175 | Test accuracy: 82.47%


Epoch 2
----------
Loss: 0.57853 | Looked at 0/60000 samples
Loss: 0.36582 | Looked at 8000/60000 samples
Loss: 0.36852 | Looked at 16000/60000 samples
Loss: 0.35338 | Looked at 24000/60000 samples
Loss: 0.36890 | Looked at 32000/60000 samples
Loss: 0.34529 | Looked at 40000/60000 samples
Loss: 0.33107 | Looked at 48000/60000 samples
Loss: 0.46185 | Looked at 56000/60000 samples

Testing for Epoch: 1
----------
Test loss: 0.52408 | Test accuracy: 81.76%


Epoch 3
----------
Loss: 0.38698 | Looked at 0/60000 samples
Loss: 0.34827 | Looked at 8000/60000 samples
Loss: 0.42298 | Looked at 16000/60000 samples
Loss: 0.53404 | Looked at 24000/60000 samples
Loss: 0.48242 | Looked at 32000/60000 samples
Loss: 0.22668 | Looked at 40000/60000 samples
Loss: 0.45466 | Looked at 48000/60000 samples
Loss: 0.41813 | Looked at 56000/60000 samples

Testing for Epoch: 2
----------
Test loss: 0.51340 | Test accuracy: 82.92%


Epoch 4
----------
Loss: 0.37360 | Looked at 0/60000 samples
Loss: 0.33119 | Looked at 8000/60000 samples
Loss: 0.20297 | Looked at 16000/60000 samples
Loss: 0.39649 | Looked at 24000/60000 samples
Loss: 0.51343 | Looked at 32000/60000 samples
Loss: 0.50143 | Looked at 40000/60000 samples
Loss: 0.36421 | Looked at 48000/60000 samples
Loss: 0.51659 | Looked at 56000/60000 samples

Testing for Epoch: 3
----------
Test loss: 0.47379 | Test accuracy: 83.18%


Epoch 5
----------
Loss: 0.26910 | Looked at 0/60000 samples
Loss: 0.16825 | Looked at 8000/60000 samples
Loss: 0.23860 | Looked at 16000/60000 samples
Loss: 0.24782 | Looked at 24000/60000 samples
Loss: 0.36713 | Looked at 32000/60000 samples
Loss: 0.31626 | Looked at 40000/60000 samples
Loss: 0.24531 | Looked at 48000/60000 samples
Loss: 0.52060 | Looked at 56000/60000 samples

Testing for Epoch: 4
----------
Test loss: 0.46712 | Test accuracy: 83.57%


Train time on cpu: 27.108 seconds

TK - 4. Make predictions and get Model 0 results

In [111]:
torch.manual_seed(42)
def eval_model(model, data_loader, loss_fn, accuracy_fn):
    loss, acc = 0, 0
    model.eval()
    with torch.inference_mode():
        for X, y in data_loader:
            y_pred = model(X)
            loss += loss_fn(y_pred, y)
            acc += accuracy_fn(y_true=y, y_pred=y_pred.argmax(dim=1))
        
        # Scale loss and acc
        loss /= len(data_loader)
        acc /= len(data_loader)
    return {"model_name": model.__class__.__name__, # only works when model was created with a class
            "model_loss": loss.item(),
            "model_acc": acc}

model_0_results = eval_model(model=model_0, data_loader=test_dataloader,
    loss_fn=loss_fn, accuracy_fn=accuracy_fn
)
model_0_results
Out [111]:
{'model_name': 'FashionMNISTModelV0',
 'model_loss': 0.46738308668136597,
 'model_acc': 83.55630990415335}
In [112]:
model_0.__class__.__name__
Out [112]:
'FashionMNISTModelV0'

TK 5. Setup device agnostic code (for using a GPU if there is one)

We've seen how long it takes to train ma PyTorch model on 60,000 samples on CPU (note: this will dramatically depend on how many CPUs you have/the type they are/how much data you have).

Now let's setup some device agnostic code for our models and data to run on GPU if it's available.

See here PyTorch CUDA best practices for more: https://pytorch.org/docs/stable/notes/cuda.html#best-practices

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

TK - 6. Model 1: Building a better model with non-linearity

This model will have non-linearity.

In [114]:
class FashionMNISTModelV1(nn.Module):
    def __init__(self, input_shape, hidden_units, output_shape):
        super().__init__()
        self.layer_stack = nn.Sequential(
            nn.Flatten(), # flatten inputs into single vector
            nn.Linear(in_features=input_shape, out_features=hidden_units),
            nn.ReLU(),
            nn.Linear(in_features=hidden_units, out_features=output_shape),
            nn.ReLU()
        )
    
    def forward(self, x):
        return self.layer_stack(x)
In [115]:
torch.manual_seed(42)
model_1 = FashionMNISTModelV1(input_shape=784,
    hidden_units=128,
    output_shape=len(class_names)
).to(device) # send model to GPU if it's available
next(model_1.parameters()).device # check model device
Out [115]:
device(type='cuda', index=0)

TK - 6.1 Setup loss, optimizer and evaluation metrics

In [116]:
from helper_functions import accuracy_fn
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model_1.parameters(), lr=0.1)

TK - 6.2 Functionizing training and test loops

So far we've been writing train and test loops over and over. Let's write them again but this time we'll put them in functions so they can be called again and again.

See loading data to device with to() - https://pytorch.org/docs/stable/generated/torch.Tensor.to.html#torch.Tensor.to

In [117]:
def train_step(data_loader, model, loss_fn, optimizer):
    for batch, (X, y) in enumerate(data_loader):
        # Send data to GPU
        X, y = X.to(device, non_blocking=True), y.to(device, non_blocking=True)

        # 1. Forward pass
        y_pred = model(X)

        # 2. Calculate loss
        loss = loss_fn(y_pred, y)

        # 3. Optimizer zero grad
        optimizer.zero_grad()

        # 4. Loss backward
        loss.backward()

        # 5. Optimizer step
        optimizer.step()

        # Print what's happening
        if batch % 250 == 0: 
            sample_number = batch * len(X)
            print(f"Loss: {loss:.5f} | Looked at {sample_number}/{len(data_loader.dataset)} samples")

def test_step(data_loader, model, loss_fn):
    test_loss, test_acc = 0, 0
    model.eval() # put model in eval mode
    # Turn on inference context manager
    with torch.inference_mode(): 
        for X, y in data_loader:
            # Send data to GPU
            X, y = X.to(device, non_blocking=True), y.to(device, non_blocking=True)
            
            # 1. Forward pass
            test_pred = model(X)
            
            # 2. Calculate loss and accuracy
            test_loss += loss_fn(test_pred, y)
            test_acc += accuracy_fn(y_true=y,
                y_pred=test_pred.argmax(dim=1)
            )
        
        # Adjust metrics and print out
        test_loss /= len(data_loader)
        test_acc /= len(data_loader)
        print(f"\nTesting for Epoch: {epoch}\n----------")
        print(f"Test loss: {test_loss:.5f} | Test accuracy: {test_acc:.2f}%\n")
In [118]:
torch.manual_seed(42)

# Measure time
from timeit import default_timer as timer
train_time_start_on_gpu = timer()

epochs=5
for epoch in range(epochs):
    print(f"Epoch: {epoch}\n---------")
    train_step(data_loader=train_dataloader, 
        model=model_1, 
        loss_fn=loss_fn,
        optimizer=optimizer
    )
    test_step(data_loader=test_dataloader,
        model=model_1,
        loss_fn=loss_fn
    )

train_time_end_on_gpu = timer()
total_train_time_on_gpu = print_train_time(start=train_time_start_on_gpu,
                                           end=train_time_end_on_gpu,
                                           device=device)
Epoch: 0
---------
Loss: 2.31576 | Looked at 0/60000 samples
Loss: 0.84441 | Looked at 8000/60000 samples
Loss: 0.72745 | Looked at 16000/60000 samples
Loss: 0.48854 | Looked at 24000/60000 samples
Loss: 0.48070 | Looked at 32000/60000 samples
Loss: 0.34006 | Looked at 40000/60000 samples
Loss: 0.60718 | Looked at 48000/60000 samples
Loss: 0.17817 | Looked at 56000/60000 samples

Testing for Epoch: 0
----------
Test loss: 0.46140 | Test accuracy: 83.58%

Epoch: 1
---------
Loss: 0.56453 | Looked at 0/60000 samples
Loss: 0.34874 | Looked at 8000/60000 samples
Loss: 0.34462 | Looked at 16000/60000 samples
Loss: 0.28178 | Looked at 24000/60000 samples
Loss: 0.34664 | Looked at 32000/60000 samples
Loss: 0.35043 | Looked at 40000/60000 samples
Loss: 0.28332 | Looked at 48000/60000 samples
Loss: 0.34145 | Looked at 56000/60000 samples

Testing for Epoch: 1
----------
Test loss: 0.44406 | Test accuracy: 84.48%

Epoch: 2
---------
Loss: 0.28065 | Looked at 0/60000 samples
Loss: 0.27538 | Looked at 8000/60000 samples
Loss: 0.32969 | Looked at 16000/60000 samples
Loss: 0.50899 | Looked at 24000/60000 samples
Loss: 0.35316 | Looked at 32000/60000 samples
Loss: 0.20153 | Looked at 40000/60000 samples
Loss: 0.30891 | Looked at 48000/60000 samples
Loss: 0.33071 | Looked at 56000/60000 samples

Testing for Epoch: 2
----------
Test loss: 0.40107 | Test accuracy: 85.62%

Epoch: 3
---------
Loss: 0.26100 | Looked at 0/60000 samples
Loss: 0.28107 | Looked at 8000/60000 samples
Loss: 0.06934 | Looked at 16000/60000 samples
Loss: 0.32541 | Looked at 24000/60000 samples
Loss: 0.33877 | Looked at 32000/60000 samples
Loss: 0.24971 | Looked at 40000/60000 samples
Loss: 0.25175 | Looked at 48000/60000 samples
Loss: 0.32383 | Looked at 56000/60000 samples

Testing for Epoch: 3
----------
Test loss: 0.38116 | Test accuracy: 86.37%

Epoch: 4
---------
Loss: 0.20655 | Looked at 0/60000 samples
Loss: 0.18057 | Looked at 8000/60000 samples
Loss: 0.14731 | Looked at 16000/60000 samples
Loss: 0.17487 | Looked at 24000/60000 samples
Loss: 0.35683 | Looked at 32000/60000 samples
Loss: 0.25929 | Looked at 40000/60000 samples
Loss: 0.19088 | Looked at 48000/60000 samples
Loss: 0.46857 | Looked at 56000/60000 samples

Testing for Epoch: 4
----------
Test loss: 0.37307 | Test accuracy: 86.46%


Train time on cuda: 27.904 seconds
In [119]:
torch.manual_seed(42)

#UPTOHERE
# Make sure model eval code can run on CPU...
model_1_results = eval_model(model=model_1, 
    data_loader=test_dataloader,
    loss_fn=loss_fn, 
    accuracy_fn=accuracy_fn) # will error due to `eval_model()` not using device agnostic code 
model_1_results 
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
/tmp/ipykernel_5140/3686544492.py in <module>
      3 #UPTOHERE
      4 # Make sure model eval code can run on CPU...
----> 5 model_1_results = eval_model(model=model_1, 
      6     data_loader=test_dataloader,
      7     loss_fn=loss_fn,

/tmp/ipykernel_5140/1274930794.py in eval_model(model, data_loader, loss_fn, accuracy_fn)
      5     with torch.inference_mode():
      6         for X, y in data_loader:
----> 7             y_pred = model(X)
      8             loss += loss_fn(y_pred, y)
      9             acc += accuracy_fn(y_true=y, y_pred=y_pred.argmax(dim=1))

~/code/pytorch/env/lib/python3.9/site-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
   1100         if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
   1101                 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1102             return forward_call(*input, **kwargs)
   1103         # Do not call functions when jit is used
   1104         full_backward_hooks, non_full_backward_hooks = [], []

/tmp/ipykernel_5140/2755272479.py in forward(self, x)
     11 
     12     def forward(self, x):
---> 13         return self.layer_stack(x)

~/code/pytorch/env/lib/python3.9/site-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
   1100         if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
   1101                 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1102             return forward_call(*input, **kwargs)
   1103         # Do not call functions when jit is used
   1104         full_backward_hooks, non_full_backward_hooks = [], []

~/code/pytorch/env/lib/python3.9/site-packages/torch/nn/modules/container.py in forward(self, input)
    139     def forward(self, input):
    140         for module in self:
--> 141             input = module(input)
    142         return input
    143 

~/code/pytorch/env/lib/python3.9/site-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
   1100         if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
   1101                 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1102             return forward_call(*input, **kwargs)
   1103         # Do not call functions when jit is used
   1104         full_backward_hooks, non_full_backward_hooks = [], []

~/code/pytorch/env/lib/python3.9/site-packages/torch/nn/modules/linear.py in forward(self, input)
    101 
    102     def forward(self, input: Tensor) -> Tensor:
--> 103         return F.linear(input, self.weight, self.bias)
    104 
    105     def extra_repr(self) -> str:

~/code/pytorch/env/lib/python3.9/site-packages/torch/nn/functional.py in linear(input, weight, bias)
   1846     if has_torch_function_variadic(input, weight, bias):
   1847         return handle_torch_function(linear, (input, weight, bias), input, weight, bias=bias)
-> 1848     return torch._C._nn.linear(input, weight, bias)
   1849 
   1850 

RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! (when checking argument for argument mat1 in method wrapper_addmm)
In [ ]:
# Move values to device
torch.manual_seed(42)
def eval_model(model, data_loader, loss_fn, accuracy_fn):
    loss, acc = 0, 0
    model.eval()
    with torch.inference_mode():
        for X, y in data_loader:
            X, y = X.to(device, non_blocking=True), y.to(device, non_blocking=True)
            y_pred = model(X)
            loss += loss_fn(y_pred, y)
            acc += accuracy_fn(y_true=y, y_pred=y_pred.argmax(dim=1))
        
        # Scale loss and acc
        loss /= len(data_loader)
        acc /= len(data_loader)
    return {"model_name": model.__class__.__name__, # only works when model was created with a class
            "model_loss": loss.item(),
            "model_acc": acc}

model_1_results = eval_model(model=model_1, data_loader=test_dataloader,
    loss_fn=loss_fn, accuracy_fn=accuracy_fn
)
model_1_results
{'model_name': 'FashionMNISTModelV1',
 'model_loss': 0.37321436405181885,
 'model_acc': 86.46166134185303}

TK - 7. Model 2: Building a Convolutional Neural Network (CNN)

In [ ]:
# UPTOHERE
# Write model v2 (conv net)
# Use same functions to train and eval
In [ ]:
### Model 2 line by line
class FashionMNISTModelV2(nn.Module):
    """
    Model architecture copying TinyVGG from: 
    https://poloclub.github.io/cnn-explainer/
    """
    def __init__(self, input_shape, hidden_units, output_shape):
        super().__init__()
        self.block_1 = nn.Sequential(
            nn.Conv2d(in_channels=input_shape, 
                      out_channels=hidden_units, 
                      kernel_size=3,
                      padding=1),
            nn.ReLU(),
            nn.Conv2d(hidden_units, 
                      hidden_units,
                      3,
                      padding=1),
            nn.ReLU(),
            nn.MaxPool2d(2)
        )
        self.block_2 = nn.Sequential(
            nn.Conv2d(hidden_units, hidden_units, 3, padding=1),
            nn.ReLU(),
            nn.Conv2d(hidden_units, hidden_units, 3, padding=1),
            nn.ReLU(),
            nn.MaxPool2d(2)
        )
        self.classifier = nn.Sequential(
            nn.Flatten(),
            nn.Linear(in_features=hidden_units*7*7, 
                      out_features=output_shape)
        )
    
    def forward(self, x):
        x = self.block_1(x)
        # print(x.shape)
        x = self.block_2(x)
        # print(x.shape)
        x = self.classifier(x)
        # print(x.shape)
        return x

torch.manual_seed(42)
model_2 = FashionMNISTModelV2(input_shape=1, 
    hidden_units=10, 
    output_shape=len(class_names)).to(device)
model_2
FashionMNISTModelV2(
  (block_1): Sequential(
    (0): Conv2d(1, 10, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (1): ReLU()
    (2): Conv2d(10, 10, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (3): ReLU()
    (4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  )
  (block_2): Sequential(
    (0): Conv2d(10, 10, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (1): ReLU()
    (2): Conv2d(10, 10, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (3): ReLU()
    (4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  )
  (classifier): Sequential(
    (0): Flatten(start_dim=1, end_dim=-1)
    (1): Linear(in_features=490, out_features=10, bias=True)
  )
)
In [ ]:
input, label = next(iter(train_dataloader))
input.shape
torch.Size([32, 1, 28, 28])
In [ ]:
# Setup loss and optimizer
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model_2.parameters(), lr=0.001)
In [ ]:
# Train and test model
torch.manual_seed(42)

# Measure time
from timeit import default_timer as timer
train_time_start_model_2 = timer()

epochs=5
for epoch in range(epochs):
    print(f"Epoch: {epoch}\n---------")
    train_step(data_loader=train_dataloader, 
        model=model_2, 
        loss_fn=loss_fn,
        optimizer=optimizer
    )
    test_step(data_loader=test_dataloader,
        model=model_2,
        loss_fn=loss_fn
    )

train_time_end_model_2 = timer()
total_train_time_model_2 = print_train_time(start=train_time_start_model_2,
                                           end=train_time_end_model_2,
                                           device=device)
Epoch: 0
---------
Loss: 2.30730 | Looked at 0/60000 samples
Loss: 0.62103 | Looked at 8000/60000 samples
Loss: 0.38208 | Looked at 16000/60000 samples
Loss: 0.25257 | Looked at 24000/60000 samples
Loss: 0.48798 | Looked at 32000/60000 samples
Loss: 0.28136 | Looked at 40000/60000 samples
Loss: 0.49253 | Looked at 48000/60000 samples
Loss: 0.13826 | Looked at 56000/60000 samples

Testing for Epoch: 0
----------
Test loss: 0.39309 | Test accuracy: 86.28%

Epoch: 1
---------
Loss: 0.35944 | Looked at 0/60000 samples
Loss: 0.31443 | Looked at 8000/60000 samples
Loss: 0.16342 | Looked at 16000/60000 samples
Loss: 0.27778 | Looked at 24000/60000 samples
Loss: 0.40699 | Looked at 32000/60000 samples
Loss: 0.32541 | Looked at 40000/60000 samples
Loss: 0.24685 | Looked at 48000/60000 samples
Loss: 0.20693 | Looked at 56000/60000 samples

Testing for Epoch: 1
----------
Test loss: 0.35872 | Test accuracy: 86.67%

Epoch: 2
---------
Loss: 0.29864 | Looked at 0/60000 samples
Loss: 0.27326 | Looked at 8000/60000 samples
Loss: 0.34129 | Looked at 16000/60000 samples
Loss: 0.55446 | Looked at 24000/60000 samples
Loss: 0.27312 | Looked at 32000/60000 samples
Loss: 0.11713 | Looked at 40000/60000 samples
Loss: 0.35022 | Looked at 48000/60000 samples
Loss: 0.35892 | Looked at 56000/60000 samples

Testing for Epoch: 2
----------
Test loss: 0.33255 | Test accuracy: 87.96%

Epoch: 3
---------
Loss: 0.21655 | Looked at 0/60000 samples
Loss: 0.31527 | Looked at 8000/60000 samples
Loss: 0.12757 | Looked at 16000/60000 samples
Loss: 0.40286 | Looked at 24000/60000 samples
Loss: 0.26378 | Looked at 32000/60000 samples
Loss: 0.17067 | Looked at 40000/60000 samples
Loss: 0.17987 | Looked at 48000/60000 samples
Loss: 0.31484 | Looked at 56000/60000 samples

Testing for Epoch: 3
----------
Test loss: 0.30930 | Test accuracy: 89.15%

Epoch: 4
---------
Loss: 0.14142 | Looked at 0/60000 samples
Loss: 0.16058 | Looked at 8000/60000 samples
Loss: 0.11565 | Looked at 16000/60000 samples
Loss: 0.14372 | Looked at 24000/60000 samples
Loss: 0.40148 | Looked at 32000/60000 samples
Loss: 0.25676 | Looked at 40000/60000 samples
Loss: 0.15010 | Looked at 48000/60000 samples
Loss: 0.63361 | Looked at 56000/60000 samples

Testing for Epoch: 4
----------
Test loss: 0.30139 | Test accuracy: 89.36%


Train time on cuda: 38.946 seconds
In [ ]:
model_2_results = eval_model(
    model=model_2,
    data_loader=test_dataloader,
    loss_fn=loss_fn,
    accuracy_fn=accuracy_fn
)
model_2_results
{'model_name': 'FashionMNISTModelV2',
 'model_loss': 0.3016848862171173,
 'model_acc': 89.3370607028754}
In [ ]:
model_0_results, model_1_results, model_2_results
({'model_name': 'FashionMNISTModelV0',
  'model_loss': 0.46738308668136597,
  'model_acc': 83.55630990415335},
 {'model_name': 'FashionMNISTModelV1',
  'model_loss': 0.37321436405181885,
  'model_acc': 86.46166134185303},
 {'model_name': 'FashionMNISTModelV2',
  'model_loss': 0.3016848862171173,
  'model_acc': 89.3370607028754})
In [ ]:
import pandas as pd
compare_results = pd.DataFrame([model_0_results, model_1_results, model_2_results])
compare_results
model_name model_loss model_acc
0 FashionMNISTModelV0 0.467383 83.556310
1 FashionMNISTModelV1 0.373214 86.461661
2 FashionMNISTModelV2 0.301685 89.337061
In [ ]:
compare_results.set_index("model_name")["model_acc"].plot(kind="bar", xlabel="model", ylabel="accuracy (%)");

TK - 8. Make and evaluate random predictions with best model

In [ ]:
def make_predictions(model, data):
    preds = []
    model.eval()
    with torch.inference_mode():
        for sample in data:
            # 1. Forward pass
            sample = torch.unsqueeze(sample, dim=0).to(device) # Add an extra dimension and send sample to device
            pred = model(sample)
            preds.append(torch.softmax(pred[0], dim=0)) # Convert to pred probabilities
    # Get off GPU for further calculations
    pred_probs = [pred_prob.cpu() for pred_prob in preds]
    return  pred_probs
In [ ]:
len(test_data)
10000
In [ ]:
import random
random.seed(42)
test_samples = []
test_labels = []
for sample, label in random.sample(list(test_data), k=9):
    test_samples.append(sample)
    test_labels.append(label)
In [ ]:
pred_probs= make_predictions(model=model_2, data=test_samples)
pred_probs[:2]
[tensor([5.3556e-10, 9.2350e-14, 5.6806e-11, 2.9492e-11, 1.2458e-11, 9.9918e-01,
         2.0111e-08, 4.8111e-07, 5.7852e-06, 8.1268e-04]),
 tensor([6.4424e-02, 7.4795e-01, 2.5071e-04, 1.3002e-01, 1.7794e-02, 3.4507e-06,
         3.9502e-02, 3.0148e-06, 3.2876e-05, 1.8275e-05])]
In [ ]:
pred_classes = torch.stack(pred_probs).argmax(dim=1)
In [ ]:
test_labels, pred_classes
([5, 1, 7, 4, 3, 0, 4, 7, 1], tensor([5, 1, 7, 4, 3, 0, 4, 7, 1]))
In [ ]:
class_names
['T-shirt/top',
 'Trouser',
 'Pullover',
 'Dress',
 'Coat',
 'Sandal',
 'Shirt',
 'Sneaker',
 'Bag',
 'Ankle boot']
In [ ]:
# Plot predictions
plt.figure(figsize=(9, 9))
nrows = 3
ncols = 3
for i, sample in enumerate(test_samples):
    plt.subplot(3, 3, i+1)
    plt.imshow(sample.squeeze(), cmap="gray")
    pred_label = class_names[pred_classes[i]]
    truth_label = class_names[test_labels[i]] 
    title_text = f"Pred: {pred_label} | Truth: {truth_label}"
    # Check for equality and change title colour accordingly
    if pred_label == truth_label:
        plt.title(title_text, fontsize=10, c="g") # green text if correct
    else:
        plt.title(title_text, fontsize=10, c="r") # red text if wrong
    plt.axis(False);

TK - 9. Making a confusion matrix for further prediction evaluaiton

TK - Use torchmetrics.ConfusionMatrix

In [ ]:
# See if torchmetrics exists, if not, install it
try:
    import torchmetrics
except:
    %pip install torchmetrics
    import torchmetrics 
In [ ]:
import torchmetrics 

TK - 10. Save and load best performing model

See more: https://pytorch.org/tutorials/beginner/saving_loading_models.html

In [ ]:
torch.save(model_2.state_dict(), "models/03_pytorch_computer_vision_model_2.pth")
In [ ]:
# Load in model state dict to new model instance (need class instance to load into)
# Note: loading model will error if the shapes here aren't the same as the saved version
loaded_model_2 = FashionMNISTModelV2(input_shape=1, 
                                    hidden_units=10, # try changing this to 128 and seeing what happens 
                                    output_shape=10) 
loaded_model_2.load_state_dict(torch.load("models/03_pytorch_computer_vision_model_2.pth"))
# Send model to GPU
loaded_model_2 = loaded_model_2.to(device)
In [ ]:
# Evaluate loaded model
torch.manual_seed(42)

loaded_model_2_results = eval_model(
    model=loaded_model_2,
    data_loader=test_dataloader,
    loss_fn=loss_fn, 
    accuracy_fn=accuracy_fn
)
loaded_model_2_results
{'model_name': 'FashionMNISTModelV2',
 'model_loss': 0.30141106247901917,
 'model_acc': 89.3570287539936}
In [ ]:
model_2_results
{'model_name': 'FashionMNISTModelV2',
 'model_loss': 0.3016848862171173,
 'model_acc': 89.3370607028754}
In [ ]:
# Check to see if results are close to each other (if they are very far away, there may be an error)
torch.isclose(torch.tensor(model_2_results["model_loss"]), 
              torch.tensor(loaded_model_2_results["model_loss"]),
              rtol=0.001)
tensor(True)

TK - Exercises

  • TK - exercises

TK - Extra-curriculum