Files
pytorch-deep-learning/docs/03_pytorch_computer_vision.ipynb
T
2021-12-15 09:16:01 +10:00

157 KiB

03. Computer Vision with PyTorch

What we're going to cover:

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
In [1]:
import torch
from torch import nn

Data

In [2]:
from torchvision import datasets
from torchvision.transforms import ToTensor, Lambda
import matplotlib.pyplot as plt

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 [3]:
# Check out the data shapes
img, label = train_data[0]
img.shape, label # image is [1, 28, 28] and has int label
Out [3]:
(torch.Size([1, 28, 28]), 9)
In [4]:
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 [5]:
# Map labels to class names - https://github.com/zalandoresearch/fashion-mnist
# List format - https://gist.github.com/mrdbourke/e0b82c52a1b374a108a47ce21c7f4835
class_names = ["T-shirt/top",
    "Trouser",
    "Pullover",
    "Dress",
    "Coat",
    "Sandal",
    "Shirt",
    "Sneaker",
    "Bag",
    "Ankle boot"
]
In [6]:
img, label = train_data[0]
plt.imshow(img.squeeze(), cmap="gray")
plt.title(class_names[label]);
In [7]:
# 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 - Can these be modelled with straight lines? Let's try.

TK - Prepare DataLoader

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

train_dataloader, test_dataloader, len(train_dataloader), len(test_dataloader)
Out [8]:
(<torch.utils.data.dataloader.DataLoader at 0x7fb53c290160>,
 <torch.utils.data.dataloader.DataLoader at 0x7fb53c221a90>,
 1875,
 313)
In [9]:
# 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 [9]:
(torch.Size([32, 1, 28, 28]), torch.Size([32]))
In [10]:
# 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 - Model 0: Build a model

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

In [11]:
flatten_model = nn.Sequential(nn.Flatten())
x = train_features_batch[0]
output = flatten_model(x)
x.shape, output.size()
Out [11]:
(torch.Size([1, 28, 28]), torch.Size([1, 784]))
In [12]:
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 [13]:
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
Out [13]:
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)
  )
)
In [14]:
# Setup loss, optimizer and accuracy metric
from helper_functions import accuracy_fn
loss_fn = nn.CrossEntropyLoss() # this is also called "criterion" in some places
optimizer = torch.optim.SGD(model_0.parameters(), lr=0.1)
In [15]:
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 [16]:
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: 26.673 seconds

Get Model 0 results

In [17]:
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 [17]:
{'model_name': 'FashionMNISTModelV0',
 'model_loss': 0.46738308668136597,
 'model_acc': 83.55630990415335}
In [18]:
model_0.__class__.__name__
Out [18]:
'FashionMNISTModelV0'

TK Setup GPU Device

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).git/

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 [19]:
# Setup device agnostic code
device = "cuda" if torch.cuda.is_available() else "cpu"
device
Out [19]:
'cuda'

TK - Model 1: Building a better model

This model will have non-linearity.

In [20]:
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 [21]:
torch.manual_seed(42)
model_1 = FashionMNISTModelV1(input_shape=784,
    hidden_units=128,
    output_shape=10
).to(device) # send model to GPU if it's available
next(model_1.parameters()).device # check model device
Out [21]:
device(type='cuda', index=0)

TK - Setup loss, optimizer and evaluation metrics

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

