Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
import matplotlib.pyplot as plt
|
| 4 |
import torch
|
| 5 |
import torchvision
|
|
@@ -13,7 +13,161 @@ device
|
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
#predict
|
| 19 |
|
|
@@ -103,7 +257,7 @@ def pred_and_plot_image(
|
|
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
-
# %%writefile model_builder.py
|
| 107 |
|
| 108 |
#model_builder
|
| 109 |
|
|
@@ -167,7 +321,9 @@ class TinyVGG(nn.Module):
|
|
| 167 |
|
| 168 |
|
| 169 |
|
| 170 |
-
|
|
|
|
|
|
|
| 171 |
|
| 172 |
#utils.py
|
| 173 |
|
|
@@ -208,204 +364,7 @@ def save_model(model: torch.nn.Module,
|
|
| 208 |
f=model_save_path)
|
| 209 |
|
| 210 |
|
| 211 |
-
# %%writefile engine.py
|
| 212 |
-
#engine.py
|
| 213 |
-
|
| 214 |
-
"""
|
| 215 |
-
Contains functions for training and testing a PyTorch model.
|
| 216 |
-
"""
|
| 217 |
-
import torch
|
| 218 |
-
|
| 219 |
-
from tqdm.auto import tqdm
|
| 220 |
-
from typing import Dict, List, Tuple
|
| 221 |
-
|
| 222 |
-
def train_step(model: torch.nn.Module,
|
| 223 |
-
dataloader: torch.utils.data.DataLoader,
|
| 224 |
-
loss_fn: torch.nn.Module,
|
| 225 |
-
optimizer: torch.optim.Optimizer,
|
| 226 |
-
device: torch.device) -> Tuple[float, float]:
|
| 227 |
-
"""Trains a PyTorch model for a single epoch.
|
| 228 |
-
|
| 229 |
-
Turns a target PyTorch model to training mode and then
|
| 230 |
-
runs through all of the required training steps (forward
|
| 231 |
-
pass, loss calculation, optimizer step).
|
| 232 |
-
|
| 233 |
-
Args:
|
| 234 |
-
model: A PyTorch model to be trained.
|
| 235 |
-
dataloader: A DataLoader instance for the model to be trained on.
|
| 236 |
-
loss_fn: A PyTorch loss function to minimize.
|
| 237 |
-
optimizer: A PyTorch optimizer to help minimize the loss function.
|
| 238 |
-
device: A target device to compute on (e.g. "cuda" or "cpu").
|
| 239 |
-
|
| 240 |
-
Returns:
|
| 241 |
-
A tuple of training loss and training accuracy metrics.
|
| 242 |
-
In the form (train_loss, train_accuracy). For example:
|
| 243 |
-
|
| 244 |
-
(0.1112, 0.8743)
|
| 245 |
-
"""
|
| 246 |
-
# Put model in train mode
|
| 247 |
-
model.train()
|
| 248 |
-
|
| 249 |
-
# Setup train loss and train accuracy values
|
| 250 |
-
train_loss, train_acc = 0, 0
|
| 251 |
-
|
| 252 |
-
# Loop through data loader data batches
|
| 253 |
-
for batch, (X, y) in enumerate(dataloader):
|
| 254 |
-
# Send data to target device
|
| 255 |
-
X, y = X.to(device), y.to(device)
|
| 256 |
-
|
| 257 |
-
# 1. Forward pass
|
| 258 |
-
y_pred = model(X)
|
| 259 |
-
|
| 260 |
-
# 2. Calculate and accumulate loss
|
| 261 |
-
loss = loss_fn(y_pred, y)
|
| 262 |
-
train_loss += loss.item()
|
| 263 |
-
|
| 264 |
-
# 3. Optimizer zero grad
|
| 265 |
-
optimizer.zero_grad()
|
| 266 |
-
|
| 267 |
-
# 4. Loss backward
|
| 268 |
-
loss.backward()
|
| 269 |
-
|
| 270 |
-
# 5. Optimizer step
|
| 271 |
-
optimizer.step()
|
| 272 |
-
|
| 273 |
-
# Calculate and accumulate accuracy metric across all batches
|
| 274 |
-
y_pred_class = torch.argmax(torch.softmax(y_pred, dim=1), dim=1)
|
| 275 |
-
train_acc += (y_pred_class == y).sum().item()/len(y_pred)
|
| 276 |
-
|
| 277 |
-
# Adjust metrics to get average loss and accuracy per batch
|
| 278 |
-
train_loss = train_loss / len(dataloader)
|
| 279 |
-
train_acc = train_acc / len(dataloader)
|
| 280 |
-
return train_loss, train_acc
|
| 281 |
-
|
| 282 |
-
def test_step(model: torch.nn.Module,
|
| 283 |
-
dataloader: torch.utils.data.DataLoader,
|
| 284 |
-
loss_fn: torch.nn.Module,
|
| 285 |
-
device: torch.device) -> Tuple[float, float]:
|
| 286 |
-
"""Tests a PyTorch model for a single epoch.
|
| 287 |
-
|
| 288 |
-
Turns a target PyTorch model to "eval" mode and then performs
|
| 289 |
-
a forward pass on a testing dataset.
|
| 290 |
-
|
| 291 |
-
Args:
|
| 292 |
-
model: A PyTorch model to be tested.
|
| 293 |
-
dataloader: A DataLoader instance for the model to be tested on.
|
| 294 |
-
loss_fn: A PyTorch loss function to calculate loss on the test data.
|
| 295 |
-
device: A target device to compute on (e.g. "cuda" or "cpu").
|
| 296 |
-
|
| 297 |
-
Returns:
|
| 298 |
-
A tuple of testing loss and testing accuracy metrics.
|
| 299 |
-
In the form (test_loss, test_accuracy). For example:
|
| 300 |
-
|
| 301 |
-
(0.0223, 0.8985)
|
| 302 |
-
"""
|
| 303 |
-
# Put model in eval mode
|
| 304 |
-
model.eval()
|
| 305 |
-
|
| 306 |
-
# Setup test loss and test accuracy values
|
| 307 |
-
test_loss, test_acc = 0, 0
|
| 308 |
-
|
| 309 |
-
# Turn on inference context manager
|
| 310 |
-
with torch.inference_mode():
|
| 311 |
-
# Loop through DataLoader batches
|
| 312 |
-
for batch, (X, y) in enumerate(dataloader):
|
| 313 |
-
# Send data to target device
|
| 314 |
-
X, y = X.to(device), y.to(device)
|
| 315 |
-
|
| 316 |
-
# 1. Forward pass
|
| 317 |
-
test_pred_logits = model(X)
|
| 318 |
-
|
| 319 |
-
# 2. Calculate and accumulate loss
|
| 320 |
-
loss = loss_fn(test_pred_logits, y)
|
| 321 |
-
test_loss += loss.item()
|
| 322 |
-
|
| 323 |
-
# Calculate and accumulate accuracy
|
| 324 |
-
test_pred_labels = test_pred_logits.argmax(dim=1)
|
| 325 |
-
test_acc += ((test_pred_labels == y).sum().item()/len(test_pred_labels))
|
| 326 |
-
|
| 327 |
-
# Adjust metrics to get average loss and accuracy per batch
|
| 328 |
-
test_loss = test_loss / len(dataloader)
|
| 329 |
-
test_acc = test_acc / len(dataloader)
|
| 330 |
-
return test_loss, test_acc
|
| 331 |
-
|
| 332 |
-
def train(model: torch.nn.Module,
|
| 333 |
-
train_dataloader: torch.utils.data.DataLoader,
|
| 334 |
-
test_dataloader: torch.utils.data.DataLoader,
|
| 335 |
-
optimizer: torch.optim.Optimizer,
|
| 336 |
-
loss_fn: torch.nn.Module,
|
| 337 |
-
epochs: int,
|
| 338 |
-
device: torch.device) -> Dict[str, List]:
|
| 339 |
-
"""Trains and tests a PyTorch model.
|
| 340 |
-
|
| 341 |
-
Passes a target PyTorch models through train_step() and test_step()
|
| 342 |
-
functions for a number of epochs, training and testing the model
|
| 343 |
-
in the same epoch loop.
|
| 344 |
-
|
| 345 |
-
Calculates, prints and stores evaluation metrics throughout.
|
| 346 |
-
|
| 347 |
-
Args:
|
| 348 |
-
model: A PyTorch model to be trained and tested.
|
| 349 |
-
train_dataloader: A DataLoader instance for the model to be trained on.
|
| 350 |
-
test_dataloader: A DataLoader instance for the model to be tested on.
|
| 351 |
-
optimizer: A PyTorch optimizer to help minimize the loss function.
|
| 352 |
-
loss_fn: A PyTorch loss function to calculate loss on both datasets.
|
| 353 |
-
epochs: An integer indicating how many epochs to train for.
|
| 354 |
-
device: A target device to compute on (e.g. "cuda" or "cpu").
|
| 355 |
-
|
| 356 |
-
Returns:
|
| 357 |
-
A dictionary of training and testing loss as well as training and
|
| 358 |
-
testing accuracy metrics. Each metric has a value in a list for
|
| 359 |
-
each epoch.
|
| 360 |
-
In the form: {train_loss: [...],
|
| 361 |
-
train_acc: [...],
|
| 362 |
-
test_loss: [...],
|
| 363 |
-
test_acc: [...]}
|
| 364 |
-
For example if training for epochs=2:
|
| 365 |
-
{train_loss: [2.0616, 1.0537],
|
| 366 |
-
train_acc: [0.3945, 0.3945],
|
| 367 |
-
test_loss: [1.2641, 1.5706],
|
| 368 |
-
test_acc: [0.3400, 0.2973]}
|
| 369 |
-
"""
|
| 370 |
-
# Create empty results dictionary
|
| 371 |
-
results = {"train_loss": [],
|
| 372 |
-
"train_acc": [],
|
| 373 |
-
"test_loss": [],
|
| 374 |
-
"test_acc": []
|
| 375 |
-
}
|
| 376 |
-
|
| 377 |
-
# Make sure model on target device
|
| 378 |
-
model.to(device)
|
| 379 |
-
|
| 380 |
-
# Loop through training and testing steps for a number of epochs
|
| 381 |
-
for epoch in tqdm(range(epochs)):
|
| 382 |
-
train_loss, train_acc = train_step(model=model,
|
| 383 |
-
dataloader=train_dataloader,
|
| 384 |
-
loss_fn=loss_fn,
|
| 385 |
-
optimizer=optimizer,
|
| 386 |
-
device=device)
|
| 387 |
-
test_loss, test_acc = test_step(model=model,
|
| 388 |
-
dataloader=test_dataloader,
|
| 389 |
-
loss_fn=loss_fn,
|
| 390 |
-
device=device)
|
| 391 |
-
|
| 392 |
-
# Print out what's happening
|
| 393 |
-
print(
|
| 394 |
-
f"Epoch: {epoch+1} | "
|
| 395 |
-
f"train_loss: {train_loss:.4f} | "
|
| 396 |
-
f"train_acc: {train_acc:.4f} | "
|
| 397 |
-
f"test_loss: {test_loss:.4f} | "
|
| 398 |
-
f"test_acc: {test_acc:.4f}"
|
| 399 |
-
)
|
| 400 |
-
|
| 401 |
-
# Update results dictionary
|
| 402 |
-
results["train_loss"].append(train_loss)
|
| 403 |
-
results["train_acc"].append(train_acc)
|
| 404 |
-
results["test_loss"].append(test_loss)
|
| 405 |
-
results["test_acc"].append(test_acc)
|
| 406 |
|
| 407 |
-
# Return the filled results at the end of the epochs
|
| 408 |
-
return results
|
| 409 |
|
| 410 |
|
| 411 |
|
|
@@ -477,9 +436,7 @@ def create_dataloaders(
|
|
| 477 |
|
| 478 |
return train_dataloader, test_dataloader, class_names
|
| 479 |
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
# %%writefile train.py
|
| 483 |
#train.py only in this cell
|
| 484 |
|
| 485 |
"""
|
|
@@ -546,6 +503,9 @@ utils.save_model(model=model,
|
|
| 546 |
model_name="05_going_modular_script_mode_tinyvgg_model.pth")
|
| 547 |
|
| 548 |
|
|
|
|
|
|
|
|
|
|
| 549 |
# 1. Get pretrained weights for ViT-Base
|
| 550 |
pretrained_vit_weights = torchvision.models.ViT_B_16_Weights.DEFAULT
|
| 551 |
|
|
@@ -564,6 +524,8 @@ pretrained_vit.heads = nn.Linear(in_features=768, out_features=len(class_names))
|
|
| 564 |
# pretrained_vit # uncomment for model output
|
| 565 |
|
| 566 |
|
|
|
|
|
|
|
| 567 |
from torchinfo import summary
|
| 568 |
|
| 569 |
# Print a summary using torchinfo (uncomment for actual output)
|
|
@@ -575,17 +537,18 @@ summary(model=pretrained_vit,
|
|
| 575 |
row_settings=["var_names"]
|
| 576 |
)
|
| 577 |
|
|
|
|
|
|
|
| 578 |
# Setup directory paths to train and test images
|
| 579 |
train_dir = '/content/drive/MyDrive/Test/test'
|
| 580 |
test_dir = '/content/drive/MyDrive/Train/train'
|
| 581 |
|
|
|
|
| 582 |
# Get automatic transforms from pretrained ViT weights
|
| 583 |
pretrained_vit_transforms = pretrained_vit_weights.transforms()
|
| 584 |
print(pretrained_vit_transforms)
|
| 585 |
|
| 586 |
|
| 587 |
-
|
| 588 |
-
|
| 589 |
import os
|
| 590 |
|
| 591 |
from torchvision import datasets, transforms
|
|
@@ -627,6 +590,8 @@ def create_dataloaders(
|
|
| 627 |
return train_dataloader, test_dataloader, class_names
|
| 628 |
|
| 629 |
|
|
|
|
|
|
|
| 630 |
# Setup dataloaders
|
| 631 |
train_dataloader_pretrained, test_dataloader_pretrained, class_names = create_dataloaders(
|
| 632 |
train_dir=train_dir,
|
|
@@ -655,212 +620,28 @@ pretrained_vit_results = engine.train(model=pretrained_vit,
|
|
| 655 |
device=device)
|
| 656 |
|
| 657 |
|
| 658 |
-
#
|
| 659 |
-
|
| 660 |
-
# helper_functions.py
|
| 661 |
|
| 662 |
-
|
| 663 |
-
A series of helper functions used throughout the course.
|
| 664 |
|
| 665 |
-
If a function gets defined once and could be used over and over, it'll go in here.
|
| 666 |
-
"""
|
| 667 |
-
import torch
|
| 668 |
-
import matplotlib.pyplot as plt
|
| 669 |
-
import numpy as np
|
| 670 |
|
| 671 |
-
from torch import nn
|
| 672 |
-
import os
|
| 673 |
-
import zipfile
|
| 674 |
-
from pathlib import Path
|
| 675 |
import requests
|
| 676 |
-
import os
|
| 677 |
-
|
| 678 |
-
|
| 679 |
-
|
| 680 |
-
# Plot linear data or training and test and predictions (optional)
|
| 681 |
-
def plot_predictions(
|
| 682 |
-
train_data, train_labels, test_data, test_labels, predictions=None
|
| 683 |
-
):
|
| 684 |
-
"""
|
| 685 |
-
Plots linear training data and test data and compares predictions.
|
| 686 |
-
"""
|
| 687 |
-
plt.figure(figsize=(10, 7))
|
| 688 |
-
|
| 689 |
-
# Plot training data in blue
|
| 690 |
-
plt.scatter(train_data, train_labels, c="b", s=4, label="Training data")
|
| 691 |
-
|
| 692 |
-
# Plot test data in green
|
| 693 |
-
plt.scatter(test_data, test_labels, c="g", s=4, label="Testing data")
|
| 694 |
-
|
| 695 |
-
if predictions is not None:
|
| 696 |
-
# Plot the predictions in red (predictions were made on the test data)
|
| 697 |
-
plt.scatter(test_data, predictions, c="r", s=4, label="Predictions")
|
| 698 |
|
| 699 |
-
|
| 700 |
-
|
| 701 |
|
|
|
|
|
|
|
| 702 |
|
| 703 |
-
#
|
| 704 |
-
|
| 705 |
-
|
|
|
|
| 706 |
|
| 707 |
-
Args:
|
| 708 |
-
y_true (torch.Tensor): Truth labels for predictions.
|
| 709 |
-
y_pred (torch.Tensor): Predictions to be compared to predictions.
|
| 710 |
-
|
| 711 |
-
Returns:
|
| 712 |
-
[torch.float]: Accuracy value between y_true and y_pred, e.g. 78.45
|
| 713 |
-
"""
|
| 714 |
-
correct = torch.eq(y_true, y_pred).sum().item()
|
| 715 |
-
acc = (correct / len(y_pred)) * 100
|
| 716 |
-
return acc
|
| 717 |
|
| 718 |
|
| 719 |
-
def print_train_time(start, end, device=None):
|
| 720 |
-
"""Prints difference between start and end time.
|
| 721 |
-
|
| 722 |
-
Args:
|
| 723 |
-
start (float): Start time of computation (preferred in timeit format).
|
| 724 |
-
end (float): End time of computation.
|
| 725 |
-
device ([type], optional): Device that compute is running on. Defaults to None.
|
| 726 |
-
|
| 727 |
-
Returns:
|
| 728 |
-
float: time between start and end in seconds (higher is longer).
|
| 729 |
-
"""
|
| 730 |
-
total_time = end - start
|
| 731 |
-
print(f"\nTrain time on {device}: {total_time:.3f} seconds")
|
| 732 |
-
return total_time
|
| 733 |
-
|
| 734 |
-
|
| 735 |
-
# Plot loss curves of a model
|
| 736 |
-
def plot_loss_curves(results):
|
| 737 |
-
"""Plots training curves of a results dictionary.
|
| 738 |
-
|
| 739 |
-
Args:
|
| 740 |
-
results (dict): dictionary containing list of values, e.g.
|
| 741 |
-
{"train_loss": [...],
|
| 742 |
-
"train_acc": [...],
|
| 743 |
-
"test_loss": [...],
|
| 744 |
-
"test_acc": [...]}
|
| 745 |
-
"""
|
| 746 |
-
loss = results["train_loss"]
|
| 747 |
-
test_loss = results["test_loss"]
|
| 748 |
-
|
| 749 |
-
accuracy = results["train_acc"]
|
| 750 |
-
test_accuracy = results["test_acc"]
|
| 751 |
-
|
| 752 |
-
epochs = range(len(results["train_loss"]))
|
| 753 |
-
|
| 754 |
-
plt.figure(figsize=(15, 7))
|
| 755 |
-
|
| 756 |
-
# Plot loss
|
| 757 |
-
plt.subplot(1, 2, 1)
|
| 758 |
-
plt.plot(epochs, loss, label="train_loss")
|
| 759 |
-
plt.plot(epochs, test_loss, label="test_loss")
|
| 760 |
-
plt.title("Loss")
|
| 761 |
-
plt.xlabel("Epochs")
|
| 762 |
-
plt.legend()
|
| 763 |
-
|
| 764 |
-
# Plot accuracy
|
| 765 |
-
plt.subplot(1, 2, 2)
|
| 766 |
-
plt.plot(epochs, accuracy, label="train_accuracy")
|
| 767 |
-
plt.plot(epochs, test_accuracy, label="test_accuracy")
|
| 768 |
-
plt.title("Accuracy")
|
| 769 |
-
plt.xlabel("Epochs")
|
| 770 |
-
plt.legend()
|
| 771 |
-
|
| 772 |
-
|
| 773 |
-
# Pred and plot image function from notebook 04
|
| 774 |
-
# See creation: https://www.learnpytorch.io/04_pytorch_custom_datasets/#113-putting-custom-image-prediction-together-building-a-function
|
| 775 |
-
from typing import List
|
| 776 |
-
import torchvision
|
| 777 |
-
|
| 778 |
-
|
| 779 |
-
def pred_and_plot_image(
|
| 780 |
-
model: torch.nn.Module,
|
| 781 |
-
image_path: str,
|
| 782 |
-
class_names: List[str] = None,
|
| 783 |
-
transform=None,
|
| 784 |
-
device: torch.device = "cuda" if torch.cuda.is_available() else "cpu",
|
| 785 |
-
):
|
| 786 |
-
"""Makes a prediction on a target image with a trained model and plots the image.
|
| 787 |
-
|
| 788 |
-
Args:
|
| 789 |
-
model (torch.nn.Module): trained PyTorch image classification model.
|
| 790 |
-
image_path (str): filepath to target image.
|
| 791 |
-
class_names (List[str], optional): different class names for target image. Defaults to None.
|
| 792 |
-
transform (_type_, optional): transform of target image. Defaults to None.
|
| 793 |
-
device (torch.device, optional): target device to compute on. Defaults to "cuda" if torch.cuda.is_available() else "cpu".
|
| 794 |
-
|
| 795 |
-
Returns:
|
| 796 |
-
Matplotlib plot of target image and model prediction as title.
|
| 797 |
-
|
| 798 |
-
Example usage:
|
| 799 |
-
pred_and_plot_image(model=model,
|
| 800 |
-
image="some_image.jpeg",
|
| 801 |
-
class_names=["class_1", "class_2", "class_3"],
|
| 802 |
-
transform=torchvision.transforms.ToTensor(),
|
| 803 |
-
device=device)
|
| 804 |
-
"""
|
| 805 |
-
|
| 806 |
-
# 1. Load in image and convert the tensor values to float32
|
| 807 |
-
target_image = torchvision.io.read_image(str(image_path)).type(torch.float32)
|
| 808 |
-
|
| 809 |
-
# 2. Divide the image pixel values by 255 to get them between [0, 1]
|
| 810 |
-
target_image = target_image / 255.0
|
| 811 |
-
|
| 812 |
-
# 3. Transform if necessary
|
| 813 |
-
if transform:
|
| 814 |
-
target_image = transform(target_image)
|
| 815 |
-
|
| 816 |
-
# 4. Make sure the model is on the target device
|
| 817 |
-
model.to(device)
|
| 818 |
-
|
| 819 |
-
# 5. Turn on model evaluation mode and inference mode
|
| 820 |
-
model.eval()
|
| 821 |
-
with torch.inference_mode():
|
| 822 |
-
# Add an extra dimension to the image
|
| 823 |
-
target_image = target_image.unsqueeze(dim=0)
|
| 824 |
-
|
| 825 |
-
# Make a prediction on image with an extra dimension and send it to the target device
|
| 826 |
-
target_image_pred = model(target_image.to(device))
|
| 827 |
-
|
| 828 |
-
# 6. Convert logits -> prediction probabilities (using torch.softmax() for multi-class classification)
|
| 829 |
-
target_image_pred_probs = torch.softmax(target_image_pred, dim=1)
|
| 830 |
-
|
| 831 |
-
# 7. Convert prediction probabilities -> prediction labels
|
| 832 |
-
target_image_pred_label = torch.argmax(target_image_pred_probs, dim=1)
|
| 833 |
-
|
| 834 |
-
# 8. Plot the image alongside the prediction and prediction probability
|
| 835 |
-
plt.imshow(
|
| 836 |
-
target_image.squeeze().permute(1, 2, 0)
|
| 837 |
-
) # make sure it's the right size for matplotlib
|
| 838 |
-
if class_names:
|
| 839 |
-
title = f"Pred: {class_names[target_image_pred_label.cpu()]} | Prob: {target_image_pred_probs.max().cpu():.3f}"
|
| 840 |
-
else:
|
| 841 |
-
title = f"Pred: {target_image_pred_label} | Prob: {target_image_pred_probs.max().cpu():.3f}"
|
| 842 |
-
plt.title(title)
|
| 843 |
-
plt.axis(False)
|
| 844 |
-
|
| 845 |
-
def set_seeds(seed: int=42):
|
| 846 |
-
"""Sets random sets for torch operations.
|
| 847 |
-
|
| 848 |
-
Args:
|
| 849 |
-
seed (int, optional): Random seed to set. Defaults to 42.
|
| 850 |
-
"""
|
| 851 |
-
# Set the seed for general torch operations
|
| 852 |
-
torch.manual_seed(seed)
|
| 853 |
-
# Set the seed for CUDA torch operations (ones that happen on the GPU)
|
| 854 |
-
torch.cuda.manual_seed(seed)
|
| 855 |
-
|
| 856 |
-
|
| 857 |
-
|
| 858 |
-
# Plot the loss curves
|
| 859 |
-
from helper_functions import plot_loss_curves
|
| 860 |
-
|
| 861 |
-
plot_loss_curves(pretrained_vit_results)
|
| 862 |
|
| 863 |
|
| 864 |
|
| 865 |
|
| 866 |
-
|
|
|
|
| 1 |
+
#writefile Helperfunction.py
|
| 2 |
+
from google.colab import files
|
| 3 |
import matplotlib.pyplot as plt
|
| 4 |
import torch
|
| 5 |
import torchvision
|
|
|
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
+
|
| 17 |
+
#Helperfunction.py
|
| 18 |
+
|
| 19 |
+
def print_train_time(start, end, device=None):
|
| 20 |
+
"""Prints difference between start and end time.
|
| 21 |
+
|
| 22 |
+
Args:
|
| 23 |
+
start (float): Start time of computation (preferred in timeit format).
|
| 24 |
+
end (float): End time of computation.
|
| 25 |
+
device ([type], optional): Device that compute is running on. Defaults to None.
|
| 26 |
+
|
| 27 |
+
Returns:
|
| 28 |
+
float: time between start and end in seconds (higher is longer).
|
| 29 |
+
"""
|
| 30 |
+
total_time = end - start
|
| 31 |
+
print(f"\nTrain time on {device}: {total_time:.3f} seconds")
|
| 32 |
+
return total_time
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# In[5]:
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
# Plot loss curves of a model
|
| 39 |
+
def plot_loss_curves(results):
|
| 40 |
+
"""Plots training curves of a results dictionary.
|
| 41 |
+
|
| 42 |
+
Args:
|
| 43 |
+
results (dict): dictionary containing list of values, e.g.
|
| 44 |
+
{"train_loss": [...],
|
| 45 |
+
"train_acc": [...],
|
| 46 |
+
"test_loss": [...],
|
| 47 |
+
"test_acc": [...]}
|
| 48 |
+
"""
|
| 49 |
+
loss = results["train_loss"]
|
| 50 |
+
test_loss = results["test_loss"]
|
| 51 |
+
|
| 52 |
+
accuracy = results["train_acc"]
|
| 53 |
+
test_accuracy = results["test_acc"]
|
| 54 |
+
|
| 55 |
+
epochs = range(len(results["train_loss"]))
|
| 56 |
+
|
| 57 |
+
plt.figure(figsize=(15, 7))
|
| 58 |
+
|
| 59 |
+
# Plot loss
|
| 60 |
+
plt.subplot(1, 2, 1)
|
| 61 |
+
plt.plot(epochs, loss, label="train_loss")
|
| 62 |
+
plt.plot(epochs, test_loss, label="test_loss")
|
| 63 |
+
plt.title("Loss")
|
| 64 |
+
plt.xlabel("Epochs")
|
| 65 |
+
plt.legend()
|
| 66 |
+
|
| 67 |
+
# Plot accuracy
|
| 68 |
+
plt.subplot(1, 2, 2)
|
| 69 |
+
plt.plot(epochs, accuracy, label="train_accuracy")
|
| 70 |
+
plt.plot(epochs, test_accuracy, label="test_accuracy")
|
| 71 |
+
plt.title("Accuracy")
|
| 72 |
+
plt.xlabel("Epochs")
|
| 73 |
+
plt.legend()
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
# In[6]:
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
# Pred and plot image function from notebook 04
|
| 80 |
+
# See creation: https://www.learnpytorch.io/04_pytorch_custom_datasets/#113-putting-custom-image-prediction-together-building-a-function
|
| 81 |
+
from typing import List
|
| 82 |
+
import torchvision
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def pred_and_plot_image(
|
| 86 |
+
model: torch.nn.Module,
|
| 87 |
+
image_path: str,
|
| 88 |
+
class_names: List[str] = None,
|
| 89 |
+
transform=None,
|
| 90 |
+
device: torch.device = "cuda" if torch.cuda.is_available() else "cpu",
|
| 91 |
+
):
|
| 92 |
+
"""Makes a prediction on a target image with a trained model and plots the image.
|
| 93 |
+
|
| 94 |
+
Args:
|
| 95 |
+
model (torch.nn.Module): trained PyTorch image classification model.
|
| 96 |
+
image_path (str): filepath to target image.
|
| 97 |
+
class_names (List[str], optional): different class names for target image. Defaults to None.
|
| 98 |
+
transform (_type_, optional): transform of target image. Defaults to None.
|
| 99 |
+
device (torch.device, optional): target device to compute on. Defaults to "cuda" if torch.cuda.is_available() else "cpu".
|
| 100 |
+
|
| 101 |
+
Returns:
|
| 102 |
+
Matplotlib plot of target image and model prediction as title.
|
| 103 |
+
|
| 104 |
+
Example usage:
|
| 105 |
+
pred_and_plot_image(model=model,
|
| 106 |
+
image="some_image.jpeg",
|
| 107 |
+
class_names=["class_1", "class_2", "class_3"],
|
| 108 |
+
transform=torchvision.transforms.ToTensor(),
|
| 109 |
+
device=device)
|
| 110 |
+
"""
|
| 111 |
+
|
| 112 |
+
# 1. Load in image and convert the tensor values to float32
|
| 113 |
+
target_image = torchvision.io.read_image(str(image_path)).type(torch.float32)
|
| 114 |
+
|
| 115 |
+
# 2. Divide the image pixel values by 255 to get them between [0, 1]
|
| 116 |
+
target_image = target_image / 255.0
|
| 117 |
+
|
| 118 |
+
# 3. Transform if necessary
|
| 119 |
+
if transform:
|
| 120 |
+
target_image = transform(target_image)
|
| 121 |
+
|
| 122 |
+
# 4. Make sure the model is on the target device
|
| 123 |
+
model.to(device)
|
| 124 |
+
|
| 125 |
+
# 5. Turn on model evaluation mode and inference mode
|
| 126 |
+
model.eval()
|
| 127 |
+
with torch.inference_mode():
|
| 128 |
+
# Add an extra dimension to the image
|
| 129 |
+
target_image = target_image.unsqueeze(dim=0)
|
| 130 |
+
|
| 131 |
+
# Make a prediction on image with an extra dimension and send it to the target device
|
| 132 |
+
target_image_pred = model(target_image.to(device))
|
| 133 |
+
|
| 134 |
+
# 6. Convert logits -> prediction probabilities (using torch.softmax() for multi-class classification)
|
| 135 |
+
target_image_pred_probs = torch.softmax(target_image_pred, dim=1)
|
| 136 |
+
|
| 137 |
+
# 7. Convert prediction probabilities -> prediction labels
|
| 138 |
+
target_image_pred_label = torch.argmax(target_image_pred_probs, dim=1)
|
| 139 |
+
|
| 140 |
+
# 8. Plot the image alongside the prediction and prediction probability
|
| 141 |
+
plt.imshow(
|
| 142 |
+
target_image.squeeze().permute(1, 2, 0)
|
| 143 |
+
) # make sure it's the right size for matplotlib
|
| 144 |
+
if class_names:
|
| 145 |
+
title = f"Pred: {class_names[target_image_pred_label.cpu()]} | Prob: {target_image_pred_probs.max().cpu():.3f}"
|
| 146 |
+
else:
|
| 147 |
+
title = f"Pred: {target_image_pred_label} | Prob: {target_image_pred_probs.max().cpu():.3f}"
|
| 148 |
+
plt.title(title)
|
| 149 |
+
plt.axis(False)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
# In[ ]:
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def set_seeds(seed: int=42):
|
| 156 |
+
"""Sets random sets for torch operations.
|
| 157 |
+
|
| 158 |
+
Args:
|
| 159 |
+
seed (int, optional): Random seed to set. Defaults to 42.
|
| 160 |
+
"""
|
| 161 |
+
# Set the seed for general torch operations
|
| 162 |
+
torch.manual_seed(seed)
|
| 163 |
+
# Set the seed for CUDA torch operations (ones that happen on the GPU)
|
| 164 |
+
torch.cuda.manual_seed(seed)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
#%%writefile predict.py
|
| 171 |
|
| 172 |
#predict
|
| 173 |
|
|
|
|
| 257 |
|
| 258 |
|
| 259 |
|
| 260 |
+
# %%writefile model_builder.py
|
| 261 |
|
| 262 |
#model_builder
|
| 263 |
|
|
|
|
| 321 |
|
| 322 |
|
| 323 |
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
# %%writefile utils.py
|
| 327 |
|
| 328 |
#utils.py
|
| 329 |
|
|
|
|
| 364 |
f=model_save_path)
|
| 365 |
|
| 366 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 367 |
|
|
|
|
|
|
|
| 368 |
|
| 369 |
|
| 370 |
|
|
|
|
| 436 |
|
| 437 |
return train_dataloader, test_dataloader, class_names
|
| 438 |
|
| 439 |
+
# %%writefile train.py
|
|
|
|
|
|
|
| 440 |
#train.py only in this cell
|
| 441 |
|
| 442 |
"""
|
|
|
|
| 503 |
model_name="05_going_modular_script_mode_tinyvgg_model.pth")
|
| 504 |
|
| 505 |
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
|
| 509 |
# 1. Get pretrained weights for ViT-Base
|
| 510 |
pretrained_vit_weights = torchvision.models.ViT_B_16_Weights.DEFAULT
|
| 511 |
|
|
|
|
| 524 |
# pretrained_vit # uncomment for model output
|
| 525 |
|
| 526 |
|
| 527 |
+
|
| 528 |
+
|
| 529 |
from torchinfo import summary
|
| 530 |
|
| 531 |
# Print a summary using torchinfo (uncomment for actual output)
|
|
|
|
| 537 |
row_settings=["var_names"]
|
| 538 |
)
|
| 539 |
|
| 540 |
+
|
| 541 |
+
|
| 542 |
# Setup directory paths to train and test images
|
| 543 |
train_dir = '/content/drive/MyDrive/Test/test'
|
| 544 |
test_dir = '/content/drive/MyDrive/Train/train'
|
| 545 |
|
| 546 |
+
|
| 547 |
# Get automatic transforms from pretrained ViT weights
|
| 548 |
pretrained_vit_transforms = pretrained_vit_weights.transforms()
|
| 549 |
print(pretrained_vit_transforms)
|
| 550 |
|
| 551 |
|
|
|
|
|
|
|
| 552 |
import os
|
| 553 |
|
| 554 |
from torchvision import datasets, transforms
|
|
|
|
| 590 |
return train_dataloader, test_dataloader, class_names
|
| 591 |
|
| 592 |
|
| 593 |
+
|
| 594 |
+
|
| 595 |
# Setup dataloaders
|
| 596 |
train_dataloader_pretrained, test_dataloader_pretrained, class_names = create_dataloaders(
|
| 597 |
train_dir=train_dir,
|
|
|
|
| 620 |
device=device)
|
| 621 |
|
| 622 |
|
| 623 |
+
# Plot the loss curves
|
| 624 |
+
from helper_functions import plot_loss_curves
|
|
|
|
| 625 |
|
| 626 |
+
plot_loss_curves(pretrained_vit_results)
|
|
|
|
| 627 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 628 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 629 |
import requests
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 630 |
|
| 631 |
+
# Import function to make predictions on images and plot them
|
| 632 |
+
from predict import pred_and_plot_image
|
| 633 |
|
| 634 |
+
# Setup custom image path
|
| 635 |
+
custom_image_path = "/content/drive/MyDrive/validation/Bad_Tire (3).jpg"
|
| 636 |
|
| 637 |
+
# Predict on custom image
|
| 638 |
+
pred_and_plot_image(model=pretrained_vit,
|
| 639 |
+
image_path=custom_image_path,
|
| 640 |
+
class_names=class_names)
|
| 641 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 642 |
|
| 643 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 644 |
|
| 645 |
|
| 646 |
|
| 647 |
|
|
|