diff --git a/09_pytorch_model_deployment.ipynb b/09_pytorch_model_deployment.ipynb
index 9ad4117..2050434 100644
--- a/09_pytorch_model_deployment.ipynb
+++ b/09_pytorch_model_deployment.ipynb
@@ -274,8 +274,10 @@
"\n",
"So our goals are:\n",
"\n",
- "1. **Speed** - A model that can classify an image at ~30FPS (0.03 seconds per image).\n",
- "2. **Performance** - A model that performs at 95%+ accuracy.\n",
+ "1. **Performance** - A model that performs at 95%+ accuracy.\n",
+ "2. **Speed** - A model that can classify an image at ~30FPS (0.03 seconds inference time per image).\n",
+ "\n",
+ "We'll put an emphasis on speed, meaning, we'd prefer a model performing at 90%+ accuracy at ~30FPS than a model performing 95%+ accuracy at 10FPS.\n",
"\n",
"To try and achieve these results, let's bring in our best performing models from the previous sections: \n",
"\n",
@@ -842,6 +844,13 @@
"effnetb2_stats"
]
},
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Epic! Looks like our EffNetB2 model is performing at over 95% accuracy! Criteria number 1: perform at 95%+ accuracy, tick!"
+ ]
+ },
{
"cell_type": "markdown",
"metadata": {},
@@ -1236,7 +1245,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Hmmm, how does the ViT feature extractor model size compare to our EffNetB2 model size?\n",
+ "Hmm, how does the ViT feature extractor model size compare to our EffNetB2 model size?\n",
"\n",
"We'll find this out shortly when we compare all of our model's characteristics."
]
@@ -1247,7 +1256,9 @@
"source": [
"### TK - Collecting ViT stats\n",
"\n",
- "UPTOHERE: collecting stats and comparing models... "
+ "Let's put together all of our ViT model statistics.\n",
+ "\n",
+ "We saw it in the summary output above but we'll calculate its total number of parameters. "
]
},
{
@@ -1272,9 +1283,20 @@
"vit_total_params"
]
},
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Woah, that looks like a fair bit more than our EffNetB2!\n",
+ "\n",
+ "> **Note:** A larger number of parameters (or weights/patterns) generally means a model has a higher *capacity* to learn, whether it actually uses this extra capacity is another story. In light of this, our EffNetB2 model has 7,705,221 parameters where as our ViT model has 85,800,963 (11.1x more) so we could assume that our ViT model has more of a capacity to learn, if given more data (more opportunities to learn). However, this larger capacity to learn ofen comes with an increased model filesize and a longer time to perform inference.\n",
+ "\n",
+ "Now let's create a dictionary with some important characteristics of our ViT model."
+ ]
+ },
{
"cell_type": "code",
- "execution_count": 30,
+ "execution_count": 105,
"metadata": {},
"outputs": [
{
@@ -1286,104 +1308,229 @@
" 'model_size (MB)': 327}"
]
},
- "execution_count": 30,
+ "execution_count": 105,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
+ "# Create ViT statistics dictionary\n",
"vit_stats = {\"test_loss\": vit_results[\"test_loss\"][-1],\n",
" \"test_acc\": vit_results[\"test_acc\"][-1],\n",
" \"number_of_parameters\": vit_total_params,\n",
" \"model_size (MB)\": pretrained_vit_model_size}\n",
+ "\n",
"vit_stats"
]
},
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Nice! Looks like our ViT model achieves over 95% accuracy too."
+ ]
+ },
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## TK - Making predictions with our trained models and timing them\n",
"\n",
- "* TK - want FoodVision Mini to be deployed and able to make predictions *fast*... real-time is good (e.g. 30 fps)\n",
- "* TK - make predictions on the CPU because might not have access to a GPU"
+ "We've got a couple of trained models, both performing pretty well.\n",
+ "\n",
+ "Now how about we test them out doing what we'd like them to do?\n",
+ "\n",
+ "As in, let's see how they go making predictions (performing inference).\n",
+ "\n",
+ "We know both of our models are performing at over 95% accuracy, but how fast are they?\n",
+ "\n",
+ "Ideally, if we're deploying our FoodVision Mini model to a mobile device so people can take photos of their food and identify it, we'd like the predictions to happen at real-time (~30 frames per second).\n",
+ "\n",
+ "That's why our second criteria is: a fast model.\n",
+ "\n",
+ "To find out how long each of our models take to performance inference, let's create a function called `pred_and_store()` to iterate over each of the test dataset images one by one and perform a prediction. \n",
+ "\n",
+ "We'll time each of the predictions as well as store the results in a common prediction format: a list of dictionaries (where each single prediction is its own dictionary). \n",
+ "\n",
+ "> **Note:** We time the predictions one by one rather than by batch because when our model is deployed, it will likely only be making a prediction on one image at a time. As in, someone takes a photo and our model predicts on that single image.\n",
+ "\n",
+ "Since we'd like to make predictions across all the images in the test set, let's first get a list of all of the test image paths so we can iterate over them. \n",
+ "\n",
+ "To do so, we'll use Python's `pathlib.Path(\"target_dir\").glob(\"*/*.jpg\"))` to find all of the filepaths in a target directory with the extension `.jpg` (all of our test images)."
]
},
{
"cell_type": "code",
- "execution_count": 31,
+ "execution_count": 118,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "[INFO] Finding all filepaths ending with '.jpg' in directory: data/pizza_steak_sushi_20_percent/test\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "[PosixPath('data/pizza_steak_sushi_20_percent/test/steak/831681.jpg'),\n",
+ " PosixPath('data/pizza_steak_sushi_20_percent/test/steak/3100563.jpg'),\n",
+ " PosixPath('data/pizza_steak_sushi_20_percent/test/steak/2752603.jpg'),\n",
+ " PosixPath('data/pizza_steak_sushi_20_percent/test/steak/39461.jpg'),\n",
+ " PosixPath('data/pizza_steak_sushi_20_percent/test/steak/730464.jpg')]"
+ ]
+ },
+ "execution_count": 118,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "from pathlib import Path\n",
+ "\n",
+ "# Get all test data paths\n",
+ "print(f\"[INFO] Finding all filepaths ending with '.jpg' in directory: {test_dir}\")\n",
+ "test_data_paths = list(Path(test_dir).glob(\"*/*.jpg\"))\n",
+ "test_data_paths[:5]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### TK - Creating a function to make predictions across the test dataset\n",
+ "\n",
+ "Now we've got a list of our test image paths, let's get to work on our `pred_and_store()` function:\n",
+ "\n",
+ "1. Create a function that takes a list of paths, a trained PyTorch model, a series of transforms (to prepare images), a list of target class names and a target device.\n",
+ "2. Create an empty list to store prediction dictionaries (we want the function to return a list of dictionaries, one for each prediction).\n",
+ "3. Loop through the target input paths (steps 4-14 will happen inside the loop).\n",
+ "4. Create an empty dictionary for each iteration in the loop to store prediction values per sample.\n",
+ "5. Get the sample path and ground truth class name (we can do this by infering the class from the path).\n",
+ "6. Start the prediction timer using Python's `timeit.default_timer`.\n",
+ "7. Open the image using `PIL.Image.open(path)`.\n",
+ "8. Transform the image so it's capable of being using with the target model as well as add a batch dimension and send the image to the target device.\n",
+ "9. Prepare the model for inference by sending it to the target device and turning on `eval()` mode.\n",
+ "10. Turn on `torch.inference_mode()` and pass the target transformed image to the model and calculate the prediction probability using `torch.softmax()` and the target label using `torch.argmax()`.\n",
+ "11. Add the prediction probability and prediction class to the prediction dictionary created in step 4. Also make sure the prediction probability is on the CPU so it can be used with non-GPU libraries such as NumPy and pandas for later inspection.\n",
+ "12. End the prediction timer started in step 6 and add the time to the prediction dictionary created in step 4.\n",
+ "13. See if the predicted class matches the ground truth class from step 5 and add the result to the prediction dictionary created in step 4.\n",
+ "14. Append the updated prediction dictionary to the empty list of predictions created in step 2.\n",
+ "15. Return the list of prediction dictionaries.\n",
+ "\n",
+ "A bunch of steps, but nothing we can't handle!\n",
+ "\n",
+ "Let's do it."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 139,
"metadata": {},
"outputs": [],
"source": [
- "from tqdm.auto import tqdm\n",
- "from pathlib import Path\n",
+ "import torch\n",
+ "\n",
"from PIL import Image\n",
"from timeit import default_timer as timer \n",
+ "from tqdm.auto import tqdm\n",
+ "from typing import List, Dict\n",
"\n",
- "# Get all test data paths\n",
- "test_data_paths = list(Path(test_dir).glob(\"*/*.jpg\"))\n",
- "test_labels = [path.parent.stem for path in test_data_paths]\n",
- "\n",
- "# Create a function to return a list of dictionaries with sample, label, prediction, pred prob\n",
- "def pred_and_store(test_paths, model, transform, class_names, device):\n",
- " test_pred_list = []\n",
- " for path in tqdm(test_paths):\n",
- " # Create empty dict to store info for each sample\n",
+ "# 1. Create a function to return a list of dictionaries with sample, truth label, prediction, prediction probability and prediction time\n",
+ "def pred_and_store(paths: List[pathlib.Path], \n",
+ " model: torch.nn.Module,\n",
+ " transform: torchvision.transforms, \n",
+ " class_names: List[str], \n",
+ " device: str = \"cuda\" if torch.cuda.is_available() else \"cpu\") -> List[Dict]:\n",
+ " \n",
+ " # 2. Create an empty list to store prediction dictionaires\n",
+ " pred_list = []\n",
+ " \n",
+ " # 3. Loop through target paths\n",
+ " for path in tqdm(paths):\n",
+ " \n",
+ " # 4. Create empty dictionary to store prediction information for each sample\n",
" pred_dict = {}\n",
"\n",
- " # Get sample path\n",
+ " # 5. Get the sample path and ground truth class name\n",
" pred_dict[\"image_path\"] = path\n",
- "\n",
- " # Get class name\n",
" class_name = path.parent.stem\n",
" pred_dict[\"class_name\"] = class_name\n",
- "\n",
- " # Get prediction and prediction probability\n",
+ " \n",
+ " # 6. Start the prediction timer\n",
" start_time = timer()\n",
- " img = Image.open(path) # open image\n",
- " transformed_image = transform(img).unsqueeze(0) # transform image and add batch dimension\n",
+ " \n",
+ " # 7. Open image path\n",
+ " img = Image.open(path)\n",
+ " \n",
+ " # 8. Transform the image, add batch dimension and put image on target device\n",
+ " transformed_image = transform(img).unsqueeze(0).to(device) \n",
+ " \n",
+ " # 9. Prepare model for inference by sending it to target device and turning on eval() mode\n",
" model.to(device)\n",
" model.eval()\n",
+ " \n",
+ " # 10. Get prediction probability, predicition label and prediction class\n",
" with torch.inference_mode():\n",
- " pred_logit = model(transformed_image.to(device))\n",
- " pred_prob = torch.softmax(pred_logit, dim=1)\n",
- " pred_label = torch.argmax(pred_prob, dim=1)\n",
- " pred_class = class_names[pred_label.cpu()]\n",
+ " pred_logit = model(transformed_image) # perform inference on target sample \n",
+ " pred_prob = torch.softmax(pred_logit, dim=1) # turn logits into prediction probabilities\n",
+ " pred_label = torch.argmax(pred_prob, dim=1) # turn prediction probabilities into prediction label\n",
+ " pred_class = class_names[pred_label.cpu()] # hardcode prediction class to be on CPU\n",
"\n",
- " # Make sure things in the dictionary are back on the CPU \n",
- " pred_dict[\"pred_prob\"] = pred_prob.unsqueeze(0).max().cpu().item()\n",
+ " # 11. Make sure things in the dictionary are on CPU (required for inspecting predictions later on) \n",
+ " pred_dict[\"pred_prob\"] = round(pred_prob.unsqueeze(0).max().cpu().item(), 4)\n",
" pred_dict[\"pred_class\"] = pred_class\n",
" \n",
- " # Calculate time per pred\n",
+ " # 12. End the timer and calculate time per pred\n",
" end_time = timer()\n",
" pred_dict[\"time_for_pred\"] = round(end_time-start_time, 4)\n",
"\n",
- " # Does the pred match the true label?\n",
+ " # 13. Does the pred match the true label?\n",
" pred_dict[\"correct\"] = class_name == pred_class\n",
"\n",
- " # print(pred_dict)\n",
- " # Add the dictionary to the list of preds\n",
- " test_pred_list.append(pred_dict)\n",
- "\n",
- " return test_pred_list"
+ " # 14. Add the dictionary to the list of preds\n",
+ " pred_list.append(pred_dict)\n",
+ " \n",
+ " # 15. Return list of prediction dictionaries\n",
+ " return pred_list"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "### TK - Make and time predictions with EffNetB2"
+ "Ho, ho! \n",
+ "\n",
+ "What a good looking function!\n",
+ "\n",
+ "And you know what, since our `pred_and_store()` is a pretty good utility function for making and storing predictions, it could be stored to [`going_modular.going_modular.predictions.py`](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/going_modular/going_modular/predictions.py) for later use. That might be an extension you'd like to try, check out [05. PyTorch Going Modular](https://www.learnpytorch.io/05_pytorch_going_modular/) for ideas."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### TK - Making and timing predictions with EffNetB2\n",
+ "\n",
+ "Time to test out our `pred_and_store()` function!\n",
+ "\n",
+ "Let's start by using it to make predictions across the test dataset with our EffNetB2 model, paying attention to two details:\n",
+ "\n",
+ "1. **Device** - We'll hard code the `device` parameter to use `\"cpu\"` because when we deploy our model, we won't always have access to a `\"cuda\"` (GPU) device.\n",
+ " * Making the predictions on CPU will be a good indicator of speed of inference too because generally predictions on CPU devices are slower than GPU devices.\n",
+ "2. **Transforms** - We'll also be sure to set the `transform` parameter to `effnetb2_transforms` to make sure the images are opened and transformed in the same way our `effnetb2` model has been trained on. "
]
},
{
"cell_type": "code",
- "execution_count": 32,
+ "execution_count": 140,
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
- "model_id": "f7dd70d57a014b579f5224ed02c6353f",
+ "model_id": "0c33cef111174da589c212fe6dbf1e90",
"version_major": 2,
"version_minor": 0
},
@@ -1393,128 +1540,172 @@
},
"metadata": {},
"output_type": "display_data"
- },
- {
- "data": {
- "text/plain": [
- "[{'image_path': PosixPath('data/pizza_steak_sushi_20_percent/test/steak/831681.jpg'),\n",
- " 'class_name': 'steak',\n",
- " 'pred_prob': 0.9293267726898193,\n",
- " 'pred_class': 'steak',\n",
- " 'time_for_pred': 0.0553,\n",
- " 'correct': True},\n",
- " {'image_path': PosixPath('data/pizza_steak_sushi_20_percent/test/steak/3100563.jpg'),\n",
- " 'class_name': 'steak',\n",
- " 'pred_prob': 0.9533632397651672,\n",
- " 'pred_class': 'steak',\n",
- " 'time_for_pred': 0.0305,\n",
- " 'correct': True},\n",
- " {'image_path': PosixPath('data/pizza_steak_sushi_20_percent/test/steak/2752603.jpg'),\n",
- " 'class_name': 'steak',\n",
- " 'pred_prob': 0.7531499266624451,\n",
- " 'pred_class': 'steak',\n",
- " 'time_for_pred': 0.0297,\n",
- " 'correct': True}]"
- ]
- },
- "execution_count": 32,
- "metadata": {},
- "output_type": "execute_result"
}
],
"source": [
- "effnetb2_test_pred_dicts = pred_and_store(test_paths=test_data_paths,\n",
+ "# Make predictions across test dataset with EffNetB2\n",
+ "effnetb2_test_pred_dicts = pred_and_store(paths=test_data_paths,\n",
" model=effnetb2,\n",
" transform=effnetb2_transforms,\n",
" class_names=class_names,\n",
- " device=\"cpu\")\n",
- "\n",
- "effnetb2_test_pred_dicts[:3]"
+ " device=\"cpu\") # make predictions on CPU "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "### TK - Make and time predictions with ViT "
+ "Nice! Look at those predictions fly!\n",
+ "\n",
+ "Let's inspect the first couple and see what they look like."
]
},
{
"cell_type": "code",
- "execution_count": 33,
+ "execution_count": 141,
"metadata": {},
"outputs": [
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "77df9b8cca754860a4d998a6aaad3713",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- " 0%| | 0/150 [00:00, ?it/s]"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
{
"data": {
"text/plain": [
"[{'image_path': PosixPath('data/pizza_steak_sushi_20_percent/test/steak/831681.jpg'),\n",
" 'class_name': 'steak',\n",
- " 'pred_prob': 0.9932767748832703,\n",
+ " 'pred_prob': 0.9293,\n",
" 'pred_class': 'steak',\n",
- " 'time_for_pred': 0.1276,\n",
+ " 'time_for_pred': 0.0387,\n",
" 'correct': True},\n",
" {'image_path': PosixPath('data/pizza_steak_sushi_20_percent/test/steak/3100563.jpg'),\n",
" 'class_name': 'steak',\n",
- " 'pred_prob': 0.9893474578857422,\n",
+ " 'pred_prob': 0.9534,\n",
" 'pred_class': 'steak',\n",
- " 'time_for_pred': 0.0649,\n",
- " 'correct': True},\n",
- " {'image_path': PosixPath('data/pizza_steak_sushi_20_percent/test/steak/2752603.jpg'),\n",
- " 'class_name': 'steak',\n",
- " 'pred_prob': 0.997147262096405,\n",
- " 'pred_class': 'steak',\n",
- " 'time_for_pred': 0.0642,\n",
+ " 'time_for_pred': 0.0387,\n",
" 'correct': True}]"
]
},
- "execution_count": 33,
+ "execution_count": 141,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
- "vit_test_pred_dicts = pred_and_store(test_paths=test_data_paths,\n",
- " model=vit,\n",
- " transform=vit_transforms,\n",
- " class_names=class_names,\n",
- " device=\"cpu\")\n",
- "\n",
- "vit_test_pred_dicts[:3]"
+ "# Inspect the first 2 prediction dictionaries\n",
+ "effnetb2_test_pred_dicts[:2]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "## TK - Compare model results, prediction times and size"
+ "Woohoo!\n",
+ "\n",
+ "It looks like our `pred_and_store()` function worked nicely.\n",
+ "\n",
+ "Thanks to our list of dictionaries data structure, we've got plenty of useful information we can further inspect.\n",
+ "\n",
+ "To do so, let's turn our list of dictionaries into a pandas DataFrame."
]
},
{
"cell_type": "code",
- "execution_count": 34,
+ "execution_count": 142,
"metadata": {},
"outputs": [
{
"data": {
+ "text/html": [
+ "
\n",
+ "\n",
+ "
\n",
+ " \n",
+ " \n",
+ " | \n",
+ " image_path | \n",
+ " class_name | \n",
+ " pred_prob | \n",
+ " pred_class | \n",
+ " time_for_pred | \n",
+ " correct | \n",
+ "
\n",
+ " \n",
+ " \n",
+ " \n",
+ " | 0 | \n",
+ " data/pizza_steak_sushi_20_percent/test/steak/8... | \n",
+ " steak | \n",
+ " 0.9293 | \n",
+ " steak | \n",
+ " 0.0387 | \n",
+ " True | \n",
+ "
\n",
+ " \n",
+ " | 1 | \n",
+ " data/pizza_steak_sushi_20_percent/test/steak/3... | \n",
+ " steak | \n",
+ " 0.9534 | \n",
+ " steak | \n",
+ " 0.0387 | \n",
+ " True | \n",
+ "
\n",
+ " \n",
+ " | 2 | \n",
+ " data/pizza_steak_sushi_20_percent/test/steak/2... | \n",
+ " steak | \n",
+ " 0.7531 | \n",
+ " steak | \n",
+ " 0.0309 | \n",
+ " True | \n",
+ "
\n",
+ " \n",
+ " | 3 | \n",
+ " data/pizza_steak_sushi_20_percent/test/steak/3... | \n",
+ " steak | \n",
+ " 0.5935 | \n",
+ " steak | \n",
+ " 0.0313 | \n",
+ " True | \n",
+ "
\n",
+ " \n",
+ " | 4 | \n",
+ " data/pizza_steak_sushi_20_percent/test/steak/7... | \n",
+ " steak | \n",
+ " 0.8959 | \n",
+ " steak | \n",
+ " 0.0318 | \n",
+ " True | \n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
"
+ ],
"text/plain": [
- "0.03083866666666667"
+ " image_path class_name pred_prob \\\n",
+ "0 data/pizza_steak_sushi_20_percent/test/steak/8... steak 0.9293 \n",
+ "1 data/pizza_steak_sushi_20_percent/test/steak/3... steak 0.9534 \n",
+ "2 data/pizza_steak_sushi_20_percent/test/steak/2... steak 0.7531 \n",
+ "3 data/pizza_steak_sushi_20_percent/test/steak/3... steak 0.5935 \n",
+ "4 data/pizza_steak_sushi_20_percent/test/steak/7... steak 0.8959 \n",
+ "\n",
+ " pred_class time_for_pred correct \n",
+ "0 steak 0.0387 True \n",
+ "1 steak 0.0387 True \n",
+ "2 steak 0.0309 True \n",
+ "3 steak 0.0313 True \n",
+ "4 steak 0.0318 True "
]
},
- "execution_count": 34,
+ "execution_count": 142,
"metadata": {},
"output_type": "execute_result"
}
@@ -1523,13 +1714,85 @@
"# Turn the test_pred_dicts into a DataFrame\n",
"import pandas as pd\n",
"effnetb2_test_pred_df = pd.DataFrame(effnetb2_test_pred_dicts)\n",
- "effnetb2_average_time_per_pred = effnetb2_test_pred_df.time_for_pred.mean()\n",
- "effnetb2_average_time_per_pred"
+ "effnetb2_test_pred_df.head()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Beautiful!\n",
+ "\n",
+ "Look how easily those prediction dictionaries turn into a structured format we can perform analysis on.\n",
+ "\n",
+ "Such as finding how many predictions our EffNetB2 model got wrong..."
]
},
{
"cell_type": "code",
- "execution_count": 35,
+ "execution_count": 143,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True 145\n",
+ "False 5\n",
+ "Name: correct, dtype: int64"
+ ]
+ },
+ "execution_count": 143,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# Check number of correct predictions\n",
+ "effnetb2_test_pred_df.correct.value_counts()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Five wrong predictions out of 150 total, not bad!\n",
+ "\n",
+ "And how about the average prediction time?"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 148,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "EffNetB2 average time per prediction: 0.0316 seconds\n"
+ ]
+ }
+ ],
+ "source": [
+ "# Find the average time per prediction \n",
+ "effnetb2_average_time_per_pred = round(effnetb2_test_pred_df.time_for_pred.mean(), 4)\n",
+ "print(f\"EffNetB2 average time per prediction: {effnetb2_average_time_per_pred} seconds\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Hmm, how does that average prediction time live up to our criteria of our model performing at real-time (~30FPS or 0.03 seconds per prediction)?\n",
+ "\n",
+ "> **Note:** Prediction times will be different across different hardware types (e.g. a local Intel i9 vs Google Colab CPU). The better and faster the hardware, generally, the faster the prediction. For example, on my local deep learning PC with an Intel i9 chip, my average prediction time with EffNetB2 is around 0.031 seconds (just under real-time). However, on Google Colab (I'm not sure what CPU hardware Colab uses but it looks like it might be an [Intel(R) Xeon(R)](https://stackoverflow.com/questions/47805170/whats-the-hardware-spec-for-google-colaboratory)), my average prediction time with EffNetB2 is about 0.1396 seconds (3-4x slower).\n",
+ "\n",
+ "Let's add our EffNetB2 average time per prediction to our `effnetb2_stats` dictionary."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 149,
"metadata": {},
"outputs": [
{
@@ -1539,31 +1802,198 @@
" 'test_acc': 0.96875,\n",
" 'number_of_parameters': 7705221,\n",
" 'model_size (MB)': 29,\n",
- " 'time_per_pred_cpu': 0.03083866666666667}"
+ " 'time_per_pred_cpu': 0.0316}"
]
},
- "execution_count": 35,
+ "execution_count": 149,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
+ "# Add EffNetB2 average prediction time to stats dictionary \n",
"effnetb2_stats[\"time_per_pred_cpu\"] = effnetb2_average_time_per_pred\n",
"effnetb2_stats"
]
},
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### TK - Making and timing predictions with ViT \n",
+ "\n",
+ "UPTOHERE: make predictions with ViT and inspect them in the same way as EffNetB2 "
+ ]
+ },
{
"cell_type": "code",
- "execution_count": 36,
+ "execution_count": 154,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "application/vnd.jupyter.widget-view+json": {
+ "model_id": "a3038b093cf44b43a711de9bce92461b",
+ "version_major": 2,
+ "version_minor": 0
+ },
+ "text/plain": [
+ " 0%| | 0/150 [00:00, ?it/s]"
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "vit_test_pred_dicts = pred_and_store(paths=test_data_paths,\n",
+ " model=vit,\n",
+ " transform=vit_transforms,\n",
+ " class_names=class_names,\n",
+ " device=\"cpu\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 155,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
- "0.06575066666666665"
+ "[{'image_path': PosixPath('data/pizza_steak_sushi_20_percent/test/steak/831681.jpg'),\n",
+ " 'class_name': 'steak',\n",
+ " 'pred_prob': 0.9933,\n",
+ " 'pred_class': 'steak',\n",
+ " 'time_for_pred': 0.0663,\n",
+ " 'correct': True},\n",
+ " {'image_path': PosixPath('data/pizza_steak_sushi_20_percent/test/steak/3100563.jpg'),\n",
+ " 'class_name': 'steak',\n",
+ " 'pred_prob': 0.9893,\n",
+ " 'pred_class': 'steak',\n",
+ " 'time_for_pred': 0.0662,\n",
+ " 'correct': True}]"
]
},
- "execution_count": 36,
+ "execution_count": 155,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "vit_test_pred_dicts[:2]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 151,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# TK - turn pred dict into pred df (show why list of dictionaries is a good structure for evaluation)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 153,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "\n",
+ "\n",
+ "
\n",
+ " \n",
+ " \n",
+ " | \n",
+ " image_path | \n",
+ " class_name | \n",
+ " pred_prob | \n",
+ " pred_class | \n",
+ " time_for_pred | \n",
+ " correct | \n",
+ "
\n",
+ " \n",
+ " \n",
+ " \n",
+ " | 0 | \n",
+ " data/pizza_steak_sushi_20_percent/test/steak/8... | \n",
+ " steak | \n",
+ " 0.9933 | \n",
+ " steak | \n",
+ " 0.1021 | \n",
+ " True | \n",
+ "
\n",
+ " \n",
+ " | 1 | \n",
+ " data/pizza_steak_sushi_20_percent/test/steak/3... | \n",
+ " steak | \n",
+ " 0.9893 | \n",
+ " steak | \n",
+ " 0.1015 | \n",
+ " True | \n",
+ "
\n",
+ " \n",
+ " | 2 | \n",
+ " data/pizza_steak_sushi_20_percent/test/steak/2... | \n",
+ " steak | \n",
+ " 0.9971 | \n",
+ " steak | \n",
+ " 0.0971 | \n",
+ " True | \n",
+ "
\n",
+ " \n",
+ " | 3 | \n",
+ " data/pizza_steak_sushi_20_percent/test/steak/3... | \n",
+ " steak | \n",
+ " 0.7685 | \n",
+ " steak | \n",
+ " 0.0984 | \n",
+ " True | \n",
+ "
\n",
+ " \n",
+ " | 4 | \n",
+ " data/pizza_steak_sushi_20_percent/test/steak/7... | \n",
+ " steak | \n",
+ " 0.9499 | \n",
+ " steak | \n",
+ " 0.0986 | \n",
+ " True | \n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
"
+ ],
+ "text/plain": [
+ " image_path class_name pred_prob \\\n",
+ "0 data/pizza_steak_sushi_20_percent/test/steak/8... steak 0.9933 \n",
+ "1 data/pizza_steak_sushi_20_percent/test/steak/3... steak 0.9893 \n",
+ "2 data/pizza_steak_sushi_20_percent/test/steak/2... steak 0.9971 \n",
+ "3 data/pizza_steak_sushi_20_percent/test/steak/3... steak 0.7685 \n",
+ "4 data/pizza_steak_sushi_20_percent/test/steak/7... steak 0.9499 \n",
+ "\n",
+ " pred_class time_for_pred correct \n",
+ "0 steak 0.1021 True \n",
+ "1 steak 0.1015 True \n",
+ "2 steak 0.0971 True \n",
+ "3 steak 0.0984 True \n",
+ "4 steak 0.0986 True "
+ ]
+ },
+ "execution_count": 153,
"metadata": {},
"output_type": "execute_result"
}
@@ -1572,13 +2002,22 @@
"# Turn the test_pred_dicts into a DataFrame\n",
"import pandas as pd\n",
"vit_test_pred_df = pd.DataFrame(vit_test_pred_dicts)\n",
- "vit_average_time_per_pred = vit_test_pred_df.time_for_pred.mean()\n",
+ "vit_test_pred_df.head()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "vit_average_time_per_pred = round(vit_test_pred_df.time_for_pred.mean(), 4)\n",
"vit_average_time_per_pred"
]
},
{
"cell_type": "code",
- "execution_count": 37,
+ "execution_count": 130,
"metadata": {},
"outputs": [
{
@@ -1588,10 +2027,10 @@
" 'test_acc': 0.984659090909091,\n",
" 'number_of_parameters': 85800963,\n",
" 'model_size (MB)': 327,\n",
- " 'time_per_pred_cpu': 0.06575066666666665}"
+ " 'time_per_pred_cpu': 0.0656}"
]
},
- "execution_count": 37,
+ "execution_count": 130,
"metadata": {},
"output_type": "execute_result"
}
@@ -1601,6 +2040,13 @@
"vit_stats"
]
},
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## TK - Comparing model results, prediction times and size"
+ ]
+ },
{
"cell_type": "code",
"execution_count": 38,
@@ -1687,6 +2133,14 @@
"df"
]
},
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "* TK - plot, accuracy vs time per pred (speed vs accuracy tradeoff graph)\n",
+ "* TK - add in prediction times on Google Colab (could save my prediction times to a CSV and then import them both and compare them)"
+ ]
+ },
{
"cell_type": "code",
"execution_count": 39,
@@ -1712,6 +2166,13 @@
"df.loc[\"vit\"] / df.loc[\"effnetb2\"]"
]
},
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "> TK **Note:** Prediction times will be different across different hardware types (e.g. Intel i9 vs Google Colab CPU)"
+ ]
+ },
{
"cell_type": "markdown",
"metadata": {},
@@ -2307,7 +2768,7 @@
}
],
"source": [
- "# UPTOHERE: Can split data into random splits with `random_split()`... https://pytorch.org/docs/stable/data.html\n",
+ "# TK - Can split data into random splits with `random_split()`... https://pytorch.org/docs/stable/data.html\n",
"# Make 10% split and use for training data \n",
"# Do the same with testing data, use these splits to train a bigger model and use that as \"FoodVision Big\"\n",
"def split_dataset(dataset, split_size:float=0.2, seed:int=42):\n",
@@ -2837,6 +3298,8 @@
"* Compare the model's prediction times on GPU vs CPU - does this close the gap?\n",
"* ViT seems to have more learning capacity than EffNetB2, how does it go on the larger Food101 dataset? - train for 5 epochs\n",
" * Use same training setup as we've done for the EffNetB2 model\n",
+ "* Use the `pred_and_store()` function to predict across Food101 data and find the \"most wrong\"\n",
+ " * Could put this function into `predictions.py`\n",
"\n",
"## TK - Extra-curriculum\n",
"\n",