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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# coding: utf-8
|
| 3 |
+
|
| 4 |
+
# In[1]:
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
A series of helper functions used throughout the course.
|
| 9 |
+
|
| 10 |
+
If a function gets defined once and could be used over and over, it'll go in here.
|
| 11 |
+
"""
|
| 12 |
+
import torch
|
| 13 |
+
import matplotlib.pyplot as plt
|
| 14 |
+
import numpy as np
|
| 15 |
+
|
| 16 |
+
from torch import nn
|
| 17 |
+
import os
|
| 18 |
+
import zipfile
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
import requests
|
| 21 |
+
import os
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
# In[2]:
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# Plot linear data or training and test and predictions (optional)
|
| 28 |
+
def plot_predictions(
|
| 29 |
+
train_data, train_labels, test_data, test_labels, predictions=None
|
| 30 |
+
):
|
| 31 |
+
"""
|
| 32 |
+
Plots linear training data and test data and compares predictions.
|
| 33 |
+
"""
|
| 34 |
+
plt.figure(figsize=(10, 7))
|
| 35 |
+
|
| 36 |
+
# Plot training data in blue
|
| 37 |
+
plt.scatter(train_data, train_labels, c="b", s=4, label="Training data")
|
| 38 |
+
|
| 39 |
+
# Plot test data in green
|
| 40 |
+
plt.scatter(test_data, test_labels, c="g", s=4, label="Testing data")
|
| 41 |
+
|
| 42 |
+
if predictions is not None:
|
| 43 |
+
# Plot the predictions in red (predictions were made on the test data)
|
| 44 |
+
plt.scatter(test_data, predictions, c="r", s=4, label="Predictions")
|
| 45 |
+
|
| 46 |
+
# Show the legend
|
| 47 |
+
plt.legend(prop={"size": 14})
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
# In[3]:
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
# Calculate accuracy (a classification metric)
|
| 54 |
+
def accuracy_fn(y_true, y_pred):
|
| 55 |
+
"""Calculates accuracy between truth labels and predictions.
|
| 56 |
+
|
| 57 |
+
Args:
|
| 58 |
+
y_true (torch.Tensor): Truth labels for predictions.
|
| 59 |
+
y_pred (torch.Tensor): Predictions to be compared to predictions.
|
| 60 |
+
|
| 61 |
+
Returns:
|
| 62 |
+
[torch.float]: Accuracy value between y_true and y_pred, e.g. 78.45
|
| 63 |
+
"""
|
| 64 |
+
correct = torch.eq(y_true, y_pred).sum().item()
|
| 65 |
+
acc = (correct / len(y_pred)) * 100
|
| 66 |
+
return acc
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# In[4]:
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def print_train_time(start, end, device=None):
|
| 73 |
+
"""Prints difference between start and end time.
|
| 74 |
+
|
| 75 |
+
Args:
|
| 76 |
+
start (float): Start time of computation (preferred in timeit format).
|
| 77 |
+
end (float): End time of computation.
|
| 78 |
+
device ([type], optional): Device that compute is running on. Defaults to None.
|
| 79 |
+
|
| 80 |
+
Returns:
|
| 81 |
+
float: time between start and end in seconds (higher is longer).
|
| 82 |
+
"""
|
| 83 |
+
total_time = end - start
|
| 84 |
+
print(f"\nTrain time on {device}: {total_time:.3f} seconds")
|
| 85 |
+
return total_time
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# In[5]:
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
# Plot loss curves of a model
|
| 92 |
+
def plot_loss_curves(results):
|
| 93 |
+
"""Plots training curves of a results dictionary.
|
| 94 |
+
|
| 95 |
+
Args:
|
| 96 |
+
results (dict): dictionary containing list of values, e.g.
|
| 97 |
+
{"train_loss": [...],
|
| 98 |
+
"train_acc": [...],
|
| 99 |
+
"test_loss": [...],
|
| 100 |
+
"test_acc": [...]}
|
| 101 |
+
"""
|
| 102 |
+
loss = results["train_loss"]
|
| 103 |
+
test_loss = results["test_loss"]
|
| 104 |
+
|
| 105 |
+
accuracy = results["train_acc"]
|
| 106 |
+
test_accuracy = results["test_acc"]
|
| 107 |
+
|
| 108 |
+
epochs = range(len(results["train_loss"]))
|
| 109 |
+
|
| 110 |
+
plt.figure(figsize=(15, 7))
|
| 111 |
+
|
| 112 |
+
# Plot loss
|
| 113 |
+
plt.subplot(1, 2, 1)
|
| 114 |
+
plt.plot(epochs, loss, label="train_loss")
|
| 115 |
+
plt.plot(epochs, test_loss, label="test_loss")
|
| 116 |
+
plt.title("Loss")
|
| 117 |
+
plt.xlabel("Epochs")
|
| 118 |
+
plt.legend()
|
| 119 |
+
|
| 120 |
+
# Plot accuracy
|
| 121 |
+
plt.subplot(1, 2, 2)
|
| 122 |
+
plt.plot(epochs, accuracy, label="train_accuracy")
|
| 123 |
+
plt.plot(epochs, test_accuracy, label="test_accuracy")
|
| 124 |
+
plt.title("Accuracy")
|
| 125 |
+
plt.xlabel("Epochs")
|
| 126 |
+
plt.legend()
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
# In[6]:
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
# Pred and plot image function from notebook 04
|
| 133 |
+
# See creation: https://www.learnpytorch.io/04_pytorch_custom_datasets/#113-putting-custom-image-prediction-together-building-a-function
|
| 134 |
+
from typing import List
|
| 135 |
+
import torchvision
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def pred_and_plot_image(
|
| 139 |
+
model: torch.nn.Module,
|
| 140 |
+
image_path: str,
|
| 141 |
+
class_names: List[str] = None,
|
| 142 |
+
transform=None,
|
| 143 |
+
device: torch.device = "cuda" if torch.cuda.is_available() else "cpu",
|
| 144 |
+
):
|
| 145 |
+
"""Makes a prediction on a target image with a trained model and plots the image.
|
| 146 |
+
|
| 147 |
+
Args:
|
| 148 |
+
model (torch.nn.Module): trained PyTorch image classification model.
|
| 149 |
+
image_path (str): filepath to target image.
|
| 150 |
+
class_names (List[str], optional): different class names for target image. Defaults to None.
|
| 151 |
+
transform (_type_, optional): transform of target image. Defaults to None.
|
| 152 |
+
device (torch.device, optional): target device to compute on. Defaults to "cuda" if torch.cuda.is_available() else "cpu".
|
| 153 |
+
|
| 154 |
+
Returns:
|
| 155 |
+
Matplotlib plot of target image and model prediction as title.
|
| 156 |
+
|
| 157 |
+
Example usage:
|
| 158 |
+
pred_and_plot_image(model=model,
|
| 159 |
+
image="some_image.jpeg",
|
| 160 |
+
class_names=["class_1", "class_2", "class_3"],
|
| 161 |
+
transform=torchvision.transforms.ToTensor(),
|
| 162 |
+
device=device)
|
| 163 |
+
"""
|
| 164 |
+
|
| 165 |
+
# 1. Load in image and convert the tensor values to float32
|
| 166 |
+
target_image = torchvision.io.read_image(str(image_path)).type(torch.float32)
|
| 167 |
+
|
| 168 |
+
# 2. Divide the image pixel values by 255 to get them between [0, 1]
|
| 169 |
+
target_image = target_image / 255.0
|
| 170 |
+
|
| 171 |
+
# 3. Transform if necessary
|
| 172 |
+
if transform:
|
| 173 |
+
target_image = transform(target_image)
|
| 174 |
+
|
| 175 |
+
# 4. Make sure the model is on the target device
|
| 176 |
+
model.to(device)
|
| 177 |
+
|
| 178 |
+
# 5. Turn on model evaluation mode and inference mode
|
| 179 |
+
model.eval()
|
| 180 |
+
with torch.inference_mode():
|
| 181 |
+
# Add an extra dimension to the image
|
| 182 |
+
target_image = target_image.unsqueeze(dim=0)
|
| 183 |
+
|
| 184 |
+
# Make a prediction on image with an extra dimension and send it to the target device
|
| 185 |
+
target_image_pred = model(target_image.to(device))
|
| 186 |
+
|
| 187 |
+
# 6. Convert logits -> prediction probabilities (using torch.softmax() for multi-class classification)
|
| 188 |
+
target_image_pred_probs = torch.softmax(target_image_pred, dim=1)
|
| 189 |
+
|
| 190 |
+
# 7. Convert prediction probabilities -> prediction labels
|
| 191 |
+
target_image_pred_label = torch.argmax(target_image_pred_probs, dim=1)
|
| 192 |
+
|
| 193 |
+
# 8. Plot the image alongside the prediction and prediction probability
|
| 194 |
+
plt.imshow(
|
| 195 |
+
target_image.squeeze().permute(1, 2, 0)
|
| 196 |
+
) # make sure it's the right size for matplotlib
|
| 197 |
+
if class_names:
|
| 198 |
+
title = f"Pred: {class_names[target_image_pred_label.cpu()]} | Prob: {target_image_pred_probs.max().cpu():.3f}"
|
| 199 |
+
else:
|
| 200 |
+
title = f"Pred: {target_image_pred_label} | Prob: {target_image_pred_probs.max().cpu():.3f}"
|
| 201 |
+
plt.title(title)
|
| 202 |
+
plt.axis(False)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
# In[ ]:
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def set_seeds(seed: int=42):
|
| 209 |
+
"""Sets random sets for torch operations.
|
| 210 |
+
|
| 211 |
+
Args:
|
| 212 |
+
seed (int, optional): Random seed to set. Defaults to 42.
|
| 213 |
+
"""
|
| 214 |
+
# Set the seed for general torch operations
|
| 215 |
+
torch.manual_seed(seed)
|
| 216 |
+
# Set the seed for CUDA torch operations (ones that happen on the GPU)
|
| 217 |
+
torch.cuda.manual_seed(seed)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
# In[ ]:
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
|
good (1).py
ADDED
|
@@ -0,0 +1,895 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""Good.ipynb
|
| 3 |
+
|
| 4 |
+
Automatically generated by Colaboratory.
|
| 5 |
+
|
| 6 |
+
Original file is located at
|
| 7 |
+
https://colab.research.google.com/drive/1AkM6wLyspo4q2ScK_pIkTAFDV-Q-JCgh
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
!pip install torchinfo
|
| 11 |
+
|
| 12 |
+
files.upload()
|
| 13 |
+
|
| 14 |
+
from google.colab import files
|
| 15 |
+
import matplotlib.pyplot as plt
|
| 16 |
+
import torch
|
| 17 |
+
import torchvision
|
| 18 |
+
|
| 19 |
+
from torch import nn
|
| 20 |
+
from torchvision import transforms
|
| 21 |
+
from Helperfunction import set_seeds
|
| 22 |
+
|
| 23 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 24 |
+
device
|
| 25 |
+
|
| 26 |
+
# Commented out IPython magic to ensure Python compatibility.
|
| 27 |
+
# %%writefile predict.py
|
| 28 |
+
#
|
| 29 |
+
# #predict
|
| 30 |
+
#
|
| 31 |
+
#
|
| 32 |
+
# """
|
| 33 |
+
# Utility functions to make predictions.
|
| 34 |
+
#
|
| 35 |
+
# Main reference for code creation: https://www.learnpytorch.io/06_pytorch_transfer_learning/#6-make-predictions-on-images-from-the-test-set
|
| 36 |
+
# """
|
| 37 |
+
# import torch
|
| 38 |
+
# import torchvision
|
| 39 |
+
# from torchvision import transforms
|
| 40 |
+
# import matplotlib.pyplot as plt
|
| 41 |
+
#
|
| 42 |
+
# from typing import List, Tuple
|
| 43 |
+
#
|
| 44 |
+
# from PIL import Image
|
| 45 |
+
#
|
| 46 |
+
# # Set device
|
| 47 |
+
# device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 48 |
+
#
|
| 49 |
+
# # Predict on a target image with a target model
|
| 50 |
+
# # Function created in: https://www.learnpytorch.io/06_pytorch_transfer_learning/#6-make-predictions-on-images-from-the-test-set
|
| 51 |
+
# def pred_and_plot_image(
|
| 52 |
+
# model: torch.nn.Module,
|
| 53 |
+
# class_names: List[str],
|
| 54 |
+
# image_path: str,
|
| 55 |
+
# image_size: Tuple[int, int] = (224, 224),
|
| 56 |
+
# transform: torchvision.transforms = None,
|
| 57 |
+
# device: torch.device = device,
|
| 58 |
+
# ):
|
| 59 |
+
# """Predicts on a target image with a target model.
|
| 60 |
+
#
|
| 61 |
+
# Args:
|
| 62 |
+
# model (torch.nn.Module): A trained (or untrained) PyTorch model to predict on an image.
|
| 63 |
+
# class_names (List[str]): A list of target classes to map predictions to.
|
| 64 |
+
# image_path (str): Filepath to target image to predict on.
|
| 65 |
+
# image_size (Tuple[int, int], optional): Size to transform target image to. Defaults to (224, 224).
|
| 66 |
+
# transform (torchvision.transforms, optional): Transform to perform on image. Defaults to None which uses ImageNet normalization.
|
| 67 |
+
# device (torch.device, optional): Target device to perform prediction on. Defaults to device.
|
| 68 |
+
# """
|
| 69 |
+
#
|
| 70 |
+
# # Open image
|
| 71 |
+
# img = Image.open(image_path)
|
| 72 |
+
#
|
| 73 |
+
# # Create transformation for image (if one doesn't exist)
|
| 74 |
+
# if transform is not None:
|
| 75 |
+
# image_transform = transform
|
| 76 |
+
# else:
|
| 77 |
+
# image_transform = transforms.Compose(
|
| 78 |
+
# [
|
| 79 |
+
# transforms.Resize(image_size),
|
| 80 |
+
# transforms.ToTensor(),
|
| 81 |
+
# transforms.Normalize(
|
| 82 |
+
# mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
|
| 83 |
+
# ),
|
| 84 |
+
# ]
|
| 85 |
+
# )
|
| 86 |
+
#
|
| 87 |
+
# ### Predict on image ###
|
| 88 |
+
#
|
| 89 |
+
# # Make sure the model is on the target device
|
| 90 |
+
# model.to(device)
|
| 91 |
+
#
|
| 92 |
+
# # Turn on model evaluation mode and inference mode
|
| 93 |
+
# model.eval()
|
| 94 |
+
# with torch.inference_mode():
|
| 95 |
+
# # Transform and add an extra dimension to image (model requires samples in [batch_size, color_channels, height, width])
|
| 96 |
+
# transformed_image = image_transform(img).unsqueeze(dim=0)
|
| 97 |
+
#
|
| 98 |
+
# # Make a prediction on image with an extra dimension and send it to the target device
|
| 99 |
+
# target_image_pred = model(transformed_image.to(device))
|
| 100 |
+
#
|
| 101 |
+
# # Convert logits -> prediction probabilities (using torch.softmax() for multi-class classification)
|
| 102 |
+
# target_image_pred_probs = torch.softmax(target_image_pred, dim=1)
|
| 103 |
+
#
|
| 104 |
+
# # Convert prediction probabilities -> prediction labels
|
| 105 |
+
# target_image_pred_label = torch.argmax(target_image_pred_probs, dim=1)
|
| 106 |
+
#
|
| 107 |
+
# # Plot image with predicted label and probability
|
| 108 |
+
# plt.figure()
|
| 109 |
+
# plt.imshow(img)
|
| 110 |
+
# plt.title(
|
| 111 |
+
# f"Pred: {class_names[target_image_pred_label]} | Prob: {target_image_pred_probs.max():.3f}"
|
| 112 |
+
# )
|
| 113 |
+
# plt.axis(False)
|
| 114 |
+
#
|
| 115 |
+
|
| 116 |
+
from google.colab import drive
|
| 117 |
+
drive.mount('/content/drive')
|
| 118 |
+
|
| 119 |
+
# Commented out IPython magic to ensure Python compatibility.
|
| 120 |
+
# %%writefile model_builder.py
|
| 121 |
+
#
|
| 122 |
+
# #model_builder
|
| 123 |
+
#
|
| 124 |
+
# """
|
| 125 |
+
# Contains PyTorch model code to instantiate a TinyVGG model.
|
| 126 |
+
# """
|
| 127 |
+
# import torch
|
| 128 |
+
# from torch import nn
|
| 129 |
+
#
|
| 130 |
+
# class TinyVGG(nn.Module):
|
| 131 |
+
# """Creates the TinyVGG architecture.
|
| 132 |
+
#
|
| 133 |
+
# Replicates the TinyVGG architecture from the CNN explainer website in PyTorch.
|
| 134 |
+
# See the original architecture here: https://poloclub.github.io/cnn-explainer/
|
| 135 |
+
#
|
| 136 |
+
# Args:
|
| 137 |
+
# input_shape: An integer indicating number of input channels.
|
| 138 |
+
# hidden_units: An integer indicating number of hidden units between layers.
|
| 139 |
+
# output_shape: An integer indicating number of output units.
|
| 140 |
+
# """
|
| 141 |
+
# def __init__(self, input_shape: int, hidden_units: int, output_shape: int) -> None:
|
| 142 |
+
# super().__init__()
|
| 143 |
+
# self.conv_block_1 = nn.Sequential(
|
| 144 |
+
# nn.Conv2d(in_channels=input_shape,
|
| 145 |
+
# out_channels=hidden_units,
|
| 146 |
+
# kernel_size=3,
|
| 147 |
+
# stride=1,
|
| 148 |
+
# padding=0),
|
| 149 |
+
# nn.ReLU(),
|
| 150 |
+
# nn.Conv2d(in_channels=hidden_units,
|
| 151 |
+
# out_channels=hidden_units,
|
| 152 |
+
# kernel_size=3,
|
| 153 |
+
# stride=1,
|
| 154 |
+
# padding=0),
|
| 155 |
+
# nn.ReLU(),
|
| 156 |
+
# nn.MaxPool2d(kernel_size=2,
|
| 157 |
+
# stride=2)
|
| 158 |
+
# )
|
| 159 |
+
# self.conv_block_2 = nn.Sequential(
|
| 160 |
+
# nn.Conv2d(hidden_units, hidden_units, kernel_size=3, padding=0),
|
| 161 |
+
# nn.ReLU(),
|
| 162 |
+
# nn.Conv2d(hidden_units, hidden_units, kernel_size=3, padding=0),
|
| 163 |
+
# nn.ReLU(),
|
| 164 |
+
# nn.MaxPool2d(2)
|
| 165 |
+
# )
|
| 166 |
+
# self.classifier = nn.Sequential(
|
| 167 |
+
# nn.Flatten(),
|
| 168 |
+
# # Where did this in_features shape come from?
|
| 169 |
+
# # It's because each layer of our network compresses and changes the shape of our inputs data.
|
| 170 |
+
# nn.Linear(in_features=hidden_units*13*13,
|
| 171 |
+
# out_features=output_shape)
|
| 172 |
+
# )
|
| 173 |
+
#
|
| 174 |
+
# def forward(self, x: torch.Tensor):
|
| 175 |
+
# x = self.conv_block_1(x)
|
| 176 |
+
# x = self.conv_block_2(x)
|
| 177 |
+
# x = self.classifier(x)
|
| 178 |
+
# return x
|
| 179 |
+
# # return self.classifier(self.block_2(self.block_1(x))) # <- leverage the benefits of operator fusion
|
| 180 |
+
|
| 181 |
+
# Commented out IPython magic to ensure Python compatibility.
|
| 182 |
+
# %%writefile utils.py
|
| 183 |
+
#
|
| 184 |
+
# #utils.py
|
| 185 |
+
#
|
| 186 |
+
# """
|
| 187 |
+
# Contains various utility functions for PyTorch model training and saving.
|
| 188 |
+
# """
|
| 189 |
+
# import torch
|
| 190 |
+
# from pathlib import Path
|
| 191 |
+
#
|
| 192 |
+
# def save_model(model: torch.nn.Module,
|
| 193 |
+
# target_dir: str,
|
| 194 |
+
# model_name: str):
|
| 195 |
+
# """Saves a PyTorch model to a target directory.
|
| 196 |
+
#
|
| 197 |
+
# Args:
|
| 198 |
+
# model: A target PyTorch model to save.
|
| 199 |
+
# target_dir: A directory for saving the model to.
|
| 200 |
+
# model_name: A filename for the saved model. Should include
|
| 201 |
+
# either ".pth" or ".pt" as the file extension.
|
| 202 |
+
#
|
| 203 |
+
# Example usage:
|
| 204 |
+
# save_model(model=model_0,
|
| 205 |
+
# target_dir="models",
|
| 206 |
+
# model_name="05_going_modular_tingvgg_model.pth")
|
| 207 |
+
# """
|
| 208 |
+
# # Create target directory
|
| 209 |
+
# target_dir_path = Path(target_dir)
|
| 210 |
+
# target_dir_path.mkdir(parents=True,
|
| 211 |
+
# exist_ok=True)
|
| 212 |
+
#
|
| 213 |
+
# # Create model save path
|
| 214 |
+
# assert model_name.endswith(".pth") or model_name.endswith(".pt"), "model_name should end with '.pt' or '.pth'"
|
| 215 |
+
# model_save_path = target_dir_path / model_name
|
| 216 |
+
#
|
| 217 |
+
# # Save the model state_dict()
|
| 218 |
+
# print(f"[INFO] Saving model to: {model_save_path}")
|
| 219 |
+
# torch.save(obj=model.state_dict(),
|
| 220 |
+
# f=model_save_path)
|
| 221 |
+
|
| 222 |
+
# Commented out IPython magic to ensure Python compatibility.
|
| 223 |
+
# %%writefile engine.py
|
| 224 |
+
# #engine.py
|
| 225 |
+
#
|
| 226 |
+
# """
|
| 227 |
+
# Contains functions for training and testing a PyTorch model.
|
| 228 |
+
# """
|
| 229 |
+
# import torch
|
| 230 |
+
#
|
| 231 |
+
# from tqdm.auto import tqdm
|
| 232 |
+
# from typing import Dict, List, Tuple
|
| 233 |
+
#
|
| 234 |
+
# def train_step(model: torch.nn.Module,
|
| 235 |
+
# dataloader: torch.utils.data.DataLoader,
|
| 236 |
+
# loss_fn: torch.nn.Module,
|
| 237 |
+
# optimizer: torch.optim.Optimizer,
|
| 238 |
+
# device: torch.device) -> Tuple[float, float]:
|
| 239 |
+
# """Trains a PyTorch model for a single epoch.
|
| 240 |
+
#
|
| 241 |
+
# Turns a target PyTorch model to training mode and then
|
| 242 |
+
# runs through all of the required training steps (forward
|
| 243 |
+
# pass, loss calculation, optimizer step).
|
| 244 |
+
#
|
| 245 |
+
# Args:
|
| 246 |
+
# model: A PyTorch model to be trained.
|
| 247 |
+
# dataloader: A DataLoader instance for the model to be trained on.
|
| 248 |
+
# loss_fn: A PyTorch loss function to minimize.
|
| 249 |
+
# optimizer: A PyTorch optimizer to help minimize the loss function.
|
| 250 |
+
# device: A target device to compute on (e.g. "cuda" or "cpu").
|
| 251 |
+
#
|
| 252 |
+
# Returns:
|
| 253 |
+
# A tuple of training loss and training accuracy metrics.
|
| 254 |
+
# In the form (train_loss, train_accuracy). For example:
|
| 255 |
+
#
|
| 256 |
+
# (0.1112, 0.8743)
|
| 257 |
+
# """
|
| 258 |
+
# # Put model in train mode
|
| 259 |
+
# model.train()
|
| 260 |
+
#
|
| 261 |
+
# # Setup train loss and train accuracy values
|
| 262 |
+
# train_loss, train_acc = 0, 0
|
| 263 |
+
#
|
| 264 |
+
# # Loop through data loader data batches
|
| 265 |
+
# for batch, (X, y) in enumerate(dataloader):
|
| 266 |
+
# # Send data to target device
|
| 267 |
+
# X, y = X.to(device), y.to(device)
|
| 268 |
+
#
|
| 269 |
+
# # 1. Forward pass
|
| 270 |
+
# y_pred = model(X)
|
| 271 |
+
#
|
| 272 |
+
# # 2. Calculate and accumulate loss
|
| 273 |
+
# loss = loss_fn(y_pred, y)
|
| 274 |
+
# train_loss += loss.item()
|
| 275 |
+
#
|
| 276 |
+
# # 3. Optimizer zero grad
|
| 277 |
+
# optimizer.zero_grad()
|
| 278 |
+
#
|
| 279 |
+
# # 4. Loss backward
|
| 280 |
+
# loss.backward()
|
| 281 |
+
#
|
| 282 |
+
# # 5. Optimizer step
|
| 283 |
+
# optimizer.step()
|
| 284 |
+
#
|
| 285 |
+
# # Calculate and accumulate accuracy metric across all batches
|
| 286 |
+
# y_pred_class = torch.argmax(torch.softmax(y_pred, dim=1), dim=1)
|
| 287 |
+
# train_acc += (y_pred_class == y).sum().item()/len(y_pred)
|
| 288 |
+
#
|
| 289 |
+
# # Adjust metrics to get average loss and accuracy per batch
|
| 290 |
+
# train_loss = train_loss / len(dataloader)
|
| 291 |
+
# train_acc = train_acc / len(dataloader)
|
| 292 |
+
# return train_loss, train_acc
|
| 293 |
+
#
|
| 294 |
+
# def test_step(model: torch.nn.Module,
|
| 295 |
+
# dataloader: torch.utils.data.DataLoader,
|
| 296 |
+
# loss_fn: torch.nn.Module,
|
| 297 |
+
# device: torch.device) -> Tuple[float, float]:
|
| 298 |
+
# """Tests a PyTorch model for a single epoch.
|
| 299 |
+
#
|
| 300 |
+
# Turns a target PyTorch model to "eval" mode and then performs
|
| 301 |
+
# a forward pass on a testing dataset.
|
| 302 |
+
#
|
| 303 |
+
# Args:
|
| 304 |
+
# model: A PyTorch model to be tested.
|
| 305 |
+
# dataloader: A DataLoader instance for the model to be tested on.
|
| 306 |
+
# loss_fn: A PyTorch loss function to calculate loss on the test data.
|
| 307 |
+
# device: A target device to compute on (e.g. "cuda" or "cpu").
|
| 308 |
+
#
|
| 309 |
+
# Returns:
|
| 310 |
+
# A tuple of testing loss and testing accuracy metrics.
|
| 311 |
+
# In the form (test_loss, test_accuracy). For example:
|
| 312 |
+
#
|
| 313 |
+
# (0.0223, 0.8985)
|
| 314 |
+
# """
|
| 315 |
+
# # Put model in eval mode
|
| 316 |
+
# model.eval()
|
| 317 |
+
#
|
| 318 |
+
# # Setup test loss and test accuracy values
|
| 319 |
+
# test_loss, test_acc = 0, 0
|
| 320 |
+
#
|
| 321 |
+
# # Turn on inference context manager
|
| 322 |
+
# with torch.inference_mode():
|
| 323 |
+
# # Loop through DataLoader batches
|
| 324 |
+
# for batch, (X, y) in enumerate(dataloader):
|
| 325 |
+
# # Send data to target device
|
| 326 |
+
# X, y = X.to(device), y.to(device)
|
| 327 |
+
#
|
| 328 |
+
# # 1. Forward pass
|
| 329 |
+
# test_pred_logits = model(X)
|
| 330 |
+
#
|
| 331 |
+
# # 2. Calculate and accumulate loss
|
| 332 |
+
# loss = loss_fn(test_pred_logits, y)
|
| 333 |
+
# test_loss += loss.item()
|
| 334 |
+
#
|
| 335 |
+
# # Calculate and accumulate accuracy
|
| 336 |
+
# test_pred_labels = test_pred_logits.argmax(dim=1)
|
| 337 |
+
# test_acc += ((test_pred_labels == y).sum().item()/len(test_pred_labels))
|
| 338 |
+
#
|
| 339 |
+
# # Adjust metrics to get average loss and accuracy per batch
|
| 340 |
+
# test_loss = test_loss / len(dataloader)
|
| 341 |
+
# test_acc = test_acc / len(dataloader)
|
| 342 |
+
# return test_loss, test_acc
|
| 343 |
+
#
|
| 344 |
+
# def train(model: torch.nn.Module,
|
| 345 |
+
# train_dataloader: torch.utils.data.DataLoader,
|
| 346 |
+
# test_dataloader: torch.utils.data.DataLoader,
|
| 347 |
+
# optimizer: torch.optim.Optimizer,
|
| 348 |
+
# loss_fn: torch.nn.Module,
|
| 349 |
+
# epochs: int,
|
| 350 |
+
# device: torch.device) -> Dict[str, List]:
|
| 351 |
+
# """Trains and tests a PyTorch model.
|
| 352 |
+
#
|
| 353 |
+
# Passes a target PyTorch models through train_step() and test_step()
|
| 354 |
+
# functions for a number of epochs, training and testing the model
|
| 355 |
+
# in the same epoch loop.
|
| 356 |
+
#
|
| 357 |
+
# Calculates, prints and stores evaluation metrics throughout.
|
| 358 |
+
#
|
| 359 |
+
# Args:
|
| 360 |
+
# model: A PyTorch model to be trained and tested.
|
| 361 |
+
# train_dataloader: A DataLoader instance for the model to be trained on.
|
| 362 |
+
# test_dataloader: A DataLoader instance for the model to be tested on.
|
| 363 |
+
# optimizer: A PyTorch optimizer to help minimize the loss function.
|
| 364 |
+
# loss_fn: A PyTorch loss function to calculate loss on both datasets.
|
| 365 |
+
# epochs: An integer indicating how many epochs to train for.
|
| 366 |
+
# device: A target device to compute on (e.g. "cuda" or "cpu").
|
| 367 |
+
#
|
| 368 |
+
# Returns:
|
| 369 |
+
# A dictionary of training and testing loss as well as training and
|
| 370 |
+
# testing accuracy metrics. Each metric has a value in a list for
|
| 371 |
+
# each epoch.
|
| 372 |
+
# In the form: {train_loss: [...],
|
| 373 |
+
# train_acc: [...],
|
| 374 |
+
# test_loss: [...],
|
| 375 |
+
# test_acc: [...]}
|
| 376 |
+
# For example if training for epochs=2:
|
| 377 |
+
# {train_loss: [2.0616, 1.0537],
|
| 378 |
+
# train_acc: [0.3945, 0.3945],
|
| 379 |
+
# test_loss: [1.2641, 1.5706],
|
| 380 |
+
# test_acc: [0.3400, 0.2973]}
|
| 381 |
+
# """
|
| 382 |
+
# # Create empty results dictionary
|
| 383 |
+
# results = {"train_loss": [],
|
| 384 |
+
# "train_acc": [],
|
| 385 |
+
# "test_loss": [],
|
| 386 |
+
# "test_acc": []
|
| 387 |
+
# }
|
| 388 |
+
#
|
| 389 |
+
# # Make sure model on target device
|
| 390 |
+
# model.to(device)
|
| 391 |
+
#
|
| 392 |
+
# # Loop through training and testing steps for a number of epochs
|
| 393 |
+
# for epoch in tqdm(range(epochs)):
|
| 394 |
+
# train_loss, train_acc = train_step(model=model,
|
| 395 |
+
# dataloader=train_dataloader,
|
| 396 |
+
# loss_fn=loss_fn,
|
| 397 |
+
# optimizer=optimizer,
|
| 398 |
+
# device=device)
|
| 399 |
+
# test_loss, test_acc = test_step(model=model,
|
| 400 |
+
# dataloader=test_dataloader,
|
| 401 |
+
# loss_fn=loss_fn,
|
| 402 |
+
# device=device)
|
| 403 |
+
#
|
| 404 |
+
# # Print out what's happening
|
| 405 |
+
# print(
|
| 406 |
+
# f"Epoch: {epoch+1} | "
|
| 407 |
+
# f"train_loss: {train_loss:.4f} | "
|
| 408 |
+
# f"train_acc: {train_acc:.4f} | "
|
| 409 |
+
# f"test_loss: {test_loss:.4f} | "
|
| 410 |
+
# f"test_acc: {test_acc:.4f}"
|
| 411 |
+
# )
|
| 412 |
+
#
|
| 413 |
+
# # Update results dictionary
|
| 414 |
+
# results["train_loss"].append(train_loss)
|
| 415 |
+
# results["train_acc"].append(train_acc)
|
| 416 |
+
# results["test_loss"].append(test_loss)
|
| 417 |
+
# results["test_acc"].append(test_acc)
|
| 418 |
+
#
|
| 419 |
+
# # Return the filled results at the end of the epochs
|
| 420 |
+
# return results
|
| 421 |
+
|
| 422 |
+
# Commented out IPython magic to ensure Python compatibility.
|
| 423 |
+
# %%writefile data_setup.py
|
| 424 |
+
# #data_setup.py
|
| 425 |
+
# """
|
| 426 |
+
# Contains functionality for creating PyTorch DataLoaders for
|
| 427 |
+
# image classification data.
|
| 428 |
+
# """
|
| 429 |
+
# import os
|
| 430 |
+
#
|
| 431 |
+
# from torchvision import datasets, transforms
|
| 432 |
+
# from torch.utils.data import DataLoader
|
| 433 |
+
#
|
| 434 |
+
# NUM_WORKERS = os.cpu_count()
|
| 435 |
+
#
|
| 436 |
+
# def create_dataloaders(
|
| 437 |
+
# train_dir: str,
|
| 438 |
+
# test_dir: str,
|
| 439 |
+
# transform: transforms.Compose,
|
| 440 |
+
# batch_size: int,
|
| 441 |
+
# num_workers: int=NUM_WORKERS
|
| 442 |
+
# ):
|
| 443 |
+
# """Creates training and testing DataLoaders.
|
| 444 |
+
#
|
| 445 |
+
# Takes in a training directory and testing directory path and turns
|
| 446 |
+
# them into PyTorch Datasets and then into PyTorch DataLoaders.
|
| 447 |
+
#
|
| 448 |
+
# Args:
|
| 449 |
+
# train_dir: Path to training directory.
|
| 450 |
+
# test_dir: Path to testing directory.
|
| 451 |
+
# transform: torchvision transforms to perform on training and testing data.
|
| 452 |
+
# batch_size: Number of samples per batch in each of the DataLoaders.
|
| 453 |
+
# num_workers: An integer for number of workers per DataLoader.
|
| 454 |
+
#
|
| 455 |
+
# Returns:
|
| 456 |
+
# A tuple of (train_dataloader, test_dataloader, class_names).
|
| 457 |
+
# Where class_names is a list of the target classes.
|
| 458 |
+
# Example usage:
|
| 459 |
+
# train_dataloader, test_dataloader, class_names = \
|
| 460 |
+
# = create_dataloaders(train_dir=path/to/train_dir,
|
| 461 |
+
# test_dir=path/to/test_dir,
|
| 462 |
+
# transform=some_transform,
|
| 463 |
+
# batch_size=32,
|
| 464 |
+
# num_workers=4)
|
| 465 |
+
# """
|
| 466 |
+
# # Use ImageFolder to create dataset(s)
|
| 467 |
+
# train_data = datasets.ImageFolder(train_dir, transform=transform)
|
| 468 |
+
# test_data = datasets.ImageFolder(test_dir, transform=transform)
|
| 469 |
+
#
|
| 470 |
+
# # Get class names
|
| 471 |
+
# class_names = train_data.classes
|
| 472 |
+
#
|
| 473 |
+
# # Turn images into data loaders
|
| 474 |
+
# train_dataloader = DataLoader(
|
| 475 |
+
# train_data,
|
| 476 |
+
# batch_size=batch_size,
|
| 477 |
+
# shuffle=True,
|
| 478 |
+
# num_workers=num_workers,
|
| 479 |
+
# pin_memory=True,
|
| 480 |
+
# )
|
| 481 |
+
# test_dataloader = DataLoader(
|
| 482 |
+
# test_data,
|
| 483 |
+
# batch_size=batch_size,
|
| 484 |
+
# shuffle=False,
|
| 485 |
+
# num_workers=num_workers,
|
| 486 |
+
# pin_memory=True,
|
| 487 |
+
# )
|
| 488 |
+
#
|
| 489 |
+
# return train_dataloader, test_dataloader, class_names
|
| 490 |
+
|
| 491 |
+
# Commented out IPython magic to ensure Python compatibility.
|
| 492 |
+
# %%writefile train.py
|
| 493 |
+
# #train.py only in this cell
|
| 494 |
+
#
|
| 495 |
+
# """
|
| 496 |
+
# Trains a PyTorch image classification model using device-agnostic code.
|
| 497 |
+
# """
|
| 498 |
+
#
|
| 499 |
+
# import os
|
| 500 |
+
# import torch
|
| 501 |
+
# #import data_setup, engine, model_builder, utils
|
| 502 |
+
#
|
| 503 |
+
# from torchvision import transforms
|
| 504 |
+
#
|
| 505 |
+
# # Setup hyperparameters
|
| 506 |
+
# NUM_EPOCHS = 5
|
| 507 |
+
# BATCH_SIZE = 32
|
| 508 |
+
# HIDDEN_UNITS = 10
|
| 509 |
+
# LEARNING_RATE = 0.001
|
| 510 |
+
#
|
| 511 |
+
# # Setup directories
|
| 512 |
+
# train_dir = "data/pizza_steak_sushi/train"
|
| 513 |
+
# test_dir = "data/pizza_steak_sushi/test"
|
| 514 |
+
#
|
| 515 |
+
# # Setup target device
|
| 516 |
+
# device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 517 |
+
#
|
| 518 |
+
# # Create transforms
|
| 519 |
+
# data_transform = transforms.Compose([
|
| 520 |
+
# transforms.Resize((64, 64)),
|
| 521 |
+
# transforms.ToTensor()
|
| 522 |
+
# ])
|
| 523 |
+
#
|
| 524 |
+
# # Create DataLoaders with help from data_setup.py
|
| 525 |
+
# train_dataloader, test_dataloader, class_names = data_setup.create_dataloaders(
|
| 526 |
+
# train_dir=train_dir,
|
| 527 |
+
# test_dir=test_dir,
|
| 528 |
+
# transform=data_transform,
|
| 529 |
+
# batch_size=BATCH_SIZE
|
| 530 |
+
# )
|
| 531 |
+
#
|
| 532 |
+
# # Create model with help from model_builder.py
|
| 533 |
+
# model = model_builder.TinyVGG(
|
| 534 |
+
# input_shape=3,
|
| 535 |
+
# hidden_units=HIDDEN_UNITS,
|
| 536 |
+
# output_shape=len(class_names)
|
| 537 |
+
# ).to(device)
|
| 538 |
+
#
|
| 539 |
+
# # Set loss and optimizer
|
| 540 |
+
# loss_fn = torch.nn.CrossEntropyLoss()
|
| 541 |
+
# optimizer = torch.optim.Adam(model.parameters(),
|
| 542 |
+
# lr=LEARNING_RATE)
|
| 543 |
+
#
|
| 544 |
+
# # Start training with help from engine.py
|
| 545 |
+
# engine.train(model=model,
|
| 546 |
+
# train_dataloader=train_dataloader,
|
| 547 |
+
# test_dataloader=test_dataloader,
|
| 548 |
+
# loss_fn=loss_fn,
|
| 549 |
+
# optimizer=optimizer,
|
| 550 |
+
# epochs=NUM_EPOCHS,
|
| 551 |
+
# device=device)
|
| 552 |
+
#
|
| 553 |
+
# # Save the model with help from utils.py
|
| 554 |
+
# utils.save_model(model=model,
|
| 555 |
+
# target_dir="models",
|
| 556 |
+
# model_name="05_going_modular_script_mode_tinyvgg_model.pth")
|
| 557 |
+
#
|
| 558 |
+
#
|
| 559 |
+
#
|
| 560 |
+
#
|
| 561 |
+
|
| 562 |
+
!python /content/data_setup.py/train.py --batch_size 64 --learning_rate 0.001 --num_epochs 25
|
| 563 |
+
|
| 564 |
+
# 1. Get pretrained weights for ViT-Base
|
| 565 |
+
pretrained_vit_weights = torchvision.models.ViT_B_16_Weights.DEFAULT
|
| 566 |
+
|
| 567 |
+
# 2. Setup a ViT model instance with pretrained weights
|
| 568 |
+
pretrained_vit = torchvision.models.vit_b_16(weights=pretrained_vit_weights).to(device)
|
| 569 |
+
|
| 570 |
+
# 3. Freeze the base parameters
|
| 571 |
+
for parameter in pretrained_vit.parameters():
|
| 572 |
+
parameter.requires_grad = False
|
| 573 |
+
|
| 574 |
+
# 4. Change the classifier head
|
| 575 |
+
class_names = ['Bad_tire','Good_tire']
|
| 576 |
+
|
| 577 |
+
set_seeds()
|
| 578 |
+
pretrained_vit.heads = nn.Linear(in_features=768, out_features=len(class_names)).to(device)
|
| 579 |
+
# pretrained_vit # uncomment for model output
|
| 580 |
+
|
| 581 |
+
from torchinfo import summary
|
| 582 |
+
|
| 583 |
+
# Print a summary using torchinfo (uncomment for actual output)
|
| 584 |
+
summary(model=pretrained_vit,
|
| 585 |
+
input_size=(32, 3, 224, 224), # (batch_size, color_channels, height, width)
|
| 586 |
+
#col_names=["input_size"], # uncomment for smaller output
|
| 587 |
+
col_names=["input_size", "output_size", "num_params", "trainable"],
|
| 588 |
+
col_width=20,
|
| 589 |
+
row_settings=["var_names"]
|
| 590 |
+
)
|
| 591 |
+
|
| 592 |
+
# Setup directory paths to train and test images
|
| 593 |
+
train_dir = '/content/drive/MyDrive/Test/test'
|
| 594 |
+
test_dir = '/content/drive/MyDrive/Train/train'
|
| 595 |
+
|
| 596 |
+
# Get automatic transforms from pretrained ViT weights
|
| 597 |
+
pretrained_vit_transforms = pretrained_vit_weights.transforms()
|
| 598 |
+
print(pretrained_vit_transforms)
|
| 599 |
+
|
| 600 |
+
import os
|
| 601 |
+
|
| 602 |
+
from torchvision import datasets, transforms
|
| 603 |
+
from torch.utils.data import DataLoader
|
| 604 |
+
|
| 605 |
+
NUM_WORKERS = os.cpu_count()
|
| 606 |
+
|
| 607 |
+
def create_dataloaders(
|
| 608 |
+
train_dir: str,
|
| 609 |
+
test_dir: str,
|
| 610 |
+
transform: transforms.Compose,
|
| 611 |
+
batch_size: int,
|
| 612 |
+
num_workers: int=NUM_WORKERS
|
| 613 |
+
):
|
| 614 |
+
|
| 615 |
+
# Use ImageFolder to create dataset(s)
|
| 616 |
+
train_data = datasets.ImageFolder(train_dir, transform=transform)
|
| 617 |
+
test_data = datasets.ImageFolder(test_dir, transform=transform)
|
| 618 |
+
|
| 619 |
+
# Get class names
|
| 620 |
+
class_names = train_data.classes
|
| 621 |
+
|
| 622 |
+
# Turn images into data loaders
|
| 623 |
+
train_dataloader = DataLoader(
|
| 624 |
+
train_data,
|
| 625 |
+
batch_size=batch_size,
|
| 626 |
+
shuffle=True,
|
| 627 |
+
num_workers=num_workers,
|
| 628 |
+
pin_memory=True,
|
| 629 |
+
)
|
| 630 |
+
test_dataloader = DataLoader(
|
| 631 |
+
test_data,
|
| 632 |
+
batch_size=batch_size,
|
| 633 |
+
shuffle=False,
|
| 634 |
+
num_workers=num_workers,
|
| 635 |
+
pin_memory=True,
|
| 636 |
+
)
|
| 637 |
+
|
| 638 |
+
return train_dataloader, test_dataloader, class_names
|
| 639 |
+
|
| 640 |
+
# Setup dataloaders
|
| 641 |
+
train_dataloader_pretrained, test_dataloader_pretrained, class_names = create_dataloaders(
|
| 642 |
+
train_dir=train_dir,
|
| 643 |
+
test_dir=test_dir,
|
| 644 |
+
transform=pretrained_vit_transforms,
|
| 645 |
+
batch_size=32) # Could increase if we had more samples, such as here: https://arxiv.org/abs/2205.01580 (there are other improvements there too...)
|
| 646 |
+
|
| 647 |
+
#import data_setup.py
|
| 648 |
+
|
| 649 |
+
!python train.py --batch_size 64 --learning_rate 0.001 --num_epochs 25
|
| 650 |
+
|
| 651 |
+
import engine
|
| 652 |
+
|
| 653 |
+
# Create optimizer and loss function
|
| 654 |
+
optimizer = torch.optim.Adam(params=pretrained_vit.parameters(),
|
| 655 |
+
lr=1e-3)
|
| 656 |
+
loss_fn = torch.nn.CrossEntropyLoss()
|
| 657 |
+
|
| 658 |
+
# Train the classifier head of the pretrained ViT feature extractor model
|
| 659 |
+
set_seeds()
|
| 660 |
+
pretrained_vit_results = engine.train(model=pretrained_vit,
|
| 661 |
+
train_dataloader=train_dataloader_pretrained,
|
| 662 |
+
test_dataloader=test_dataloader_pretrained,
|
| 663 |
+
optimizer=optimizer,
|
| 664 |
+
loss_fn=loss_fn,
|
| 665 |
+
epochs=10,
|
| 666 |
+
device=device)
|
| 667 |
+
|
| 668 |
+
# Commented out IPython magic to ensure Python compatibility.
|
| 669 |
+
# %%writefile helper_functions.py
|
| 670 |
+
#
|
| 671 |
+
# # helper_functions.py
|
| 672 |
+
#
|
| 673 |
+
# """
|
| 674 |
+
# A series of helper functions used throughout the course.
|
| 675 |
+
#
|
| 676 |
+
# If a function gets defined once and could be used over and over, it'll go in here.
|
| 677 |
+
# """
|
| 678 |
+
# import torch
|
| 679 |
+
# import matplotlib.pyplot as plt
|
| 680 |
+
# import numpy as np
|
| 681 |
+
#
|
| 682 |
+
# from torch import nn
|
| 683 |
+
# import os
|
| 684 |
+
# import zipfile
|
| 685 |
+
# from pathlib import Path
|
| 686 |
+
# import requests
|
| 687 |
+
# import os
|
| 688 |
+
#
|
| 689 |
+
#
|
| 690 |
+
#
|
| 691 |
+
# # Plot linear data or training and test and predictions (optional)
|
| 692 |
+
# def plot_predictions(
|
| 693 |
+
# train_data, train_labels, test_data, test_labels, predictions=None
|
| 694 |
+
# ):
|
| 695 |
+
# """
|
| 696 |
+
# Plots linear training data and test data and compares predictions.
|
| 697 |
+
# """
|
| 698 |
+
# plt.figure(figsize=(10, 7))
|
| 699 |
+
#
|
| 700 |
+
# # Plot training data in blue
|
| 701 |
+
# plt.scatter(train_data, train_labels, c="b", s=4, label="Training data")
|
| 702 |
+
#
|
| 703 |
+
# # Plot test data in green
|
| 704 |
+
# plt.scatter(test_data, test_labels, c="g", s=4, label="Testing data")
|
| 705 |
+
#
|
| 706 |
+
# if predictions is not None:
|
| 707 |
+
# # Plot the predictions in red (predictions were made on the test data)
|
| 708 |
+
# plt.scatter(test_data, predictions, c="r", s=4, label="Predictions")
|
| 709 |
+
#
|
| 710 |
+
# # Show the legend
|
| 711 |
+
# plt.legend(prop={"size": 14})
|
| 712 |
+
#
|
| 713 |
+
#
|
| 714 |
+
# # Calculate accuracy (a classification metric)
|
| 715 |
+
# def accuracy_fn(y_true, y_pred):
|
| 716 |
+
# """Calculates accuracy between truth labels and predictions.
|
| 717 |
+
#
|
| 718 |
+
# Args:
|
| 719 |
+
# y_true (torch.Tensor): Truth labels for predictions.
|
| 720 |
+
# y_pred (torch.Tensor): Predictions to be compared to predictions.
|
| 721 |
+
#
|
| 722 |
+
# Returns:
|
| 723 |
+
# [torch.float]: Accuracy value between y_true and y_pred, e.g. 78.45
|
| 724 |
+
# """
|
| 725 |
+
# correct = torch.eq(y_true, y_pred).sum().item()
|
| 726 |
+
# acc = (correct / len(y_pred)) * 100
|
| 727 |
+
# return acc
|
| 728 |
+
#
|
| 729 |
+
#
|
| 730 |
+
# def print_train_time(start, end, device=None):
|
| 731 |
+
# """Prints difference between start and end time.
|
| 732 |
+
#
|
| 733 |
+
# Args:
|
| 734 |
+
# start (float): Start time of computation (preferred in timeit format).
|
| 735 |
+
# end (float): End time of computation.
|
| 736 |
+
# device ([type], optional): Device that compute is running on. Defaults to None.
|
| 737 |
+
#
|
| 738 |
+
# Returns:
|
| 739 |
+
# float: time between start and end in seconds (higher is longer).
|
| 740 |
+
# """
|
| 741 |
+
# total_time = end - start
|
| 742 |
+
# print(f"\nTrain time on {device}: {total_time:.3f} seconds")
|
| 743 |
+
# return total_time
|
| 744 |
+
#
|
| 745 |
+
#
|
| 746 |
+
# # Plot loss curves of a model
|
| 747 |
+
# def plot_loss_curves(results):
|
| 748 |
+
# """Plots training curves of a results dictionary.
|
| 749 |
+
#
|
| 750 |
+
# Args:
|
| 751 |
+
# results (dict): dictionary containing list of values, e.g.
|
| 752 |
+
# {"train_loss": [...],
|
| 753 |
+
# "train_acc": [...],
|
| 754 |
+
# "test_loss": [...],
|
| 755 |
+
# "test_acc": [...]}
|
| 756 |
+
# """
|
| 757 |
+
# loss = results["train_loss"]
|
| 758 |
+
# test_loss = results["test_loss"]
|
| 759 |
+
#
|
| 760 |
+
# accuracy = results["train_acc"]
|
| 761 |
+
# test_accuracy = results["test_acc"]
|
| 762 |
+
#
|
| 763 |
+
# epochs = range(len(results["train_loss"]))
|
| 764 |
+
#
|
| 765 |
+
# plt.figure(figsize=(15, 7))
|
| 766 |
+
#
|
| 767 |
+
# # Plot loss
|
| 768 |
+
# plt.subplot(1, 2, 1)
|
| 769 |
+
# plt.plot(epochs, loss, label="train_loss")
|
| 770 |
+
# plt.plot(epochs, test_loss, label="test_loss")
|
| 771 |
+
# plt.title("Loss")
|
| 772 |
+
# plt.xlabel("Epochs")
|
| 773 |
+
# plt.legend()
|
| 774 |
+
#
|
| 775 |
+
# # Plot accuracy
|
| 776 |
+
# plt.subplot(1, 2, 2)
|
| 777 |
+
# plt.plot(epochs, accuracy, label="train_accuracy")
|
| 778 |
+
# plt.plot(epochs, test_accuracy, label="test_accuracy")
|
| 779 |
+
# plt.title("Accuracy")
|
| 780 |
+
# plt.xlabel("Epochs")
|
| 781 |
+
# plt.legend()
|
| 782 |
+
#
|
| 783 |
+
#
|
| 784 |
+
# # Pred and plot image function from notebook 04
|
| 785 |
+
# # See creation: https://www.learnpytorch.io/04_pytorch_custom_datasets/#113-putting-custom-image-prediction-together-building-a-function
|
| 786 |
+
# from typing import List
|
| 787 |
+
# import torchvision
|
| 788 |
+
#
|
| 789 |
+
#
|
| 790 |
+
# def pred_and_plot_image(
|
| 791 |
+
# model: torch.nn.Module,
|
| 792 |
+
# image_path: str,
|
| 793 |
+
# class_names: List[str] = None,
|
| 794 |
+
# transform=None,
|
| 795 |
+
# device: torch.device = "cuda" if torch.cuda.is_available() else "cpu",
|
| 796 |
+
# ):
|
| 797 |
+
# """Makes a prediction on a target image with a trained model and plots the image.
|
| 798 |
+
#
|
| 799 |
+
# Args:
|
| 800 |
+
# model (torch.nn.Module): trained PyTorch image classification model.
|
| 801 |
+
# image_path (str): filepath to target image.
|
| 802 |
+
# class_names (List[str], optional): different class names for target image. Defaults to None.
|
| 803 |
+
# transform (_type_, optional): transform of target image. Defaults to None.
|
| 804 |
+
# device (torch.device, optional): target device to compute on. Defaults to "cuda" if torch.cuda.is_available() else "cpu".
|
| 805 |
+
#
|
| 806 |
+
# Returns:
|
| 807 |
+
# Matplotlib plot of target image and model prediction as title.
|
| 808 |
+
#
|
| 809 |
+
# Example usage:
|
| 810 |
+
# pred_and_plot_image(model=model,
|
| 811 |
+
# image="some_image.jpeg",
|
| 812 |
+
# class_names=["class_1", "class_2", "class_3"],
|
| 813 |
+
# transform=torchvision.transforms.ToTensor(),
|
| 814 |
+
# device=device)
|
| 815 |
+
# """
|
| 816 |
+
#
|
| 817 |
+
# # 1. Load in image and convert the tensor values to float32
|
| 818 |
+
# target_image = torchvision.io.read_image(str(image_path)).type(torch.float32)
|
| 819 |
+
#
|
| 820 |
+
# # 2. Divide the image pixel values by 255 to get them between [0, 1]
|
| 821 |
+
# target_image = target_image / 255.0
|
| 822 |
+
#
|
| 823 |
+
# # 3. Transform if necessary
|
| 824 |
+
# if transform:
|
| 825 |
+
# target_image = transform(target_image)
|
| 826 |
+
#
|
| 827 |
+
# # 4. Make sure the model is on the target device
|
| 828 |
+
# model.to(device)
|
| 829 |
+
#
|
| 830 |
+
# # 5. Turn on model evaluation mode and inference mode
|
| 831 |
+
# model.eval()
|
| 832 |
+
# with torch.inference_mode():
|
| 833 |
+
# # Add an extra dimension to the image
|
| 834 |
+
# target_image = target_image.unsqueeze(dim=0)
|
| 835 |
+
#
|
| 836 |
+
# # Make a prediction on image with an extra dimension and send it to the target device
|
| 837 |
+
# target_image_pred = model(target_image.to(device))
|
| 838 |
+
#
|
| 839 |
+
# # 6. Convert logits -> prediction probabilities (using torch.softmax() for multi-class classification)
|
| 840 |
+
# target_image_pred_probs = torch.softmax(target_image_pred, dim=1)
|
| 841 |
+
#
|
| 842 |
+
# # 7. Convert prediction probabilities -> prediction labels
|
| 843 |
+
# target_image_pred_label = torch.argmax(target_image_pred_probs, dim=1)
|
| 844 |
+
#
|
| 845 |
+
# # 8. Plot the image alongside the prediction and prediction probability
|
| 846 |
+
# plt.imshow(
|
| 847 |
+
# target_image.squeeze().permute(1, 2, 0)
|
| 848 |
+
# ) # make sure it's the right size for matplotlib
|
| 849 |
+
# if class_names:
|
| 850 |
+
# title = f"Pred: {class_names[target_image_pred_label.cpu()]} | Prob: {target_image_pred_probs.max().cpu():.3f}"
|
| 851 |
+
# else:
|
| 852 |
+
# title = f"Pred: {target_image_pred_label} | Prob: {target_image_pred_probs.max().cpu():.3f}"
|
| 853 |
+
# plt.title(title)
|
| 854 |
+
# plt.axis(False)
|
| 855 |
+
#
|
| 856 |
+
# def set_seeds(seed: int=42):
|
| 857 |
+
# """Sets random sets for torch operations.
|
| 858 |
+
#
|
| 859 |
+
# Args:
|
| 860 |
+
# seed (int, optional): Random seed to set. Defaults to 42.
|
| 861 |
+
# """
|
| 862 |
+
# # Set the seed for general torch operations
|
| 863 |
+
# torch.manual_seed(seed)
|
| 864 |
+
# # Set the seed for CUDA torch operations (ones that happen on the GPU)
|
| 865 |
+
# torch.cuda.manual_seed(seed)
|
| 866 |
+
#
|
| 867 |
+
|
| 868 |
+
# Plot the loss curves
|
| 869 |
+
from helper_functions import plot_loss_curves
|
| 870 |
+
|
| 871 |
+
plot_loss_curves(pretrained_vit_results)
|
| 872 |
+
|
| 873 |
+
import requests
|
| 874 |
+
|
| 875 |
+
# Import function to make predictions on images and plot them
|
| 876 |
+
from predict import pred_and_plot_image
|
| 877 |
+
|
| 878 |
+
# Setup custom image path
|
| 879 |
+
custom_image_path = "/content/drive/MyDrive/validation/Bad_Tire (3).jpg"
|
| 880 |
+
|
| 881 |
+
# Predict on custom image
|
| 882 |
+
pred_and_plot_image(model=pretrained_vit,
|
| 883 |
+
image_path=custom_image_path,
|
| 884 |
+
class_names=class_names)
|
| 885 |
+
|
| 886 |
+
# Import function to make predictions on images and plot them
|
| 887 |
+
from predict import pred_and_plot_image
|
| 888 |
+
|
| 889 |
+
# Setup custom image path
|
| 890 |
+
custom_image_path = "/content/drive/MyDrive/validation/Good_Tire (4).jpg"
|
| 891 |
+
|
| 892 |
+
# Predict on custom image
|
| 893 |
+
pred_and_plot_image(model=pretrained_vit,
|
| 894 |
+
image_path=custom_image_path,
|
| 895 |
+
class_names=class_names)
|