diff --git a/02_test_computer_vision.ipynb b/02_test_computer_vision.ipynb index f9c67a9..dc78994 100644 --- a/02_test_computer_vision.ipynb +++ b/02_test_computer_vision.ipynb @@ -3392,13 +3392,236 @@ "> **Exercise:** Use the trained `model_2` to make predictions on the test FashionMNIST dataset. Then plot some predictions where the model was wrong alongside what the label of the image should've been. After visualing these predictions do you think it's more of a modelling error or a data error? As in, could the model do better or are the labels of the data too close to each other (e.g. a \"Shirt\" label is too close to \"T-shirt/top\")?" ] }, + { + "cell_type": "markdown", + "id": "0d032a8b-8c43-4af8-a8d3-fea7e8c52639", + "metadata": {}, + "source": [ + "## TK - 11. Save and load best performing model\n", + "\n", + "Let's finish this section off by saving and loading in our best performing model.\n", + "\n", + "Recall from [notebook 01](https://www.learnpytorch.io/01_pytorch_workflow/#5-saving-and-loading-a-pytorch-model) we can save and load a PyTorch model using a combination of:\n", + "* `torch.save` - a function to save a whole PyTorch model or a model's `state_dict()`. \n", + "* `torch.load` - a function to load in a saved PyTorch object.\n", + "* `torch.nn.Module.load_state_dict()` - a function to load a saved `state_dict()` into an existing model instance.\n", + "\n", + "You can see more of these three in the [PyTorch saving and loading models documentation](https://pytorch.org/tutorials/beginner/saving_loading_models.html).\n", + "\n", + "For now, let's save our `model_2`'s `state_dict()` then load it back in and evaluate it to make sure the save and load went correctly. " + ] + }, { "cell_type": "code", - "execution_count": null, - "id": "78f45489-d5a1-4d86-8a06-fb037f631153", + "execution_count": 68, + "id": "6c61a025-2d30-48d7-a78e-79f22e17b5a2", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Saving model to: models/03_pytorch_computer_vision_model_2.pth\n" + ] + } + ], + "source": [ + "from pathlib import Path\n", + "\n", + "# Create models directory (if it doesn't already exist), see: https://docs.python.org/3/library/pathlib.html#pathlib.Path.mkdir\n", + "MODEL_PATH = Path(\"models\")\n", + "MODEL_PATH.mkdir(parents=True, # create parent directories if needed\n", + " exist_ok=True # if models directory already exists, don't error\n", + ")\n", + "\n", + "# Create model save path\n", + "MODEL_NAME = \"03_pytorch_computer_vision_model_2.pth\"\n", + "MODEL_SAVE_PATH = MODEL_PATH / MODEL_NAME\n", + "\n", + "# Save the model state dict\n", + "print(f\"Saving model to: {MODEL_SAVE_PATH}\")\n", + "torch.save(obj=model_2.state_dict(), # only saving the state_dict() only saves the learned parameters\n", + " f=MODEL_SAVE_PATH)" + ] + }, + { + "cell_type": "markdown", + "id": "3db5eb74-baf4-4e9d-be28-76cfb07ce9cc", + "metadata": {}, + "source": [ + "Now we've got a saved model `state_dict()` we can load it back in using a combination of `load_state_dict()` and `torch.load()`.\n", + "\n", + "Since we're using `load_state_dict()`, we'll need to create a new instance of `FashionMNISTModelV2()` with the same input parameters as our saved model `state_dict()`." + ] + }, + { + "cell_type": "code", + "execution_count": 69, + "id": "467a0096-ef34-443a-9ef1-c3e6dfc1059e", "metadata": {}, "outputs": [], - "source": [] + "source": [ + "# Create a new instance of FashionMNISTModelV2 (the same class as our saved state_dict())\n", + "# Note: loading model will error if the shapes here aren't the same as the saved version\n", + "loaded_model_2 = FashionMNISTModelV2(input_shape=1, \n", + " hidden_units=10, # try changing this to 128 and seeing what happens \n", + " output_shape=10) \n", + "\n", + "# Load in the saved state_dict()\n", + "loaded_model_2.load_state_dict(torch.load(f=MODEL_SAVE_PATH))\n", + "\n", + "# Send model to GPU\n", + "loaded_model_2 = loaded_model_2.to(device)" + ] + }, + { + "cell_type": "markdown", + "id": "7f5d2a13-a46f-4287-9f70-e92b07b6f48d", + "metadata": {}, + "source": [ + "And now we've got a loaded model we can evaluate it with `eval_model()` to make sure its parameters work similarly to `model_2` prior to saving. " + ] + }, + { + "cell_type": "code", + "execution_count": 70, + "id": "0d19e01a-047f-4933-bf20-0affef638e52", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{'model_name': 'FashionMNISTModelV2',\n", + " 'model_loss': 0.3181978464126587,\n", + " 'model_acc': 88.4285143769968}" + ] + }, + "execution_count": 70, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Evaluate loaded model\n", + "torch.manual_seed(42)\n", + "\n", + "loaded_model_2_results = eval_model(\n", + " model=loaded_model_2,\n", + " data_loader=test_dataloader,\n", + " loss_fn=loss_fn, \n", + " accuracy_fn=accuracy_fn\n", + ")\n", + "\n", + "loaded_model_2_results" + ] + }, + { + "cell_type": "markdown", + "id": "a475055d-0429-4306-9e08-5a3be4d6a16f", + "metadata": {}, + "source": [ + "Do these results look the same as `model_2_results`?" + ] + }, + { + "cell_type": "code", + "execution_count": 71, + "id": "f31f3f75-4b56-4a9b-b0f0-204587e76caf", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{'model_name': 'FashionMNISTModelV2',\n", + " 'model_loss': 0.3181978464126587,\n", + " 'model_acc': 88.4285143769968}" + ] + }, + "execution_count": 71, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "model_2_results" + ] + }, + { + "cell_type": "markdown", + "id": "fa7d57a8-18af-40c9-baff-318bd8ec1246", + "metadata": {}, + "source": [ + "We can find out if two tensors are close to each other using `torch.isclose()` and passing in a tolerance level of closeness via the parameters `atol` (absolute tolerance) and `rtol` (relative tolerance).\n", + "\n", + "If our model's results are close, the output of `torch.isclose()` should be true." + ] + }, + { + "cell_type": "code", + "execution_count": 72, + "id": "dc4baa90-cd41-438f-8bb2-011ea80a3ce5", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "tensor(True)" + ] + }, + "execution_count": 72, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check to see if results are close to each other (if they are very far away, there may be an error)\n", + "torch.isclose(torch.tensor(model_2_results[\"model_loss\"]), \n", + " torch.tensor(loaded_model_2_results[\"model_loss\"]),\n", + " atol=1e-08, # absolute tolerance\n", + " rtol=0.0001) # relative tolerance" + ] + }, + { + "cell_type": "markdown", + "id": "10f4edf9-b52f-4dbe-b2d4-482cba91f5ce", + "metadata": {}, + "source": [ + "## TK - Exercises\n", + "\n", + "All of the exercises are focused on practicing the code in the sections above.\n", + "\n", + "You should be able to complete them by referencing each section or by following the resource(s) linked.\n", + "\n", + "All exercises should be completed using [device-agonistic code](https://pytorch.org/docs/stable/notes/cuda.html#device-agnostic-code).\n", + "\n", + "Resources:\n", + "* TK - Exercise template notebook for 03\n", + "* TK - Example solutions notebook for 03 (try the exercises *before* looking at this)\n", + "\n", + "1. What are 3 areas in industry where computer vision is currently being used?\n", + "2. Search \"what is overfitting in machine learning\" and write down a sentence about what you find. \n", + "3. Search \"ways to prevent overfitting in machine learning\", write down 3 of the things you find and a sentence about each. **Note:** there are lots of these, so don't worry too much about all of them, just pick 3 and start with those.\n", + "4. Spend 20-minutes reading and clicking through the [CNN Explainer website](https://poloclub.github.io/cnn-explainer/).\n", + " * Upload your own example image using the \"upload\" button and see what happens in each layer of a CNN as your image passes through it.\n", + "5. Load the [`torchvision.datasets.MNIST()`](https://pytorch.org/vision/stable/generated/torchvision.datasets.MNIST.html#torchvision.datasets.MNIST) train and test datasets.\n", + "6. Visualize at least 5 different samples of the MNIST training dataset.\n", + "7. Turn the MNIST train and test datasets into dataloaders using `torch.utils.data.DataLoader`, set the `batch_size=32`.\n", + "8. Recreate `model_2` used in this notebook (the same model from the [CNN Explainer website](https://poloclub.github.io/cnn-explainer/), also known as TinyVGG) capable of fitting on the MNIST dataset.\n", + "9. Train the model you built in 8. on CPU and GPU and see how long it takes on each.\n", + "10. Make predictions using your trained model and visualize at least 5 of them comparing the prediciton to the target label.\n", + "11. Plot a confusion matrix comparing your model's predictions to the truth labels.\n", + "12. Create a random tensor of shape `[1, 3, 64, 64]` and pass it through a `nn.Conv2d()` layer with various hyperparameter settings (these can be any settings you choose), what do you notice if the `kernel_size` parameter goes up and down?\n", + "13. Use the trained `model_2` from this notebook to make predictions on the test [`torchvision.datasets.FashionMNIST`](https://pytorch.org/vision/main/generated/torchvision.datasets.FashionMNIST.html) dataset. \n", + " * Then plot some predictions where the model was wrong alongside what the label of the image should've been. \n", + " * After visualing these predictions do you think it's more of a modelling error or a data error? \n", + " * As in, could the model do better or are the labels of the data too close to each other (e.g. a \"Shirt\" label is too close to \"T-shirt/top\")?\n", + "\n", + "## TK - Extra-curriculum\n", + "* **Watch:** [MIT's Introduction to Deep Computer Vision](https://www.youtube.com/watch?v=iaSUYvmCekI&list=PLtBw6njQRU-rwp5__7C0oIVt26ZgjG9NI&index=3) lecture. This will give you a great intuition behind convolutional neural networks.\n", + "* Spend 10-minutes clicking thorugh the different options of the [PyTorch vision library](https://pytorch.org/vision/stable/index.html), what different modules are available?\n", + "* Lookup \"most common convolutional neural networks\", what architectures do you find? Are any of them contained within the [`torchvision.models`](https://pytorch.org/vision/stable/models.html) library? What do you think you could do with these?\n", + "* For a large number of pretrained PyTorch computer vision models as well as many different extensions to PyTorch's computer vision functionalities check out the [PyTorch Image Models library `timm`](https://github.com/rwightman/pytorch-image-models/) (Torch Image Models) by Ross Wightman." + ] } ], "metadata": {