{ "cells": [ { "cell_type": "raw", "id": "copyright-header", "metadata": {}, "source": [ "# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES\n", "# SPDX-License-Identifier: Apache-2.0 AND CC-BY-4.0" ] }, { "cell_type": "markdown", "metadata": { "id": "J1AHrcF83Y-g" }, "source": [ "
\"Header\"
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## License\n", "\n", "Unless otherwise noted:\n", "\n", "- Code cells are licensed under the\n", " [Apache License 2.0](../../LICENSES/Apache-2.0.txt).\n", "- Markdown and raw cells are licensed under the\n", " [Creative Commons Attribution 4.0 International License](../../LICENSES/CC-BY-4.0.txt).\n", "- Third-party material retains its original license and is identified in\n", " [`THIRD_PARTY_NOTICES.md`](../../THIRD_PARTY_NOTICES.md).\n", "\n", "Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES." ] }, { "cell_type": "markdown", "metadata": { "id": "bBNeKAyF3Y-h" }, "source": [ "# 4a. Data Augmentation" ] }, { "cell_type": "markdown", "metadata": { "id": "HTHY1Otu3Y-h" }, "source": [ "So far, we've selected a model architecture that vastly improves the model's performance, as it is designed to recognize important features in the images. The validation accuracy is still lagging behind the training accuracy, which is a sign of overfitting: the model is getting confused by things it has not seen before when it tests against the validation dataset.\n", "\n", "In order to teach our model to be more robust when looking at new data, we're going to programmatically increase the size and variance in our dataset. This is known as [*data augmentation*](https://link.springer.com/article/10.1186/s40537-019-0197-0), a useful technique for many deep learning applications.\n", "\n", "The increase in size gives the model more images to learn from while training. The increase in variance helps the model ignore unimportant features and select only the features that are truly important in classification, allowing it to generalize better." ] }, { "cell_type": "markdown", "metadata": { "id": "k01AskqI3Y-h" }, "source": [ "## 4a.1 Objectives" ] }, { "cell_type": "markdown", "metadata": { "id": "YCFOyxKS3Y-h" }, "source": [ "* Augment the ASL dataset\n", "* Use the augmented data to train an improved model\n", "* Save the well-trained model to disk for use in deployment" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Setup for Google Colab\n", "\n", "**Only run this cell if you are using Google Colab.** In other environments, skip it and continue with the lesson." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form" }, "outputs": [], "source": [ "%%bash\n", "# @title Setup for Google Colab { display-mode: \"form\" }\n", "# @markdown **Only run this cell if you are using Google Colab.** Otherwise, skip it. Select a GPU under **Runtime → Change runtime type** before running it.\n", "set -e\n", "\n", "# Skip setup outside Google Colab.\n", "if [ -z \"${COLAB_RELEASE_TAG:-}${COLAB_BACKEND_VERSION:-}\" ]; then\n", " exit 0\n", "fi\n", "\n", "# Download only the support files used by this lab.\n", "course_url=https://raw.githubusercontent.com/NVDLI/fundamentals-of-deep-learning/main/course_content\n", "\n", "# Download only this lab's support files; preserve existing files and student work.\n", "for course_file in utils.py data/data.py; do\n", " if [ ! -e \"$course_file\" ]; then\n", " mkdir -p \"$(dirname \"$course_file\")\"\n", " curl -fsSL \"$course_url/tutorials/$course_file\" -o \"$course_file.download\"\n", " mv \"$course_file.download\" \"$course_file\"\n", " fi\n", "done\n", "\n", "# Install only this lab's packages that are missing from the current runtime.\n", "missing_packages=()\n", "for course_package in torch torchvision numpy pandas matplotlib datasets kagglehub; do\n", " if ! pip show \"$course_package\" >/dev/null 2>&1; then\n", " missing_packages+=(\"$course_package\")\n", " fi\n", "done\n", "if [ \"${#missing_packages[@]}\" -gt 0 ]; then\n", " pip install --quiet \"${missing_packages[@]}\"\n", "fi\n", "\n", "echo \"Course ready. Continue with the next cell.\"\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 6560, "status": "ok", "timestamp": 1715241340700, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "ocl26UO63Y-i", "outputId": "b097ecfc-e330-4c6e-d386-4b2b7cbb55bb" }, "outputs": [], "source": [ "import torch.nn as nn\n", "import pandas as pd\n", "import torch\n", "from torch.optim import Adam\n", "from torch.utils.data import Dataset, DataLoader\n", "import torchvision.transforms.v2 as transforms\n", "import torchvision.transforms.functional as F\n", "import matplotlib.pyplot as plt\n", "\n", "import utils\n", "from data.data import download_asl_dataset\n", "\n", "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", "torch.cuda.is_available()" ] }, { "cell_type": "markdown", "metadata": { "id": "u-FCWlRg3Y-h" }, "source": [ "## 4a.2 Preparing the Data" ] }, { "cell_type": "markdown", "metadata": { "id": "JjSagpmG3Y-i" }, "source": [ "As we're in a new notebook, we will load and process our data again. To do this, execute the following cell:\n", "\n", "*Running this code will automatically download data from https://huggingface.co/datasets/juanjodurillo/asl-hg. Before you run the code, please confirm the content of the dataset and licensing is appropriate for your intended use*" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 3988, "status": "ok", "timestamp": 1715241345056, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "jYhhD7yo2WEI" }, "outputs": [], "source": [ "IMG_HEIGHT = 28\n", "IMG_WIDTH = 28\n", "IMG_CHS = 1\n", "N_CLASSES = 24\n", "\n", "train_df, valid_df = download_asl_dataset()\n", "\n", "class MyDataset(Dataset):\n", " def __init__(self, base_df):\n", " x_df = base_df.copy()\n", " y_df = x_df.pop('label')\n", " x_df = x_df.values / 255 # Normalize values from 0 to 1\n", " x_df = x_df.reshape(-1, IMG_CHS, IMG_WIDTH, IMG_HEIGHT)\n", " self.xs = torch.tensor(x_df).float().to(device)\n", " self.ys = torch.tensor(y_df).to(device)\n", "\n", " def __getitem__(self, idx):\n", " x = self.xs[idx]\n", " y = self.ys[idx]\n", " return x, y\n", "\n", " def __len__(self):\n", " return len(self.xs)\n", "\n", "n = 32\n", "train_data = MyDataset(train_df)\n", "train_loader = DataLoader(train_data, batch_size=n, shuffle=True)\n", "train_N = len(train_loader.dataset)\n", "\n", "valid_data = MyDataset(valid_df)\n", "valid_loader = DataLoader(valid_data, batch_size=n)\n", "valid_N = len(valid_loader.dataset)" ] }, { "cell_type": "markdown", "metadata": { "id": "qwsfoZkE3Y-i" }, "source": [ "## 4a.3 Model Creation" ] }, { "cell_type": "markdown", "metadata": { "id": "ze7Tv-Aj3Y-i" }, "source": [ "We will also need to create our model again. As we learned in the last lesson, convolutional neural networks use a repeated sequence of layers. Let's take advantage of this pattern to make our own [custom module](https://pytorch.org/tutorials/beginner/examples_nn/two_layer_net_module.html). We can then use this module like a layer in our [Sequential](https://pytorch.org/docs/stable/generated/torch.nn.Sequential.html) model.\n", "\n", "To do this, we will extend the [Module](https://pytorch.org/docs/stable/generated/torch.nn.Module.html) class. Then we will define two methods:\n", "* `__init__`: defines any properties we want our module to have, including our neural network layers. We will effectively be using a model within a model.\n", "* `forward`: defines how we want the module to process any incoming data from the previous layer it is connected to. Since we are using a `Sequential` model, we can pass the input data into it like we are making a prediction." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 322, "status": "ok", "timestamp": 1715241347583, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "_o8Y7C91Bfl8" }, "outputs": [], "source": [ "class MyConvBlock(nn.Module):\n", " def __init__(self, in_ch, out_ch, dropout_p):\n", " kernel_size = 3\n", " super().__init__()\n", "\n", " self.model = nn.Sequential(\n", " nn.Conv2d(in_ch, out_ch, kernel_size, stride=1, padding=1),\n", " nn.BatchNorm2d(out_ch),\n", " nn.ReLU(),\n", " nn.Dropout(dropout_p),\n", " nn.MaxPool2d(2, stride=2)\n", " )\n", "\n", " def forward(self, x):\n", " return self.model(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now that we've define our custom module, let's see it in action. The below model ia archecturially the same as in the previous lesson. Can you see the connection?" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 2, "status": "ok", "timestamp": 1715241351435, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "I0A_7iJvB8Kc" }, "outputs": [], "source": [ "flattened_img_size = 75 * 3 * 3\n", "\n", "# Input 1 x 28 x 28\n", "base_model = nn.Sequential(\n", " MyConvBlock(IMG_CHS, 25, 0), # 25 x 14 x 14\n", " MyConvBlock(25, 50, 0.2), # 50 x 7 x 7\n", " MyConvBlock(50, 75, 0), # 75 x 3 x 3\n", " # Flatten to Dense Layers\n", " nn.Flatten(),\n", " nn.Linear(flattened_img_size, 512),\n", " nn.Dropout(.3),\n", " nn.ReLU(),\n", " nn.Linear(512, N_CLASSES)\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When we print the model, not only will it now show the use of our custom module, it will also show the layers within our custom module:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 465, "status": "ok", "timestamp": 1715241354080, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "4THc2t0HhNcv", "outputId": "e25d69a9-e51a-4a90-90df-dc69a586f54b" }, "outputs": [], "source": [ "loss_function = nn.CrossEntropyLoss()\n", "optimizer = Adam(base_model.parameters())\n", "\n", "model = torch.compile(base_model.to(device))\n", "model" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Custom modules are flexible, and we can define any other methods or properties we wish to have. This makes them powerful when data scientists are trying to solve complex problems." ] }, { "cell_type": "markdown", "metadata": { "id": "kjBNCzfc3Y-j" }, "source": [ "## 4a.4 Data Augmentation" ] }, { "cell_type": "markdown", "metadata": { "id": "y8HdHKtM3Y-j" }, "source": [ "Before defining our training loop, it's time to set up our data augmentation.\n", "\n", "We've seen [TorchVision](https://pytorch.org/vision/stable/index.html)'s [Transforms](https://pytorch.org/vision/0.9/transforms.html) before, but in this lesson, we will further explore its data augmentation tools. First, let's get a sample image to test with:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 312, "status": "ok", "timestamp": 1715241358482, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "-LT7NvrXhYwB", "outputId": "4c1c1af4-811b-46d7-fa73-594772907549" }, "outputs": [], "source": [ "row_0 = train_df.head(1)\n", "y_0 = row_0.pop('label')\n", "x_0 = row_0.values / 255\n", "x_0 = x_0.reshape(IMG_CHS, IMG_WIDTH, IMG_HEIGHT)\n", "x_0 = torch.tensor(x_0)\n", "x_0.shape" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 447 }, "executionInfo": { "elapsed": 332, "status": "ok", "timestamp": 1715241364072, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "XKFRYIpvkUEF", "outputId": "fb3f72ab-ce59-4bfc-a54a-0a4d575e497c" }, "outputs": [], "source": [ "image = F.to_pil_image(x_0)\n", "plt.imshow(image, cmap='gray')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 4a.4.1 [RandomResizeCrop](https://pytorch.org/vision/0.9/transforms.html#torchvision.transforms.RandomResizedCrop)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This transform will randomly resize the input image based on `scale`, and then [crop](https://en.wikipedia.org/wiki/Cropping_(image)) it to a size we specify. In this case, we will crop it to the original image dimensions. To do this, TorchVision needs to know the [aspect ratio](https://en.wikipedia.org/wiki/Aspect_ratio_(image)) of the image it is scaling. Since our height is the same as our width, our aspect `ratio` is 1:1." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 2, "status": "ok", "timestamp": 1715241375000, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "qWINTqKypE5J" }, "outputs": [], "source": [ "trans = transforms.Compose([\n", " transforms.RandomResizedCrop((IMG_WIDTH, IMG_HEIGHT), scale=(.7, 1), ratio=(1, 1)),\n", "])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Try running the below cell a few times. It should be different each time." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 447 }, "executionInfo": { "elapsed": 507, "status": "ok", "timestamp": 1715241377237, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "6ZugUNuJpPG2", "outputId": "52caec17-6a25-4484-c2f4-2aed78b5ffe8" }, "outputs": [], "source": [ "new_x_0 = trans(x_0)\n", "image = F.to_pil_image(new_x_0)\n", "plt.imshow(image, cmap='gray')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 333, "status": "ok", "timestamp": 1715241385987, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "8VQJ1vwKp4nJ", "outputId": "63521e3a-5a63-48c8-8823-bd60d6814b64" }, "outputs": [], "source": [ "new_x_0.shape" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 4a.4.2 [RandomHorizontalFlip](https://pytorch.org/vision/0.9/transforms.html#torchvision.transforms.RandomHorizontalFlip)" ] }, { "cell_type": "markdown", "metadata": { "id": "Yrmm_inJ3Y-j" }, "source": [ "We can also randomly flip our images [Horizontally](https://pytorch.org/vision/0.9/transforms.html#torchvision.transforms.RandomHorizontalFlip) or [Vertically](https://pytorch.org/vision/0.9/transforms.html#torchvision.transforms.RandomVerticalFlip). However, for these images, we will only flip them horizontally.\n", "\n", "Take a moment to think about why we would want to flip images horizontally, but not vertically. When you have an idea, reveal the text below." ] }, { "cell_type": "markdown", "metadata": { "id": "XCLufCeF3Y-j" }, "source": [ "`# SOLUTION` Fun fact: American Sign Language can be done with either the left or right hand being dominant. However, it is unlikely to see sign language from upside down. This kind of domain-specific reasoning can help make good decisions for your own deep learning applications." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "trans = transforms.Compose([\n", " transforms.RandomHorizontalFlip()\n", "])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Try running the below cell a few times. Does the image flip about half the time?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "new_x_0 = trans(x_0)\n", "image = F.to_pil_image(new_x_0)\n", "plt.imshow(image, cmap='gray')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 4a.4.3 [RandomRotation](https://pytorch.org/vision/0.9/transforms.html#torchvision.transforms.RandomRotation)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also randomly rotate the image to add more variability. Just like with with other augmentation techniques, it's easy to accidentally go too far. With ASL, if we rotate too much, our `D`s might look like `G`s and visa versa. Because of this, let's limit it to `30` degrees." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "trans = transforms.Compose([\n", " transforms.RandomRotation(10)\n", "])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When we run the cell block below, some black pixels may appear. The corners or our image disappear when we rotate, and for almost every pixel we lose, we gain an empty pixel." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "new_x_0 = trans(x_0)\n", "image = F.to_pil_image(new_x_0)\n", "plt.imshow(image, cmap='gray')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 4a.4.3 [ColorJitter](https://pytorch.org/vision/0.9/transforms.html#torchvision.transforms.ColorJitter)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `ColorJitter` transform has 4 arguments:\n", "* [brightness](https://en.wikipedia.org/wiki/Brightness)\n", "* [contrast](https://en.wikipedia.org/wiki/Contrast_(vision))\n", "* [saturation](https://en.wikipedia.org/wiki/Colorfulness#Saturation)\n", "* [hue](https://en.wikipedia.org/wiki/Hue)\n", "\n", "\n", "The latter 2 apply to color images, so we will only use the first 2 for now." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "brightness = .2 # Change to be from 0 to 1\n", "contrast = .5 # Change to be from 0 to 1\n", "\n", "trans = transforms.Compose([\n", " transforms.ColorJitter(brightness=brightness, contrast=contrast)\n", "])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Try running the below a few times, but also try changing either `brightness` or `contrast` to `1`. Get any intersting results?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "new_x_0 = trans(x_0)\n", "image = F.to_pil_image(new_x_0)\n", "plt.imshow(image, cmap='gray')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 4a.3.4 [Compose](https://pytorch.org/vision/0.9/transforms.html#torchvision.transforms.Compose)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Time to bring it all together. We can create a sequence of these random transformations with `Compose`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 1, "status": "ok", "timestamp": 1715241387886, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "ZkXjesFKFH_b" }, "outputs": [], "source": [ "random_transforms = transforms.Compose([\n", " transforms.RandomRotation(5),\n", " transforms.RandomResizedCrop((IMG_WIDTH, IMG_HEIGHT), scale=(.9, 1), ratio=(1, 1)),\n", " transforms.RandomHorizontalFlip(),\n", " transforms.ColorJitter(brightness=.2, contrast=.5)\n", "])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's test it out. With all the different combinations how many varations are there of this one image? Infinite?" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 447 }, "executionInfo": { "elapsed": 347, "status": "ok", "timestamp": 1715241391170, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "ewG_7NAgqEnf", "outputId": "24142f9f-286f-42ab-9769-bfd38c9defbf" }, "outputs": [], "source": [ "new_x_0 = random_transforms(x_0)\n", "image = F.to_pil_image(new_x_0)\n", "plt.imshow(image, cmap='gray')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 4a.4 Training with Augmentation" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Our training is mostly the same, but there is one line of change. Before passing our images to our model, we will apply our `random_transforms`. For conveneince, we moved `get_batch_accuracy` to a [utils](./utils.py) file." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 317, "status": "ok", "timestamp": 1715241479297, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "IcgAmvx7rI13" }, "outputs": [], "source": [ "def train():\n", " loss = 0\n", " accuracy = 0\n", "\n", " model.train()\n", " for x, y in train_loader:\n", " output = model(random_transforms(x)) # Updated\n", " optimizer.zero_grad()\n", " batch_loss = loss_function(output, y)\n", " batch_loss.backward()\n", " optimizer.step()\n", "\n", " loss += batch_loss.item()\n", " accuracy += utils.get_batch_accuracy(output, y, train_N)\n", " print('Train - Loss: {:.4f} Accuracy: {:.4f}'.format(loss, accuracy))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "On the other hamd, validation remains the same. There are no random transformations. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 382, "status": "ok", "timestamp": 1715241482250, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "iXc6lnRAR4qZ" }, "outputs": [], "source": [ "def validate():\n", " loss = 0\n", " accuracy = 0\n", "\n", " model.eval()\n", " with torch.no_grad():\n", " for x, y in valid_loader:\n", " output = model(x)\n", "\n", " loss += loss_function(output, y).item()\n", " accuracy += utils.get_batch_accuracy(output, y, valid_N)\n", " print('Valid - Loss: {:.4f} Accuracy: {:.4f}'.format(loss, accuracy))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's put data augmentation to the test. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 45384, "status": "ok", "timestamp": 1715241529445, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "isjOJIVArTLR", "outputId": "5d4b6a5f-2ad9-4276-d65e-d84b9874ec3b" }, "outputs": [], "source": [ "epochs = 20\n", "\n", "for epoch in range(epochs):\n", " print('Epoch: {}'.format(epoch))\n", " train()\n", " validate()" ] }, { "cell_type": "markdown", "metadata": { "id": "h0WoN84J3Y-l" }, "source": [ "## Discussion of Results" ] }, { "cell_type": "markdown", "metadata": { "id": "-EPTunxK3Y-l" }, "source": [ "You will notice that the validation accuracy is higher, and more consistent. This means that our model is no longer overfitting in the way it was; it generalizes better, making better predictions on new data.\n", "\n", "The training accuracy may be lower, and that's ok. Compared to before, the model is being exposed to a much larger variety of data." ] }, { "cell_type": "markdown", "metadata": { "id": "npYY9cvA3Y-l" }, "source": [ "## Saving the Model" ] }, { "cell_type": "markdown", "metadata": { "id": "EW_TgWkN3Y-l" }, "source": [ "Now that we have a well-trained model, we will want to deploy it to perform inference on new images.\n", "\n", "It is common, once we have a trained model that we are happy with to save it to disk. PyTorch has [multiple ways](https://pytorch.org/tutorials/beginner/saving_loading_models.html) to do this, but for now, we will use `torch.save`. We will also need to save the code for our `MyConvBlock` custom module, which we did in [utils.py](./utils.py). In the next notebook, we'll load the model and use it to read new sign language pictures.\n", "\n", "PyTorch cannot save a compiled model ([see this post](https://discuss.pytorch.org/t/how-to-save-load-a-model-with-torch-compile/179739)), so we will instead " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 326, "status": "ok", "timestamp": 1715241533765, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "snAS8LalsMv4" }, "outputs": [], "source": [ "torch.save(base_model, 'model.pth')" ] }, { "cell_type": "markdown", "metadata": { "id": "hfePFALr3Y-l" }, "source": [ "## Summary" ] }, { "cell_type": "markdown", "metadata": { "id": "7fo5z3M03Y-l" }, "source": [ "In this section, you used TorchVision to augment a dataset. This resulted in a trained model with less overfitting and excellent validation image results." ] }, { "cell_type": "markdown", "metadata": { "id": "TgDmGUB93Y-l" }, "source": [ "### Clear the Memory\n", "Before moving on, please execute the following cell to clear up the GPU memory." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "R6EXCtGr3Y-l" }, "outputs": [], "source": [ "import IPython\n", "app = IPython.Application.instance()\n", "app.kernel.do_shutdown(True)" ] }, { "cell_type": "markdown", "metadata": { "id": "8DIV9ZNW3Y-l" }, "source": [ "## Next" ] }, { "cell_type": "markdown", "metadata": { "id": "E4iefhaq3Y-l" }, "source": [ "Now that you have a well-trained model saved to disk, you will, in the next section, deploy it to make predictions on not-yet-seen images.\n", "\n", "Please continue to the next notebook: [*Model Predictions*](04b_asl_predictions.ipynb)." ] }, { "cell_type": "markdown", "metadata": { "id": "j3I_B1M63Y-l" }, "source": [ "
\"Header\"
" ] } ], "metadata": { "accelerator": "GPU", "colab": { "gpuType": "T4", "provenance": [] }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.13" } }, "nbformat": 4, "nbformat_minor": 4 }