mirror of
https://github.com/mrdbourke/pytorch-deep-learning.git
synced 2026-11-27 06:07:09 +00:00
179 KiB
179 KiB
In [1]:
import torch
import torchvision
print(torch.__version__)
print(torchvision.__version__)1.12.0+cu102 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]:
def create_effnetb2_model(num_classes:int=3, seed:int=42):
weights = torchvision.models.EfficientNet_B2_Weights.DEFAULT
transforms = weights.transforms()
model = torchvision.models.efficientnet_b2(weights=weights)
# Freeze base model
for param in model.parameters():
param.requires_grad = False
# Change classifier head
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, transforms
effnetb2, effnetb2_transforms = create_effnetb2_model(num_classes=3,
seed=42)In [7]:
# Setup dataloaders
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 [8]:
# summary(effnetb2,
# input_size=(1, 3, 224, 224), # try swapping this for "random_input_image_error"
# col_names=["input_size", "output_size", "num_params", "trainable"],
# col_width=20,
# row_settings=["var_names"])In [9]:
# Train the model
from going_modular.going_modular import engine
optimizer = torch.optim.Adam(params=effnetb2.parameters(),
lr=1e-3)
loss_fn = torch.nn.CrossEntropyLoss()
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 [10]:
from helper_functions import plot_loss_curves
plot_loss_curves(effnetb2_results)In [11]:
# Save the model
from going_modular.going_modular import utils
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 [12]:
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 [13]:
effnetb2_stats = {"test_loss": effnetb2_results["test_loss"][-1],
"test_acc": effnetb2_results["test_acc"][-1],
"model_size (MB)": pretrained_effnetb2_model_size}
effnetb2_statsOut [13]:
{'test_loss': 0.281286683678627, 'test_acc': 0.96875, 'model_size (MB)': 29}In [14]:
def create_vit_model(num_classes: int=3, seed: int=42):
weights = torchvision.models.ViT_B_16_Weights.DEFAULT
transforms = weights.transforms()
model = torchvision.models.vit_b_16(weights=weights)
# Freeze base model
for param in model.parameters():
param.requires_grad = False
# Change classifier head
torch.manual_seed(seed)
model.heads = nn.Sequential(nn.Linear(in_features=768,
out_features=len(class_names)))
return model, transforms
vit, vit_transforms = create_vit_model(num_classes=3,
seed=42)In [15]:
# Setup dataloaders
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 [16]:
# Train the model
from going_modular.going_modular import engine
optimizer = torch.optim.Adam(params=vit.parameters(),
lr=1e-3)
loss_fn = torch.nn.CrossEntropyLoss()
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 [17]:
from helper_functions import plot_loss_curves
plot_loss_curves(vit_results)In [18]:
# 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 [19]:
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 [20]:
vit_stats = {"test_loss": vit_results["test_loss"][-1],
"test_acc": vit_results["test_acc"][-1],
"model_size (MB)": pretrained_vit_model_size}
vit_statsOut [20]:
{'test_loss': 0.06418213145807386,
'test_acc': 0.984659090909091,
'model_size (MB)': 327}In [21]:
from tqdm.auto import tqdm
from pathlib import Path
from PIL import Image
from timeit import default_timer as timer
# Get all test data paths
test_data_paths = list(Path(test_dir).glob("*/*.jpg"))
test_labels = [path.parent.stem for path in test_data_paths]
# Create a function to return a list of dictionaries with sample, label, prediction, pred prob
def pred_and_store(test_paths, model, transform, class_names, device):
test_pred_list = []
for path in tqdm(test_paths):
# Create empty dict to store info for each sample
pred_dict = {}
# Get sample path
pred_dict["image_path"] = path
# Get class name
class_name = path.parent.stem
pred_dict["class_name"] = class_name
# Get prediction and prediction probability
start_time = timer()
img = Image.open(path) # open image
transformed_image = transform(img).unsqueeze(0) # transform image and add batch dimension
model.to(device)
model.eval()
with torch.inference_mode():
pred_logit = model(transformed_image.to(device))
pred_prob = torch.softmax(pred_logit, dim=1)
pred_label = torch.argmax(pred_prob, dim=1)
pred_class = class_names[pred_label.cpu()]
# Make sure things in the dictionary are back on the CPU
pred_dict["pred_prob"] = pred_prob.unsqueeze(0).max().cpu().item()
pred_dict["pred_class"] = pred_class
# Calculate time per pred
end_time = timer()
pred_dict["time_for_pred"] = round(end_time-start_time, 4)
# Does the pred match the true label?
pred_dict["correct"] = class_name == pred_class
# print(pred_dict)
# Add the dictionary to the list of preds
test_pred_list.append(pred_dict)
return test_pred_listIn [22]:
effnetb2_test_pred_dicts = pred_and_store(test_paths=test_data_paths,
model=effnetb2,
transform=effnetb2_transforms,
class_names=class_names,
device="cpu")
effnetb2_test_pred_dicts[:3]Out [22]:
0%| | 0/150 [00:00<?, ?it/s]
[{'image_path': PosixPath('data/pizza_steak_sushi_20_percent/test/steak/831681.jpg'),
'class_name': 'steak',
'pred_prob': 0.9293267726898193,
'pred_class': 'steak',
'time_for_pred': 0.0582,
'correct': True},
{'image_path': PosixPath('data/pizza_steak_sushi_20_percent/test/steak/3100563.jpg'),
'class_name': 'steak',
'pred_prob': 0.9533632397651672,
'pred_class': 'steak',
'time_for_pred': 0.0325,
'correct': True},
{'image_path': PosixPath('data/pizza_steak_sushi_20_percent/test/steak/2752603.jpg'),
'class_name': 'steak',
'pred_prob': 0.7531499266624451,
'pred_class': 'steak',
'time_for_pred': 0.0317,
'correct': True}]In [23]:
vit_test_pred_dicts = pred_and_store(test_paths=test_data_paths,
model=vit,
transform=vit_transforms,
class_names=class_names,
device="cpu")
vit_test_pred_dicts[:3]Out [23]:
0%| | 0/150 [00:00<?, ?it/s]
[{'image_path': PosixPath('data/pizza_steak_sushi_20_percent/test/steak/831681.jpg'),
'class_name': 'steak',
'pred_prob': 0.9932767748832703,
'pred_class': 'steak',
'time_for_pred': 0.1292,
'correct': True},
{'image_path': PosixPath('data/pizza_steak_sushi_20_percent/test/steak/3100563.jpg'),
'class_name': 'steak',
'pred_prob': 0.9893474578857422,
'pred_class': 'steak',
'time_for_pred': 0.0651,
'correct': True},
{'image_path': PosixPath('data/pizza_steak_sushi_20_percent/test/steak/2752603.jpg'),
'class_name': 'steak',
'pred_prob': 0.997147262096405,
'pred_class': 'steak',
'time_for_pred': 0.0638,
'correct': True}]In [24]:
# Turn the test_pred_dicts into a DataFrame
import pandas as pd
effnetb2_test_pred_df = pd.DataFrame(effnetb2_test_pred_dicts)
effnetb2_average_time_per_pred = effnetb2_test_pred_df.time_for_pred.mean()
effnetb2_average_time_per_predOut [24]:
0.03031466666666668
In [25]:
effnetb2_stats["time_per_pred_cpu"] = effnetb2_average_time_per_pred
effnetb2_statsOut [25]:
{'test_loss': 0.281286683678627,
'test_acc': 0.96875,
'model_size (MB)': 29,
'time_per_pred_cpu': 0.03031466666666668}In [26]:
# Turn the test_pred_dicts into a DataFrame
import pandas as pd
vit_test_pred_df = pd.DataFrame(vit_test_pred_dicts)
vit_average_time_per_pred = vit_test_pred_df.time_for_pred.mean()
vit_average_time_per_predOut [26]:
0.065996
In [27]:
vit_stats["time_per_pred_cpu"] = vit_average_time_per_pred
vit_statsOut [27]:
{'test_loss': 0.06418213145807386,
'test_acc': 0.984659090909091,
'model_size (MB)': 327,
'time_per_pred_cpu': 0.065996}In [28]:
df = pd.DataFrame([effnetb2_stats, vit_stats])
df["model"] = ["effnetb2", "vit"]
df = df.set_index("model")
dfOut [28]:
| test_loss | test_acc | model_size (MB) | time_per_pred_cpu | |
|---|---|---|---|---|
| model | ||||
| effnetb2 | 0.281287 | 0.968750 | 29 | 0.030315 |
| vit | 0.064182 | 0.984659 | 327 | 0.065996 |
In [29]:
df.loc["vit"] / df.loc["effnetb2"]Out [29]:
test_loss 0.228173 test_acc 1.016422 model_size (MB) 11.275862 time_per_pred_cpu 2.177032 dtype: float64
In [30]:
try:
import gradio as gr
except:
!pip -q install gradio
import gradio as grIn [31]:
effnetb2.to("cpu")
vit.to("cpu")
def predict(img):
start_time = timer()
img = effnetb2_transforms(img).unsqueeze(0)
effnetb2.eval()
with torch.inference_mode():
pred_probs = torch.softmax(effnetb2(img), dim=1)
pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}
pred_time = round(timer() - start_time, 5)
return pred_labels_and_probs, pred_time
import random
test_data_paths = list(Path(test_dir).glob("*/*.jpg"))
random_image_path = random.sample(test_data_paths, k=1)[0]
print(random_image_path)
image = Image.open(random_image_path)
predict(img=image)Out [31]:
data/pizza_steak_sushi_20_percent/test/pizza/416067.jpg
({'pizza': 0.9558159708976746,
'steak': 0.0371665358543396,
'sushi': 0.007017466705292463},
0.03259)In [32]:
import gradio as gr
title = "FoodVision Mini 🍕🥩🍣"
description = "An EfficientNetB2 feature extractor computer vision model to classify images of food as pizza, steak or sushi."
article = "Created at [09. PyTorch Model Deployment](https://www.learnpytorch.io/09_pytorch_model_deployment/)."
example_dir = "demo/examples"
demo = gr.Interface(fn=predict,
inputs=gr.Image(type="pil"),
outputs=[gr.Label(num_top_classes=3, label="Predictions"),
gr.Number(label="Prediction time (s)")],
# examples="demo/foodvision_mini/examples",
interpretation="default",
title=title,
description=description,
article=article)
demo.launch(debug=False)Out [32]:
Running on local URL: http://127.0.0.1:7862/ To create a public link, set `share=True` in `launch()`.
(<gradio.routes.App at 0x7f2799f25790>, 'http://127.0.0.1:7862/', None)
In [33]:
%%writefile demo/model.py
import torchvision
from torch import nn
def create_effnetb2_model(num_classes: int):
weights = torchvision.models.EfficientNet_B2_Weights.DEFAULT
transforms = weights.transforms()
model = torchvision.models.efficientnet_b2(weights=weights)
# Freeze base model
for param in model.parameters():
param.requires_grad = False
# Change classifier head
model.classifier = nn.Sequential(
nn.Dropout(p=0.3, inplace=True),
nn.Linear(in_features=1408, out_features=num_classes),
)
return model, transformsOverwriting demo/model.py
In [34]:
%%writefile demo/app.py
import gradio as gr
import torch
from model import create_effnetb2_model
from timeit import default_timer as timer
# Setup class names
class_names = ["pizza", "steak", "sushi"]
# Create model
model, transforms = create_effnetb2_model(
num_classes=3,
)
# Load saved weights
model.load_state_dict(
torch.load(
f="../models/09_pretrained_effnetb2_feature_extractor_pizza_steak_sushi_20_percent.pth",
map_location=torch.device("cpu"), # load to CPU
)
)
# Create prediction code
def predict(img):
start_time = timer()
img = transforms(img).unsqueeze(0)
model.eval()
with torch.inference_mode():
pred_probs = torch.softmax(model(img), dim=1)
pred_labels_and_probs = {
class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))
}
pred_time = round(timer() - start_time, 5)
return pred_labels_and_probs, pred_time
# Create Gradio app
title = "FoodVision Mini 🍕🥩🍣"
description = "An EfficientNetB2 feature extractor computer vision model to classify images of food as pizza, steak or sushi."
article = "Created at [09. PyTorch Model Deployment](https://www.learnpytorch.io/09_pytorch_model_deployment/)."
example_dir = "demo/examples"
demo = gr.Interface(
fn=predict,
inputs=gr.Image(type="pil"),
outputs=[
gr.Label(num_top_classes=3, label="Predictions"),
gr.Number(label="Prediction time (s)"),
],
# examples="demo/foodvision_mini/examples",
interpretation="default",
title=title,
description=description,
article=article,
)
demo.launch()
Overwriting demo/app.py
In [74]:
effnetb2_food101, effnetb2_transforms = create_effnetb2_model(num_classes=101)
train_transforms = torchvision.transforms.Compose([
torchvision.transforms.TrivialAugmentWide(),
effnetb2_transforms,
])In [75]:
effnetb2_transformsOut [75]:
ImageClassification(
crop_size=[288]
resize_size=[288]
mean=[0.485, 0.456, 0.406]
std=[0.229, 0.224, 0.225]
interpolation=InterpolationMode.BICUBIC
)In [76]:
from torchvision import datasets
from torchvision import transforms
# Setup data directory
import pathlib
data_dir = pathlib.Path("data")
# Get training data
train_data = datasets.Food101(root=data_dir,
split="train",
transform=train_transforms,
download=True)
# Get testing data
test_data = datasets.Food101(root=data_dir,
split="test",
transform=effnetb2_transforms,
download=True)
# Get class names
food101_class_names = train_data.classes
food101_class_names[:10]Out [76]:
['apple_pie', 'baby_back_ribs', 'baklava', 'beef_carpaccio', 'beef_tartare', 'beet_salad', 'beignets', 'bibimbap', 'bread_pudding', 'breakfast_burrito']
In [77]:
# UPTOHERE: Can split data into random splits with `random_split()`... https://pytorch.org/docs/stable/data.html
# Make 10% split and use for training data
# Do the same with testing data, use these splits to train a bigger model and use that as "FoodVision Big"
def split_dataset(dataset, split_size:float=0.2, seed:int=42):
length_1 = int(len(dataset) * split_size)
length_2 = len(dataset) - length_1
random_split_1, random_split_2 = torch.utils.data.random_split(dataset,
lengths=[length_1, length_2],
generator=torch.manual_seed(seed))
return random_split_1, random_split_2
train_data_food101_20_percent, _ = split_dataset(dataset=train_data,
split_size=0.2)
test_data_food101_20_percent, _ = split_dataset(dataset=test_data,
split_size=0.2)
len(train_data_food101_20_percent), len(test_data_food101_20_percent)Out [77]:
(15150, 5050)
In [78]:
import torch
BATCH_SIZE = 32
train_dataloader_food101_20_percent = torch.utils.data.DataLoader(train_data_food101_20_percent,
batch_size=BATCH_SIZE,
shuffle=True,
num_workers=2)
test_dataloader_food101_20_percent = torch.utils.data.DataLoader(test_data_food101_20_percent,
batch_size=BATCH_SIZE,
shuffle=False,
num_workers=2)In [79]:
from going_modular.going_modular import engine
optimizer = torch.optim.Adam(params=effnetb2_food101.parameters(),
lr=1e-3)
loss_fn = torch.nn.CrossEntropyLoss(label_smoothing=0.1) # throw in a little label smoothing because so many classes
# Want to beat original Food101 paper with 20% of data,
# see paper here: https://data.vision.ee.ethz.ch/cvl/datasets_extra/food-101/static/bossard_eccv14_food-101.pdf
# need 56.40% acc on test dataset
set_seeds()
effnetb2_food101_results = engine.train(model=effnetb2_food101,
train_dataloader=train_dataloader_food101_20_percent,
test_dataloader=test_dataloader_food101_20_percent,
optimizer=optimizer,
loss_fn=loss_fn,
epochs=5,
device=device)0%| | 0/5 [00:00<?, ?it/s]
Epoch: 1 | train_loss: 3.6411 | train_acc: 0.2814 | test_loss: 2.7810 | test_acc: 0.4947 Epoch: 2 | train_loss: 2.8608 | train_acc: 0.4421 | test_loss: 2.4720 | test_acc: 0.5355 Epoch: 3 | train_loss: 2.6546 | train_acc: 0.4862 | test_loss: 2.3634 | test_acc: 0.5612 Epoch: 4 | train_loss: 2.5434 | train_acc: 0.5125 | test_loss: 2.3020 | test_acc: 0.5765 Epoch: 5 | train_loss: 2.4951 | train_acc: 0.5236 | test_loss: 2.2794 | test_acc: 0.5796
In [80]:
plot_loss_curves(effnetb2_food101_results)In [ ]:
# UPTOHERE: create a Gradio app similar to FoodVision Mini but for FoodVision BigIn [ ]:
effnetb2_scripted = torch.jit.script(effnetb2)
vit_scripted = torch.jit.script(vit)
# effnetb2_scriptedIn [ ]: