diff --git a/07_pytorch_experiment_tracking.ipynb b/07_pytorch_experiment_tracking.ipynb index ed69b8b..37cde2c 100644 --- a/07_pytorch_experiment_tracking.ipynb +++ b/07_pytorch_experiment_tracking.ipynb @@ -4,7 +4,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "\"Open" + "\"Open" ] }, { @@ -34,7 +34,17 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## TK 0. Getting setup " + "## TK 0. Getting setup \n", + "\n", + "Let's start by download all of the modules we'll need for this section.\n", + "\n", + "To save us writing extra code, we're going to be leveraging some of the Python scripts (such as `data_setup.py` and `engine.py`) we created in the previous section, [05. PyTorch Going Modular](https://www.learnpytorch.io/05_pytorch_going_modular/).\n", + "\n", + "Specifically, we're going to download the [`going_modular`](https://github.com/mrdbourke/pytorch-deep-learning/tree/main/going_modular) directory from the `pytorch-deep-learning` repository (if we don't already have it).\n", + "\n", + "We'll also get the [`torchinfo`](https://github.com/TylerYep/torchinfo) package if it's not available. \n", + "\n", + "`torchinfo` will help later on to give us a visual representation of our model." ] }, { @@ -74,7 +84,9 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### Setup device" + "Now let's setup device agnostic code.\n", + "\n", + "> **Note:** If you're using Google Colab, and you don't have a GPU turned on yet, it's now time to turn one on via `Runtime -> Change runtime type -> Hardware accelerator -> GPU`." ] }, { @@ -102,7 +114,51 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## TK 1. Get data" + "### TK Create a helper function to set seeds\n", + "\n", + "Since we've been setting random seeds a whole bunch throughout previous sections, how about we functionize it?\n", + "\n", + "Let's create a function to \"set the seeds\" called `set_seeds()`.\n", + "\n", + "> **Note:** Recall a [random seed](https://en.wikipedia.org/wiki/Random_seed) is a way of flavouring the randomness generated by a computer. They aren't necessary to always set when running machine learning code, however, they help ensure there's an element of reproducibility (the numbers I get with my code are similar to the numbers you get with your code). Outside of an education or experimental setting, random seeds generally aren't required." + ] + }, + { + "cell_type": "code", + "execution_count": 50, + "metadata": {}, + "outputs": [], + "source": [ + "# Set seeds\n", + "def set_seeds(seed: int=42):\n", + " \"\"\"Sets random sets for torch operations.\n", + "\n", + " Args:\n", + " seed (int, optional): Random seed to set. Defaults to 42.\n", + " \"\"\"\n", + " # Set the seed for general torch operations\n", + " torch.manual_seed(seed)\n", + " # Set the seed for CUDA torch operations (ones that happen on the GPU)\n", + " torch.cuda.manual_seed(seed)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## TK 1. Get data\n", + "\n", + "As always, before we can run machine learning experiments, we'll need a dataset.\n", + "\n", + "We're going to continue trying to improve upon the results we've been getting on FoodVision Mini.\n", + "\n", + "In the previous section, [06. PyTorch Transfer Learning](https://www.learnpytorch.io/06_pytorch_transfer_learning/), we saw how powerful using a pretrained model could be when classifying images of pizza, steak and sushi.\n", + "\n", + "So how about we try and improve our results?\n", + "\n", + "To do so, we'll use similar code to the previous section to download the [`pizza_steak_sushi.zip`](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/data/pizza_steak_sushi.zip) (if the data doesn't already exist) except this time its been functionised.\n", + "\n", + "This will allow us to use it again later. " ] }, { @@ -191,23 +247,47 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## TK 2. Create Datasets and DataLoaders" + "Excellent! Looks like we've got our pizza, steak and sushi images in standard image classification format ready to go." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## TK 2. Create Datasets and DataLoaders\n", + "\n", + "Now we've got some data, let's turn it into PyTorch DataLoaders.\n", + "\n", + "We can do so using the `create_dataloaders()` function we created in [05. PyTorch Going Modular part 2](https://www.learnpytorch.io/05_pytorch_going_modular/#2-create-datasets-and-dataloaders-data_setuppy).\n", + "\n", + "And since we'll be using transfer learning and specifically pretrained models from [`torchvision.models`](https://pytorch.org/vision/stable/models.html), we'll create a transform to prepare our images correctly.\n", + "\n", + "To transform our images in tensors, we'll be using `torchvision.transforms`.\n", + "\n", + "With the main transformation being to ensure all of our images are normalized in ImageNet format (this is because pretrained `torchvision.models` are all pretrained on ImageNet).\n", + "\n", + "We can do this with:\n", + "\n", + "```python\n", + "normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n", + " std=[0.229, 0.224, 0.225])\n", + "```" ] }, { "cell_type": "code", - "execution_count": 4, + "execution_count": 51, "metadata": {}, "outputs": [ { "data": { "text/plain": [ - "(,\n", - " ,\n", + "(,\n", + " ,\n", " ['pizza', 'steak', 'sushi'])" ] }, - "execution_count": 4, + "execution_count": 51, "metadata": {}, "output_type": "execute_result" } @@ -243,48 +323,78 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## TK 3. Getting a pretrained model, freezing the base layers and changing the classifier head" + "## TK 3. Getting a pretrained model, freezing the base layers and changing the classifier head\n", + "\n", + "Before we run multiple modelling experiments, let's see what it's like to track one.\n", + "\n", + "And since our data is ready, the next thing we'll need is a model.\n", + "\n", + "Let's download a pretrained `torchvision.models.efficientnet_b0(pretrained=True)` and prepare it for use with our own data." ] }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 53, "metadata": {}, "outputs": [], "source": [ "model = torchvision.models.efficientnet_b0(pretrained=True).to(device)\n", + "\n", + "# View the output of the model\n", "# model" ] }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": {}, - "outputs": [], - "source": [ - "torch.manual_seed(42)\n", - "torch.cuda.manual_seed(42)\n", - "\n", - "# Update the classifier\n", - "model.classifier = torch.nn.Sequential(\n", - " nn.Dropout(p=0.2),\n", - " nn.Linear(1280, len(class_names)).to(device))\n", - "\n", - "# Freeze all base layers \n", - "for param in model.features.parameters():\n", - " param.requires_grad = False" - ] - }, { "cell_type": "markdown", "metadata": {}, "source": [ - "## TK 4. Train model and track results" + "Wonderful!\n", + "\n", + "Now we've got a pretrained model let's turn into a feature extractor model.\n", + "\n", + "In essence, we'll freeze the base layers of the model (use these feature extracting) and we'll change the classifier head (output layer) to suit the number of classes we're working with (we've got 3 classes: pizza, steak, sushi).\n", + "\n", + "> **Note:** The idea of creating a feature extractor model (what we're doing here) was covered in more depth in [06. PyTorch Transfer Learning section 3.2: Setting up a pretrained model](https://www.learnpytorch.io/06_pytorch_transfer_learning/#32-setting-up-a-pretrained-model)." ] }, { "cell_type": "code", - "execution_count": 7, + "execution_count": 25, + "metadata": {}, + "outputs": [], + "source": [ + "# Since we're creating a new layer with random weights (torch.nn.Linear), \n", + "# let's set the seeds\n", + "set_seeds()\n", + "\n", + "# Freeze all base layers by setting requires_grad attribute to False\n", + "for param in model.features.parameters():\n", + " param.requires_grad = False\n", + "\n", + "# Update the classifier head to suit our problem\n", + "model.classifier = torch.nn.Sequential(\n", + " nn.Dropout(p=0.2),\n", + " nn.Linear(1280, len(class_names)).to(device))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## TK 4. Train model and track results\n", + "\n", + "Model ready to go!\n", + "\n", + "Let's get ready to train it by creating a loss function and an optimizer.\n", + "\n", + "Since we're working with multiple classes, we'll use [`torch.nn.CrossEntropyLoss()`](https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html) as the loss function.\n", + "\n", + "And we'll stick with [`torch.optim.Adam()`](https://pytorch.org/docs/stable/optim.html) with learning rate of `0.001` for the optimizer. " + ] + }, + { + "cell_type": "code", + "execution_count": 27, "metadata": {}, "outputs": [], "source": [ @@ -299,39 +409,44 @@ "source": [ "### TK Adjust training function to track results with `SummaryWriter`\n", "\n", - "See `SummaryWriter()` here: https://pytorch.org/docs/stable/tensorboard.html\n" + "Beautiful!\n", + "\n", + "All of the pieces of our training code are starting to come together.\n", + "\n", + "Let's now add the final piece to track our experiments.\n", + "\n", + "Previously we've tracked our modelling experiments using multiple Python dictionaries (one for each model).\n", + "\n", + "But you can imagine this could get out of hand if we were running anything more than a few experiments.\n", + "\n", + "Not to worry, there's a better option!\n", + "\n", + "We can use PyTorch's [`torch.utils.tensorboard.SummaryWriter()`](https://pytorch.org/docs/stable/tensorboard.html) class to save various parts of our model's training progress to file.\n", + "\n", + "By default, the `SummaryWriter()` class saves various information about our model to a file set by the `log_dir` parameter.\n", + "\n", + "The default location for `log_dir` is under `runs/CURRENT_DATETIME_HOSTNAME`, where the `HOSTNAME` is the name of your computer.\n", + "\n", + "But of course, you can change where your experiments are tracked (the filename is as customisable as you'd like).\n", + "\n", + "The outputs of the `SummaryWriter()` are saved in [TensorBoard format](https://www.tensorflow.org/tensorboard/).\n", + "\n", + "TensorBoard is a part of the TensorFlow deep learning library and is an excellent way to visualize different parts of your model.\n", + "\n", + "Let's import part of our training code from [`engine.py`](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/going_modular/going_modular/engine.py) and create a default `SummaryWriter()` instance.\n", + "\n" ] }, { "cell_type": "code", - "execution_count": 8, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'EfficietNetB0'" - ] - }, - "execution_count": 8, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "model.name = \"EfficietNetB0\"\n", - "model.name" - ] - }, - { - "cell_type": "code", - "execution_count": 9, + "execution_count": 28, "metadata": {}, "outputs": [], "source": [ "from torch.utils.tensorboard import SummaryWriter\n", "from going_modular.going_modular.engine import train_step, test_step\n", "\n", + "# Create a writer with all default settings\n", "writer = SummaryWriter()" ] }, @@ -339,18 +454,36 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "* TK - Now to use the writer, we've got to adjust the `train()` function from `engine.py`...\n", - "* TK - `train()` is from: https://github.com/mrdbourke/pytorch-deep-learning/blob/main/going_modular/going_modular/engine.py " + "Now to use the writer, we could write a new training loop or we could adjust the existing `train()` function we created in [05. PyTorch Going Modular](https://www.learnpytorch.io/05_pytorch_going_modular/#4-creating-train_step-and-test_step-functions-and-train-to-combine-them).\n", + "\n", + "Let's take the latter option.\n", + "\n", + "We'll get the `train()` function from `engine.py` and adjust it to use `writer`.\n", + "\n", + "Specifically, we'll add the ability for our `train()` function to log our model's training and test loss and accuracy values.\n", + "\n", + "We can do this with [`writer.add_scalars(main_tag, tag_scalar_dict)`](https://pytorch.org/docs/stable/tensorboard.html#torch.utils.tensorboard.writer.SummaryWriter.add_scalars), where:\n", + "* `main_tag` (string) - the name for the scalars being tracked (e.g. \"Accuracy\")\n", + "* `tag_scalar_dict` (dict) - a dictionary of the values being tracked (e.g. `{\"train_loss\": 0.3454}`)\n", + "\n", + "Once we've finished tracking values, we'll call `writer.close()` to tell the `writer` to stop looking for values to track. \n", + "\n", + "> **Note:** You can track information about your model almost anywhere in your code. But quite often experiments will be tracked *while* a model is training (inside a training/testing loop).\n", + ">\n", + "> The `torch.utils.tensorboard.SummaryWriter()` class also has many different methods to track different things about your model/data, such as [`add_graph()`](https://pytorch.org/docs/stable/tensorboard.html#torch.utils.tensorboard.writer.SummaryWriter.add_graph) which tracks the computation graph of your model. For more options, [check the PyTorch documentation](https://pytorch.org/docs/stable/tensorboard.html#torch.utils.tensorboard.writer.SummaryWriter)." ] }, { "cell_type": "code", - "execution_count": 10, + "execution_count": 33, "metadata": {}, "outputs": [], "source": [ "from typing import Dict, List\n", "from tqdm.auto import tqdm\n", + "\n", + "# Import train() function from: \n", + "# https://github.com/mrdbourke/pytorch-deep-learning/blob/main/going_modular/going_modular/engine.py\n", "def train(model: torch.nn.Module, \n", " train_dataloader: torch.utils.data.DataLoader, \n", " test_dataloader: torch.utils.data.DataLoader, \n", @@ -359,31 +492,35 @@ " 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", + " 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", + " 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", @@ -419,15 +556,23 @@ " results[\"test_loss\"].append(test_loss)\n", " results[\"test_acc\"].append(test_acc)\n", "\n", - " # Add results to SummaryWriter\n", + " ### New ###\n", + " # Add loss results to SummaryWriter\n", " writer.add_scalars(main_tag=\"Loss\", \n", " tag_scalar_dict={\"train_loss\": train_loss,\n", " \"test_loss\": test_loss},\n", " global_step=epoch)\n", + "\n", + " # Add accuracy results to SummaryWriter\n", " writer.add_scalars(main_tag=\"Accuracy\", \n", " tag_scalar_dict={\"train_acc\": train_acc,\n", " \"test_acc\": test_acc}, \n", " global_step=epoch)\n", + " \n", + " # Track the PyTorch model architecture\n", + " writer.add_graph(model=model, \n", + " # Pass in an example input\n", + " input_to_model=torch.randn(32, 3, 224, 224).to(device))\n", " \n", " # Close the writer\n", " writer.close()\n", @@ -436,15 +581,26 @@ " return results" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Woohoo!\n", + "\n", + "Our `train()` function is now updated to use a `SummaryWriter()` instance to track our model's results.\n", + "\n", + "How about we try it out for 5 epochs?" + ] + }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 34, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "c7acb79d1dd2456785ddb69b477682ec", + "model_id": "8aeb1c9ee1614bc387a5beb5651e008d", "version_major": 2, "version_minor": 0 }, @@ -459,17 +615,18 @@ "name": "stdout", "output_type": "stream", "text": [ - "Epoch: 1 | train_loss: 1.0520 | train_acc: 0.4961 | test_loss: 0.9212 | test_acc: 0.4782\n", - "Epoch: 2 | train_loss: 0.8743 | train_acc: 0.6875 | test_loss: 0.8136 | test_acc: 0.6203\n", - "Epoch: 3 | train_loss: 0.8097 | train_acc: 0.6523 | test_loss: 0.7196 | test_acc: 0.8258\n", - "Epoch: 4 | train_loss: 0.7096 | train_acc: 0.7578 | test_loss: 0.5920 | test_acc: 0.8864\n", - "Epoch: 5 | train_loss: 0.5999 | train_acc: 0.9062 | test_loss: 0.5689 | test_acc: 0.8864\n" + "Epoch: 1 | train_loss: 0.6792 | train_acc: 0.9023 | test_loss: 0.7201 | test_acc: 0.8873\n", + "Epoch: 2 | train_loss: 0.7398 | train_acc: 0.7266 | test_loss: 0.6405 | test_acc: 0.9176\n", + "Epoch: 3 | train_loss: 0.6312 | train_acc: 0.7773 | test_loss: 0.5622 | test_acc: 0.8968\n", + "Epoch: 4 | train_loss: 0.5676 | train_acc: 0.8711 | test_loss: 0.5712 | test_acc: 0.8864\n", + "Epoch: 5 | train_loss: 0.6329 | train_acc: 0.7305 | test_loss: 0.5846 | test_acc: 0.8456\n" ] } ], "source": [ "# Train model\n", "# Note: Not using engine.train() since the original script isn't updated\n", + "set_seeds()\n", "results = train(model=model,\n", " train_dataloader=train_dataloader,\n", " test_dataloader=test_dataloader,\n", @@ -483,86 +640,135 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## TK 5. View the above in TensorBoard...\n", + "Alright, looks like nothing different here but behind the scenes our `writer` instance has created a `runs/` directory storing our model's results.\n", "\n", - "TK - What is TensorBoard?\n", + "TK - filename of \"runs/...\" dir\n", "\n", - "TK You can view the training results above in TensorBoard in a number of ways:\n", - "\n", - "| Code environment | How to view TensorBoard | Resource |\n", - "| ----- | ----- | ----- |\n", - "| VS Code (notebooks or Python scripts) | Press `SHIFT + CMD + P` to open the Command Palette and search for the command \"Python: Launch TensorBoard\". | [VS Code Guide on TensorBoard and PyTorch](https://code.visualstudio.com/docs/datascience/pytorch-support#_tensorboard-integration) |\n", - "| Jupyter and Colab Notebooks | Make sure [TensorBoard is installed](https://pypi.org/project/tensorboard/), load it with `%load_ext tensorboard` and then view your results with `%tensorboard --logdir DIR_WITH_LOGS`. | [`torch.utils.tensorboard`](https://pytorch.org/docs/stable/tensorboard.html) and [Get started with TensorBoard](https://www.tensorflow.org/tensorboard/get_started) |\n", - "\n", - "You can also upload your experiments to [tensorboard.dev](https://tensorboard.dev/) to share them publicly with others." + "We'll check these out in a second but just as a reminder, we were previously tracking our model's results in a dictionary." ] }, { "cell_type": "code", - "execution_count": 12, + "execution_count": 55, "metadata": {}, "outputs": [ { "data": { "text/plain": [ - "Reusing TensorBoard on port 6006 (pid 1168517), started 2 days, 3:10:48 ago. (Use '!kill 1168517' to kill it.)" + "{'train_loss': [0.6791654154658318,\n", + " 0.7398175299167633,\n", + " 0.6312201134860516,\n", + " 0.5675686299800873,\n", + " 0.6329038292169571],\n", + " 'train_acc': [0.90234375, 0.7265625, 0.77734375, 0.87109375, 0.73046875],\n", + " 'test_loss': [0.7201185425122579,\n", + " 0.6404749552408854,\n", + " 0.5622232655684153,\n", + " 0.5712322692076365,\n", + " 0.5846467117468516],\n", + " 'test_acc': [0.8873106060606061,\n", + " 0.9176136363636364,\n", + " 0.8967803030303031,\n", + " 0.8863636363636364,\n", + " 0.8456439393939394]}" ] }, + "execution_count": 55, "metadata": {}, - "output_type": "display_data" - }, - { - "data": { - "text/html": [ - "\n", - " \n", - " \n", - " " - ], - "text/plain": [ - "" - ] - }, - "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" } ], "source": [ - "# Example code to run in Google Colab\n", - "%load_ext tensorboard\n", - "%tensorboard --logdir runs" + "# Check out the model results\n", + "results" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "## TK 6. Create a helper function to build `SummaryWriter()` instances" + "Hmmm, we could format this to be a nice plot but could you image keeping track of a bunch of these dictionaries?\n", + "\n", + "There has to be a better way..." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## TK 5. View our model's results in TensorBoard\n", + "\n", + "The `SummaryWriter()` class stores our model's results by default in a directory called `runs/` in TensorBoard format.\n", + "\n", + "TensorBoard is a visualization program created by the TensorFlow team to view and inspect information about models and data.\n", + "\n", + "You know what that means?\n", + "\n", + "It's time to follow the data visualizer's motto and *visualize, visualize, visualize!* \n", + "\n", + "You can view TensorBoard in a number of ways:\n", + "\n", + "| Code environment | How to view TensorBoard | Resource |\n", + "| ----- | ----- | ----- |\n", + "| VS Code (notebooks or Python scripts) | Press `SHIFT + CMD + P` to open the Command Palette and search for the command \"Python: Launch TensorBoard\". | [VS Code Guide on TensorBoard and PyTorch](https://code.visualstudio.com/docs/datascience/pytorch-support#_tensorboard-integration) |\n", + "| Jupyter and Colab Notebooks | Make sure [TensorBoard is installed](https://pypi.org/project/tensorboard/), load it with `%load_ext tensorboard` and then view your results with `%tensorboard --logdir DIR_WITH_LOGS`. | [`torch.utils.tensorboard`](https://pytorch.org/docs/stable/tensorboard.html) and [Get started with TensorBoard](https://www.tensorflow.org/tensorboard/get_started) |\n", + "\n", + "You can also upload your experiments to [tensorboard.dev](https://tensorboard.dev/) to share them publicly with others.\n", + "\n", + "Running the following code in a Google Colab or Jupyter Notebook will start an interactive TensorBoard session to view TensorBoard files in the `runs/` directory.\n", + "\n", + "```python\n", + "%load_ext tensorboard # line magic to load TensorBoard\n", + "%tensorboard --logdir runs # run TensorBoard session with the \"runs/\" directory\n", + "```" ] }, { "cell_type": "code", - "execution_count": 35, + "execution_count": 56, + "metadata": {}, + "outputs": [], + "source": [ + "# Example code to run in Jupyter or Google Colab Notebook (uncomment to try it out)\n", + "# %load_ext tensorboard\n", + "# %tensorboard --logdir runs" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If all went correctly, you should see something like the following:\n", + "\n", + "* TK image - tensorboard session with `runs/` directory \n", + "* TK explain the different things you can view on TensorBoard\n", + "\n", + "> **Note:** For more information on running TensorBoard in notebooks or in other locations, see the following:\n", + "> * [Using TensorBoard in Notebooks guide by TensorFlow](https://www.tensorflow.org/tensorboard/tensorboard_in_notebooks)\n", + "> * [Get started with TensorBoard.dev](https://tensorboard.dev/#get-started) (helpful for uploading your TensorBoard logs to a shareable link)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## TK 6. Create a helper function to build `SummaryWriter()` instances\n", + "\n", + "UPTOHERE" + ] + }, + { + "cell_type": "code", + "execution_count": 36, "metadata": {}, "outputs": [ { "data": { "text/plain": [ - "'2022-06-02'" + "'2022-06-03'" ] }, - "execution_count": 35, + "execution_count": 36, "metadata": {}, "output_type": "execute_result" } @@ -574,7 +780,7 @@ }, { "cell_type": "code", - "execution_count": 36, + "execution_count": 37, "metadata": {}, "outputs": [], "source": [ @@ -592,15 +798,23 @@ " return SummaryWriter(log_dir=log_dir)" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### TK 6.1 Update the `train()` function to include `create_writer()` " + ] + }, { "cell_type": "code", - "execution_count": 37, + "execution_count": 38, "metadata": {}, "outputs": [], "source": [ "# Add create_writer() to train()\n", "from typing import Dict, List\n", "from tqdm.auto import tqdm\n", + "\n", "def train(model: torch.nn.Module, \n", " train_dataloader: torch.utils.data.DataLoader, \n", " test_dataloader: torch.utils.data.DataLoader, \n", @@ -704,23 +918,53 @@ "\n", "TK - turn this into a table...\n", "\n", - "TK - experiments to track:\n", - "- model_0 = 10% data, effnet_b0, 5 epochs\n", - "- model_1 = 10% data, effnet_b0, 10 epochs (double training time)\n", - "- model_2 = 20% data, effnet_b0, 5 epochs (double data)\n", - "- model_3 = 10% data, effnet_b2, 5 epochs (double model parameters)\n", - "- 2 x epochs, 2 x models, 2 x datasets = 6 models total\n", + "TK - what kind of experiments should you run?\n", + "* all different hyperparameters - image size, learning rate, number of epochs\n", + "* different amounts of data\n", + "* different kinds of data augmentation\n", + "* if something works better than others, scale it up\n", + "\n", + "TK - things to know about running experiments (generally, the quicker the better)\n", + "\n", + "TK - where did data come from? - https://github.com/mrdbourke/pytorch-deep-learning/blob/main/extras/04_custom_data_creation.ipynb \n", + "\n", + "| Experiment number | Dataset | Model | Number of epochs |\n", + "| ----- | ----- | ----- | ----- |\n", + "| 1 | Pizza, Steak, Sushi 10% percent | EfficientNetB0 | 5 |\n", + "| 2 | Pizza, Steak, Sushi 10% percent | EfficientNetB2 | 5 | \n", + "| 3 | Pizza, Steak, Sushi 10% percent | EfficientNetB0 | 10 | \n", + "| 4 | Pizza, Steak, Sushi 10% percent | EfficientNetB2 | 10 |\n", + "| 5 | Pizza, Steak, Sushi 20% percent | EfficientNetB0 | 5 |\n", + "| 6 | Pizza, Steak, Sushi 20% percent | EfficientNetB2 | 5 |\n", + "| 7 | Pizza, Steak, Sushi 20% percent | EfficientNetB0 | 10 |\n", + "| 8 | Pizza, Steak, Sushi 20% percent | EfficientNetB2 | 10 |\n", + "\n", + "Notice how we're running a series of experiments to slowly increase the amount of data, the model size and the length of training.\n", + "\n", + "By the end, experiment 8 will be using double the data, double the model size and double the length of training compared to experiment 1. \n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### TK - Load and prepare different datasets\n", + "\n", + "* TK - Create two datasets for:\n", + " * Train with 10% of data\n", + " * Train with 20% of data\n", + "* TK - See how the data was created: https://github.com/mrdbourke/pytorch-deep-learning/blob/main/extras/04_custom_data_creation.ipynb \n", "\n", "See a list of Torch pretrained models here: https://pytorch.org/vision/stable/models.html, all pretrained models are expected to have data inputs that are normalized with the following:\n", "```python\n", "normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n", " std=[0.229, 0.224, 0.225])\n", - "``` \n" + "``` " ] }, { "cell_type": "code", - "execution_count": 38, + "execution_count": 39, "metadata": {}, "outputs": [], "source": [ @@ -736,21 +980,9 @@ "])" ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### TK - Load data\n", - "\n", - "* TK - Create two datasets for:\n", - " * Train with 10% of data\n", - " * Train with 20% of data\n", - "* TK - See how the data was created: https://github.com/mrdbourke/pytorch-deep-learning/blob/main/extras/04_custom_data_creation.ipynb " - ] - }, { "cell_type": "code", - "execution_count": 39, + "execution_count": 40, "metadata": {}, "outputs": [ { @@ -763,6 +995,7 @@ } ], "source": [ + "# Download 10 percent and 20 percent training data (if necessary)\n", "data_10_percent_path = download_data(source=\"https://github.com/mrdbourke/pytorch-deep-learning/raw/main/data/pizza_steak_sushi.zip\",\n", " destination=\"pizza_steak_sushi\")\n", "\n", @@ -772,7 +1005,7 @@ }, { "cell_type": "code", - "execution_count": 40, + "execution_count": 41, "metadata": {}, "outputs": [], "source": [ @@ -786,37 +1019,42 @@ }, { "cell_type": "code", - "execution_count": 41, + "execution_count": 48, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "(8, 15, 3, 3)" - ] - }, - "execution_count": 41, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "Number of batches of size 32 in 10 percent training data: 8\n", + "Number of batches of size 32 in 20 percent training data: 15\n", + "Number of batches of size 32 in testing data: 8 (all experiments will use the same test set)\n", + "Number of classes: 3, class names: ['pizza', 'steak', 'sushi']\n" + ] } ], "source": [ - "# Create 10% dataloaders\n", + "BATCH_SIZE = 32\n", + "\n", + "# Create 10% training data dataloaders\n", "train_dataloader_10_percent, test_dataloader, class_names = data_setup.create_dataloaders(train_dir=train_dir_10_percent,\n", " test_dir=test_dir,\n", " transform=simple_transform,\n", - " batch_size=32\n", + " batch_size=BATCH_SIZE\n", ")\n", "\n", - "# Create 20% dataloaders\n", + "# Create 20% training data dataloaders\n", "train_dataloader_20_percent, test_dataloader, class_names = data_setup.create_dataloaders(train_dir=train_dir_20_percent,\n", " test_dir=test_dir,\n", " transform=simple_transform,\n", - " batch_size=32\n", + " batch_size=BATCH_SIZE\n", ")\n", "\n", - "# TK - number of samples/batches per dataloader (using the same test_dataloader for both experiments)\n", - "len(train_dataloader_10_percent), len(train_dataloader_20_percent), len(test_dataloader), len(class_names)" + "# Find the number of samples/batches per dataloader (using the same test_dataloader for both experiments)\n", + "print(f\"Number of batches of size {BATCH_SIZE} in 10 percent training data: {len(train_dataloader_10_percent)}\")\n", + "print(f\"Number of batches of size {BATCH_SIZE} in 20 percent training data: {len(train_dataloader_20_percent)}\")\n", + "print(f\"Number of batches of size {BATCH_SIZE} in testing data: {len(train_dataloader_10_percent)} (all experiments will use the same test set)\")\n", + "print(f\"Number of classes: {len(class_names)}, class names: {class_names}\")" ] }, { @@ -830,7 +1068,7 @@ }, { "cell_type": "code", - "execution_count": 42, + "execution_count": 43, "metadata": {}, "outputs": [], "source": [ @@ -846,7 +1084,7 @@ }, { "cell_type": "code", - "execution_count": 43, + "execution_count": 44, "metadata": {}, "outputs": [ { @@ -855,7 +1093,7 @@ "1408" ] }, - "execution_count": 43, + "execution_count": 44, "metadata": {}, "output_type": "execute_result" } @@ -867,18 +1105,13 @@ }, { "cell_type": "code", - "execution_count": 44, + "execution_count": 45, "metadata": {}, "outputs": [], "source": [ "import torchvision\n", "from torch import nn\n", "\n", - "# Set seeds\n", - "def set_seeds(seed=42):\n", - " torch.manual_seed(seed)\n", - " torch.cuda.manual_seed(seed)\n", - "\n", "# Get num out features\n", "OUT_FEATURES = len(class_names)\n", "\n", @@ -929,12 +1162,12 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Create experiments" + "### TK - Create experiments and set up training code" ] }, { "cell_type": "code", - "execution_count": 45, + "execution_count": 46, "metadata": {}, "outputs": [], "source": [ @@ -951,7 +1184,7 @@ }, { "cell_type": "code", - "execution_count": 51, + "execution_count": 49, "metadata": {}, "outputs": [ { @@ -963,13 +1196,13 @@ "[INFO] DataLoader: data_10_percent\n", "[INFO] Training for 5 epochs\n", "----------\n", - "Created SummaryWriter and saving to runs/2022-06-02/data_10_percent/effnetb0/_5_epochs...\n" + "Created SummaryWriter and saving to runs/2022-06-03/data_10_percent/effnetb0/5_epochs...\n" ] }, { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "8c07e32372d243ab9c8cbbab97efaa1d", + "model_id": "22fa4b3b64a1412283c4fe3365f31cb9", "version_major": 2, "version_minor": 0 }, @@ -989,7 +1222,6 @@ "Epoch: 3 | train_loss: 0.8097 | train_acc: 0.6523 | test_loss: 0.7196 | test_acc: 0.8258\n", "Epoch: 4 | train_loss: 0.7096 | train_acc: 0.7578 | test_loss: 0.5920 | test_acc: 0.8864\n", "Epoch: 5 | train_loss: 0.5999 | train_acc: 0.9062 | test_loss: 0.5689 | test_acc: 0.8864\n", - "[INFO] Saving model to 07_effnetb0_data_10_percent_5_epochs.pth\n", "[INFO] Saving model to: models/07_effnetb0_data_10_percent_5_epochs.pth\n", "----------\n", "\n", @@ -998,13 +1230,13 @@ "[INFO] DataLoader: data_10_percent\n", "[INFO] Training for 5 epochs\n", "----------\n", - "Created SummaryWriter and saving to runs/2022-06-02/data_10_percent/effnetb2/_5_epochs...\n" + "Created SummaryWriter and saving to runs/2022-06-03/data_10_percent/effnetb2/5_epochs...\n" ] }, { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "da29eefda13f4105b3cc2fde3e1e1e56", + "model_id": "84d43c55bd0d449dbd89342b9714e2eb", "version_major": 2, "version_minor": 0 }, @@ -1024,7 +1256,6 @@ "Epoch: 3 | train_loss: 0.8080 | train_acc: 0.7578 | test_loss: 0.7511 | test_acc: 0.9072\n", "Epoch: 4 | train_loss: 0.7182 | train_acc: 0.8867 | test_loss: 0.7161 | test_acc: 0.9081\n", "Epoch: 5 | train_loss: 0.6847 | train_acc: 0.7656 | test_loss: 0.7087 | test_acc: 0.8873\n", - "[INFO] Saving model to 07_effnetb2_data_10_percent_5_epochs.pth\n", "[INFO] Saving model to: models/07_effnetb2_data_10_percent_5_epochs.pth\n", "----------\n", "\n", @@ -1033,13 +1264,13 @@ "[INFO] DataLoader: data_10_percent\n", "[INFO] Training for 10 epochs\n", "----------\n", - "Created SummaryWriter and saving to runs/2022-06-02/data_10_percent/effnetb0/_10_epochs...\n" + "Created SummaryWriter and saving to runs/2022-06-03/data_10_percent/effnetb0/10_epochs...\n" ] }, { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "242b96e6f5e1436c97f8454d4fc49b66", + "model_id": "bda0cea43afa466691557a2582d2f61c", "version_major": 2, "version_minor": 0 }, @@ -1064,7 +1295,6 @@ "Epoch: 8 | train_loss: 0.4700 | train_acc: 0.9492 | test_loss: 0.5199 | test_acc: 0.8759\n", "Epoch: 9 | train_loss: 0.5729 | train_acc: 0.7695 | test_loss: 0.5120 | test_acc: 0.8873\n", "Epoch: 10 | train_loss: 0.4782 | train_acc: 0.8242 | test_loss: 0.4650 | test_acc: 0.9072\n", - "[INFO] Saving model to 07_effnetb0_data_10_percent_10_epochs.pth\n", "[INFO] Saving model to: models/07_effnetb0_data_10_percent_10_epochs.pth\n", "----------\n", "\n", @@ -1073,13 +1303,13 @@ "[INFO] DataLoader: data_10_percent\n", "[INFO] Training for 10 epochs\n", "----------\n", - "Created SummaryWriter and saving to runs/2022-06-02/data_10_percent/effnetb2/_10_epochs...\n" + "Created SummaryWriter and saving to runs/2022-06-03/data_10_percent/effnetb2/10_epochs...\n" ] }, { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "5c30dac86f8b40f7bef3c83bcc581453", + "model_id": "7217e45ae841404685e06b34ba4f48e4", "version_major": 2, "version_minor": 0 }, @@ -1104,7 +1334,6 @@ "Epoch: 8 | train_loss: 0.5196 | train_acc: 0.9336 | test_loss: 0.6201 | test_acc: 0.8977\n", "Epoch: 9 | train_loss: 0.5421 | train_acc: 0.8086 | test_loss: 0.6231 | test_acc: 0.8769\n", "Epoch: 10 | train_loss: 0.4919 | train_acc: 0.8086 | test_loss: 0.5879 | test_acc: 0.8873\n", - "[INFO] Saving model to 07_effnetb2_data_10_percent_10_epochs.pth\n", "[INFO] Saving model to: models/07_effnetb2_data_10_percent_10_epochs.pth\n", "----------\n", "\n", @@ -1113,13 +1342,13 @@ "[INFO] DataLoader: data_20_percent\n", "[INFO] Training for 5 epochs\n", "----------\n", - "Created SummaryWriter and saving to runs/2022-06-02/data_20_percent/effnetb0/_5_epochs...\n" + "Created SummaryWriter and saving to runs/2022-06-03/data_20_percent/effnetb0/5_epochs...\n" ] }, { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "beb5a98ddda24d2cbd524541791e27b4", + "model_id": "e50fa786facb4351b77b28445cdcfad1", "version_major": 2, "version_minor": 0 }, @@ -1139,7 +1368,6 @@ "Epoch: 3 | train_loss: 0.5805 | train_acc: 0.8604 | test_loss: 0.4576 | test_acc: 0.9176\n", "Epoch: 4 | train_loss: 0.4937 | train_acc: 0.8646 | test_loss: 0.4454 | test_acc: 0.9176\n", "Epoch: 5 | train_loss: 0.4886 | train_acc: 0.8500 | test_loss: 0.3913 | test_acc: 0.9176\n", - "[INFO] Saving model to 07_effnetb0_data_20_percent_5_epochs.pth\n", "[INFO] Saving model to: models/07_effnetb0_data_20_percent_5_epochs.pth\n", "----------\n", "\n", @@ -1148,13 +1376,13 @@ "[INFO] DataLoader: data_20_percent\n", "[INFO] Training for 5 epochs\n", "----------\n", - "Created SummaryWriter and saving to runs/2022-06-02/data_20_percent/effnetb2/_5_epochs...\n" + "Created SummaryWriter and saving to runs/2022-06-03/data_20_percent/effnetb2/5_epochs...\n" ] }, { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "be92607064144c84a8e45607cd1dcff9", + "model_id": "ca0159cbcdff43c99e3d6f2304343da4", "version_major": 2, "version_minor": 0 }, @@ -1174,7 +1402,6 @@ "Epoch: 3 | train_loss: 0.6011 | train_acc: 0.8458 | test_loss: 0.5633 | test_acc: 0.9280\n", "Epoch: 4 | train_loss: 0.5429 | train_acc: 0.8354 | test_loss: 0.5685 | test_acc: 0.8977\n", "Epoch: 5 | train_loss: 0.4410 | train_acc: 0.8708 | test_loss: 0.4470 | test_acc: 0.9384\n", - "[INFO] Saving model to 07_effnetb2_data_20_percent_5_epochs.pth\n", "[INFO] Saving model to: models/07_effnetb2_data_20_percent_5_epochs.pth\n", "----------\n", "\n", @@ -1183,13 +1410,13 @@ "[INFO] DataLoader: data_20_percent\n", "[INFO] Training for 10 epochs\n", "----------\n", - "Created SummaryWriter and saving to runs/2022-06-02/data_20_percent/effnetb0/_10_epochs...\n" + "Created SummaryWriter and saving to runs/2022-06-03/data_20_percent/effnetb0/10_epochs...\n" ] }, { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "7a5c4e7a584e4664901c7edb94a40262", + "model_id": "f7e034a9e2f749229fd359939e06793b", "version_major": 2, "version_minor": 0 }, @@ -1214,7 +1441,6 @@ "Epoch: 8 | train_loss: 0.3739 | train_acc: 0.8938 | test_loss: 0.3346 | test_acc: 0.8977\n", "Epoch: 9 | train_loss: 0.2975 | train_acc: 0.9375 | test_loss: 0.3088 | test_acc: 0.9280\n", "Epoch: 10 | train_loss: 0.3625 | train_acc: 0.8479 | test_loss: 0.2771 | test_acc: 0.9072\n", - "[INFO] Saving model to 07_effnetb0_data_20_percent_10_epochs.pth\n", "[INFO] Saving model to: models/07_effnetb0_data_20_percent_10_epochs.pth\n", "----------\n", "\n", @@ -1223,13 +1449,13 @@ "[INFO] DataLoader: data_20_percent\n", "[INFO] Training for 10 epochs\n", "----------\n", - "Created SummaryWriter and saving to runs/2022-06-02/data_20_percent/effnetb2/_10_epochs...\n" + "Created SummaryWriter and saving to runs/2022-06-03/data_20_percent/effnetb2/10_epochs...\n" ] }, { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "3e904514585b49339ff7c4434f44ac50", + "model_id": "969b861a30e04ef8abef8189ca5be6a2", "version_major": 2, "version_minor": 0 }, @@ -1254,12 +1480,11 @@ "Epoch: 8 | train_loss: 0.3861 | train_acc: 0.8792 | test_loss: 0.4350 | test_acc: 0.9280\n", "Epoch: 9 | train_loss: 0.3315 | train_acc: 0.8979 | test_loss: 0.4254 | test_acc: 0.9081\n", "Epoch: 10 | train_loss: 0.3382 | train_acc: 0.8979 | test_loss: 0.3909 | test_acc: 0.9384\n", - "[INFO] Saving model to 07_effnetb2_data_20_percent_10_epochs.pth\n", "[INFO] Saving model to: models/07_effnetb2_data_20_percent_10_epochs.pth\n", "----------\n", "\n", - "CPU times: user 36 s, sys: 31.4 s, total: 1min 7s\n", - "Wall time: 1min 19s\n" + "CPU times: user 36.5 s, sys: 46.2 s, total: 1min 22s\n", + "Wall time: 1min 36s\n" ] } ], @@ -1310,7 +1535,6 @@ " \n", " # Save the model to file so we can get back the best model\n", " save_filepath = f\"07_{model_name}_{dataloader_name}_{epochs}_epochs.pth\"\n", - " print(f\"[INFO] Saving model to {save_filepath}\")\n", " save_model(model=model,\n", " target_dir=\"models\",\n", " model_name=save_filepath)\n", @@ -1321,7 +1545,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## View experiments in TensorBoard\n", + "## TK 8. View experiments in TensorBoard\n", "\n", "* TK - See example notebook: https://colab.research.google.com/github/tensorflow/tensorboard/blob/master/docs/tensorboard_in_notebooks.ipynb#scrollTo=GUSM8yLrO2yZ \n", "\n", @@ -1390,7 +1614,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## TK - Load in the best model and make predictions with it\n", + "## TK - 9. Load in the best model and make predictions with it\n", "\n", "TK - best model = effnetb2 + 10 epochs + 20% data (double parameters, double data, double training time)" ] @@ -1468,7 +1692,8 @@ } ], "source": [ - "# TK - import function from previously created section: https://www.learnpytorch.io/06_pytorch_transfer_learning/#6-make-predictions-on-images-from-the-test-set \n", + "# Import function to make predictions on images and plot them \n", + "# See the function previously created in section: https://www.learnpytorch.io/06_pytorch_transfer_learning/#6-make-predictions-on-images-from-the-test-set\n", "from going_modular.going_modular.predictions import pred_and_plot_image\n", "\n", "# Get a random list of 3 images from 20% test set\n", @@ -1545,9 +1770,9 @@ "metadata": {}, "source": [ "## Exercises\n", - "* Add functionality to save the best model?\n", - "* Scale up the dataset (e.g. could use *all* of Food101 + track experiment)\n", + "* Upload TensorBoard results to [Get started with TensorBoard.dev](https://tensorboard.dev/#get-started) (helpful for uploading your TensorBoard logs to a shareable link)\n", "* Introduce data augmentation to the list of experiments, does this change anything?\n", + "* Scale up the dataset (e.g. could use *all* of Food101 + design 2 experiments, perhaps a large and a small model, track experiments)\n", "* Could use the following for data augmentation:\n", "\n", "```python\n", @@ -1627,26 +1852,12 @@ "source": [ "## Extra-curriculum\n", "\n", + "* Check out the PyTorch YouTube tutorial for TensorBoard -- https://pytorch.org/tutorials/beginner/introyt/tensorboardyt_tutorial.html \n", "* See here for more on the profiler: https://pytorch.org/blog/introducing-pytorch-profiler-the-new-and-improved-performance-tool/\n", "* See here on setting up TensorBoard in VSCode: https://code.visualstudio.com/docs/datascience/pytorch-support\n", "* See more on ML experiment tracking - https://madewithml.com/courses/mlops/experiment-tracking/ \n", "* Does changing the data input size to EfficientNetB4 change its results? E.g. input image size of (380, 380) instead of (224, 224)?" ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "
\n", - "Example: Use yellow boxes for examples that are not \n", - "inside code cells, or use for mathematical formulas if needed.\n", - "
" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [] } ], "metadata": {