mirror of
https://github.com/mrdbourke/pytorch-deep-learning.git
synced 2026-11-27 06:07:09 +00:00
364 KiB
364 KiB
In [1]:
# For this notebook to run with updated APIs, we need torch 1.12+ and torchvision 0.13+
try:
import torch
import torchvision
assert int(torch.__version__.split(".")[1]) >= 12, "torch version should be 1.12+"
assert int(torchvision.__version__.split(".")[1]) >= 13, "torchvision version should be 0.13+"
print(f"torch version: {torch.__version__}")
print(f"torchvision version: {torchvision.__version__}")
except:
print(f"[INFO] torch/torchvision versions not as required, installing nightly versions.")
!pip3 install -U --pre torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/nightly/cu113
import torch
import torchvision
print(f"torch version: {torch.__version__}")
print(f"torchvision version: {torchvision.__version__}")torch version: 1.12.0+cu102 torchvision version: 0.13.0+cu102
In [2]:
# Continue with regular imports
import matplotlib.pyplot as plt
import torch
import torchvision
from torch import nn
from torchvision import transforms
# Try to get torchinfo, install it if it doesn't work
try:
from torchinfo import summary
except:
print("[INFO] Couldn't find torchinfo... installing it.")
!pip install -q torchinfo
from torchinfo import summary
# Try to import the going_modular directory, download it from GitHub if it doesn't work
try:
from going_modular.going_modular import data_setup, engine
from helper_functions import download_data, set_seeds, plot_loss_curves
except:
# Get the going_modular scripts
print("[INFO] Couldn't find going_modular or helper_functions scripts... downloading them from GitHub.")
!git clone https://github.com/mrdbourke/pytorch-deep-learning
!mv pytorch-deep-learning/going_modular .
!mv pytorch-deep-learning/helper_functions.py . # get the helper_functions.py script
!rm -rf pytorch-deep-learning
from going_modular.going_modular import data_setup, engine
from helper_functions import download_data, set_seeds, plot_loss_curvesIn [3]:
device = "cuda" if torch.cuda.is_available() else "cpu"
deviceOut [3]:
'cuda'
In [4]:
# Download pizza, steak, sushi images from GitHub
data_20_percent_path = download_data(source="https://github.com/mrdbourke/pytorch-deep-learning/raw/main/data/pizza_steak_sushi_20_percent.zip",
destination="pizza_steak_sushi_20_percent")
data_20_percent_pathOut [4]:
[INFO] data/pizza_steak_sushi_20_percent directory exists, skipping download.
PosixPath('data/pizza_steak_sushi_20_percent')In [5]:
# Setup directory paths to train and test images
train_dir = data_20_percent_path / "train"
test_dir = data_20_percent_path / "test"In [6]:
# 1. Setup pretrained EffNetB2 weights
effnetb2_weights = torchvision.models.EfficientNet_B2_Weights.DEFAULT
# 2. Get EffNetB2 transforms
effnetb2_transforms = effnetb2_weights.transforms()
# 3. Setup pretrained model
effnetb2 = torchvision.models.efficientnet_b2(weights=effnetb2_weights) # could also use weights="DEFAULT"
# 4. Freeze the base layers in the model (this will freeze all layers to begin with)
for param in effnetb2.parameters():
param.requires_grad = FalseIn [7]:
# Check out EffNetB2 classifier head
effnetb2.classifierOut [7]:
Sequential( (0): Dropout(p=0.3, inplace=True) (1): Linear(in_features=1408, out_features=1000, bias=True) )
In [8]:
# 5. Update the classifier head
effnetb2.classifier = nn.Sequential(
nn.Dropout(p=0.3, inplace=True), # keep dropout layer same
nn.Linear(in_features=1408, # keep in_features same
out_features=3)) # change out_features to suit our number of classesIn [9]:
def create_effnetb2_model(num_classes:int=3,
seed:int=42):
"""Creates an EfficientNetB2 feature extractor model and transforms.
Args:
num_classes (int, optional): number of classes in the classifier head.
Defaults to 3.
seed (int, optional): random seed value. Defaults to 42.
Returns:
model (torch.nn.Module): EffNetB2 feature extractor model.
transforms (torchvision.transforms): EffNetB2 image transforms.
"""
# 1, 2, 3. Create EffNetB2 pretrained weights, transforms and model
weights = torchvision.models.EfficientNet_B2_Weights.DEFAULT
transforms = weights.transforms()
model = torchvision.models.efficientnet_b2(weights=weights)
# 4. Freeze all layers in base model
for param in model.parameters():
param.requires_grad = False
# 5. Change classifier head with random seed for reproducibility
torch.manual_seed(seed)
model.classifier = nn.Sequential(
nn.Dropout(p=0.3, inplace=True),
nn.Linear(in_features=1408, out_features=num_classes),
)
return model, transformsIn [10]:
effnetb2, effnetb2_transforms = create_effnetb2_model(num_classes=3,
seed=42)In [11]:
from torchinfo import summary
summary(effnetb2,
input_size=(1, 3, 224, 224),
col_names=["input_size", "output_size", "num_params", "trainable"],
col_width=20,
row_settings=["var_names"])Out [11]:
============================================================================================================================================ Layer (type (var_name)) Input Shape Output Shape Param # Trainable ============================================================================================================================================ EfficientNet (EfficientNet) [1, 3, 224, 224] [1, 3] -- Partial ├─Sequential (features) [1, 3, 224, 224] [1, 1408, 7, 7] -- False │ └─Conv2dNormActivation (0) [1, 3, 224, 224] [1, 32, 112, 112] -- False │ │ └─Conv2d (0) [1, 3, 224, 224] [1, 32, 112, 112] (864) False │ │ └─BatchNorm2d (1) [1, 32, 112, 112] [1, 32, 112, 112] (64) False │ │ └─SiLU (2) [1, 32, 112, 112] [1, 32, 112, 112] -- -- │ └─Sequential (1) [1, 32, 112, 112] [1, 16, 112, 112] -- False │ │ └─MBConv (0) [1, 32, 112, 112] [1, 16, 112, 112] (1,448) False │ │ └─MBConv (1) [1, 16, 112, 112] [1, 16, 112, 112] (612) False │ └─Sequential (2) [1, 16, 112, 112] [1, 24, 56, 56] -- False │ │ └─MBConv (0) [1, 16, 112, 112] [1, 24, 56, 56] (6,004) False │ │ └─MBConv (1) [1, 24, 56, 56] [1, 24, 56, 56] (10,710) False │ │ └─MBConv (2) [1, 24, 56, 56] [1, 24, 56, 56] (10,710) False │ └─Sequential (3) [1, 24, 56, 56] [1, 48, 28, 28] -- False │ │ └─MBConv (0) [1, 24, 56, 56] [1, 48, 28, 28] (16,518) False │ │ └─MBConv (1) [1, 48, 28, 28] [1, 48, 28, 28] (43,308) False │ │ └─MBConv (2) [1, 48, 28, 28] [1, 48, 28, 28] (43,308) False │ └─Sequential (4) [1, 48, 28, 28] [1, 88, 14, 14] -- False │ │ └─MBConv (0) [1, 48, 28, 28] [1, 88, 14, 14] (50,300) False │ │ └─MBConv (1) [1, 88, 14, 14] [1, 88, 14, 14] (123,750) False │ │ └─MBConv (2) [1, 88, 14, 14] [1, 88, 14, 14] (123,750) False │ │ └─MBConv (3) [1, 88, 14, 14] [1, 88, 14, 14] (123,750) False │ └─Sequential (5) [1, 88, 14, 14] [1, 120, 14, 14] -- False │ │ └─MBConv (0) [1, 88, 14, 14] [1, 120, 14, 14] (149,158) False │ │ └─MBConv (1) [1, 120, 14, 14] [1, 120, 14, 14] (237,870) False │ │ └─MBConv (2) [1, 120, 14, 14] [1, 120, 14, 14] (237,870) False │ │ └─MBConv (3) [1, 120, 14, 14] [1, 120, 14, 14] (237,870) False │ └─Sequential (6) [1, 120, 14, 14] [1, 208, 7, 7] -- False │ │ └─MBConv (0) [1, 120, 14, 14] [1, 208, 7, 7] (301,406) False │ │ └─MBConv (1) [1, 208, 7, 7] [1, 208, 7, 7] (686,868) False │ │ └─MBConv (2) [1, 208, 7, 7] [1, 208, 7, 7] (686,868) False │ │ └─MBConv (3) [1, 208, 7, 7] [1, 208, 7, 7] (686,868) False │ │ └─MBConv (4) [1, 208, 7, 7] [1, 208, 7, 7] (686,868) False │ └─Sequential (7) [1, 208, 7, 7] [1, 352, 7, 7] -- False │ │ └─MBConv (0) [1, 208, 7, 7] [1, 352, 7, 7] (846,900) False │ │ └─MBConv (1) [1, 352, 7, 7] [1, 352, 7, 7] (1,888,920) False │ └─Conv2dNormActivation (8) [1, 352, 7, 7] [1, 1408, 7, 7] -- False │ │ └─Conv2d (0) [1, 352, 7, 7] [1, 1408, 7, 7] (495,616) False │ │ └─BatchNorm2d (1) [1, 1408, 7, 7] [1, 1408, 7, 7] (2,816) False │ │ └─SiLU (2) [1, 1408, 7, 7] [1, 1408, 7, 7] -- -- ├─AdaptiveAvgPool2d (avgpool) [1, 1408, 7, 7] [1, 1408, 1, 1] -- -- ├─Sequential (classifier) [1, 1408] [1, 3] -- True │ └─Dropout (0) [1, 1408] [1, 1408] -- -- │ └─Linear (1) [1, 1408] [1, 3] 4,227 True ============================================================================================================================================ Total params: 7,705,221 Trainable params: 4,227 Non-trainable params: 7,700,994 Total mult-adds (M): 657.64 ============================================================================================================================================ Input size (MB): 0.60 Forward/backward pass size (MB): 156.80 Params size (MB): 30.82 Estimated Total Size (MB): 188.22 ============================================================================================================================================
In [12]:
# Setup DataLoaders
from going_modular.going_modular import data_setup
train_dataloader_effnetb2, test_dataloader_effnetb2, class_names = data_setup.create_dataloaders(train_dir=train_dir,
test_dir=test_dir,
transform=effnetb2_transforms,
batch_size=32)In [13]:
from going_modular.going_modular import engine
# Setup optimizer
optimizer = torch.optim.Adam(params=effnetb2.parameters(),
lr=1e-3)
# Setup loss function
loss_fn = torch.nn.CrossEntropyLoss()
# Set seeds for reproducibility and train the model
set_seeds()
effnetb2_results = engine.train(model=effnetb2,
train_dataloader=train_dataloader_effnetb2,
test_dataloader=test_dataloader_effnetb2,
epochs=10,
optimizer=optimizer,
loss_fn=loss_fn,
device=device)0%| | 0/10 [00:00<?, ?it/s]
Epoch: 1 | train_loss: 0.9856 | train_acc: 0.5604 | test_loss: 0.7408 | test_acc: 0.9347 Epoch: 2 | train_loss: 0.7175 | train_acc: 0.8438 | test_loss: 0.5869 | test_acc: 0.9409 Epoch: 3 | train_loss: 0.5876 | train_acc: 0.8917 | test_loss: 0.4909 | test_acc: 0.9500 Epoch: 4 | train_loss: 0.4474 | train_acc: 0.9062 | test_loss: 0.4355 | test_acc: 0.9409 Epoch: 5 | train_loss: 0.4290 | train_acc: 0.9104 | test_loss: 0.3915 | test_acc: 0.9443 Epoch: 6 | train_loss: 0.4381 | train_acc: 0.8896 | test_loss: 0.3512 | test_acc: 0.9688 Epoch: 7 | train_loss: 0.4245 | train_acc: 0.8771 | test_loss: 0.3268 | test_acc: 0.9563 Epoch: 8 | train_loss: 0.3897 | train_acc: 0.8958 | test_loss: 0.3457 | test_acc: 0.9381 Epoch: 9 | train_loss: 0.3749 | train_acc: 0.8812 | test_loss: 0.3129 | test_acc: 0.9131 Epoch: 10 | train_loss: 0.3757 | train_acc: 0.8604 | test_loss: 0.2813 | test_acc: 0.9688
In [14]:
from helper_functions import plot_loss_curves
plot_loss_curves(effnetb2_results)In [15]:
from going_modular.going_modular import utils
# Save the model
utils.save_model(model=effnetb2,
target_dir="models",
model_name="09_pretrained_effnetb2_feature_extractor_pizza_steak_sushi_20_percent.pth")[INFO] Saving model to: models/09_pretrained_effnetb2_feature_extractor_pizza_steak_sushi_20_percent.pth
In [16]:
from pathlib import Path
# Get the model size in bytes then convert to megabytes
pretrained_effnetb2_model_size = Path("models/09_pretrained_effnetb2_feature_extractor_pizza_steak_sushi_20_percent.pth").stat().st_size // (1024*1024) # division converts bytes to megabytes (roughly)
print(f"Pretrained EffNetB2 feature extractor model size: {pretrained_effnetb2_model_size} MB")Pretrained EffNetB2 feature extractor model size: 29 MB
In [17]:
# Count number of parameters in EffNetB2
effnetb2_total_params = sum(torch.numel(param) for param in effnetb2.parameters())
effnetb2_total_paramsOut [17]:
7705221
In [18]:
# Create a dictionary with EffNetB2 statistics
effnetb2_stats = {"test_loss": effnetb2_results["test_loss"][-1],
"test_acc": effnetb2_results["test_acc"][-1],
"number_of_parameters": effnetb2_total_params,
"model_size (MB)": pretrained_effnetb2_model_size}
effnetb2_statsOut [18]:
{'test_loss': 0.281286683678627,
'test_acc': 0.96875,
'number_of_parameters': 7705221,
'model_size (MB)': 29}In [19]:
# Check out ViT heads layer
vit = torchvision.models.vit_b_16()
vit.headsOut [19]:
Sequential( (head): Linear(in_features=768, out_features=1000, bias=True) )
In [20]:
def create_vit_model(num_classes:int=3,
seed:int=42):
"""Creates a ViT-B/16 feature extractor model and transforms.
Args:
num_classes (int, optional): number of target classes. Defaults to 3.
seed (int, optional): random seed value for output layer. Defaults to 42.
Returns:
model (torch.nn.Module): ViT-B/16 feature extractor model.
transforms (torchvision.transforms): ViT-B/16 image transforms.
"""
# Create EffNetB2 pretrained weights, transforms and model
weights = torchvision.models.ViT_B_16_Weights.DEFAULT
transforms = weights.transforms()
model = torchvision.models.vit_b_16(weights=weights)
# Freeze all layers in model
for param in model.parameters():
param.requires_grad = False
# Change classifier head to suit our needs (this will be trainable)
torch.manual_seed(seed)
model.heads = nn.Sequential(nn.Linear(in_features=768, # keep this the same as original model
out_features=num_classes)) # update to reflect target number of classes
return model, transformsIn [21]:
# Create ViT model and transforms
vit, vit_transforms = create_vit_model(num_classes=3,
seed=42)In [22]:
from torchinfo import summary
summary(vit,
input_size=(1, 3, 224, 224),
col_names=["input_size", "output_size", "num_params", "trainable"],
col_width=20,
row_settings=["var_names"])Out [22]:
====================================================================================================================================================== Layer (type (var_name)) Input Shape Output Shape Param # Trainable ====================================================================================================================================================== VisionTransformer (VisionTransformer) [1, 3, 224, 224] [1, 3] 768 Partial ├─Conv2d (conv_proj) [1, 3, 224, 224] [1, 768, 14, 14] (590,592) False ├─Encoder (encoder) [1, 197, 768] [1, 197, 768] 151,296 False │ └─Dropout (dropout) [1, 197, 768] [1, 197, 768] -- -- │ └─Sequential (layers) [1, 197, 768] [1, 197, 768] -- False │ │ └─EncoderBlock (encoder_layer_0) [1, 197, 768] [1, 197, 768] (7,087,872) False │ │ └─EncoderBlock (encoder_layer_1) [1, 197, 768] [1, 197, 768] (7,087,872) False │ │ └─EncoderBlock (encoder_layer_2) [1, 197, 768] [1, 197, 768] (7,087,872) False │ │ └─EncoderBlock (encoder_layer_3) [1, 197, 768] [1, 197, 768] (7,087,872) False │ │ └─EncoderBlock (encoder_layer_4) [1, 197, 768] [1, 197, 768] (7,087,872) False │ │ └─EncoderBlock (encoder_layer_5) [1, 197, 768] [1, 197, 768] (7,087,872) False │ │ └─EncoderBlock (encoder_layer_6) [1, 197, 768] [1, 197, 768] (7,087,872) False │ │ └─EncoderBlock (encoder_layer_7) [1, 197, 768] [1, 197, 768] (7,087,872) False │ │ └─EncoderBlock (encoder_layer_8) [1, 197, 768] [1, 197, 768] (7,087,872) False │ │ └─EncoderBlock (encoder_layer_9) [1, 197, 768] [1, 197, 768] (7,087,872) False │ │ └─EncoderBlock (encoder_layer_10) [1, 197, 768] [1, 197, 768] (7,087,872) False │ │ └─EncoderBlock (encoder_layer_11) [1, 197, 768] [1, 197, 768] (7,087,872) False │ └─LayerNorm (ln) [1, 197, 768] [1, 197, 768] (1,536) False ├─Sequential (heads) [1, 768] [1, 3] -- True │ └─Linear (0) [1, 768] [1, 3] 2,307 True ====================================================================================================================================================== Total params: 85,800,963 Trainable params: 2,307 Non-trainable params: 85,798,656 Total mult-adds (M): 172.47 ====================================================================================================================================================== Input size (MB): 0.60 Forward/backward pass size (MB): 104.09 Params size (MB): 257.55 Estimated Total Size (MB): 362.24 ======================================================================================================================================================
In [23]:
# Setup ViT DataLoaders
from going_modular.going_modular import data_setup
train_dataloader_vit, test_dataloader_vit, class_names = data_setup.create_dataloaders(train_dir=train_dir,
test_dir=test_dir,
transform=vit_transforms,
batch_size=32)In [24]:
from going_modular.going_modular import engine
# Setup optimizer
optimizer = torch.optim.Adam(params=vit.parameters(),
lr=1e-3)
# Setup loss function
loss_fn = torch.nn.CrossEntropyLoss()
# Train ViT model with seeds set for reproducibility
set_seeds()
vit_results = engine.train(model=vit,
train_dataloader=train_dataloader_vit,
test_dataloader=test_dataloader_vit,
epochs=10,
optimizer=optimizer,
loss_fn=loss_fn,
device=device)0%| | 0/10 [00:00<?, ?it/s]
Epoch: 1 | train_loss: 0.7023 | train_acc: 0.7500 | test_loss: 0.2714 | test_acc: 0.9290 Epoch: 2 | train_loss: 0.2531 | train_acc: 0.9104 | test_loss: 0.1669 | test_acc: 0.9602 Epoch: 3 | train_loss: 0.1766 | train_acc: 0.9542 | test_loss: 0.1270 | test_acc: 0.9693 Epoch: 4 | train_loss: 0.1277 | train_acc: 0.9625 | test_loss: 0.1072 | test_acc: 0.9722 Epoch: 5 | train_loss: 0.1163 | train_acc: 0.9646 | test_loss: 0.0950 | test_acc: 0.9784 Epoch: 6 | train_loss: 0.1270 | train_acc: 0.9375 | test_loss: 0.0830 | test_acc: 0.9722 Epoch: 7 | train_loss: 0.0899 | train_acc: 0.9771 | test_loss: 0.0844 | test_acc: 0.9784 Epoch: 8 | train_loss: 0.0928 | train_acc: 0.9812 | test_loss: 0.0759 | test_acc: 0.9722 Epoch: 9 | train_loss: 0.0933 | train_acc: 0.9792 | test_loss: 0.0729 | test_acc: 0.9784 Epoch: 10 | train_loss: 0.0662 | train_acc: 0.9833 | test_loss: 0.0642 | test_acc: 0.9847
In [25]:
from helper_functions import plot_loss_curves
plot_loss_curves(vit_results)In [26]:
# Save the model
from going_modular.going_modular import utils
utils.save_model(model=vit,
target_dir="models",
model_name="09_pretrained_vit_feature_extractor_pizza_steak_sushi_20_percent.pth")[INFO] Saving model to: models/09_pretrained_vit_feature_extractor_pizza_steak_sushi_20_percent.pth
In [27]:
from pathlib import Path
# Get the model size in bytes then convert to megabytes
pretrained_vit_model_size = Path("models/09_pretrained_vit_feature_extractor_pizza_steak_sushi_20_percent.pth").stat().st_size // (1024*1024) # division converts bytes to megabytes (roughly)
print(f"Pretrained ViT feature extractor model size: {pretrained_vit_model_size} MB")Pretrained ViT feature extractor model size: 327 MB
In [28]:
# Count number of parameters in ViT
vit_total_params = sum(torch.numel(param) for param in vit.parameters())
vit_total_paramsOut [28]:
85800963
In [29]:
# Create ViT statistics dictionary
vit_stats = {"test_loss": vit_results["test_loss"][-1],
"test_acc": vit_results["test_acc"][-1],
"number_of_parameters": vit_total_params,
"model_size (MB)": pretrained_vit_model_size}
vit_statsOut [29]:
{'test_loss': 0.06418213145807386,
'test_acc': 0.984659090909091,
'number_of_parameters': 85800963,
'model_size (MB)': 327}In [30]:
from pathlib import Path
# Get all test data paths
print(f"[INFO] Finding all filepaths ending with '.jpg' in directory: {test_dir}")
test_data_paths = list(Path(test_dir).glob("*/*.jpg"))
test_data_paths[:5]Out [30]:
[INFO] Finding all filepaths ending with '.jpg' in directory: data/pizza_steak_sushi_20_percent/test
[PosixPath('data/pizza_steak_sushi_20_percent/test/steak/831681.jpg'),
PosixPath('data/pizza_steak_sushi_20_percent/test/steak/3100563.jpg'),
PosixPath('data/pizza_steak_sushi_20_percent/test/steak/2752603.jpg'),
PosixPath('data/pizza_steak_sushi_20_percent/test/steak/39461.jpg'),
PosixPath('data/pizza_steak_sushi_20_percent/test/steak/730464.jpg')]In [31]:
import pathlib
import torch
from PIL import Image
from timeit import default_timer as timer
from tqdm.auto import tqdm
from typing import List, Dict
# 1. Create a function to return a list of dictionaries with sample, truth label, prediction, prediction probability and prediction time
def pred_and_store(paths: List[pathlib.Path],
model: torch.nn.Module,
transform: torchvision.transforms,
class_names: List[str],
device: str = "cuda" if torch.cuda.is_available() else "cpu") -> List[Dict]:
# 2. Create an empty list to store prediction dictionaires
pred_list = []
# 3. Loop through target paths
for path in tqdm(paths):
# 4. Create empty dictionary to store prediction information for each sample
pred_dict = {}
# 5. Get the sample path and ground truth class name
pred_dict["image_path"] = path
class_name = path.parent.stem
pred_dict["class_name"] = class_name
# 6. Start the prediction timer
start_time = timer()
# 7. Open image path
img = Image.open(path)
# 8. Transform the image, add batch dimension and put image on target device
transformed_image = transform(img).unsqueeze(0).to(device)
# 9. Prepare model for inference by sending it to target device and turning on eval() mode
model.to(device)
model.eval()
# 10. Get prediction probability, predicition label and prediction class
with torch.inference_mode():
pred_logit = model(transformed_image) # perform inference on target sample
pred_prob = torch.softmax(pred_logit, dim=1) # turn logits into prediction probabilities
pred_label = torch.argmax(pred_prob, dim=1) # turn prediction probabilities into prediction label
pred_class = class_names[pred_label.cpu()] # hardcode prediction class to be on CPU
# 11. Make sure things in the dictionary are on CPU (required for inspecting predictions later on)
pred_dict["pred_prob"] = round(pred_prob.unsqueeze(0).max().cpu().item(), 4)
pred_dict["pred_class"] = pred_class
# 12. End the timer and calculate time per pred
end_time = timer()
pred_dict["time_for_pred"] = round(end_time-start_time, 4)
# 13. Does the pred match the true label?
pred_dict["correct"] = class_name == pred_class
# 14. Add the dictionary to the list of preds
pred_list.append(pred_dict)
# 15. Return list of prediction dictionaries
return pred_listIn [32]:
# Make predictions across test dataset with EffNetB2
effnetb2_test_pred_dicts = pred_and_store(paths=test_data_paths,
model=effnetb2,
transform=effnetb2_transforms,
class_names=class_names,
device="cpu") # make predictions on CPU 0%| | 0/150 [00:00<?, ?it/s]
In [33]:
# Inspect the first 2 prediction dictionaries
effnetb2_test_pred_dicts[:2]Out [33]:
[{'image_path': PosixPath('data/pizza_steak_sushi_20_percent/test/steak/831681.jpg'),
'class_name': 'steak',
'pred_prob': 0.9293,
'pred_class': 'steak',
'time_for_pred': 0.0574,
'correct': True},
{'image_path': PosixPath('data/pizza_steak_sushi_20_percent/test/steak/3100563.jpg'),
'class_name': 'steak',
'pred_prob': 0.9534,
'pred_class': 'steak',
'time_for_pred': 0.0326,
'correct': True}]In [34]:
# Turn the test_pred_dicts into a DataFrame
import pandas as pd
effnetb2_test_pred_df = pd.DataFrame(effnetb2_test_pred_dicts)
effnetb2_test_pred_df.head()Out [34]:
| image_path | class_name | pred_prob | pred_class | time_for_pred | correct | |
|---|---|---|---|---|---|---|
| 0 | data/pizza_steak_sushi_20_percent/test/steak/8... | steak | 0.9293 | steak | 0.0574 | True |
| 1 | data/pizza_steak_sushi_20_percent/test/steak/3... | steak | 0.9534 | steak | 0.0326 | True |
| 2 | data/pizza_steak_sushi_20_percent/test/steak/2... | steak | 0.7531 | steak | 0.0313 | True |
| 3 | data/pizza_steak_sushi_20_percent/test/steak/3... | steak | 0.5935 | steak | 0.0320 | True |
| 4 | data/pizza_steak_sushi_20_percent/test/steak/7... | steak | 0.8959 | steak | 0.0328 | True |
In [35]:
# Check number of correct predictions
effnetb2_test_pred_df.correct.value_counts()Out [35]:
True 145 False 5 Name: correct, dtype: int64
In [36]:
# Find the average time per prediction
effnetb2_average_time_per_pred = round(effnetb2_test_pred_df.time_for_pred.mean(), 4)
print(f"EffNetB2 average time per prediction: {effnetb2_average_time_per_pred} seconds")EffNetB2 average time per prediction: 0.0298 seconds
In [37]:
# Add EffNetB2 average prediction time to stats dictionary
effnetb2_stats["time_per_pred_cpu"] = effnetb2_average_time_per_pred
effnetb2_statsOut [37]:
{'test_loss': 0.281286683678627,
'test_acc': 0.96875,
'number_of_parameters': 7705221,
'model_size (MB)': 29,
'time_per_pred_cpu': 0.0298}In [38]:
# Make list of prediction dictionaries with ViT feature extractor model on test images
vit_test_pred_dicts = pred_and_store(paths=test_data_paths,
model=vit,
transform=vit_transforms,
class_names=class_names,
device="cpu")0%| | 0/150 [00:00<?, ?it/s]
In [39]:
# Check the first couple of ViT predictions on the test dataset
vit_test_pred_dicts[:2]Out [39]:
[{'image_path': PosixPath('data/pizza_steak_sushi_20_percent/test/steak/831681.jpg'),
'class_name': 'steak',
'pred_prob': 0.9933,
'pred_class': 'steak',
'time_for_pred': 0.1304,
'correct': True},
{'image_path': PosixPath('data/pizza_steak_sushi_20_percent/test/steak/3100563.jpg'),
'class_name': 'steak',
'pred_prob': 0.9893,
'pred_class': 'steak',
'time_for_pred': 0.0654,
'correct': True}]In [40]:
# Turn vit_test_pred_dicts into a DataFrame
import pandas as pd
vit_test_pred_df = pd.DataFrame(vit_test_pred_dicts)
vit_test_pred_df.head()Out [40]:
| image_path | class_name | pred_prob | pred_class | time_for_pred | correct | |
|---|---|---|---|---|---|---|
| 0 | data/pizza_steak_sushi_20_percent/test/steak/8... | steak | 0.9933 | steak | 0.1304 | True |
| 1 | data/pizza_steak_sushi_20_percent/test/steak/3... | steak | 0.9893 | steak | 0.0654 | True |
| 2 | data/pizza_steak_sushi_20_percent/test/steak/2... | steak | 0.9971 | steak | 0.0642 | True |
| 3 | data/pizza_steak_sushi_20_percent/test/steak/3... | steak | 0.7685 | steak | 0.0649 | True |
| 4 | data/pizza_steak_sushi_20_percent/test/steak/7... | steak | 0.9499 | steak | 0.0658 | True |
In [41]:
# Count the number of correct predictions
vit_test_pred_df.correct.value_counts()Out [41]:
True 148 False 2 Name: correct, dtype: int64
In [42]:
# Calculate average time per prediction for ViT model
vit_average_time_per_pred = round(vit_test_pred_df.time_for_pred.mean(), 4)
print(f"ViT average time per prediction: {vit_average_time_per_pred} seconds")ViT average time per prediction: 0.0679 seconds
In [43]:
# Add average prediction time for ViT model on CPU
vit_stats["time_per_pred_cpu"] = vit_average_time_per_pred
vit_statsOut [43]:
{'test_loss': 0.06418213145807386,
'test_acc': 0.984659090909091,
'number_of_parameters': 85800963,
'model_size (MB)': 327,
'time_per_pred_cpu': 0.0679}In [44]:
# Turn stat dictionaries into DataFrame
df = pd.DataFrame([effnetb2_stats, vit_stats])
# Add column for model names
df["model"] = ["EffNetB2", "ViT"]
# Convert accuracy to percentages
df["test_acc"] = round(df["test_acc"] * 100, 2)
dfOut [44]:
| test_loss | test_acc | number_of_parameters | model_size (MB) | time_per_pred_cpu | model | |
|---|---|---|---|---|---|---|
| 0 | 0.281287 | 96.88 | 7705221 | 29 | 0.0298 | EffNetB2 |
| 1 | 0.064182 | 98.47 | 85800963 | 327 | 0.0679 | ViT |
Warning:
Output truncated. This notebook contains too many cells to display efficiently.