TK - Functionizing training and test

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 [23]:
def train(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(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 [24]:
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(data_loader=train_dataloader, 
        model=model_1, 
        loss_fn=loss_fn,
        optimizer=optimizer
    )
    test(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: 28.596 seconds
In [25]:
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_60941/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_60941/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_60941/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 [26]:
# 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
Out [26]:
{'model_name': 'FashionMNISTModelV1',
 'model_loss': 0.37321436405181885,
 'model_acc': 86.46166134185303}

TK - Model 2: Convolutional Neural Networks

In [27]:
# UPTOHERE
# Write model v2 (conv net)
# Use same functions to train and eval
In [32]:
# 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.layer_stack = nn.Sequential(
#             # nn.Flatten(), # flatten inputs into single vector
#             nn.Conv2d(in_channels=1, 
#                       out_channels=hidden_units, 
#                       kernel_size=3),
#             nn.ReLU(),
#             nn.Conv2d(hidden_units, 
#                       hidden_units,
#                       3),
#             nn.ReLU(),
#             nn.MaxPool2d(2),
#             nn.Conv2d(hidden_units, hidden_units, 3),
#             nn.ReLU(),
#             nn.MaxPool2d(2),
#             nn.Linear(in_features=hidden_units, out_features=output_shape)
#         )
    
#     def forward(self, x):
#         return self.layer_stack(x)

# model_2 = FashionMNISTModelV2(input_shape=784, 
#     hidden_units=128, 
#     output_shape=len(class_names)).to(device)
# model_2

### 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=1, 
                      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

model_2 = FashionMNISTModelV2(input_shape=1, 
    hidden_units=10, 
    output_shape=len(class_names)).to(device)
model_2
Out [32]:
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 [33]:
input, label = next(iter(train_dataloader))
input.shape
Out [33]:
torch.Size([32, 1, 28, 28])
In [34]:
torch.Size([32, 128, 4, 4])
Out [34]:
torch.Size([32, 128, 4, 4])
In [35]:
32*128*4
Out [35]:
16384
In [36]:
# Setup loss and optimizer
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model_2.parameters(), lr=0.001)
In [37]:
# 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(data_loader=train_dataloader, 
        model=model_2, 
        loss_fn=loss_fn,
        optimizer=optimizer
    )
    test(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.30454 | Looked at 0/60000 samples
Loss: 0.57641 | Looked at 8000/60000 samples
Loss: 0.36825 | Looked at 16000/60000 samples
Loss: 0.36582 | Looked at 24000/60000 samples
Loss: 0.44872 | Looked at 32000/60000 samples
Loss: 0.24972 | Looked at 40000/60000 samples
Loss: 0.57585 | Looked at 48000/60000 samples
Loss: 0.10089 | Looked at 56000/60000 samples

Testing for Epoch: 0
----------
Test loss: 0.38344 | Test accuracy: 86.22%

Epoch: 1
---------
Loss: 0.36397 | Looked at 0/60000 samples
Loss: 0.29526 | Looked at 8000/60000 samples
Loss: 0.24492 | Looked at 16000/60000 samples
Loss: 0.30383 | Looked at 24000/60000 samples
Loss: 0.31548 | Looked at 32000/60000 samples
Loss: 0.24291 | Looked at 40000/60000 samples
Loss: 0.20189 | Looked at 48000/60000 samples
Loss: 0.21553 | Looked at 56000/60000 samples

Testing for Epoch: 1
----------
Test loss: 0.35467 | Test accuracy: 86.94%

Epoch: 2
---------
Loss: 0.27195 | Looked at 0/60000 samples
Loss: 0.23987 | Looked at 8000/60000 samples
Loss: 0.28975 | Looked at 16000/60000 samples
Loss: 0.39636 | Looked at 24000/60000 samples
Loss: 0.24336 | Looked at 32000/60000 samples
Loss: 0.09933 | Looked at 40000/60000 samples
Loss: 0.21368 | Looked at 48000/60000 samples
Loss: 0.36726 | Looked at 56000/60000 samples

Testing for Epoch: 2
----------
Test loss: 0.30670 | Test accuracy: 89.16%

Epoch: 3
---------
Loss: 0.17519 | Looked at 0/60000 samples
Loss: 0.31724 | Looked at 8000/60000 samples
Loss: 0.07558 | Looked at 16000/60000 samples
Loss: 0.34291 | Looked at 24000/60000 samples
Loss: 0.26814 | Looked at 32000/60000 samples
Loss: 0.12187 | Looked at 40000/60000 samples
Loss: 0.12363 | Looked at 48000/60000 samples
Loss: 0.29629 | Looked at 56000/60000 samples

Testing for Epoch: 3
----------
Test loss: 0.28936 | Test accuracy: 89.63%

Epoch: 4
---------
Loss: 0.09023 | Looked at 0/60000 samples
Loss: 0.14286 | Looked at 8000/60000 samples
Loss: 0.15002 | Looked at 16000/60000 samples
Loss: 0.27805 | Looked at 24000/60000 samples
Loss: 0.36720 | Looked at 32000/60000 samples
Loss: 0.25269 | Looked at 40000/60000 samples
Loss: 0.11466 | Looked at 48000/60000 samples
Loss: 0.77091 | Looked at 56000/60000 samples

Testing for Epoch: 4
----------
Test loss: 0.27614 | Test accuracy: 89.97%


Train time on cuda: 38.961 seconds
In [38]:
model_2_results = eval_model(
    model=model_2,
    data_loader=test_dataloader,
    loss_fn=loss_fn,
    accuracy_fn=accuracy_fn
)
model_2_results
Out [38]:
{'model_name': 'FashionMNISTModelV2',
 'model_loss': 0.27648669481277466,
 'model_acc': 89.94608626198082}
In [39]:
model_0_results, model_1_results, model_2_results
Out [39]:
({'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.27648669481277466,
  'model_acc': 89.94608626198082})
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.223272 92.092652
In [ ]:
compare_results["model_acc"].plot(kind="bar")
<AxesSubplot:>

Make 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([1.8396e-12, 1.5738e-18, 5.4805e-12, 9.7204e-18, 1.9830e-14, 1.0000e+00,
         3.4461e-12, 3.7136e-11, 5.5659e-13, 5.0743e-08]),
 tensor([6.6449e-03, 9.8245e-01, 8.2975e-04, 1.7679e-03, 4.6107e-03, 7.3583e-05,
         3.5653e-03, 2.4977e-06, 2.5370e-05, 2.5053e-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")
    plt.title(f"Pred: {class_names[pred_classes[i]]} | Truth: {class_names[test_labels[i]]}")
    plt.axis(False);
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)
loaded_model_2 = FashionMNISTModelV2(input_shape=1, hidden_units=128, 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.223284050822258,
 'model_acc': 92.0826677316294}
In [ ]:
model_2_results
{'model_name': 'FashionMNISTModelV2',
 'model_loss': 0.22327210009098053,
 'model_acc': 92.09265175718849}
In [ ]:
# Check to see if results are close
torch.isclose(torch.tensor(model_2_results["model_loss"]), 
              torch.tensor(loaded_model_2_results["model_loss"]),
              rtol=0.0001)
tensor(True)

TODO:

  • make testing code for training loop above
  • bring in accuracy function to measure accuracy function
  • upload accuracy function to helper_functions.py
  • "We're writing a lot of boiler plate code... but that's to practice"
  • bring in non-linearity for model 1 (it works on FashionMNIST)
  • ~Create Conv model to really step things up - https://poloclub.github.io/cnn-explainer/
  • Calculate all different model results (on same data)
    • Eval model 1
    • Eval model 2
  • Compare model results
  • Make predictions with best model
  • Save and load best model

TODO: Exercises and Extra-curriculum