From 7a93928ee06aae32cd32e3324f2017a1b796fb6c Mon Sep 17 00:00:00 2001 From: Daniel Bourke Date: Wed, 11 May 2022 10:26:28 +1000 Subject: [PATCH] update 05 materials --- 05_pytorch_going_modular.md | 6 +- .../05_pytorch_going_modular_cell_mode.ipynb | 101 ++- ...05_pytorch_going_modular_script_mode.ipynb | 744 ++++++++++-------- 3 files changed, 494 insertions(+), 357 deletions(-) diff --git a/05_pytorch_going_modular.md b/05_pytorch_going_modular.md index 927b796..79b9d95 100644 --- a/05_pytorch_going_modular.md +++ b/05_pytorch_going_modular.md @@ -57,7 +57,7 @@ I usually start machine learning projects in Jupyter/Google Colab notebooks for Then when I've got something working, I move the most useful pieces of code to Python scripts. -one possible workflow for writing machine learning code, start with jupyter or google colab notebooks and then move to Python scripts when you've got something working. +one possible workflow for writing machine learning code, start with jupyter or google colab notebooks and then move to Python scripts when you've got something working. *There are many possible workflows for writing machine learning code. Some prefer to start with scripts, others (like me) prefer to start with notebooks and go to scripts later on.* @@ -71,7 +71,7 @@ For example, you might be instructred to run code like the following in a termin python train.py --model MODEL_NAME --batch_size BATCH_SIZE --lr LEARNING_RATE --num_epochs NUM_EPOCHS ``` -command line call for training a PyTorch model with different hyperparameters +command line call for training a PyTorch model with different hyperparameters *Running a PyTorch `train.py` script on the command line with various hyperparameter settings.* @@ -114,7 +114,7 @@ Because sometimes the best way to learn something is to see how it *differs* fro If you run each notebook side-by-side you'll see how they differ and that's where the key learnings are. -running cell mode notebook vs a script mode notebook +running cell mode notebook vs a script mode notebook *Running the two notebooks for section 05 side-by-side. You'll notice that the **script mode notebook has extra code cells** to turn code from the cell mode notebook into Python scripts.* diff --git a/going_modular/05_pytorch_going_modular_cell_mode.ipynb b/going_modular/05_pytorch_going_modular_cell_mode.ipynb index f5ad936..ad03f9e 100644 --- a/going_modular/05_pytorch_going_modular_cell_mode.ipynb +++ b/going_modular/05_pytorch_going_modular_cell_mode.ipynb @@ -16,16 +16,64 @@ "id": "1M5tsObEa17-" }, "source": [ - "# 05. Going Modular (cell mode)\n", + "# 05. Going Modular: Part 1 (cell 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", + "This notebook is part 1/2 of section [05. Going Modular](https://www.learnpytorch.io/05_pytorch_going_modular/).\n", "\n", - "Turn notebook -> python scripts\n", + "For reference, the two parts are: \n", + "1. [**05. Going Modular: Part 1 (cell mode)**](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/going_modular/05_pytorch_going_modular_cell_mode.ipynb) - this notebook is run as a traditional Jupyter Notebook/Google Colab notebook and is a condensed version of [notebook 04](https://www.learnpytorch.io/04_pytorch_custom_datasets/).\n", + "2. [**05. Going Modular: Part 2 (script mode)**](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/going_modular/05_pytorch_going_modular_script_mode.ipynb) - this notebook is the same as number 1 but with added functionality to turn each of the major sections into Python scripts, such as, `data_setup.py` and `train.py`. \n", "\n", - "Code in this notebook based off code in notebook 04 with minimal changes.\n", + "Why two parts?\n", "\n", - "TK - get GPU (for Google Colab)" + "Because sometimes the best way to learn something is to see how it *differs* from something else.\n", + "\n", + "If you run each notebook side-by-side you'll see how they differ and that's where the key learnings are." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "1M5tsObEa17-" + }, + "source": [ + "## What is cell mode?\n", + "\n", + "A cell mode notebook is a regular notebook run exactly how we've been running them through the course.\n", + "\n", + "Some cells contain text and others contain code." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "1M5tsObEa17-" + }, + "source": [ + "## What's the difference between this notebook (Part 1) and the script mode notebook (Part 2)?\n", + "\n", + "This notebook, 05. PyTorch Going Modular: Part 1 (cell mode), runs a cleaned up version of the most useful code from section [04. PyTorch Custom Datasets](https://www.learnpytorch.io/04_pytorch_custom_datasets/).\n", + "\n", + "Running this notebook end-to-end will result in recreating the image classification model we built in notebook 04 (TinyVGG) trained on images of pizza, steak and sushi.\n", + "\n", + "The main difference between this notebook (Part 1) and Part 2 is that each section in Part 2 (script mode) has an extra subsection (e.g. 2.1, 3.1, 4.1) for turning cell code into script code." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "1M5tsObEa17-" + }, + "source": [ + "## Where can you get help?\n", + "\n", + "You can find the book version of this section [05. PyTorch Going Modular on learnpytorch.io](https://www.learnpytorch.io/05_pytorch_going_modular/).\n", + "\n", + "The rest of the materials for this course [are available on GitHub](https://github.com/mrdbourke/pytorch-deep-learning).\n", + "\n", + "If you run into trouble, you can ask a question on the course [GitHub Discussions page](https://github.com/mrdbourke/pytorch-deep-learning/discussions).\n", + "\n", + "And of course, there's the [PyTorch documentation](https://pytorch.org/docs/stable/index.html) and [PyTorch developer forums](https://discuss.pytorch.org/), a very helpful place for all things PyTorch. " ] }, { @@ -34,9 +82,13 @@ "id": "I_0BPjLcawE-" }, "source": [ - "## TK - 0. Running a notebook in cell mode\n", + "## 0. Running a notebook in cell mode\n", "\n", - "TK - What is cell mode? ... running a notebook normally." + "As discussed, we're going to be running this notebook normally.\n", + "\n", + "One cell at a time.\n", + "\n", + "The code is from notebook 04, however, it has been condensed down to its core functionality." ] }, { @@ -45,7 +97,7 @@ "id": "1XgXFr97bCsI" }, "source": [ - "## TK - 1. Get data\n", + "## 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." ] @@ -140,7 +192,7 @@ "id": "eYL6NynybU9Z" }, "source": [ - "## TK - 2. Create Datasets and DataLoaders\n", + "## 2. Create Datasets and DataLoaders\n", "\n", "Now we'll turn the image dataset into PyTorch `Dataset`'s and `DataLoader`'s. " ] @@ -298,8 +350,8 @@ { "data": { "text/plain": [ - "(,\n", - " )" + "(,\n", + " )" ] }, "execution_count": 7, @@ -547,7 +599,7 @@ "id": "8OB4xIsXcHrp" }, "source": [ - "## TK - 4. Creating `train_step()` and `test_step()` functions and `train()` to combine them \n", + "## 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", @@ -884,7 +936,7 @@ { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "54c42865cdff4fee8e2bb710e947e313", + "model_id": "803ff7aab243491e8451a74a5722b18d", "version_major": 2, "version_minor": 0 }, @@ -899,12 +951,12 @@ "name": "stdout", "output_type": "stream", "text": [ - "Epoch: 1 | train_loss: 1.0956 | train_acc: 0.3867 | test_loss: 1.0629 | test_acc: 0.4133\n", - "Epoch: 2 | train_loss: 1.0114 | train_acc: 0.5067 | test_loss: 1.0214 | test_acc: 0.4533\n", - "Epoch: 3 | train_loss: 0.9571 | train_acc: 0.5689 | test_loss: 0.9993 | test_acc: 0.4533\n", - "Epoch: 4 | train_loss: 0.8963 | train_acc: 0.5733 | test_loss: 1.0074 | test_acc: 0.4667\n", - "Epoch: 5 | train_loss: 0.8658 | train_acc: 0.6356 | test_loss: 1.0082 | test_acc: 0.5200\n", - "[INFO] Total training time: 5.185 seconds\n", + "Epoch: 1 | train_loss: 1.0955 | train_acc: 0.3867 | test_loss: 1.0627 | test_acc: 0.4133\n", + "Epoch: 2 | train_loss: 1.0102 | train_acc: 0.5200 | test_loss: 1.0222 | test_acc: 0.4400\n", + "Epoch: 3 | train_loss: 0.9552 | train_acc: 0.5822 | test_loss: 1.0067 | test_acc: 0.4667\n", + "Epoch: 4 | train_loss: 0.8913 | train_acc: 0.5867 | test_loss: 1.0090 | test_acc: 0.4400\n", + "Epoch: 5 | train_loss: 0.8608 | train_acc: 0.6311 | test_loss: 1.0214 | test_acc: 0.4533\n", + "[INFO] Total training time: 5.859 seconds\n", "[INFO] Saving model to: models/05_going_modular_cell_mode_tinyvgg_model.pth\n" ] } @@ -948,6 +1000,15 @@ " target_dir=\"models\",\n", " model_name=\"05_going_modular_cell_mode_tinyvgg_model.pth\")" ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We finish with a saved image classification model at `models/05_going_modular_cell_mode_tinyvgg_model.pth`.\n", + "\n", + "The code continues in [05. Going Modular: Part 2 (script mode)](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/going_modular/05_pytorch_going_modular_script_mode.ipynb)." + ] } ], "metadata": { diff --git a/going_modular/05_pytorch_going_modular_script_mode.ipynb b/going_modular/05_pytorch_going_modular_script_mode.ipynb index 5b63260..c904053 100644 --- a/going_modular/05_pytorch_going_modular_script_mode.ipynb +++ b/going_modular/05_pytorch_going_modular_script_mode.ipynb @@ -17,11 +17,11 @@ "tags": [] }, "source": [ - "# 05. Going Modular (script mode)\n", + "# 05. Going Modular: Part 2 (script mode)\n", "\n", - "This notebook is part 2/2 of section 05. Going Modular.\n", + "This notebook is part 2/2 of section [05. Going Modular](https://www.learnpytorch.io/05_pytorch_going_modular/).\n", "\n", - "More specifically, the two parts are: \n", + "For reference, the two parts are: \n", "1. [**05. Going Modular: Part 1 (cell mode)**](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/going_modular/05_pytorch_going_modular_cell_mode.ipynb) - this notebook is run as a traditional Jupyter Notebook/Google Colab notebook and is a condensed version of [notebook 04](https://www.learnpytorch.io/04_pytorch_custom_datasets/).\n", "2. [**05. Going Modular: Part 2 (script mode)**](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/going_modular/05_pytorch_going_modular_script_mode.ipynb) - this notebook is the same as number 1 but with added functionality to turn each of the major sections into Python scripts, such as, `data_setup.py` and `train.py`. \n", "\n", @@ -29,9 +29,17 @@ "\n", "Because sometimes the best way to learn something is to see how it *differs* from something else.\n", "\n", - "If you run each notebook side-by-side you'll see how they differ and that's where the key learnings are.\n", - "\n", - "## TK - What is script mode?\n", + "If you run each notebook side-by-side you'll see how they differ and that's where the key learnings are." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "1M5tsObEa17-", + "tags": [] + }, + "source": [ + "## What is script mode?\n", "\n", "**Script mode** uses [Jupyter Notebook cell magic](https://ipython.readthedocs.io/en/stable/interactive/magics.html) (special commands) to turn specific cells into Python scripts.\n", "\n", @@ -56,9 +64,17 @@ "\n", "> **Question:** Do I have to create Python files like this? Can't I just start directly with a Python file and skip using a Google Colab notebook?\n", ">\n", - "> **Answer:** Yes. This is only *one* way of creating Python scripts. If you know the kind of script you'd like to write, you could start writing it straight away. But since using Jupyter/Google Colab notebooks is a popular way of starting off data science and machine learning projects, knowing about the `%%writefile` magic command is a handy tip. \n", - "\n", - "## TK - What has script mode got to do with PyTorch?\n", + "> **Answer:** Yes. This is only *one* way of creating Python scripts. If you know the kind of script you'd like to write, you could start writing it straight away. But since using Jupyter/Google Colab notebooks is a popular way of starting off data science and machine learning projects, knowing about the `%%writefile` magic command is a handy tip. " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "1M5tsObEa17-", + "tags": [] + }, + "source": [ + "## What has script mode got to do with PyTorch?\n", "\n", "If you've written some useful code in a Jupyter Notebook or Google Colab notebook, chances are you'll want to use that code again.\n", "\n", @@ -66,9 +82,17 @@ "\n", "This practice is not PyTorch specific.\n", "\n", - "But it's how you'll see many different online PyTorch repositories structured.\n", - "\n", - "### TK - PyTorch in the wild\n", + "But it's how you'll see many different online PyTorch repositories structured." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "1M5tsObEa17-", + "tags": [] + }, + "source": [ + "### PyTorch in the wild\n", "\n", "For example, if you find a PyTorch project on GitHub, it may be structured in the following way:\n", "\n", @@ -99,17 +123,33 @@ "\n", "And the `models` and `data` directories could hold PyTorch models and data files respectively (though due to the size of models and data files, it's unlikely you'll find the *full* versions of these on GitHub, these directories are present above mainly for demonstration purposes).\n", "\n", - "> **Note:** There are many different ways to structure a Python project and subsequently a PyTorch project. This isn't a guide on *how* to structure your projects, only an example of how you *might* come across PyTorch projects in the wild. For more on structuring Python projects, see Real Python's [*Python Application Layouts: A Reference*](https://realpython.com/python-application-layouts/) guide.\n", - "\n", - "## TK - What's the difference between this notebook (Part 2) and the cell mode notebook (Part 1)?\n", + "> **Note:** There are many different ways to structure a Python project and subsequently a PyTorch project. This isn't a guide on *how* to structure your projects, only an example of how you *might* come across PyTorch projects in the wild. For more on structuring Python projects, see Real Python's [*Python Application Layouts: A Reference*](https://realpython.com/python-application-layouts/) guide." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "1M5tsObEa17-", + "tags": [] + }, + "source": [ + "## What's the difference between this notebook (Part 2) and the cell mode notebook (Part 1)?\n", "\n", "This notebook, 05 Going Modular: Part 2 (script mode), creates Python scripts out of the cells created in part 1.\n", "\n", "Running this notebook end-to-end will result in having a directory structure very similar to the `pytorch_project` structure above.\n", "\n", - "You'll notice each section in Part 2 (script mode) has an extra subsection (e.g. 2.1, 3.1, 4.1) for turning cell code into script code.\n", - "\n", - "## TK - What we're going to cover\n", + "You'll notice each section in Part 2 (script mode) has an extra subsection (e.g. 2.1, 3.1, 4.1) for turning cell code into script code." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "1M5tsObEa17-", + "tags": [] + }, + "source": [ + "## What we're going to cover\n", "\n", "By the end of this notebook you should finish with a directory structure of: \n", "\n", @@ -150,11 +190,21 @@ "python going_modular/train.py\n", "```\n", "\n", - "In essence, we will have turned our helpful notebook code into **reusable modular code**.\n", + "In essence, we will have turned our helpful notebook code into **reusable modular code**." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "1M5tsObEa17-", + "tags": [] + }, + "source": [ + "## Where can you get help?\n", "\n", - "## TK - Where can you get help?\n", + "You can find the book version of this section [05. PyTorch Going Modular on learnpytorch.io](https://www.learnpytorch.io/05_pytorch_going_modular/).\n", "\n", - "All of the materials for this course [are available on GitHub](https://github.com/mrdbourke/pytorch-deep-learning).\n", + "The rest of the materials for this course [are available on GitHub](https://github.com/mrdbourke/pytorch-deep-learning).\n", "\n", "If you run into trouble, you can ask a question on the course [GitHub Discussions page](https://github.com/mrdbourke/pytorch-deep-learning/discussions).\n", "\n", @@ -167,9 +217,11 @@ "id": "OW_3D_fOap2I" }, "source": [ - "## TK - 0. Creating a folder for storing Python scripts\n", + "## 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)." + "Since we're going to be creating Python scripts out of our most useful code cells, let's create a folder for storing those scripts.\n", + "\n", + "We'll call the folder `going_modular` and create it using Python's [`os.makedirs()`](https://docs.python.org/3/library/os.html) method." ] }, { @@ -190,7 +242,7 @@ "id": "1XgXFr97bCsI" }, "source": [ - "## TK - 1. Get data\n", + "## 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." ] @@ -210,7 +262,7 @@ "name": "stdout", "output_type": "stream", "text": [ - "Did not find data/pizza_steak_sushi directory, creating one...\n", + "data/pizza_steak_sushi directory exists.\n", "Downloading pizza, steak, sushi data...\n", "Unzipping pizza, steak, sushi data...\n" ] @@ -285,7 +337,9 @@ "id": "eYL6NynybU9Z" }, "source": [ - "## TK - 2. Create Datasets and DataLoaders" + "## 2. Create Datasets and DataLoaders\n", + "\n", + "Let's turn our data into PyTorch `Dataset`'s and `DataLoader`'s and find out a few useful attributes from them such as `classes` and their lengths. " ] }, { @@ -441,8 +495,8 @@ { "data": { "text/plain": [ - "(,\n", - " )" + "(,\n", + " )" ] }, "execution_count": 8, @@ -501,10 +555,11 @@ "id": "RjINjcyGdwL9" }, "source": [ - "### TK - 2.1 Create Datasets and DataLoaders (script mode)\n", + "### 2.1 Create Datasets and DataLoaders (script mode)\n", "\n", - "* TK - Turn the above into a function.\n", - "* TK - write docstring" + "Rather than rewriting all of the code above everytime we wanted to load data, we can turn it into a script called `data_setup.py`.\n", + "\n", + "Let's capture all of the above functionality into a function called `create_dataloaders()`." ] }, { @@ -522,7 +577,7 @@ "name": "stdout", "output_type": "stream", "text": [ - "Writing going_modular/data_setup.py\n" + "Overwriting going_modular/data_setup.py\n" ] } ], @@ -601,9 +656,11 @@ "id": "gAQLp1dCbrY0" }, "source": [ - "## 3. TK - Making a model (TinyVGG) \n", + "## 3. Making a model (TinyVGG) \n", "\n", - "TK - clean up this model code" + "We're going to use the same model we used in notebook 04: TinyVGG from the CNN Explainer website.\n", + "\n", + "The only change here from notebook 04 is that a docstring has been added using [Google's Style Guide for Python](https://google.github.io/styleguide/pyguide.html#384-classes). " ] }, { @@ -618,19 +675,19 @@ "from torch import nn \n", "\n", "class TinyVGG(nn.Module):\n", - " \"\"\"Creates the TinyVGG architecture.\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", + " 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", + " \"\"\"\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", @@ -645,28 +702,28 @@ " nn.ReLU(),\n", " nn.MaxPool2d(kernel_size=2,\n", " stride=2)\n", - " )\n", - " self.conv_block_2 = nn.Sequential(\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", + " )\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", " \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" + " 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" ] }, { @@ -739,7 +796,7 @@ "id": "C1CwvPiMcEfZ" }, "source": [ - "Do a dummy forward pass." + "Let's check out our model by doing a dummy forward pass." ] }, { @@ -799,9 +856,13 @@ "id": "wSaDm_W7bc3y" }, "source": [ - "### TK - 3.1 Making a model (TinyVGG) (script mode)\n", + "### 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) " + "Over the past few notebooks (notebook 03 and notebook 04), we've built the TinyVGG model a few times.\n", + "\n", + "So it makes sense to put the model into its file so we can reuse it again and again.\n", + "\n", + "Let's put our `TinyVGG()` model class into a script called `model_builder.py` with the line `%%writefile going_modular/model_builder.py`. " ] }, { @@ -819,7 +880,7 @@ "name": "stdout", "output_type": "stream", "text": [ - "Writing going_modular/model_builder.py\n" + "Overwriting going_modular/model_builder.py\n" ] } ], @@ -832,19 +893,19 @@ "from torch import nn \n", "\n", "class TinyVGG(nn.Module):\n", - " \"\"\"Creates the TinyVGG architecture.\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", + " 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", + " \"\"\"\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", @@ -859,28 +920,28 @@ " nn.ReLU(),\n", " nn.MaxPool2d(kernel_size=2,\n", " stride=2)\n", - " )\n", - " self.conv_block_2 = nn.Sequential(\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", + " )\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", " \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" + " 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" ] }, { @@ -1012,7 +1073,7 @@ "id": "8OB4xIsXcHrp" }, "source": [ - "## TK - 4. Creating `train_step()` and `test_step()` functions and `train()` to combine them \n", + "## 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", @@ -1038,60 +1099,60 @@ " 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", + " \"\"\"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", + " 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", + " 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", + " Returns:\n", " A tuple of training loss and training accuracy metrics.\n", " In the form (train_loss, train_accuracy). For example:\n", - " \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", + " # Put model in train mode\n", + " model.train()\n", "\n", - " # 1. Forward pass\n", - " y_pred = model(X)\n", + " # Setup train loss and train accuracy values\n", + " train_loss, train_acc = 0, 0\n", "\n", - " # 2. Calculate and accumulate loss\n", - " loss = loss_fn(y_pred, y)\n", - " train_loss += loss.item() \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", - " # 3. Optimizer zero grad\n", - " optimizer.zero_grad()\n", + " # 1. Forward pass\n", + " y_pred = model(X)\n", "\n", - " # 4. Loss backward\n", - " loss.backward()\n", + " # 2. Calculate and accumulate loss\n", + " loss = loss_fn(y_pred, y)\n", + " train_loss += loss.item() \n", "\n", - " # 5. Optimizer step\n", - " optimizer.step()\n", + " # 3. Optimizer zero grad\n", + " optimizer.zero_grad()\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", + " # 4. Loss backward\n", + " loss.backward()\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" + " # 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" ] }, { @@ -1115,51 +1176,51 @@ " 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", + " \"\"\"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", + " Turns a target PyTorch model to \"eval\" mode and then performs\n", + " a forward pass on a testing dataset.\n", "\n", - " Args:\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", + " 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" + " (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" ] }, { @@ -1189,15 +1250,15 @@ " loss_fn: torch.nn.Module,\n", " epochs: int,\n", " device: torch.device) -> Dict[str, List]:\n", - " \"\"\"Trains and tests a PyTorch model.\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", + " 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", + " Calculates, prints and stores evaluation metrics throughout.\n", "\n", - " Args:\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", @@ -1206,7 +1267,7 @@ " 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", + " 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", @@ -1219,43 +1280,43 @@ " 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", + " \"\"\"\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", + " }\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", + " 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", + "\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", "\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", + " # 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" + " # Return the filled results at the end of the epochs\n", + " return results" ] }, { @@ -1264,7 +1325,7 @@ "id": "tw_nYa4kfQeI" }, "source": [ - "### TK - 4.1 Creating `train_step()` and `test_step()` functions and `train()` to combine them (script mode) \n", + "### 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", @@ -1290,7 +1351,7 @@ "name": "stdout", "output_type": "stream", "text": [ - "Writing going_modular/engine.py\n" + "Overwriting going_modular/engine.py\n" ] } ], @@ -1309,110 +1370,110 @@ " 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", + " \"\"\"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", + " 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", + " 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", + " Returns:\n", " A tuple of training loss and training accuracy metrics.\n", " In the form (train_loss, train_accuracy). For example:\n", - " \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", + " # Put model in train mode\n", + " model.train()\n", "\n", - " # 1. Forward pass\n", - " y_pred = model(X)\n", + " # Setup train loss and train accuracy values\n", + " train_loss, train_acc = 0, 0\n", "\n", - " # 2. Calculate and accumulate loss\n", - " loss = loss_fn(y_pred, y)\n", - " train_loss += loss.item() \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", - " # 3. Optimizer zero grad\n", - " optimizer.zero_grad()\n", + " # 1. Forward pass\n", + " y_pred = model(X)\n", "\n", - " # 4. Loss backward\n", - " loss.backward()\n", + " # 2. Calculate and accumulate loss\n", + " loss = loss_fn(y_pred, y)\n", + " train_loss += loss.item() \n", "\n", - " # 5. Optimizer step\n", - " optimizer.step()\n", + " # 3. Optimizer zero grad\n", + " optimizer.zero_grad()\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", + " # 4. Loss backward\n", + " loss.backward()\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", + " # 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", + " \"\"\"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", + " Turns a target PyTorch model to \"eval\" mode and then performs\n", + " a forward pass on a testing dataset.\n", "\n", - " Args:\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", + " 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", + " (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", @@ -1421,15 +1482,15 @@ " loss_fn: torch.nn.Module,\n", " epochs: int,\n", " device: torch.device) -> Dict[str, List]:\n", - " \"\"\"Trains and tests a PyTorch model.\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", + " 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", + " Calculates, prints and stores evaluation metrics throughout.\n", "\n", - " Args:\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", @@ -1438,56 +1499,56 @@ " 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", + " 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", + " 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", + " {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", + " 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", + "\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", "\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", + " # 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" + " # Return the filled results at the end of the epochs\n", + " return results" ] }, { @@ -1496,7 +1557,7 @@ "id": "A2nXumITc9DL" }, "source": [ - "## TK - 5. Creating a function to save the model\n", + "## 5. Creating a function to save the model\n", "\n", "Let's setup a function to save our model to a directory." ] @@ -1514,31 +1575,31 @@ "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", + " \"\"\"Saves a PyTorch model to a target directory.\n", "\n", - " Args:\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", + "\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", + " \"\"\"\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", + " # 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)" ] }, @@ -1548,7 +1609,7 @@ "id": "F7SnPGOfc_Wc" }, "source": [ - "### TK - 5.1 Creating a function to save the model (script mode)\n", + "### 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", @@ -1570,7 +1631,7 @@ "name": "stdout", "output_type": "stream", "text": [ - "Writing going_modular/utils.py\n" + "Overwriting going_modular/utils.py\n" ] } ], @@ -1585,31 +1646,31 @@ "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", + " \"\"\"Saves a PyTorch model to a target directory.\n", "\n", - " Args:\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", + "\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", + " \"\"\"\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", + " # 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)" ] }, @@ -1652,7 +1713,7 @@ { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "c9be7bc9d56b4880b4329f814f6690ed", + "model_id": "205f478a42ca42f2ab32113d597dc388", "version_major": 2, "version_minor": 0 }, @@ -1667,12 +1728,12 @@ "name": "stdout", "output_type": "stream", "text": [ - "Epoch: 1 | train_loss: 1.0956 | train_acc: 0.3867 | test_loss: 1.0629 | test_acc: 0.4133\n", - "Epoch: 2 | train_loss: 1.0114 | train_acc: 0.5067 | test_loss: 1.0199 | test_acc: 0.4400\n", - "Epoch: 3 | train_loss: 0.9563 | train_acc: 0.5644 | test_loss: 0.9977 | test_acc: 0.4400\n", - "Epoch: 4 | train_loss: 0.8970 | train_acc: 0.5689 | test_loss: 1.0071 | test_acc: 0.4667\n", - "Epoch: 5 | train_loss: 0.8618 | train_acc: 0.6178 | test_loss: 1.0213 | test_acc: 0.4800\n", - "[INFO] Total training time: 5.192 seconds\n", + "Epoch: 1 | train_loss: 1.0956 | train_acc: 0.3867 | test_loss: 1.0630 | test_acc: 0.4133\n", + "Epoch: 2 | train_loss: 1.0141 | train_acc: 0.5111 | test_loss: 1.0210 | test_acc: 0.4533\n", + "Epoch: 3 | train_loss: 0.9591 | train_acc: 0.5644 | test_loss: 0.9961 | test_acc: 0.4400\n", + "Epoch: 4 | train_loss: 0.8994 | train_acc: 0.5778 | test_loss: 0.9986 | test_acc: 0.4533\n", + "Epoch: 5 | train_loss: 0.8652 | train_acc: 0.6267 | test_loss: 1.0010 | test_acc: 0.5467\n", + "[INFO] Total training time: 5.461 seconds\n", "[INFO] Saving model to: models/05_going_modular_cell_mode_tinyvgg_model.pth\n" ] } @@ -1764,7 +1825,7 @@ "name": "stdout", "output_type": "stream", "text": [ - "Writing going_modular/train.py\n" + "Overwriting going_modular/train.py\n" ] } ], @@ -1892,12 +1953,12 @@ "name": "stdout", "output_type": "stream", "text": [ - " 0%| | 0/5 [00:00