mirror of
https://github.com/mrdbourke/pytorch-deep-learning.git
synced 2026-11-27 06:07:09 +00:00
430 KiB
430 KiB
In [73]:
# 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 torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu113
import torch
import torchvision
print(f"torch version: {torch.__version__}")
print(f"torchvision version: {torchvision.__version__}")torch version: 1.12.1+cu113 torchvision version: 0.13.1+cu113
In [74]:
# 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 [75]:
!ls going_modular/going_modulardata_setup.py model_builder.py __pycache__ train.py engine.py predictions.py README.md utils.py
In [76]:
device = "cuda" if torch.cuda.is_available() else "cpu"
device Out [76]:
'cuda'
In [77]:
# 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 [77]:
[INFO] data/pizza_steak_sushi_20_percent directory exists, skipping download.
PosixPath('data/pizza_steak_sushi_20_percent')In [78]:
# Setup training and test paths
train_dir = data_20_percent_path / "train"
test_dir = data_20_percent_path / "test"
train_dir, test_dirOut [78]:
(PosixPath('data/pizza_steak_sushi_20_percent/train'),
PosixPath('data/pizza_steak_sushi_20_percent/test'))In [79]:
import torchvision
# 1. Setup pretrained EffNetB2 weights
effnetb2_weights = torchvision.models.EfficientNet_B2_Weights.DEFAULT # "DEFAULT" is equivalent to saying "best available"
# 2. Get EffNetB2 transforms
effnetb2_transforms = effnetb2_weights.transforms()
# 3. Setup pretrained model instance
effnetb2 = torchvision.models.efficientnet_b2(weights=effnetb2_weights) # could also use weights="DEFAULT"
# 4. Freeze the base layers in the model (this will stop all layers from training)
for param in effnetb2.parameters():
param.requires_grad = FalseIn [80]:
from torchinfo import summary
# # Print EffNetB2 model summary (uncomment for full output)
# summary(effnetb2,
# input_size=(1, 3, 224, 224),
# col_names=["input_size", "output_size", "num_params", "trainable"],
# col_width=20,
# row_settings=["var_names"])In [81]:
effnetb2.classifierOut [81]:
Sequential( (0): Dropout(p=0.3, inplace=True) (1): Linear(in_features=1408, out_features=1000, bias=True) )
In [82]:
# Set seeds for reproducibility
set_seeds()
effnetb2.classifier = nn.Sequential(
nn.Dropout(p=0.3, inplace=True),
nn.Linear(in_features=1408, out_features=3, bias=True))In [83]:
# from torchinfo import summary
# # Print EffNetB2 model summary (uncomment for full output)
# summary(effnetb2,
# input_size=(1, 3, 224, 224),
# col_names=["input_size", "output_size", "num_params", "trainable"],
# col_width=20,
# row_settings=["var_names"])In [84]:
def create_effnetb2_model(num_classes:int=3, # default output classes = 3 (pizza, steak, sushi)
seed:int=42):
# 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 the 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 [85]:
effnetb2, effnetb2_transforms = create_effnetb2_model(num_classes=3,
seed=42)In [86]:
# from torchinfo import summary
# # Print EffNetB2 model summary (uncomment for full output)
# summary(effnetb2,
# input_size=(1, 3, 288, 288),
# col_names=["input_size", "output_size", "num_params", "trainable"],
# col_width=20,
# row_settings=["var_names"])In [87]:
# 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 [88]:
len(train_dataloader_effnetb2), len(test_dataloader_effnetb2), class_namesOut [88]:
(15, 5, ['pizza', 'steak', 'sushi'])
In [89]:
from going_modular.going_modular import engine
# Loss function
loss_fn = torch.nn.CrossEntropyLoss()
# Optimizer
optimizer = torch.optim.Adam(params=effnetb2.parameters(),
lr=1e-3)
# Training function (engine.py)
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 [90]:
from helper_functions import plot_loss_curves
plot_loss_curves(effnetb2_results)In [91]:
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 [92]:
from pathlib import Path
# Get the model size in bytes and 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)
print(f"Pretrained EffNetB2 feature extractor model size: {round(pretrained_effnetb2_model_size, 2)} MB")Pretrained EffNetB2 feature extractor model size: 29.82 MB
In [93]:
# Count number of parameters in EffNetB2
effnetb2_total_params = sum(torch.numel(param) for param in effnetb2.parameters())
effnetb2_total_paramsOut [93]:
7705221
In [94]:
# 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 [94]:
{'test_loss': 0.28128677904605864,
'test_acc': 0.96875,
'number_of_parameters': 7705221,
'model_size (MB)': 29.824288368225098}In [95]:
# Check out the ViT heads layer
vit = torchvision.models.vit_b_16()
vit.headsOut [95]:
Sequential( (head): Linear(in_features=768, out_features=1000, bias=True) )
In [96]:
def create_vit_model(num_classes:int=3,
seed:int=42):
# Create ViT_B_16 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 of the base layers
for param in model.parameters():
param.requires_grad = False
# Change classifier head to suit our needs
torch.manual_seed(seed)
model.heads = nn.Sequential(nn.Linear(in_features=768,
out_features=num_classes))
return model, transformsIn [97]:
vit, vit_transforms = create_vit_model()
vit_transformsOut [97]:
ImageClassification(
crop_size=[224]
resize_size=[256]
mean=[0.485, 0.456, 0.406]
std=[0.229, 0.224, 0.225]
interpolation=InterpolationMode.BILINEAR
)In [98]:
# from torchinfo import summary
# # Print ViT model summary (uncomment for full output)
# summary(vit,
# input_size=(1, 3, 224, 224),
# col_names=["input_size", "output_size", "num_params", "trainable"],
# col_width=20,
# row_settings=["var_names"])In [99]:
# 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)
len(train_dataloader_vit), len(test_dataloader_vit), class_namesOut [99]:
(15, 5, ['pizza', 'steak', 'sushi'])
In [100]:
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 feature extractor 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 [101]:
from helper_functions import plot_loss_curves
plot_loss_curves(vit_results)In [102]:
# Save 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 [103]:
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)
print(f"Pretrained ViT feature extractor model size: {pretrained_vit_model_size} MB")Pretrained ViT feature extractor model size: 327.36128330230713 MB
In [104]:
# Count number of parameters in ViT
vit_total_params = sum(torch.numel(param) for param in vit.parameters())
vit_total_paramsOut [104]:
85800963
In [105]:
# 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}In [106]:
vit_statsOut [106]:
{'test_loss': 0.06418212698772549,
'test_acc': 0.984659090909091,
'number_of_parameters': 85800963,
'model_size (MB)': 327.36128330230713}In [107]:
from pathlib import Path
# Get all test data paths
test_data_paths = list(Path(test_dir).glob("*/*.jpg"))
test_data_paths[:5]Out [107]:
[PosixPath('data/pizza_steak_sushi_20_percent/test/sushi/1203702.jpg'),
PosixPath('data/pizza_steak_sushi_20_percent/test/sushi/46797.jpg'),
PosixPath('data/pizza_steak_sushi_20_percent/test/sushi/389730.jpg'),
PosixPath('data/pizza_steak_sushi_20_percent/test/sushi/3227791.jpg'),
PosixPath('data/pizza_steak_sushi_20_percent/test/sushi/1844723.jpg')]In [108]:
import pathlib
import torch
from PIL import Image
from timeit import default_timer as timer # https://docs.python.org/3/library/timeit.html#timeit.default_timer
from tqdm.auto import tqdm
from typing import List, Dict
# 1. Create a function that takes a list of paths and a trained PyTorch and a series of transforms a list of target class names and a target device.
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 (can return a full list of all predictions later).
pred_list = []
# 3. Loop through the target input paths (the rest of the steps will take place inside the loop).
for path in tqdm(paths):
# 4. Create an empty dictionary for each sample (prediction statistics will go in here).
pred_dict = {}
# 5. Get the sample path and ground truth class from the filepath.
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 the image using Image.open(path)
img = Image.open(path)
# 8. Transform the image to be usable with a given model (also add a batch dimension and send to target device)
transformed_image = transform(img).unsqueeze(0).to(device)
# 9. Prepare the model model for inference by sending to the target device and turning on eval() mode.
model = model.to(device)
model.eval()
# 10. Turn on `torch.inference_mode()` and pass the target transformed image to the model and perform forward pass + calculate pred prob + pred class.
with torch.inference_mode():
pred_logit = model(transformed_image)
pred_prob = torch.softmax(pred_logit, dim=1) # turn logits into predicition probabilities
pred_label = torch.argmax(pred_prob, dim=1) # turn prediction probability into prediction label
pred_class = class_names[pred_label.cpu()] # hardcode prediction class to be on CPU (Python variables live on CPU)
# 11. Add the pred prob + pred class to empty dictionary from step 4.
pred_dict["pred_prob"] = round(pred_prob.unsqueeze(0).max().cpu().item(), 4)
pred_dict["pred_class"] = pred_class
# 12. End the prediction timer started in step 6 and add the time to the prediction dictionary.
end_time = timer()
pred_dict["time_for_pred"] = round(end_time-start_time, 4)
# 13. See if the predicted class matches the ground truth class.
pred_dict["correct"] = class_name == pred_class
# 14. Append the updated prediction dictionary to the empty list of predictions we created in step 2.
pred_list.append(pred_dict)
# 15. Return the list of prediction dictionaries.
return pred_listIn [109]:
# Make predictions 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") # hardcode predictions to happen on CPU0%| | 0/150 [00:00<?, ?it/s]
In [110]:
effnetb2_test_pred_dicts[:2]Out [110]:
[{'image_path': PosixPath('data/pizza_steak_sushi_20_percent/test/sushi/1203702.jpg'),
'class_name': 'sushi',
'pred_prob': 0.8812,
'pred_class': 'sushi',
'time_for_pred': 0.1742,
'correct': True},
{'image_path': PosixPath('data/pizza_steak_sushi_20_percent/test/sushi/46797.jpg'),
'class_name': 'sushi',
'pred_prob': 0.9184,
'pred_class': 'sushi',
'time_for_pred': 0.1266,
'correct': True}]In [111]:
# 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 [111]:
| image_path | class_name | pred_prob | pred_class | time_for_pred | correct | |
|---|---|---|---|---|---|---|
| 0 | data/pizza_steak_sushi_20_percent/test/sushi/1... | sushi | 0.8812 | sushi | 0.1742 | True |
| 1 | data/pizza_steak_sushi_20_percent/test/sushi/4... | sushi | 0.9184 | sushi | 0.1266 | True |
| 2 | data/pizza_steak_sushi_20_percent/test/sushi/3... | sushi | 0.6810 | sushi | 0.1276 | True |
| 3 | data/pizza_steak_sushi_20_percent/test/sushi/3... | sushi | 0.8659 | sushi | 0.1258 | True |
| 4 | data/pizza_steak_sushi_20_percent/test/sushi/1... | sushi | 0.8830 | sushi | 0.1247 | True |
In [112]:
# Check number of correct predictions
effnetb2_test_pred_df.correct.value_counts()Out [112]:
True 145 False 5 Name: correct, dtype: int64
In [113]:
# 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}")EffNetB2 average time per prediction: 0.1244
In [114]:
# Add time per pred to EffNetB2 stats dictionary
effnetb2_stats["time_per_pred_cpu"] = effnetb2_average_time_per_pred
effnetb2_statsOut [114]:
{'test_loss': 0.28128677904605864,
'test_acc': 0.96875,
'number_of_parameters': 7705221,
'model_size (MB)': 29.824288368225098,
'time_per_pred_cpu': 0.1244}In [115]:
# 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") # hardcode device to CPU because not sure if GPU available when we deploy 0%| | 0/150 [00:00<?, ?it/s]
In [116]:
# Check the first couple of ViT predictions
vit_test_pred_dicts[:2]Out [116]:
[{'image_path': PosixPath('data/pizza_steak_sushi_20_percent/test/sushi/1203702.jpg'),
'class_name': 'sushi',
'pred_prob': 0.9589,
'pred_class': 'sushi',
'time_for_pred': 0.7028,
'correct': True},
{'image_path': PosixPath('data/pizza_steak_sushi_20_percent/test/sushi/46797.jpg'),
'class_name': 'sushi',
'pred_prob': 0.9927,
'pred_class': 'sushi',
'time_for_pred': 0.5721,
'correct': True}]In [117]:
# Turn vit_test_pred_dicts
import pandas as pd
vit_test_pred_df = pd.DataFrame(vit_test_pred_dicts)
vit_test_pred_df.head()Out [117]:
| image_path | class_name | pred_prob | pred_class | time_for_pred | correct | |
|---|---|---|---|---|---|---|
| 0 | data/pizza_steak_sushi_20_percent/test/sushi/1... | sushi | 0.9589 | sushi | 0.7028 | True |
| 1 | data/pizza_steak_sushi_20_percent/test/sushi/4... | sushi | 0.9927 | sushi | 0.5721 | True |
| 2 | data/pizza_steak_sushi_20_percent/test/sushi/3... | sushi | 0.9908 | sushi | 0.5463 | True |
| 3 | data/pizza_steak_sushi_20_percent/test/sushi/3... | sushi | 0.4956 | pizza | 0.5606 | False |
| 4 | data/pizza_steak_sushi_20_percent/test/sushi/1... | sushi | 0.9870 | sushi | 0.5535 | True |
In [118]:
# See how many correct
vit_test_pred_df.correct.value_counts()Out [118]:
True 148 False 2 Name: correct, dtype: int64
In [119]:
# 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}")ViT average time per prediction: 0.5554
In [120]:
# Add average time per prediction to ViT stats
vit_stats["time_per_pred_cpu"] = vit_average_time_per_pred
vit_statsOut [120]:
{'test_loss': 0.06418212698772549,
'test_acc': 0.984659090909091,
'number_of_parameters': 85800963,
'model_size (MB)': 327.36128330230713,
'time_per_pred_cpu': 0.5554}In [121]:
# 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 [121]:
| test_loss | test_acc | number_of_parameters | model_size (MB) | time_per_pred_cpu | model | |
|---|---|---|---|---|---|---|
| 0 | 0.281287 | 96.88 | 7705221 | 29.824288 | 0.1244 | EffNetB2 |
| 1 | 0.064182 | 98.47 | 85800963 | 327.361283 | 0.5554 | ViT |
In [122]:
# Compare ViT to EffNetB2 across different characteristics
pd.DataFrame(data=(df.set_index("model").loc["ViT"] / df.set_index("model").loc["EffNetB2"]),
columns=["ViT to EffNetB2 ratios"]).TOut [122]:
| test_loss | test_acc | number_of_parameters | model_size (MB) | time_per_pred_cpu | |
|---|---|---|---|---|---|
| ViT to EffNetB2 ratios | 0.228173 | 1.016412 | 11.135432 | 10.976332 | 4.46463 |
In [123]:
dfOut [123]:
| test_loss | test_acc | number_of_parameters | model_size (MB) | time_per_pred_cpu | model | |
|---|---|---|---|---|---|---|
| 0 | 0.281287 | 96.88 | 7705221 | 29.824288 | 0.1244 | EffNetB2 |
| 1 | 0.064182 | 98.47 | 85800963 | 327.361283 | 0.5554 | ViT |
In [124]:
import matplotlib
matplotlib.__version__Out [124]:
'3.2.2'
In [125]:
# 1. Create a plot from model comparison DataFrame
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(12, 8))
scatter = ax.scatter(data=df,
x="time_per_pred_cpu",
y="test_acc",
c=["blue", "orange"],
s="model_size (MB)")
# 2. Add titles and labels to make our plot look good
ax.set_title("FoodVision Mini Inference Speed vs Performance", fontsize=18)
ax.set_xlabel("Prediction time per image (seconds)", fontsize=14)
ax.set_ylabel("Test accuracy (%)", fontsize=14)
ax.tick_params(axis="both", labelsize=12)
ax.grid(True)
# 3. Annotate the samples on the scatter plot so we know what's going on.
for index, row in df.iterrows():
ax.annotate(s=row["model"], # note: in some versions of Matplotlib, this may need to be "text" rather than "s"
xy=(row["time_per_pred_cpu"]+0.0006, row["test_acc"]+0.03),
size=12)
# 4. Create a legend based on the model sizes (model_size (MB)).
handles, labels = scatter.legend_elements(prop="sizes", alpha=0.5)
model_size_legend = ax.legend(handles,
labels,
loc="lower right",
title="Model size (MB)",
fontsize=12)
# Save the figure
plt.savefig("09-foodvision-mini-inference-speed-vs-performance.png")In [126]:
# Import/install Gradio
try:
import gradio as gr
except:
!pip -q install gradio
import gradio as gr
print(f"Gradio version: {gr.__version__}")Gradio version: 3.1.7
In [127]:
# Put our model on the CPU
effnetb2 = effnetb2.to("cpu")
# Check the device
next(iter(effnetb2.parameters())).deviceOut [127]:
device(type='cpu')
In [128]:
from typing import Tuple, Dict
def predict(img) -> Tuple[Dict, float]:
# Start a timer
start_time = timer()
# Transform the input image for use with EffNetB2
img = effnetb2_transforms(img).unsqueeze(0) # unsqueeze = add batch dimension on 0th index
# Put model into eval mode, make prediction
effnetb2.eval()
with torch.inference_mode():
# Pass transformed image through the model and turn the prediction logits into probaiblities
pred_probs = torch.softmax(effnetb2(img), dim=1)
# Create a prediction label and prediction probability dictionary
pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}
# Calculate pred time
end_time = timer()
pred_time = round(end_time - start_time, 4)
# Return pred dict and pred time
return pred_labels_and_probs, pred_time
In [129]:
import random
from PIL import Image
# Get a list of all test image filepaths
test_data_paths = list(Path(test_dir).glob("*/*.jpg"))
print(f"Example test data path: {test_data_paths[0]}")
# Randomly select a test image path
random_image_path = random.sample(test_data_paths, k=1)[0]
random_image_path
# Open the target image
image = Image.open(random_image_path)
print(f"[INFO] Predicting on image at path: {random_image_path}\n")
# Predict on the target image and print out the outputs
pred_dict, pred_time = predict(img=image)
print(pred_dict)
print(pred_time)Example test data path: data/pizza_steak_sushi_20_percent/test/sushi/1203702.jpg
[INFO] Predicting on image at path: data/pizza_steak_sushi_20_percent/test/pizza/129666.jpg
{'pizza': 0.6918998956680298, 'steak': 0.15962719917297363, 'sushi': 0.14847293496131897}
0.1745
In [130]:
# Create list of example inputs to our Gradio demo
example_list = [[str(filepath)] for filepath in random.sample(test_data_paths, k=3)]
example_listOut [130]:
[['data/pizza_steak_sushi_20_percent/test/sushi/1346344.jpg'], ['data/pizza_steak_sushi_20_percent/test/pizza/998005.jpg'], ['data/pizza_steak_sushi_20_percent/test/sushi/3401466.jpg']]
In [131]:
import gradio as gr
# Create title, description and article
title = "FoodVision Mini 🍕🥩🍣"
description = "An [EfficientNetB2 feature extractor](https://pytorch.org/vision/stable/models/generated/torchvision.models.efficientnet_b2.html#torchvision.models.efficientnet_b2) computer vision model to classify images as pizza, steak or sushi."
article = "Created at [09. PyTorch Model Deployment](https://www.learnpytorch.io/09_pytorch_model_deployment/#74-building-a-gradio-interface)."
# Create the Gradio demo
demo = gr.Interface(fn=predict, # maps inputs to outputs
inputs=gr.Image(type="pil"),
outputs=[gr.Label(num_top_classes=3, label="Predictions"),
gr.Number(label="Prediction time (s)")],
examples=example_list,
title=title,
description=description,
article=article)
# Launch the demo!
demo.launch(debug=False, # print errors locally?
share=True) # generate a publically shareable URL Out [131]:
Colab notebook detected. To show errors in colab notebook, set `debug=True` in `launch()` Running on public URL: https://27876.gradio.app This share link expires in 72 hours. For free permanent hosting, check out Spaces: https://huggingface.co/spaces
(<gradio.routes.App at 0x7f0a593100d0>, 'http://127.0.0.1:7861/', 'https://27876.gradio.app')
In [132]:
import shutil
from pathlib import Path
# Create FoodVision mini demo path
foodvision_mini_demo_path = Path("demos/foodvision_mini/")
# Remove files that might exist and create a new directory
if foodvision_mini_demo_path.exists():
shutil.rmtree(foodvision_mini_demo_path)
foodvision_mini_demo_path.mkdir(parents=True,
exist_ok=True)
else:
foodvision_mini_demo_path.mkdir(parents=True,
exist_ok=True)
!ls demos/foodvision_mini/Warning:
Output truncated. This notebook contains too many cells to display efficiently.