{ "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": "RDQqqfRXTjyJ" }, "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": "Oq7vdepBTjyK" }, "source": [ "# 2. Image Classification of an American Sign Language Dataset" ] }, { "cell_type": "markdown", "metadata": { "id": "2nP3rWXBTjyK" }, "source": [ "In this section, we will perform the data preparation, model creation, and model training steps we observed in the last section using a different dataset: images of hands making letters in [American Sign Language](http://www.asl.gs/)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2.1 Setup for Google Colab" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**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 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 numpy pandas matplotlib pillow 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": "markdown", "metadata": { "id": "Cs1ioXE2TjyK" }, "source": [ "## 2.1 Objectives" ] }, { "cell_type": "markdown", "metadata": { "id": "WzY0p5NZTjyK" }, "source": [ "* Prepare image data for training\n", "* Create and compile a simple model for image classification\n", "* Train an image classification model and observe the results" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 849, "status": "ok", "timestamp": 1715066695195, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "Ev0pS0GdTjyM", "outputId": "63e4a89f-c58b-4401-e6a5-4350b5df7714" }, "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", "\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": "mhGii0pzTjyL" }, "source": [ "## 2.2 American Sign Language Dataset" ] }, { "cell_type": "markdown", "metadata": { "id": "x3IH42b2TjyL" }, "source": [ "The [American Sign Language alphabet](http://www.asl.gs/) contains 26 letters. Two of those letters (j and z) require movement, so they are not included in the training dataset. " ] }, { "cell_type": "markdown", "metadata": { "id": "Xtnc5S_lTjyL" }, "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "ihN8_4hfTjyL" }, "source": [ "### 2.2.1 HuggingFace" ] }, { "cell_type": "markdown", "metadata": { "id": "winTCTjiTjyL" }, "source": [ "This dataset is available on [HuggingFace Hub](https://huggingface.co/datasets/juanjodurillo/asl-hg), a public repository for machine learning datasets and models. No account or API token is required to download it. It is mirror of the [ASL-HG: American Sign Language Hand Gesture Image Dataset](https://data.mendeley.com/datasets/j4y5w2c8w9/1) by Md. Famidul Islam Pranto, Md. Rifatul Islam, Md. Ali Akbor, Nabonita Ghosh, Md. Rahatun Alam, Sudipto Chaki, Md Masudul Islam\n", "\n", "The helper function `download_asl_dataset()` in `data/data.py` downloads the dataset automatically the first time it is called, converts each image to a 28×28 grayscale representation, and caches the results as CSV files so that subsequent calls load from disk instantly.\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": {}, "outputs": [], "source": [ "download_asl_dataset()" ] }, { "cell_type": "markdown", "metadata": { "id": "xzRiOTvsTjyL" }, "source": [ "## 2.3 Loading the Data" ] }, { "cell_type": "markdown", "metadata": { "id": "7OouJPWVTjyL" }, "source": [ "This dataset is not available via TorchVision in the same way that MNIST is, so let's learn how to load custom data. By the end of this section we will have `x_train`, `y_train`, `x_valid`, and `y_valid` variables." ] }, { "cell_type": "markdown", "metadata": { "id": "rpKiBdCsTjyL" }, "source": [ "### 2.3.1 Reading in the Data" ] }, { "cell_type": "markdown", "metadata": { "id": "mRBOfwA9TjyM" }, "source": [ "The sign language dataset is in [CSV](https://en.wikipedia.org/wiki/Comma-separated_values) (Comma Separated Values) format, the same data structure behind Microsoft Excel and Google Sheets. It is a grid of rows and columns with labels at the top, as seen in the [train](data/asl_data/sign_mnist_train.csv) and [valid](data/asl_data/sign_mnist_valid.csv) datasets (they may take a moment to load).\n", "\n", "To load and work with the data, we'll be using a library called [Pandas](https://pandas.pydata.org/), which is a highly performant tool for loading and manipulating data. We'll read the CSV files into a format called a [DataFrame](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html)." ] }, { "cell_type": "markdown", "metadata": { "id": "bbhLk9sVTjyM" }, "source": [ "Pandas has a [read_csv](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html) method that expects a csv file, and returns a DataFrame:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "JeIOe1X4TjyM" }, "outputs": [], "source": [ "train_df, valid_df = download_asl_dataset()\n", "train_df.head()" ] }, { "cell_type": "markdown", "metadata": { "id": "BuiUoPWzTjyM" }, "source": [ "### 2.3.2 Exploring the Data" ] }, { "cell_type": "markdown", "metadata": { "id": "GbirW1rxTjyM" }, "source": [ "Let's take a look at our data. We can use the [head](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.head.html) method to print the first few rows of the DataFrame. Each row is an image which has a `label` column, and also, 784 values representing each pixel value in the image, just like with the MNIST dataset. Note that the labels currently are numerical values, not letters of the alphabet:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 255 }, "executionInfo": { "elapsed": 8, "status": "ok", "timestamp": 1715064545381, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "_jEITmvETjyM", "outputId": "5444b9eb-1948-4140-95c4-91649677766b" }, "outputs": [], "source": [ "train_df.head()" ] }, { "cell_type": "markdown", "metadata": { "id": "9vZwdu4yTjyN" }, "source": [ "### 2.3.3 Extracting the Labels" ] }, { "cell_type": "markdown", "metadata": { "id": "wxRL89IvTjyN" }, "source": [ "Let's store our training and validation labels in `y_train` and `y_valid` variables. We can use the [pop](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.pop.html) method to remove a column from our DataFrame and assign the removed values to a variable." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 2, "status": "ok", "timestamp": 1715064546558, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "EYujv09jTjyN", "outputId": "572b986c-d128-4b25-9083-9d9607c9b680" }, "outputs": [], "source": [ "y_train = train_df.pop('label')\n", "y_valid = valid_df.pop('label')\n", "y_train" ] }, { "cell_type": "markdown", "metadata": { "id": "WQ6EtXGYTjyN" }, "source": [ "### 2.3.4 Extracting the Images" ] }, { "cell_type": "markdown", "metadata": { "id": "_mue0q7BTjyN" }, "source": [ "Next, let's store our training and validation images in `x_train` and `x_valid` variables. Here we create those variables:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 2, "status": "ok", "timestamp": 1715064548501, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "7sP3fSkETjyN", "outputId": "6e04f85b-fb2d-444d-fc08-28a5741c3c6f" }, "outputs": [], "source": [ "x_train = train_df.values\n", "x_valid = valid_df.values\n", "x_train" ] }, { "cell_type": "markdown", "metadata": { "id": "6s7y8MYOTjyN" }, "source": [ "### 2.3.5 Summarizing the Training and Validation Data" ] }, { "cell_type": "markdown", "metadata": { "id": "YkVK5sL_TjyN" }, "source": [ "We now have 19,200 images with 784 pixels each for training..." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 270, "status": "ok", "timestamp": 1715064412921, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "l7liruaxTjyN", "outputId": "9b462f1d-6306-47bf-d292-151b9847e1ad" }, "outputs": [], "source": [ "x_train.shape" ] }, { "cell_type": "markdown", "metadata": { "id": "WKP6-UT0TjyN" }, "source": [ "...as well as their corresponding labels:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 3, "status": "ok", "timestamp": 1715064415052, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "d4OguU-wTjyN", "outputId": "d2030105-2f87-44ff-a13d-d530a63c46df" }, "outputs": [], "source": [ "y_train.shape" ] }, { "cell_type": "markdown", "metadata": { "id": "VKuHu4V2TjyN" }, "source": [ "For validation, we have 4,800 images..." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 3, "status": "ok", "timestamp": 1715064416314, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "AFx0PRCsTjyN", "outputId": "e25714a6-07a2-4a5f-9dcb-e197e9fee5cb" }, "outputs": [], "source": [ "x_valid.shape" ] }, { "cell_type": "markdown", "metadata": { "id": "cfEP85sSTjyN" }, "source": [ "...and their corresponding labels:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 3, "status": "ok", "timestamp": 1715064417463, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "5UgDUqppTjyO", "outputId": "98f60c26-9975-4da8-e108-3b6b1503721d" }, "outputs": [], "source": [ "y_valid.shape" ] }, { "cell_type": "markdown", "metadata": { "id": "UWrF4zYPTjyO" }, "source": [ "## 2.4 Visualizing the Data" ] }, { "cell_type": "markdown", "metadata": { "id": "HJnxfcGJTjyO" }, "source": [ "To visualize the images, we will again use the matplotlib library. We don't need to worry about the details of this visualization, but if interested, you can learn more about [matplotlib](https://matplotlib.org/) at a later time.\n", "\n", "Note that we'll have to reshape the data from its current 1D shape of 784 pixels, to a 2D shape of 28x28 pixels to make sense of the image:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 58 }, "executionInfo": { "elapsed": 972, "status": "ok", "timestamp": 1715064554564, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "k-Fkl2mTTjyO", "outputId": "3fe64867-d689-497c-d0b7-4a27edf8e89d" }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "import numpy as np\n", "plt.figure(figsize=(40,40))\n", "\n", "num_images = 20\n", "sample_indices = np.random.choice(len(x_train), num_images, replace=False)\n", "for i, idx in enumerate(sample_indices):\n", " row = x_train[idx]\n", " label = y_train.iloc[idx]\n", "\n", " image = row.reshape(28,28)\n", " plt.subplot(1, num_images, i+1)\n", " plt.title(label, fontdict={'fontsize': 30})\n", " plt.axis('off')\n", " plt.imshow(image, cmap='gray')" ] }, { "cell_type": "markdown", "metadata": { "id": "2j5Nwh7zTjyO" }, "source": [ "### 2.4.1 Normalize the Image Data" ] }, { "cell_type": "markdown", "metadata": { "id": "xYfdAXx5TjyV" }, "source": [ "As we did with the MNIST dataset, we are going to normalize the image data, meaning that their pixel values, instead of being between 0 and 255 as they are currently:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 3, "status": "ok", "timestamp": 1715064422916, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "zbEOSxuYTjyV", "outputId": "d30e221e-99db-4e20-fdb6-cf67fb273225" }, "outputs": [], "source": [ "x_train.min()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 2, "status": "ok", "timestamp": 1715064423943, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "kAERnWUcTjyV", "outputId": "57e592d4-a36e-4f3e-f924-d157fa9680ef" }, "outputs": [], "source": [ "x_train.max()" ] }, { "cell_type": "markdown", "metadata": { "id": "_KWYaVLTTjyV" }, "source": [ "In the previous lab, we used [ToTensor](https://pytorch.org/vision/main/generated/torchvision.transforms.ToTensor.html), but we can also modify our data before turning it into a tensor." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "s3bf3TvgTjyW" }, "outputs": [], "source": [ "x_train = train_df.values / 255\n", "x_valid = valid_df.values / 255" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2.4.2 Custom Datasets" ] }, { "cell_type": "markdown", "metadata": { "id": "iKQR2ouf7Q2r" }, "source": [ "We can use PyTorch's [Dataset](https://pytorch.org/tutorials/beginner/basics/data_tutorial.html) tools in order to create our own dataset. `__init__` will run once when the class is initialized. `__getitem__` returns our images and labels.\n", "\n", "Since our dataset is small enough, we can store it on our GPU for faster processing. In the previous lab, we sent our data to the GPU when it was drawn from each batch. Here, we will send it to the GPU in the `__init__` function." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "KeKWb8tZ6jCy" }, "outputs": [], "source": [ "class MyDataset(Dataset):\n", " def __init__(self, x_df, y_df):\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)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A custom PyTorch dataset works just like a prebuilt one. It should be passed to a [DataLoader](https://pytorch.org/tutorials/beginner/basics/data_tutorial.html#preparing-your-data-for-training-with-dataloaders) for model training." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "XoSSM2YEAh_6" }, "outputs": [], "source": [ "BATCH_SIZE = 32\n", "\n", "train_data = MyDataset(x_train, y_train)\n", "train_loader = DataLoader(train_data, batch_size=BATCH_SIZE, shuffle=True)\n", "train_N = len(train_loader.dataset)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "cfAM1uoP1anX" }, "outputs": [], "source": [ "valid_data = MyDataset(x_valid, y_valid)\n", "valid_loader = DataLoader(valid_data, batch_size=BATCH_SIZE)\n", "valid_N = len(valid_loader.dataset)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can verify the DataLoader works as expected with the code below. We'll make the DataLoader [iterable](https://docs.python.org/3/library/functions.html#iter), and then call [next](https://docs.python.org/3/library/functions.html#next) to draw the first hand from the deck." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "train_loader" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Try running the below a few times. The values should change each time." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 3, "status": "ok", "timestamp": 1715068148957, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "5nRQD_koZ5jm", "outputId": "f24f27e7-2452-46a2-ca83-0710c822b9f3" }, "outputs": [], "source": [ "batch = next(iter(train_loader))\n", "batch" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice the batch has two values. The first is our `x`, and the second is our `y`. The first dimension of each should have `32` values, which is the `batch_size`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "batch[0].shape" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "batch[1].shape" ] }, { "cell_type": "markdown", "metadata": { "id": "KkD0MEZ1TjyX" }, "source": [ "## 2.5 Build the Model" ] }, { "cell_type": "markdown", "metadata": { "id": "PHyHRWPdTjyX" }, "source": [ "We've created our DataLoaders, now it's time to build our models." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Exercise" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For this exercise we are going to build a sequential model. Just like last time, build a model that:\n", "\n", "* Has a flatten layer.\n", "* Has a dense input layer. This layer should contain 512 neurons amd use the `relu` activation function\n", "* Has a second dense layer with 512 neurons which uses the `relu` activation function\n", "* Has a dense output layer with neurons equal to the number of classes\n", "\n", "We will define a few variables to get started:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "input_size = 28 * 28\n", "n_classes = 24" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Do your work in the cell below, creating a `model` variable to store the model. We've imported the [Sequental](https://pytorch.org/docs/stable/generated/torch.nn.Sequential.html) model class and [Linear](https://pytorch.org/docs/stable/generated/torch.nn.Linear.html) layer class to get you started. Reveal the solution below for a hint:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "model = nn.Sequential(\n", "\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Solution" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "_WckEGM9Tr-D", "jupyter": { "source_hidden": true } }, "outputs": [], "source": [ "# SOLUTION\n", "model = nn.Sequential(\n", " nn.Flatten(),\n", " nn.Linear(input_size, 512), # Input\n", " nn.ReLU(), # Activation for input\n", " nn.Linear(512, 512), # Hidden\n", " nn.ReLU(), # Activation for hidden\n", " nn.Linear(512, n_classes) # Output\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This time, we'll combine compiling the model and sending it to the GPU in one step:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 326, "status": "ok", "timestamp": 1715068155362, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "TjXGJyWuUGcH", "outputId": "f3474939-80a3-4715-aea4-991a2629232a" }, "outputs": [], "source": [ "model = torch.compile(model.to(device))\n", "model" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Since categorizing these ASL images is similar to categorizing MNIST's handwritten digits, we will use the same `loss_function` ([Categorical CrossEntropy](https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html)) and `optimizer` ([Adam](https://pytorch.org/docs/stable/generated/torch.optim.Adam.html)). `nn.CrossEntropyLoss` includes the softmax function, and is computationally faster when passing class indices as opposed to predicted probabilities." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "LtHYbXz7UZQW" }, "outputs": [], "source": [ "loss_function = nn.CrossEntropyLoss()\n", "optimizer = Adam(model.parameters())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2.6 Training the Model" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This time, let's look at our `train` and `validate` functions in more detail." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2.6.1 The Train Function" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This code is almost the same as in the previous notebook, but we no longer send `x` and `y` to our GPU because our DataLoader already does that.\n", "\n", "Before looping through the DataLoader, we will set the model to [model.train](https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.train) to make sure its parameters can be updated. To make it easier for us to follow training progress, we'll keep track of the total `loss` and `accuracy`.\n", "\n", "Then, for each batch in our `train_loader`, we will:\n", "1. Get an `output` prediction from the model\n", "2. Set the gradient to zero with the `optimizer`'s [zero_grad](https://pytorch.org/docs/stable/generated/torch.optim.Optimizer.zero_grad.html) function\n", "3. Calculate the loss with our `loss_function`\n", "4. Compute the gradient with [backward](https://pytorch.org/docs/stable/generated/torch.Tensor.backward.html)\n", "5. Update our model parameters with the `optimizer`'s [step](https://pytorch.org/docs/stable/generated/torch.optim.Optimizer.step.html) function.\n", "6. Update the `loss` and `accuracy` totals" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "AfgrATXFV_og" }, "outputs": [], "source": [ "def train():\n", " loss = 0\n", " accuracy = 0\n", "\n", " model.train()\n", " for x, y in train_loader:\n", " output = model(x)\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 += get_batch_accuracy(output, y, train_N)\n", " print('Train - Loss: {:.4f} Accuracy: {:.4f}'.format(loss, accuracy))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2.6.2 The Validate Function" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The model does not learn during validation, so the `validate` function is simpler than the `train` function above.\n", "\n", "One key difference is we will set the model to evaluation mode with [model.evaluate](https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.eval), which will prevent the model from updating any parameters." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "8LQcAtcc0ggk" }, "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 += get_batch_accuracy(output, y, valid_N)\n", " print('Valid - Loss: {:.4f} Accuracy: {:.4f}'.format(loss, accuracy))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2.6.3 Calculating the Accuracy" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Both the `train` and `validate` functions use `get_batch_accuracy`, but we have not defined that in this notebook yet. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Exercise" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The function below has three `FIXME`s. Each one corresponds to the functions input arguments. Can you replace each FIXME with the correct argument?\n", "\n", "It may help to view the documentation for [argmax](https://pytorch.org/docs/stable/generated/torch.argmax.html), [eq](https://pytorch.org/docs/stable/generated/torch.eq.html), and [view_as](https://pytorch.org/docs/stable/generated/torch.Tensor.view_as.html)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def get_batch_accuracy(output, y, N):\n", " pred = FIXME.argmax(dim=1, keepdim=True)\n", " correct = pred.eq(FIXME.view_as(pred)).sum().item()\n", " return correct / FIXME" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Solution" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Click the `...` below for the solution." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "jupyter": { "source_hidden": true } }, "outputs": [], "source": [ "# SOLUTION\n", "def get_batch_accuracy(output, y, N):\n", " pred = output.argmax(dim=1, keepdim=True)\n", " correct = pred.eq(y.view_as(pred)).sum().item()\n", " return correct / N" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2.6.3 The Training Loop" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's bring it all together! Run the cell below to train the data for 20 `epochs`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 38185, "status": "ok", "timestamp": 1715068198222, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "JXzlHJw8-j5L", "outputId": "40b9eda4-352d-45f5-dc95-4193f7f13423" }, "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": "asDVasm6TjyY" }, "source": [ "### 2.6.4 Discussion: What happened?" ] }, { "cell_type": "markdown", "metadata": { "id": "YWYAlfHzTjyY" }, "source": [ "We can see that the training accuracy got to a fairly high level, but the validation accuracy was not as high. What happened here?\n", "\n", "Think about it for a bit before clicking on the '...' below to reveal the answer." ] }, { "cell_type": "markdown", "metadata": { "id": "BGB3jWGRTjyY" }, "source": [ "`# SOLUTION`\n", "This is an example of the model learning to categorize the training data, but performing poorly against new data that it has not been trained on. Essentially, it is memorizing the dataset, but not gaining a robust and general understanding of the problem. This is a common issue called *overfitting*. We will discuss overfitting in the next two lectures, as well as some ways to address it." ] }, { "cell_type": "markdown", "metadata": { "id": "OI5xFCVLTjyY" }, "source": [ "## 2.7 Summary" ] }, { "cell_type": "markdown", "metadata": { "id": "cFcIcMOQTjyZ" }, "source": [ "In this section you built your own neural network to perform image classification that is quite accurate. Congrats!\n", "\n", "At this point we should be getting somewhat familiar with the process of loading data (including labels), preparing it, creating a model, and then training the model with prepared data." ] }, { "cell_type": "markdown", "metadata": { "id": "CDYpo3ByTjyZ" }, "source": [ "### 2.7.1 Clear the Memory\n", "Before moving on, please execute the following cell to clear up the GPU memory. This is required to move on to the next notebook." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Mm_uKgfxTjyZ" }, "outputs": [], "source": [ "import IPython\n", "app = IPython.Application.instance()\n", "app.kernel.do_shutdown(True)" ] }, { "cell_type": "markdown", "metadata": { "id": "vuUgx9kPTjyZ" }, "source": [ "### 2.7.2 Next" ] }, { "cell_type": "markdown", "metadata": { "id": "WeMVBJwMTjyZ" }, "source": [ "Now that you have built some very basic, somewhat effective models, we will begin to learn about more sophisticated models, including *Convolutional Neural Networks*." ] }, { "cell_type": "markdown", "metadata": { "id": "QW2ZlBpITjyZ" }, "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 }