diff --git a/going_modular/05_pytorch_going_modular_script_mode.ipynb b/going_modular/05_pytorch_going_modular_script_mode.ipynb new file mode 100644 index 0000000..96a6713 --- /dev/null +++ b/going_modular/05_pytorch_going_modular_script_mode.ipynb @@ -0,0 +1,2140 @@ +{ + "nbformat": 4, + "nbformat_minor": 0, + "metadata": { + "colab": { + "name": "05_pytorch_going_modular_script_mode.ipynb", + "provenance": [], + "collapsed_sections": [], + "authorship_tag": "ABX9TyOtemTdOJk4sI2quxZNvUuS", + "include_colab_link": true + }, + "kernelspec": { + "name": "python3", + "display_name": "Python 3" + }, + "language_info": { + "name": "python" + }, + "widgets": { + "application/vnd.jupyter.widget-state+json": { + "84317b054c244ee4b1bed7b2f86660b7": { + "model_module": "@jupyter-widgets/controls", + "model_name": "HBoxModel", + "model_module_version": "1.5.0", + "state": { + "_dom_classes": [], + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "HBoxModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/controls", + "_view_module_version": "1.5.0", + "_view_name": "HBoxView", + "box_style": "", + "children": [ + "IPY_MODEL_a0a72aed7e2743f8a95c6af3b6e4a457", + "IPY_MODEL_b517f855551f4c53969677161952a1ac", + "IPY_MODEL_4d780e75e5d24241b1f6c0203a8bd73e" + ], + "layout": "IPY_MODEL_a0caf8f4760c4935b5b9be86566ee8e0" + } + }, + "a0a72aed7e2743f8a95c6af3b6e4a457": { + "model_module": "@jupyter-widgets/controls", + "model_name": "HTMLModel", + "model_module_version": "1.5.0", + "state": { + "_dom_classes": [], + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "HTMLModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/controls", + "_view_module_version": "1.5.0", + "_view_name": "HTMLView", + "description": "", + "description_tooltip": null, + "layout": "IPY_MODEL_83cf71b79abd4fc5ae9daaac8f586841", + "placeholder": "​", + "style": "IPY_MODEL_3402f79d3df643efbed25c72aac94642", + "value": "100%" + } + }, + "b517f855551f4c53969677161952a1ac": { + "model_module": "@jupyter-widgets/controls", + "model_name": "FloatProgressModel", + "model_module_version": "1.5.0", + "state": { + "_dom_classes": [], + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "FloatProgressModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/controls", + "_view_module_version": "1.5.0", + "_view_name": "ProgressView", + "bar_style": "success", + "description": "", + "description_tooltip": null, + "layout": "IPY_MODEL_1e79615e722f456189e07874d13564d2", + "max": 5, + "min": 0, + "orientation": "horizontal", + "style": "IPY_MODEL_bac27d87b4d54b6cbaf85dd7b7ecdc64", + "value": 5 + } + }, + "4d780e75e5d24241b1f6c0203a8bd73e": { + "model_module": "@jupyter-widgets/controls", + "model_name": "HTMLModel", + "model_module_version": "1.5.0", + "state": { + "_dom_classes": [], + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "HTMLModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/controls", + "_view_module_version": "1.5.0", + "_view_name": "HTMLView", + "description": "", + "description_tooltip": null, + "layout": "IPY_MODEL_f9b7fbae53e84883ac281343bb6a9da9", + "placeholder": "​", + "style": "IPY_MODEL_4bc100911d7d4303b6ab7efb59d3420c", + "value": " 5/5 [00:11<00:00, 2.23s/it]" + } + }, + "a0caf8f4760c4935b5b9be86566ee8e0": { + "model_module": "@jupyter-widgets/base", + "model_name": "LayoutModel", + "model_module_version": "1.2.0", + "state": { + "_model_module": "@jupyter-widgets/base", + "_model_module_version": "1.2.0", + "_model_name": "LayoutModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "LayoutView", + "align_content": null, + "align_items": null, + "align_self": null, + "border": null, + "bottom": null, + "display": null, + "flex": null, + "flex_flow": null, + "grid_area": null, + "grid_auto_columns": null, + "grid_auto_flow": null, + "grid_auto_rows": null, + "grid_column": null, + "grid_gap": null, + "grid_row": null, + "grid_template_areas": null, + "grid_template_columns": null, + "grid_template_rows": null, + "height": null, + "justify_content": null, + "justify_items": null, + "left": null, + "margin": null, + "max_height": null, + "max_width": null, + "min_height": null, + "min_width": null, + "object_fit": null, + "object_position": null, + "order": null, + "overflow": null, + "overflow_x": null, + "overflow_y": null, + "padding": null, + "right": null, + "top": null, + "visibility": null, + "width": null + } + }, + "83cf71b79abd4fc5ae9daaac8f586841": { + "model_module": "@jupyter-widgets/base", + "model_name": "LayoutModel", + "model_module_version": "1.2.0", + "state": { + "_model_module": "@jupyter-widgets/base", + "_model_module_version": "1.2.0", + "_model_name": "LayoutModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "LayoutView", + "align_content": null, + "align_items": null, + "align_self": null, + "border": null, + "bottom": null, + "display": null, + "flex": null, + "flex_flow": null, + "grid_area": null, + "grid_auto_columns": null, + "grid_auto_flow": null, + "grid_auto_rows": null, + "grid_column": null, + "grid_gap": null, + "grid_row": null, + "grid_template_areas": null, + "grid_template_columns": null, + "grid_template_rows": null, + "height": null, + "justify_content": null, + "justify_items": null, + "left": null, + "margin": null, + "max_height": null, + "max_width": null, + "min_height": null, + "min_width": null, + "object_fit": null, + "object_position": null, + "order": null, + "overflow": null, + "overflow_x": null, + "overflow_y": null, + "padding": null, + "right": null, + "top": null, + "visibility": null, + "width": null + } + }, + "3402f79d3df643efbed25c72aac94642": { + "model_module": "@jupyter-widgets/controls", + "model_name": "DescriptionStyleModel", + "model_module_version": "1.5.0", + "state": { + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "DescriptionStyleModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "StyleView", + "description_width": "" + } + }, + "1e79615e722f456189e07874d13564d2": { + "model_module": "@jupyter-widgets/base", + "model_name": "LayoutModel", + "model_module_version": "1.2.0", + "state": { + "_model_module": "@jupyter-widgets/base", + "_model_module_version": "1.2.0", + "_model_name": "LayoutModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "LayoutView", + "align_content": null, + "align_items": null, + "align_self": null, + "border": null, + "bottom": null, + "display": null, + "flex": null, + "flex_flow": null, + "grid_area": null, + "grid_auto_columns": null, + "grid_auto_flow": null, + "grid_auto_rows": null, + "grid_column": null, + "grid_gap": null, + "grid_row": null, + "grid_template_areas": null, + "grid_template_columns": null, + "grid_template_rows": null, + "height": null, + "justify_content": null, + "justify_items": null, + "left": null, + "margin": null, + "max_height": null, + "max_width": null, + "min_height": null, + "min_width": null, + "object_fit": null, + "object_position": null, + "order": null, + "overflow": null, + "overflow_x": null, + "overflow_y": null, + "padding": null, + "right": null, + "top": null, + "visibility": null, + "width": null + } + }, + "bac27d87b4d54b6cbaf85dd7b7ecdc64": { + "model_module": "@jupyter-widgets/controls", + "model_name": "ProgressStyleModel", + "model_module_version": "1.5.0", + "state": { + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "ProgressStyleModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "StyleView", + "bar_color": null, + "description_width": "" + } + }, + "f9b7fbae53e84883ac281343bb6a9da9": { + "model_module": "@jupyter-widgets/base", + "model_name": "LayoutModel", + "model_module_version": "1.2.0", + "state": { + "_model_module": "@jupyter-widgets/base", + "_model_module_version": "1.2.0", + "_model_name": "LayoutModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "LayoutView", + "align_content": null, + "align_items": null, + "align_self": null, + "border": null, + "bottom": null, + "display": null, + "flex": null, + "flex_flow": null, + "grid_area": null, + "grid_auto_columns": null, + "grid_auto_flow": null, + "grid_auto_rows": null, + "grid_column": null, + "grid_gap": null, + "grid_row": null, + "grid_template_areas": null, + "grid_template_columns": null, + "grid_template_rows": null, + "height": null, + "justify_content": null, + "justify_items": null, + "left": null, + "margin": null, + "max_height": null, + "max_width": null, + "min_height": null, + "min_width": null, + "object_fit": null, + "object_position": null, + "order": null, + "overflow": null, + "overflow_x": null, + "overflow_y": null, + "padding": null, + "right": null, + "top": null, + "visibility": null, + "width": null + } + }, + "4bc100911d7d4303b6ab7efb59d3420c": { + "model_module": "@jupyter-widgets/controls", + "model_name": "DescriptionStyleModel", + "model_module_version": "1.5.0", + "state": { + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "DescriptionStyleModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "StyleView", + "description_width": "" + } + } + } + }, + "accelerator": "GPU" + }, + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "id": "view-in-github", + "colab_type": "text" + }, + "source": [ + "\"Open" + ] + }, + { + "cell_type": "markdown", + "source": [ + "# 05. Going Modular (script mode)\n", + "\n", + "* TK - this notebook condenses the code from 04 into a handful of cells.\n", + "* TK - there will another version of this notebook \"script mode\" that turns these handful of cells into a handful of scripts\n", + "\n", + "Turn notebook -> python scripts\n", + "\n", + "Code in this notebook based off code in notebook 04 with minimal changes.\n", + "\n", + "TK - get GPU (for Google Colab)" + ], + "metadata": { + "id": "1M5tsObEa17-" + } + }, + { + "cell_type": "markdown", + "source": [ + "# TK - 0. Creating a folder for storing Python scripts\n", + "\n", + "TK - What is script mode? ... writing code cells but storing them in Python Scripts (you could run these cells as normal but we'll be creating scripts with them)." + ], + "metadata": { + "id": "OW_3D_fOap2I" + } + }, + { + "cell_type": "code", + "source": [ + "import os\n", + "os.makedirs(\"going_modular\", exist_ok=True)" + ], + "metadata": { + "id": "K29qwItveNm9" + }, + "execution_count": 1, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "## TK - 1. Get data\n", + "\n", + "We're going to start by downloading the same data we used in [notebook 04](https://www.learnpytorch.io/04_pytorch_custom_datasets/#1-get-data), the `pizza_steak_sushi` dataset with images of pizza, steak and sushi." + ], + "metadata": { + "id": "1XgXFr97bCsI" + } + }, + { + "cell_type": "code", + "source": [ + "import os\n", + "import requests\n", + "import zipfile\n", + "from pathlib import Path\n", + "\n", + "# Setup path to data folder\n", + "data_path = Path(\"data/\")\n", + "image_path = data_path / \"pizza_steak_sushi\"\n", + "\n", + "# If the image folder doesn't exist, download it and prepare it... \n", + "if image_path.is_dir():\n", + " print(f\"{image_path} directory exists.\")\n", + "else:\n", + " print(f\"Did not find {image_path} directory, creating one...\")\n", + " image_path.mkdir(parents=True, exist_ok=True)\n", + " \n", + "# Download pizza, steak, sushi data\n", + "with open(data_path / \"pizza_steak_sushi.zip\", \"wb\") as f:\n", + " request = requests.get(\"https://github.com/mrdbourke/pytorch-deep-learning/raw/main/data/pizza_steak_sushi.zip\")\n", + " print(\"Downloading pizza, steak, sushi data...\")\n", + " f.write(request.content)\n", + "\n", + "# Unzip pizza, steak, sushi data\n", + "with zipfile.ZipFile(data_path / \"pizza_steak_sushi.zip\", \"r\") as zip_ref:\n", + " print(\"Unzipping pizza, steak, sushi data...\") \n", + " zip_ref.extractall(image_path)\n", + "\n", + "# Remove zip file\n", + "os.remove(data_path / \"pizza_steak_sushi.zip\")" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "wl_jfPzVbGDS", + "outputId": "51a3e5e8-991c-4309-b1ba-b24d32bbdb61" + }, + "execution_count": 2, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Did not find data/pizza_steak_sushi directory, creating one...\n", + "Downloading pizza, steak, sushi data...\n", + "Unzipping pizza, steak, sushi data...\n" + ] + } + ] + }, + { + "cell_type": "code", + "source": [ + "# Setup train and testing paths\n", + "train_dir = image_path / \"train\"\n", + "test_dir = image_path / \"test\"\n", + "\n", + "train_dir, test_dir" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "8qYMdiBMbde0", + "outputId": "a5093c72-455f-471c-9e95-5b391eea9ebf" + }, + "execution_count": 3, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "(PosixPath('data/pizza_steak_sushi/train'),\n", + " PosixPath('data/pizza_steak_sushi/test'))" + ] + }, + "metadata": {}, + "execution_count": 3 + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "## TK - 2. Create Datasets and DataLoaders" + ], + "metadata": { + "id": "eYL6NynybU9Z" + } + }, + { + "cell_type": "code", + "source": [ + "from torchvision import datasets, transforms\n", + "\n", + "# Create simple transform\n", + "data_transform = transforms.Compose([ \n", + " transforms.Resize((64, 64)),\n", + " transforms.ToTensor(),\n", + "])\n", + "\n", + "# Use ImageFolder to create dataset(s)\n", + "train_data = datasets.ImageFolder(root=train_dir, # target folder of images\n", + " transform=data_transform, # transforms to perform on data (images)\n", + " target_transform=None) # transforms to perform on labels (if necessary)\n", + "\n", + "test_data = datasets.ImageFolder(root=test_dir, \n", + " transform=data_transform)\n", + "\n", + "print(f\"Train data:\\n{train_data}\\nTest data:\\n{test_data}\")" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "DaOJOd-QbOQk", + "outputId": "dc7168b3-8bee-40c4-867e-58aa058175b5" + }, + "execution_count": 4, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Train data:\n", + "Dataset ImageFolder\n", + " Number of datapoints: 225\n", + " Root location: data/pizza_steak_sushi/train\n", + " StandardTransform\n", + "Transform: Compose(\n", + " Resize(size=(64, 64), interpolation=bilinear, max_size=None, antialias=None)\n", + " ToTensor()\n", + " )\n", + "Test data:\n", + "Dataset ImageFolder\n", + " Number of datapoints: 75\n", + " Root location: data/pizza_steak_sushi/test\n", + " StandardTransform\n", + "Transform: Compose(\n", + " Resize(size=(64, 64), interpolation=bilinear, max_size=None, antialias=None)\n", + " ToTensor()\n", + " )\n" + ] + } + ] + }, + { + "cell_type": "code", + "source": [ + "# Get class names as a list\n", + "class_names = train_data.classes\n", + "class_names" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "eEln0VFmbfyY", + "outputId": "c514574e-e3ab-4689-a5ee-6a2aef6a11d2" + }, + "execution_count": 5, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "['pizza', 'steak', 'sushi']" + ] + }, + "metadata": {}, + "execution_count": 5 + } + ] + }, + { + "cell_type": "code", + "source": [ + "# Can also get class names as a dict\n", + "class_dict = train_data.class_to_idx\n", + "class_dict" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "IMGTFVr8bgwE", + "outputId": "4268d11f-8899-447a-baba-7e91ade01f13" + }, + "execution_count": 6, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "{'pizza': 0, 'steak': 1, 'sushi': 2}" + ] + }, + "metadata": {}, + "execution_count": 6 + } + ] + }, + { + "cell_type": "code", + "source": [ + "# Check the lengths\n", + "len(train_data), len(test_data)" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "6a8IW-IYbhGX", + "outputId": "87bc60ac-3be3-499f-e0a8-aed5964a3075" + }, + "execution_count": 7, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "(225, 75)" + ] + }, + "metadata": {}, + "execution_count": 7 + } + ] + }, + { + "cell_type": "code", + "source": [ + "# Turn train and test Datasets into DataLoaders\n", + "from torch.utils.data import DataLoader\n", + "train_dataloader = DataLoader(dataset=train_data, \n", + " batch_size=1, # how many samples per batch?\n", + " num_workers=1, # how many subprocesses to use for data loading? (higher = more)\n", + " shuffle=True) # shuffle the data?\n", + "\n", + "test_dataloader = DataLoader(dataset=test_data, \n", + " batch_size=1, \n", + " num_workers=1, \n", + " shuffle=False) # don't usually need to shuffle testing data\n", + "\n", + "train_dataloader, test_dataloader" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "f1UxnvvmblUj", + "outputId": "1dd0c011-912e-498b-ea34-ee4bf05c7b87" + }, + "execution_count": 8, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "(,\n", + " )" + ] + }, + "metadata": {}, + "execution_count": 8 + } + ] + }, + { + "cell_type": "code", + "source": [ + "# Check out single image size/shape\n", + "img, label = next(iter(train_dataloader))\n", + "\n", + "# Batch size will now be 1, try changing the batch_size parameter above and see what happens\n", + "print(f\"Image shape: {img.shape} -> [batch_size, color_channels, height, width]\")\n", + "print(f\"Label shape: {label.shape}\")" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "JJKRqXNGbnI5", + "outputId": "2d5320fc-ac72-4ef8-94f8-0ef283fc3a30" + }, + "execution_count": 9, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Image shape: torch.Size([1, 3, 64, 64]) -> [batch_size, color_channels, height, width]\n", + "Label shape: torch.Size([1])\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "### TK - 2.1 Create Datasets and DataLoaders (script mode)\n", + "\n", + "* TK - Turn the above into a function.\n", + "* TK - write docstring" + ], + "metadata": { + "id": "RjINjcyGdwL9" + } + }, + { + "cell_type": "code", + "source": [ + "%%writefile going_modular/data_setup.py\n", + "\"\"\"\n", + "Contains functionality for creating PyTorch DataLoaders for \n", + "image classification data.\n", + "\"\"\"\n", + "import os\n", + "\n", + "from torchvision import datasets, transforms\n", + "from torch.utils.data import DataLoader\n", + "\n", + "NUM_WORKERS = os.cpu_count()\n", + "\n", + "def create_dataloaders(\n", + " train_dir: str, \n", + " test_dir: str, \n", + " transform: transforms.Compose, \n", + " batch_size: int, \n", + " num_workers: int=NUM_WORKERS\n", + "):\n", + " \"\"\"Creates training and testing DataLoaders.\n", + "\n", + " Takes in a training directory and testing directory path and turns\n", + " them into PyTorch Datasets and then into PyTorch DataLoaders.\n", + "\n", + " Args:\n", + " train_dir: Path to training directory.\n", + " test_dir: Path to testing directory.\n", + " transform: torchvision transforms to perform on training and testing data.\n", + " batch_size: Number of samples per batch in each of the DataLoaders.\n", + " num_workers: An integer for number of workers per DataLoader.\n", + "\n", + " Returns:\n", + " A tuple of (train_dataloader, test_dataloader, class_names).\n", + " Where class_names is a list of the target classes.\n", + " Example usage:\n", + " train_dataloader, test_dataloader, class_names = \\\n", + " = create_dataloaders(train_dir=path/to/train_dir,\n", + " test_dir=path/to/test_dir,\n", + " transform=some_transform,\n", + " batch_size=32,\n", + " num_workers=4)\n", + " \"\"\"\n", + " # Use ImageFolder to create dataset(s)\n", + " train_data = datasets.ImageFolder(train_dir, transform=transform)\n", + " test_data = datasets.ImageFolder(test_dir, transform=transform)\n", + "\n", + " # Get class names\n", + " class_names = train_data.classes\n", + "\n", + " # Turn images into data loaders\n", + " train_dataloader = DataLoader(\n", + " train_data,\n", + " batch_size=batch_size,\n", + " shuffle=True,\n", + " num_workers=num_workers,\n", + " pin_memory=True,\n", + " )\n", + " test_dataloader = DataLoader(\n", + " test_data,\n", + " batch_size=batch_size,\n", + " shuffle=True,\n", + " num_workers=num_workers,\n", + " pin_memory=True,\n", + " )\n", + "\n", + " return train_dataloader, test_dataloader, class_names" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "CmjK-b04du_-", + "outputId": "07d3450d-bc24-4aa4-a6d6-57d60bf11416" + }, + "execution_count": 10, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Writing going_modular/data_setup.py\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "## 3. TK - Making a model (TinyVGG) \n", + "\n", + "TK - clean up this model code" + ], + "metadata": { + "id": "gAQLp1dCbrY0" + } + }, + { + "cell_type": "code", + "source": [ + "import torch\n", + "from torch import nn \n", + "\n", + "class TinyVGG(nn.Module):\n", + " \"\"\"Creates the TinyVGG architecture.\n", + "\n", + " Replicates the TinyVGG architecture from the CNN explainer website in PyTorch.\n", + " See the original architecture here: https://poloclub.github.io/cnn-explainer/\n", + " \n", + " Args:\n", + " input_shape: An integer indicating number of input channels.\n", + " hidden_units: An integer indicating number of hidden units between layers.\n", + " output_shape: An integer indicating number of output units.\n", + " \"\"\"\n", + " def __init__(self, input_shape: int, hidden_units: int, output_shape: int) -> None:\n", + " super().__init__()\n", + " self.conv_block_1 = nn.Sequential(\n", + " nn.Conv2d(in_channels=input_shape, \n", + " out_channels=hidden_units, \n", + " kernel_size=3, \n", + " stride=1, \n", + " padding=0), \n", + " nn.ReLU(),\n", + " nn.Conv2d(in_channels=hidden_units, \n", + " out_channels=hidden_units,\n", + " kernel_size=3,\n", + " stride=1,\n", + " padding=0),\n", + " nn.ReLU(),\n", + " nn.MaxPool2d(kernel_size=2,\n", + " stride=2)\n", + " )\n", + " self.conv_block_2 = nn.Sequential(\n", + " nn.Conv2d(hidden_units, hidden_units, kernel_size=3, padding=0),\n", + " nn.ReLU(),\n", + " nn.Conv2d(hidden_units, hidden_units, kernel_size=3, padding=0),\n", + " nn.ReLU(),\n", + " nn.MaxPool2d(2)\n", + " )\n", + " self.classifier = nn.Sequential(\n", + " nn.Flatten(),\n", + " # Where did this in_features shape come from? \n", + " # It's because each layer of our network compresses and changes the shape of our inputs data.\n", + " nn.Linear(in_features=hidden_units*13*13,\n", + " out_features=output_shape)\n", + " )\n", + " \n", + " def forward(self, x: torch.Tensor):\n", + " x = self.conv_block_1(x)\n", + " x = self.conv_block_2(x)\n", + " x = self.classifier(x)\n", + " return x\n", + " # return self.classifier(self.block_2(self.block_1(x))) # <- leverage the benefits of operator fusion" + ], + "metadata": { + "id": "Z6i2xWcwbvom" + }, + "execution_count": 11, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "Create an instance of `TinyVGG`." + ], + "metadata": { + "id": "ROZsju1d9Cbu" + } + }, + { + "cell_type": "code", + "source": [ + "import torch\n", + "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n", + "\n", + "# Instantiate an instance of the model\n", + "torch.manual_seed(42)\n", + "model_0 = TinyVGG(input_shape=3, # number of color channels (3 for RGB) \n", + " hidden_units=10, \n", + " output_shape=len(train_data.classes)).to(device)\n", + "model_0" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "tXOOAEHHc6-L", + "outputId": "3207fda6-896b-4cb5-9f08-f1e46879bf75" + }, + "execution_count": 12, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "TinyVGG(\n", + " (conv_block_1): Sequential(\n", + " (0): Conv2d(3, 10, kernel_size=(3, 3), stride=(1, 1))\n", + " (1): ReLU()\n", + " (2): Conv2d(10, 10, kernel_size=(3, 3), stride=(1, 1))\n", + " (3): ReLU()\n", + " (4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n", + " )\n", + " (conv_block_2): Sequential(\n", + " (0): Conv2d(10, 10, kernel_size=(3, 3), stride=(1, 1))\n", + " (1): ReLU()\n", + " (2): Conv2d(10, 10, kernel_size=(3, 3), stride=(1, 1))\n", + " (3): ReLU()\n", + " (4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n", + " )\n", + " (classifier): Sequential(\n", + " (0): Flatten(start_dim=1, end_dim=-1)\n", + " (1): Linear(in_features=1690, out_features=3, bias=True)\n", + " )\n", + ")" + ] + }, + "metadata": {}, + "execution_count": 12 + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "Do a dummy forward pass." + ], + "metadata": { + "id": "C1CwvPiMcEfZ" + } + }, + { + "cell_type": "code", + "source": [ + "# 1. Get a batch of images and labels from the DataLoader\n", + "img_batch, label_batch = next(iter(train_dataloader))\n", + "\n", + "# 2. Get a single image from the batch and unsqueeze the image so its shape fits the model\n", + "img_single, label_single = img_batch[0].unsqueeze(dim=0), label_batch[0]\n", + "print(f\"Single image shape: {img_single.shape}\\n\")\n", + "\n", + "# 3. Perform a forward pass on a single image\n", + "model_0.eval()\n", + "with torch.inference_mode():\n", + " pred = model_0(img_single.to(device))\n", + " \n", + "# 4. Print out what's happening and convert model logits -> pred probs -> pred label\n", + "print(f\"Output logits:\\n{pred}\\n\")\n", + "print(f\"Output prediction probabilities:\\n{torch.softmax(pred, dim=1)}\\n\")\n", + "print(f\"Output prediction label:\\n{torch.argmax(torch.softmax(pred, dim=1), dim=1)}\\n\")\n", + "print(f\"Actual label:\\n{label_single}\")" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "__p5G2ArcFko", + "outputId": "341f2b73-a0fa-4fdb-f458-142510dcfcca" + }, + "execution_count": 13, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Single image shape: torch.Size([1, 3, 64, 64])\n", + "\n", + "Output logits:\n", + "tensor([[ 0.0208, -0.0019, 0.0095]], device='cuda:0')\n", + "\n", + "Output prediction probabilities:\n", + "tensor([[0.3371, 0.3295, 0.3333]], device='cuda:0')\n", + "\n", + "Output prediction label:\n", + "tensor([0], device='cuda:0')\n", + "\n", + "Actual label:\n", + "0\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "### TK - 3.1 Making a model (TinyVGG) (script mode)\n", + "\n", + "TK - turn the above modelling code into a script... (and then import it and do a dummy forward pass) " + ], + "metadata": { + "id": "wSaDm_W7bc3y" + } + }, + { + "cell_type": "code", + "source": [ + "%%writefile going_modular/model_builder.py\n", + "\"\"\"\n", + "Contains PyTorch model code to instantiate a TinyVGG model.\n", + "\"\"\"\n", + "import torch\n", + "from torch import nn \n", + "\n", + "class TinyVGG(nn.Module):\n", + " \"\"\"Creates the TinyVGG architecture.\n", + "\n", + " Replicates the TinyVGG architecture from the CNN explainer website in PyTorch.\n", + " See the original architecture here: https://poloclub.github.io/cnn-explainer/\n", + " \n", + " Args:\n", + " input_shape: An integer indicating number of input channels.\n", + " hidden_units: An integer indicating number of hidden units between layers.\n", + " output_shape: An integer indicating number of output units.\n", + " \"\"\"\n", + " def __init__(self, input_shape: int, hidden_units: int, output_shape: int) -> None:\n", + " super().__init__()\n", + " self.conv_block_1 = nn.Sequential(\n", + " nn.Conv2d(in_channels=input_shape, \n", + " out_channels=hidden_units, \n", + " kernel_size=3, \n", + " stride=1, \n", + " padding=0), \n", + " nn.ReLU(),\n", + " nn.Conv2d(in_channels=hidden_units, \n", + " out_channels=hidden_units,\n", + " kernel_size=3,\n", + " stride=1,\n", + " padding=0),\n", + " nn.ReLU(),\n", + " nn.MaxPool2d(kernel_size=2,\n", + " stride=2)\n", + " )\n", + " self.conv_block_2 = nn.Sequential(\n", + " nn.Conv2d(hidden_units, hidden_units, kernel_size=3, padding=0),\n", + " nn.ReLU(),\n", + " nn.Conv2d(hidden_units, hidden_units, kernel_size=3, padding=0),\n", + " nn.ReLU(),\n", + " nn.MaxPool2d(2)\n", + " )\n", + " self.classifier = nn.Sequential(\n", + " nn.Flatten(),\n", + " # Where did this in_features shape come from? \n", + " # It's because each layer of our network compresses and changes the shape of our inputs data.\n", + " nn.Linear(in_features=hidden_units*13*13,\n", + " out_features=output_shape)\n", + " )\n", + " \n", + " def forward(self, x: torch.Tensor):\n", + " x = self.conv_block_1(x)\n", + " x = self.conv_block_2(x)\n", + " x = self.classifier(x)\n", + " return x\n", + " # return self.classifier(self.block_2(self.block_1(x))) # <- leverage the benefits of operator fusion" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "oEH3bklL86hF", + "outputId": "b3f7e983-e51c-4e35-a991-df5ff99d63e6" + }, + "execution_count": 14, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Writing going_modular/model_builder.py\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "Create an instance of `TinyVGG` (from the script)." + ], + "metadata": { + "id": "3-WijBWM9K2c" + } + }, + { + "cell_type": "code", + "source": [ + "import torch\n", + "from going_modular import model_builder\n", + "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n", + "\n", + "# Instantiate an instance of the model from the \"model_builder.py\" script\n", + "torch.manual_seed(42)\n", + "model_1 = model_builder.TinyVGG(input_shape=3, # number of color channels (3 for RGB) \n", + " hidden_units=10, \n", + " output_shape=len(train_data.classes)).to(device)\n", + "model_1" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "F__hbQwZ9A56", + "outputId": "4e8abd04-cbc4-4aa8-b71c-3a8ff8617407" + }, + "execution_count": 15, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "TinyVGG(\n", + " (conv_block_1): Sequential(\n", + " (0): Conv2d(3, 10, kernel_size=(3, 3), stride=(1, 1))\n", + " (1): ReLU()\n", + " (2): Conv2d(10, 10, kernel_size=(3, 3), stride=(1, 1))\n", + " (3): ReLU()\n", + " (4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n", + " )\n", + " (conv_block_2): Sequential(\n", + " (0): Conv2d(10, 10, kernel_size=(3, 3), stride=(1, 1))\n", + " (1): ReLU()\n", + " (2): Conv2d(10, 10, kernel_size=(3, 3), stride=(1, 1))\n", + " (3): ReLU()\n", + " (4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n", + " )\n", + " (classifier): Sequential(\n", + " (0): Flatten(start_dim=1, end_dim=-1)\n", + " (1): Linear(in_features=1690, out_features=3, bias=True)\n", + " )\n", + ")" + ] + }, + "metadata": {}, + "execution_count": 15 + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "Do a dummy forward pass on `model_1`." + ], + "metadata": { + "id": "vBD-yWcp9QVT" + } + }, + { + "cell_type": "code", + "source": [ + "# 1. Get a batch of images and labels from the DataLoader\n", + "img_batch, label_batch = next(iter(train_dataloader))\n", + "\n", + "# 2. Get a single image from the batch and unsqueeze the image so its shape fits the model\n", + "img_single, label_single = img_batch[0].unsqueeze(dim=0), label_batch[0]\n", + "print(f\"Single image shape: {img_single.shape}\\n\")\n", + "\n", + "# 3. Perform a forward pass on a single image\n", + "model_1.eval()\n", + "with torch.inference_mode():\n", + " pred = model_1(img_single.to(device))\n", + " \n", + "# 4. Print out what's happening and convert model logits -> pred probs -> pred label\n", + "print(f\"Output logits:\\n{pred}\\n\")\n", + "print(f\"Output prediction probabilities:\\n{torch.softmax(pred, dim=1)}\\n\")\n", + "print(f\"Output prediction label:\\n{torch.argmax(torch.softmax(pred, dim=1), dim=1)}\\n\")\n", + "print(f\"Actual label:\\n{label_single}\")" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "NCQWeeMj9kHE", + "outputId": "cb33c4ec-4848-423c-aea3-89a131e07cfd" + }, + "execution_count": 16, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Single image shape: torch.Size([1, 3, 64, 64])\n", + "\n", + "Output logits:\n", + "tensor([[ 0.0208, -0.0019, 0.0095]], device='cuda:0')\n", + "\n", + "Output prediction probabilities:\n", + "tensor([[0.3371, 0.3295, 0.3333]], device='cuda:0')\n", + "\n", + "Output prediction label:\n", + "tensor([0], device='cuda:0')\n", + "\n", + "Actual label:\n", + "0\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "## TK - 4. Creating `train_step()` and `test_step()` functions and `train()` to combine them \n", + "\n", + "Rather than writing them again, we can reuse the `train_step()` and `test_step()` functions from [notebook 04](https://www.learnpytorch.io/04_pytorch_custom_datasets/#75-create-train-test-loop-functions).\n", + "\n", + "The same goes for the `train()` function we created.\n", + "\n", + "The only difference here is that these functions have had docstrings added to them in [Google's Python Functions and Methods Style Guide](https://google.github.io/styleguide/pyguide.html#383-functions-and-methods).\n", + "\n", + "Let's start by making `train_step()`." + ], + "metadata": { + "id": "8OB4xIsXcHrp" + } + }, + { + "cell_type": "code", + "source": [ + "from typing import Tuple\n", + "\n", + "def train_step(model: torch.nn.Module, \n", + " dataloader: torch.utils.data.DataLoader, \n", + " loss_fn: torch.nn.Module, \n", + " optimizer: torch.optim.Optimizer,\n", + " device: torch.device) -> Tuple[float, float]:\n", + " \"\"\"Trains a PyTorch model for a single epoch.\n", + "\n", + " Turns a target PyTorch model to training mode and then\n", + " runs through all of the required training steps (forward\n", + " pass, loss calculation, optimizer step).\n", + "\n", + " Args:\n", + " model: A PyTorch model to be trained.\n", + " dataloader: A DataLoader instance for the model to be trained on.\n", + " loss_fn: A PyTorch loss function to minimize.\n", + " optimizer: A PyTorch optimizer to help minimize the loss function.\n", + " device: A target device to compute on (e.g. \"cuda\" or \"cpu\").\n", + "\n", + " Returns:\n", + " A tuple of training loss and training accuracy metrics.\n", + " In the form (train_loss, train_accuracy). For example:\n", + " \n", + " (0.1112, 0.8743)\n", + " \"\"\"\n", + " # Put model in train mode\n", + " model.train()\n", + " \n", + " # Setup train loss and train accuracy values\n", + " train_loss, train_acc = 0, 0\n", + " \n", + " # Loop through data loader data batches\n", + " for batch, (X, y) in enumerate(dataloader):\n", + " # Send data to target device\n", + " X, y = X.to(device), y.to(device)\n", + "\n", + " # 1. Forward pass\n", + " y_pred = model(X)\n", + "\n", + " # 2. Calculate and accumulate loss\n", + " loss = loss_fn(y_pred, y)\n", + " train_loss += loss.item() \n", + "\n", + " # 3. Optimizer zero grad\n", + " optimizer.zero_grad()\n", + "\n", + " # 4. Loss backward\n", + " loss.backward()\n", + "\n", + " # 5. Optimizer step\n", + " optimizer.step()\n", + "\n", + " # Calculate and accumulate accuracy metric across all batches\n", + " y_pred_class = torch.argmax(torch.softmax(y_pred, dim=1), dim=1)\n", + " train_acc += (y_pred_class == y).sum().item()/len(y_pred)\n", + "\n", + " # Adjust metrics to get average loss and accuracy per batch \n", + " train_loss = train_loss / len(dataloader)\n", + " train_acc = train_acc / len(dataloader)\n", + " return train_loss, train_acc" + ], + "metadata": { + "id": "t_0zRYZecJZ6" + }, + "execution_count": 17, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "Now we'll do `test_step()`." + ], + "metadata": { + "id": "1nwAPwNh-f3k" + } + }, + { + "cell_type": "code", + "source": [ + "def test_step(model: torch.nn.Module, \n", + " dataloader: torch.utils.data.DataLoader, \n", + " loss_fn: torch.nn.Module,\n", + " device: torch.device) -> Tuple[float, float]:\n", + " \"\"\"Tests a PyTorch model for a single epoch.\n", + "\n", + " Turns a target PyTorch model to \"eval\" mode and then performs\n", + " a forward pass on a testing dataset.\n", + "\n", + " Args:\n", + " model: A PyTorch model to be tested.\n", + " dataloader: A DataLoader instance for the model to be tested on.\n", + " loss_fn: A PyTorch loss function to calculate loss on the test data.\n", + " device: A target device to compute on (e.g. \"cuda\" or \"cpu\").\n", + "\n", + " Returns:\n", + " A tuple of testing loss and testing accuracy metrics.\n", + " In the form (test_loss, test_accuracy). For example:\n", + " \n", + " (0.0223, 0.8985)\n", + " \"\"\"\n", + " # Put model in eval mode\n", + " model.eval() \n", + " \n", + " # Setup test loss and test accuracy values\n", + " test_loss, test_acc = 0, 0\n", + " \n", + " # Turn on inference context manager\n", + " with torch.inference_mode():\n", + " # Loop through DataLoader batches\n", + " for batch, (X, y) in enumerate(dataloader):\n", + " # Send data to target device\n", + " X, y = X.to(device), y.to(device)\n", + " \n", + " # 1. Forward pass\n", + " test_pred_logits = model(X)\n", + "\n", + " # 2. Calculate and accumulate loss\n", + " loss = loss_fn(test_pred_logits, y)\n", + " test_loss += loss.item()\n", + " \n", + " # Calculate and accumulate accuracy\n", + " test_pred_labels = test_pred_logits.argmax(dim=1)\n", + " test_acc += ((test_pred_labels == y).sum().item()/len(test_pred_labels))\n", + " \n", + " # Adjust metrics to get average loss and accuracy per batch \n", + " test_loss = test_loss / len(dataloader)\n", + " test_acc = test_acc / len(dataloader)\n", + " return test_loss, test_acc" + ], + "metadata": { + "id": "sr_9AspYcKkW" + }, + "execution_count": 18, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "And we'll combine `train_step()` and `test_step()` into `train()`." + ], + "metadata": { + "id": "weqHDd5b-iGz" + } + }, + { + "cell_type": "code", + "source": [ + "from tqdm.auto import tqdm\n", + "from typing import Dict, List\n", + "\n", + "def train(model: torch.nn.Module, \n", + " train_dataloader: torch.utils.data.DataLoader, \n", + " test_dataloader: torch.utils.data.DataLoader, \n", + " optimizer: torch.optim.Optimizer,\n", + " loss_fn: torch.nn.Module,\n", + " epochs: int,\n", + " device: torch.device) -> Dict[str, List]:\n", + " \"\"\"Trains and tests a PyTorch model.\n", + "\n", + " Passes a target PyTorch models through train_step() and test_step()\n", + " functions for a number of epochs, training and testing the model\n", + " in the same epoch loop.\n", + "\n", + " Calculates, prints and stores evaluation metrics throughout.\n", + "\n", + " Args:\n", + " model: A PyTorch model to be trained and tested.\n", + " train_dataloader: A DataLoader instance for the model to be trained on.\n", + " test_dataloader: A DataLoader instance for the model to be tested on.\n", + " optimizer: A PyTorch optimizer to help minimize the loss function.\n", + " loss_fn: A PyTorch loss function to calculate loss on both datasets.\n", + " epochs: An integer indicating how many epochs to train for.\n", + " device: A target device to compute on (e.g. \"cuda\" or \"cpu\").\n", + "\n", + " Returns:\n", + " A dictionary of training and testing loss as well as training and\n", + " testing accuracy metrics. Each metric has a value in a list for \n", + " each epoch.\n", + " In the form: {train_loss: [...],\n", + " train_acc: [...],\n", + " test_loss: [...],\n", + " test_acc: [...]} \n", + " For example if training for epochs=2: \n", + " {train_loss: [2.0616, 1.0537],\n", + " train_acc: [0.3945, 0.3945],\n", + " test_loss: [1.2641, 1.5706],\n", + " test_acc: [0.3400, 0.2973]} \n", + " \"\"\"\n", + " # Create empty results dictionary\n", + " results = {\"train_loss\": [],\n", + " \"train_acc\": [],\n", + " \"test_loss\": [],\n", + " \"test_acc\": []\n", + " }\n", + " \n", + " # Loop through training and testing steps for a number of epochs\n", + " for epoch in tqdm(range(epochs)):\n", + " train_loss, train_acc = train_step(model=model,\n", + " dataloader=train_dataloader,\n", + " loss_fn=loss_fn,\n", + " optimizer=optimizer,\n", + " device=device)\n", + " test_loss, test_acc = test_step(model=model,\n", + " dataloader=test_dataloader,\n", + " loss_fn=loss_fn,\n", + " device=device)\n", + " \n", + " # Print out what's happening\n", + " print(\n", + " f\"Epoch: {epoch+1} | \"\n", + " f\"train_loss: {train_loss:.4f} | \"\n", + " f\"train_acc: {train_acc:.4f} | \"\n", + " f\"test_loss: {test_loss:.4f} | \"\n", + " f\"test_acc: {test_acc:.4f}\"\n", + " )\n", + "\n", + " # Update results dictionary\n", + " results[\"train_loss\"].append(train_loss)\n", + " results[\"train_acc\"].append(train_acc)\n", + " results[\"test_loss\"].append(test_loss)\n", + " results[\"test_acc\"].append(test_acc)\n", + "\n", + " # Return the filled results at the end of the epochs\n", + " return results" + ], + "metadata": { + "id": "-oze8b6icWE7" + }, + "execution_count": 19, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "### TK - 4.1 Creating `train_step()` and `test_step()` functions and `train()` to combine them (script mode) \n", + "\n", + "To create a script for `train_step()`, `test_step()` and `train()`, we'll combine their code all into a single cell.\n", + "\n", + "We'll then write that cell to a file called `engine.py` because these functions will be the \"engine\" of our training pipeline.\n", + "\n", + "We can do so with the magic line `%%writefile going_modular/engine.py`.\n", + "\n", + "We'll also make sure to put all the imports we need (`torch`, `typing`, and `tqdm`) at the top of the cell." + ], + "metadata": { + "id": "tw_nYa4kfQeI" + } + }, + { + "cell_type": "code", + "source": [ + "%%writefile going_modular/engine.py\n", + "\"\"\"\n", + "Contains functions for training and testing a PyTorch model.\n", + "\"\"\"\n", + "import torch\n", + "\n", + "from tqdm.auto import tqdm\n", + "from typing import Dict, List, Tuple\n", + "\n", + "def train_step(model: torch.nn.Module, \n", + " dataloader: torch.utils.data.DataLoader, \n", + " loss_fn: torch.nn.Module, \n", + " optimizer: torch.optim.Optimizer,\n", + " device: torch.device) -> Tuple[float, float]:\n", + " \"\"\"Trains a PyTorch model for a single epoch.\n", + "\n", + " Turns a target PyTorch model to training mode and then\n", + " runs through all of the required training steps (forward\n", + " pass, loss calculation, optimizer step).\n", + "\n", + " Args:\n", + " model: A PyTorch model to be trained.\n", + " dataloader: A DataLoader instance for the model to be trained on.\n", + " loss_fn: A PyTorch loss function to minimize.\n", + " optimizer: A PyTorch optimizer to help minimize the loss function.\n", + " device: A target device to compute on (e.g. \"cuda\" or \"cpu\").\n", + "\n", + " Returns:\n", + " A tuple of training loss and training accuracy metrics.\n", + " In the form (train_loss, train_accuracy). For example:\n", + " \n", + " (0.1112, 0.8743)\n", + " \"\"\"\n", + " # Put model in train mode\n", + " model.train()\n", + " \n", + " # Setup train loss and train accuracy values\n", + " train_loss, train_acc = 0, 0\n", + " \n", + " # Loop through data loader data batches\n", + " for batch, (X, y) in enumerate(dataloader):\n", + " # Send data to target device\n", + " X, y = X.to(device), y.to(device)\n", + "\n", + " # 1. Forward pass\n", + " y_pred = model(X)\n", + "\n", + " # 2. Calculate and accumulate loss\n", + " loss = loss_fn(y_pred, y)\n", + " train_loss += loss.item() \n", + "\n", + " # 3. Optimizer zero grad\n", + " optimizer.zero_grad()\n", + "\n", + " # 4. Loss backward\n", + " loss.backward()\n", + "\n", + " # 5. Optimizer step\n", + " optimizer.step()\n", + "\n", + " # Calculate and accumulate accuracy metric across all batches\n", + " y_pred_class = torch.argmax(torch.softmax(y_pred, dim=1), dim=1)\n", + " train_acc += (y_pred_class == y).sum().item()/len(y_pred)\n", + "\n", + " # Adjust metrics to get average loss and accuracy per batch \n", + " train_loss = train_loss / len(dataloader)\n", + " train_acc = train_acc / len(dataloader)\n", + " return train_loss, train_acc\n", + "\n", + "def test_step(model: torch.nn.Module, \n", + " dataloader: torch.utils.data.DataLoader, \n", + " loss_fn: torch.nn.Module,\n", + " device: torch.device) -> Tuple[float, float]:\n", + " \"\"\"Tests a PyTorch model for a single epoch.\n", + "\n", + " Turns a target PyTorch model to \"eval\" mode and then performs\n", + " a forward pass on a testing dataset.\n", + "\n", + " Args:\n", + " model: A PyTorch model to be tested.\n", + " dataloader: A DataLoader instance for the model to be tested on.\n", + " loss_fn: A PyTorch loss function to calculate loss on the test data.\n", + " device: A target device to compute on (e.g. \"cuda\" or \"cpu\").\n", + "\n", + " Returns:\n", + " A tuple of testing loss and testing accuracy metrics.\n", + " In the form (test_loss, test_accuracy). For example:\n", + " \n", + " (0.0223, 0.8985)\n", + " \"\"\"\n", + " # Put model in eval mode\n", + " model.eval() \n", + " \n", + " # Setup test loss and test accuracy values\n", + " test_loss, test_acc = 0, 0\n", + " \n", + " # Turn on inference context manager\n", + " with torch.inference_mode():\n", + " # Loop through DataLoader batches\n", + " for batch, (X, y) in enumerate(dataloader):\n", + " # Send data to target device\n", + " X, y = X.to(device), y.to(device)\n", + " \n", + " # 1. Forward pass\n", + " test_pred_logits = model(X)\n", + "\n", + " # 2. Calculate and accumulate loss\n", + " loss = loss_fn(test_pred_logits, y)\n", + " test_loss += loss.item()\n", + " \n", + " # Calculate and accumulate accuracy\n", + " test_pred_labels = test_pred_logits.argmax(dim=1)\n", + " test_acc += ((test_pred_labels == y).sum().item()/len(test_pred_labels))\n", + " \n", + " # Adjust metrics to get average loss and accuracy per batch \n", + " test_loss = test_loss / len(dataloader)\n", + " test_acc = test_acc / len(dataloader)\n", + " return test_loss, test_acc\n", + "\n", + "def train(model: torch.nn.Module, \n", + " train_dataloader: torch.utils.data.DataLoader, \n", + " test_dataloader: torch.utils.data.DataLoader, \n", + " optimizer: torch.optim.Optimizer,\n", + " loss_fn: torch.nn.Module,\n", + " epochs: int,\n", + " device: torch.device) -> Dict[str, List]:\n", + " \"\"\"Trains and tests a PyTorch model.\n", + "\n", + " Passes a target PyTorch models through train_step() and test_step()\n", + " functions for a number of epochs, training and testing the model\n", + " in the same epoch loop.\n", + "\n", + " Calculates, prints and stores evaluation metrics throughout.\n", + "\n", + " Args:\n", + " model: A PyTorch model to be trained and tested.\n", + " train_dataloader: A DataLoader instance for the model to be trained on.\n", + " test_dataloader: A DataLoader instance for the model to be tested on.\n", + " optimizer: A PyTorch optimizer to help minimize the loss function.\n", + " loss_fn: A PyTorch loss function to calculate loss on both datasets.\n", + " epochs: An integer indicating how many epochs to train for.\n", + " device: A target device to compute on (e.g. \"cuda\" or \"cpu\").\n", + "\n", + " Returns:\n", + " A dictionary of training and testing loss as well as training and\n", + " testing accuracy metrics. Each metric has a value in a list for \n", + " each epoch.\n", + " In the form: {train_loss: [...],\n", + " train_acc: [...],\n", + " test_loss: [...],\n", + " test_acc: [...]} \n", + " For example if training for epochs=2: \n", + " {train_loss: [2.0616, 1.0537],\n", + " train_acc: [0.3945, 0.3945],\n", + " test_loss: [1.2641, 1.5706],\n", + " test_acc: [0.3400, 0.2973]} \n", + " \"\"\"\n", + " # Create empty results dictionary\n", + " results = {\"train_loss\": [],\n", + " \"train_acc\": [],\n", + " \"test_loss\": [],\n", + " \"test_acc\": []\n", + " }\n", + " \n", + " # Loop through training and testing steps for a number of epochs\n", + " for epoch in tqdm(range(epochs)):\n", + " train_loss, train_acc = train_step(model=model,\n", + " dataloader=train_dataloader,\n", + " loss_fn=loss_fn,\n", + " optimizer=optimizer,\n", + " device=device)\n", + " test_loss, test_acc = test_step(model=model,\n", + " dataloader=test_dataloader,\n", + " loss_fn=loss_fn,\n", + " device=device)\n", + " \n", + " # Print out what's happening\n", + " print(\n", + " f\"Epoch: {epoch+1} | \"\n", + " f\"train_loss: {train_loss:.4f} | \"\n", + " f\"train_acc: {train_acc:.4f} | \"\n", + " f\"test_loss: {test_loss:.4f} | \"\n", + " f\"test_acc: {test_acc:.4f}\"\n", + " )\n", + "\n", + " # Update results dictionary\n", + " results[\"train_loss\"].append(train_loss)\n", + " results[\"train_acc\"].append(train_acc)\n", + " results[\"test_loss\"].append(test_loss)\n", + " results[\"test_acc\"].append(test_acc)\n", + "\n", + " # Return the filled results at the end of the epochs\n", + " return results" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "d47bhfY3fVq5", + "outputId": "41053838-2e28-4702-d833-d8c97eed119b" + }, + "execution_count": 20, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Writing going_modular/engine.py\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "## TK - 5. Creating a function to save the model\n", + "\n", + "Let's setup a function to save our model to a directory." + ], + "metadata": { + "id": "A2nXumITc9DL" + } + }, + { + "cell_type": "code", + "source": [ + "from pathlib import Path\n", + "\n", + "def save_model(model: torch.nn.Module,\n", + " target_dir: str,\n", + " model_name: str):\n", + " \"\"\"Saves a PyTorch model to a target directory.\n", + "\n", + " Args:\n", + " model: A target PyTorch model to save.\n", + " target_dir: A directory for saving the model to.\n", + " model_name: A filename for the saved model. Should include\n", + " either \".pth\" or \".pt\" as the file extension.\n", + " \n", + " Example usage:\n", + " save_model(model=model_0,\n", + " target_dir=\"models\",\n", + " model_name=\"05_going_modular_tingvgg_model.pth\")\n", + " \"\"\"\n", + " # Create target directory\n", + " target_dir_path = Path(target_dir)\n", + " target_dir_path.mkdir(parents=True,\n", + " exist_ok=True)\n", + " \n", + " # Create model save path\n", + " assert model_name.endswith(\".pth\") or model_name.endswith(\".pt\"), \"model_name should end with '.pt' or '.pth'\"\n", + " model_save_path = target_dir_path / model_name\n", + "\n", + " # Save the model state_dict()\n", + " print(f\"[INFO] Saving model to: {model_save_path}\")\n", + " torch.save(obj=model.state_dict(),\n", + " f=model_save_path)" + ], + "metadata": { + "id": "lu_vyjq-c933" + }, + "execution_count": 21, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "### TK - 5.1 Creating a function to save the model (script mode)\n", + "\n", + "How about we add our `save_model()` function to a script called `utils.py` which is short for \"utilities\".\n", + "\n", + "We can do so with the magic line `%%writefile going_modular/utils.py`." + ], + "metadata": { + "id": "F7SnPGOfc_Wc" + } + }, + { + "cell_type": "code", + "source": [ + "%%writefile going_modular/utils.py\n", + "\"\"\"\n", + "Contains various utility functions for PyTorch model training and saving.\n", + "\"\"\"\n", + "import torch\n", + "from pathlib import Path\n", + "\n", + "def save_model(model: torch.nn.Module,\n", + " target_dir: str,\n", + " model_name: str):\n", + " \"\"\"Saves a PyTorch model to a target directory.\n", + "\n", + " Args:\n", + " model: A target PyTorch model to save.\n", + " target_dir: A directory for saving the model to.\n", + " model_name: A filename for the saved model. Should include\n", + " either \".pth\" or \".pt\" as the file extension.\n", + " \n", + " Example usage:\n", + " save_model(model=model_0,\n", + " target_dir=\"models\",\n", + " model_name=\"05_going_modular_tingvgg_model.pth\")\n", + " \"\"\"\n", + " # Create target directory\n", + " target_dir_path = Path(target_dir)\n", + " target_dir_path.mkdir(parents=True,\n", + " exist_ok=True)\n", + " \n", + " # Create model save path\n", + " assert model_name.endswith(\".pth\") or model_name.endswith(\".pt\"), \"model_name should end with '.pt' or '.pth'\"\n", + " model_save_path = target_dir_path / model_name\n", + "\n", + " # Save the model state_dict()\n", + " print(f\"[INFO] Saving model to: {model_save_path}\")\n", + " torch.save(obj=model.state_dict(),\n", + " f=model_save_path)" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "20LC4xwN_2ZT", + "outputId": "30852196-8138-4f9e-9f43-578dc6277682" + }, + "execution_count": 22, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Writing going_modular/utils.py\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "## 6. Train, evaluate and save the model\n", + "\n", + "Let's leverage the functions we've got above to train, test and save a model to file." + ], + "metadata": { + "id": "20ZO64U2cZY_" + } + }, + { + "cell_type": "code", + "source": [ + "# Set random seeds\n", + "torch.manual_seed(42) \n", + "torch.cuda.manual_seed(42)\n", + "\n", + "# Set number of epochs\n", + "NUM_EPOCHS = 5\n", + "\n", + "# Recreate an instance of TinyVGG\n", + "model_0 = TinyVGG(input_shape=3, # number of color channels (3 for RGB) \n", + " hidden_units=10, \n", + " output_shape=len(train_data.classes)).to(device)\n", + "\n", + "# Setup loss function and optimizer\n", + "loss_fn = nn.CrossEntropyLoss()\n", + "optimizer = torch.optim.Adam(params=model_0.parameters(), lr=0.001)\n", + "\n", + "# Start the timer\n", + "from timeit import default_timer as timer \n", + "start_time = timer()\n", + "\n", + "# Train model_0 \n", + "model_0_results = train(model=model_0, \n", + " train_dataloader=train_dataloader,\n", + " test_dataloader=test_dataloader,\n", + " optimizer=optimizer,\n", + " loss_fn=loss_fn, \n", + " epochs=NUM_EPOCHS,\n", + " device=device)\n", + "\n", + "# End the timer and print out how long it took\n", + "end_time = timer()\n", + "print(f\"[INFO] Total training time: {end_time-start_time:.3f} seconds\")\n", + "\n", + "# Save the model\n", + "save_model(model=model_0,\n", + " target_dir=\"models\",\n", + " model_name=\"05_going_modular_cell_mode_tinyvgg_model.pth\")" + ], + "metadata": { + "id": "FjeRMiLjccVc", + "colab": { + "base_uri": "https://localhost:8080/", + "height": 173, + "referenced_widgets": [ + "84317b054c244ee4b1bed7b2f86660b7", + "a0a72aed7e2743f8a95c6af3b6e4a457", + "b517f855551f4c53969677161952a1ac", + "4d780e75e5d24241b1f6c0203a8bd73e", + "a0caf8f4760c4935b5b9be86566ee8e0", + "83cf71b79abd4fc5ae9daaac8f586841", + "3402f79d3df643efbed25c72aac94642", + "1e79615e722f456189e07874d13564d2", + "bac27d87b4d54b6cbaf85dd7b7ecdc64", + "f9b7fbae53e84883ac281343bb6a9da9", + "4bc100911d7d4303b6ab7efb59d3420c" + ] + }, + "outputId": "2d9005a4-afce-4230-c758-1c6efa01a5e8" + }, + "execution_count": 23, + "outputs": [ + { + "output_type": "display_data", + "data": { + "text/plain": [ + " 0%| | 0/5 [00:00