{ "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": "weabkZTF3ZZM" }, "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": "Dz8YI6Fb3ZZN" }, "source": [ "# 3. Convolutional Neural Networks" ] }, { "cell_type": "markdown", "metadata": { "id": "8UWR4l4X3ZZN" }, "source": [ "In the previous section, we built and trained a simple model to classify ASL images. The model was able to learn how to correctly classify the training dataset with very high accuracy, but, it did not perform nearly as well on validation dataset. This behavior of not generalizing well to non-training data is called [overfitting](https://scikit-learn.org/stable/auto_examples/model_selection/plot_underfitting_overfitting.html), and in this section, we will introduce a popular kind of model called a [convolutional neural network](https://towardsdatascience.com/a-comprehensive-guide-to-convolutional-neural-networks-the-eli5-way-3bd2b1164a53) that is especially good for reading images and classifying them." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3.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 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": {}, "source": [ "We will use the same dataset as the previous notebook. If you're starting in a fresh environment, please run the below to re-download the data.\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": [ "from data.data import download_asl_dataset\n", "\n", "download_asl_dataset()" ] }, { "cell_type": "markdown", "metadata": { "id": "GmRLS07k3ZZN" }, "source": [ "## 3.2 Objectives" ] }, { "cell_type": "markdown", "metadata": { "id": "Iuvwj_tr3ZZN" }, "source": [ "* Prep data specifically for a CNN\n", "* Create a more sophisticated CNN model, understanding a greater variety of model layers\n", "* Train a CNN model and observe its performance" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 221, "status": "ok", "timestamp": 1715240535370, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "9kMRTHEV2AFm", "outputId": "f1fb3858-e6a7-4906-ec7e-c4d34abcf013" }, "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", "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", "torch.cuda.is_available()" ] }, { "cell_type": "markdown", "metadata": { "id": "xEGukATl3ZZN" }, "source": [ "## 3.3 Loading and Preparing the Data" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3.3.1 Preparing Images" ] }, { "cell_type": "markdown", "metadata": { "id": "-SyD7hID3ZZN" }, "source": [ "Let's begin by loading our DataFrames like we did in the previous lab:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 3372, "status": "ok", "timestamp": 1715240541334, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "XMMgEMcc2Ehg" }, "outputs": [], "source": [ "train_df, valid_df = download_asl_dataset()\n", "train_df.head()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This ASL data is already flattened." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sample_df = train_df.head().copy() # Grab the top 5 rows\n", "sample_df.pop('label')\n", "sample_x = sample_df.values\n", "sample_x" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sample_x.shape" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this format, we don't have all the information about which pixels are near each other. Because of this, we can't apply convolutions that will detect features. Let's [reshape](https://numpy.org/doc/stable/reference/generated/numpy.reshape.html) our dataset so that they are in a 28x28 pixel format. This will allow our convolutions to associate groups of pixels and detect important features.\n", "\n", "Note that for the first convolutional layer of our model, we need to have not only the height and width of the image, but also the number of [color channels](https://www.photoshopessentials.com/essentials/rgb/). Our images are grayscale, so we'll just have 1 channel.\n", "\n", "That means that we need to convert the current shape `(5, 784)` to `(5, 1, 28, 28)`. With [NumPy](https://numpy.org/doc/stable/index.html) arrays, we can pass a `-1` for any dimension we wish to remain the same." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "IMG_HEIGHT = 28\n", "IMG_WIDTH = 28\n", "IMG_CHS = 1\n", "\n", "sample_x = sample_x.reshape(-1, IMG_CHS, IMG_HEIGHT, IMG_WIDTH)\n", "sample_x.shape" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3.3.2 Create a Dataset" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's add the steps above into our `MyDataset` class." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Exercise" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are 4 `FIXME`s in the class definition below. Can you replace them with the correct values?" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 173, "status": "ok", "timestamp": 1715240547901, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "tpzGOri32Klj" }, "outputs": [], "source": [ "class MyDataset(Dataset):\n", " def __init__(self, base_df):\n", " x_df = base_df.copy() # Some operations below are in-place\n", " y_df = x_df.pop(FIXME)\n", " x_df = x_df.values / 255 # Normalize values from 0 to 1\n", " x_df = x_df.reshape(-1, FIXME, FIXME, FIXME)\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": [ "#### 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", "class MyDataset(Dataset):\n", " def __init__(self, base_df):\n", " x_df = base_df.copy() # Some operations below are in-place\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)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3.3.3 Create a DataLoader" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Next, let's create the DataLoader from the Dataset" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Exercise" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "One of these function calls is missing the `shuffle=True` argument. Can you remember which one it is and add it back in?" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 1096, "status": "ok", "timestamp": 1715240550115, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "unf8Cz4WcK_M" }, "outputs": [], "source": [ "BATCH_SIZE = 32\n", "\n", "train_data = MyDataset(train_df)\n", "train_loader = DataLoader(train_data, batch_size=BATCH_SIZE)\n", "train_N = len(train_loader.dataset)\n", "\n", "valid_data = MyDataset(valid_df)\n", "valid_loader = DataLoader(valid_data, batch_size=BATCH_SIZE)\n", "valid_N = len(valid_loader.dataset)" ] }, { "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", "train_loader = DataLoader(train_data, batch_size=BATCH_SIZE, shuffle=True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's grab a batch from the DataLoader to make sure it works." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 2, "status": "ok", "timestamp": 1715240550382, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "Z4xylt03dz1W", "outputId": "80447d85-302d-4549-976b-f4c3ac0f0644" }, "outputs": [], "source": [ "batch = next(iter(train_loader))\n", "batch" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It looks different, but let's check the `shape`s to be sure." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 205, "status": "ok", "timestamp": 1715240552534, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "vannMV7sd6R_", "outputId": "627858a2-a4ed-467c-cf82-2b7c1a01c13f" }, "outputs": [], "source": [ "batch[0].shape" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 204, "status": "ok", "timestamp": 1715240553488, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "YHJgP3A7d9lu", "outputId": "4a40ceb8-039b-4517-de8a-bdcb814c4164" }, "outputs": [], "source": [ "batch[1].shape" ] }, { "cell_type": "markdown", "metadata": { "id": "6biSPXKJ3ZZP" }, "source": [ "## 3.4 Creating a Convolutional Model" ] }, { "cell_type": "markdown", "metadata": { "id": "ppdkNb1A3ZZP" }, "source": [ "These days, many data scientists start their projects by borrowing model properties from a similar project. Assuming the problem is not totally unique, there's a great chance that people have created models that will perform well which are posted in online repositories like [TensorFlow Hub](https://www.tensorflow.org/hub) and the [NGC Catalog](https://ngc.nvidia.com/catalog/models). Today, we'll provide a model that will work well for this problem.\n", "\n", "
\n", "\n", "We covered many of the different kinds of layers in the lecture, and we will go over them all here with links to their documentation. When in doubt, read the official documentation (or ask [Stack Overflow](https://stackoverflow.com/))." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 202, "status": "ok", "timestamp": 1715240555184, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "p_bvGpMId_6q" }, "outputs": [], "source": [ "n_classes = 24\n", "kernel_size = 3\n", "flattened_img_size = 75 * 3 * 3\n", "\n", "model = nn.Sequential(\n", " # First convolution\n", " nn.Conv2d(IMG_CHS, 25, kernel_size, stride=1, padding=1), # 25 x 28 x 28\n", " nn.BatchNorm2d(25),\n", " nn.ReLU(),\n", " nn.MaxPool2d(2, stride=2), # 25 x 14 x 14\n", " # Second convolution\n", " nn.Conv2d(25, 50, kernel_size, stride=1, padding=1), # 50 x 14 x 14\n", " nn.BatchNorm2d(50),\n", " nn.ReLU(),\n", " nn.Dropout(.2),\n", " nn.MaxPool2d(2, stride=2), # 50 x 7 x 7\n", " # Third convolution\n", " nn.Conv2d(50, 75, kernel_size, stride=1, padding=1), # 75 x 7 x 7\n", " nn.BatchNorm2d(75),\n", " nn.ReLU(),\n", " nn.MaxPool2d(2, stride=2), # 75 x 3 x 3\n", " # Flatten to Dense\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": { "id": "8WsDr9gE3ZZP" }, "source": [ "### 3.4.1 [Conv2D](https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html)" ] }, { "cell_type": "markdown", "metadata": { "id": "8eHXRtWa3ZZP" }, "source": [ "\n", "\n", "These are our 2D convolutional layers. Small kernels will go over the input image and detect features that are important for classification. Earlier convolutions in the model will detect simple features such as lines. Later convolutions will detect more complex features. Let's look at our first Conv2D layer:\n", "```Python\n", "nn.Conv2d(IMG_CHS, 25, kernel_size, stride=1, padding=1)\n", "```\n", "25 refers to the number of filters that will be learned. Even though `kernel_size = 3`, PyTorch will assume we want 3 x 3 filters. Stride refer to the step size that the filter will take as it passes over the image. Padding refers to whether the output image that's created from the filter will match the size of the input image." ] }, { "cell_type": "markdown", "metadata": { "id": "OiuMlsan3ZZQ" }, "source": [ "### 3.4.2 [BatchNormalization](https://pytorch.org/docs/stable/generated/torch.nn.BatchNorm2d.html)" ] }, { "cell_type": "markdown", "metadata": { "id": "Mp72aAnK3ZZQ" }, "source": [ "Like normalizing our inputs, batch normalization scales the values in the hidden layers to improve training. [Read more about it in detail here](https://blog.paperspace.com/busting-the-myths-about-batch-normalization/).\n", "\n", "There is a debate on best where to put the batch normalization layer. [This Stack Overflow post](https://stackoverflow.com/questions/39691902/ordering-of-batch-normalization-and-dropout) compiles many perspectives." ] }, { "cell_type": "markdown", "metadata": { "id": "twarf_s63ZZQ" }, "source": [ "### 3.4.3 [MaxPool2D](https://pytorch.org/docs/stable/generated/torch.nn.MaxPool2d.html)" ] }, { "cell_type": "markdown", "metadata": { "id": "MoNIzZZW3ZZQ" }, "source": [ "\n", "Max pooling takes an image and essentially shrinks it to a lower resolution. It does this to help the model be robust to translation (objects moving side to side), and also makes our model faster." ] }, { "cell_type": "markdown", "metadata": { "id": "mzHlBRja3ZZQ" }, "source": [ "### 3.4.4 [Dropout](https://pytorch.org/docs/stable/generated/torch.nn.Dropout.html)" ] }, { "cell_type": "markdown", "metadata": { "id": "FJjrPvkm3ZZQ" }, "source": [ "\n", "Dropout is a technique for preventing overfitting. Dropout randomly selects a subset of neurons and turns them off, so that they do not participate in forward or backward propagation in that particular pass. This helps to make sure that the network is robust and redundant, and does not rely on any one area to come up with answers. " ] }, { "cell_type": "markdown", "metadata": { "id": "NRYPkQPA3ZZQ" }, "source": [ "### 3.4.5 [Flatten](https://pytorch.org/docs/stable/generated/torch.nn.Flatten.html)" ] }, { "cell_type": "markdown", "metadata": { "id": "QuMt-DpZ3ZZQ" }, "source": [ "Flatten takes the output of one layer which is multidimensional, and flattens it into a one-dimensional array. The output is called a feature vector and will be connected to the final classification layer." ] }, { "cell_type": "markdown", "metadata": { "id": "pSur4TGx3ZZQ" }, "source": [ "### 3.4.6 [Linear](https://pytorch.org/docs/stable/generated/torch.nn.Linear.html)" ] }, { "cell_type": "markdown", "metadata": { "id": "PATqMedY3ZZQ" }, "source": [ "We have seen dense linear layers before in our earlier models. Our first dense layer (512 units) takes the feature vector as input and learns which features will contribute to a particular classification. The second dense layer (24 units) is the final classification layer that outputs our prediction." ] }, { "cell_type": "markdown", "metadata": { "id": "_opXKGWj3ZZQ" }, "source": [ "## 3.5 Summarizing the Model" ] }, { "cell_type": "markdown", "metadata": { "id": "Eo6eRrp23ZZQ" }, "source": [ "This may feel like a lot of information, but don't worry. It's not critical that to understand everything right now in order to effectively train convolutional models. Most importantly we know that they can help with extracting useful information from images, and can be used in classification tasks." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 200, "status": "ok", "timestamp": 1715240557183, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "2IAS92gZwcP3", "outputId": "56678948-aed0-4aa3-dde9-b8cecbaff44d" }, "outputs": [], "source": [ "model = torch.compile(model.to(device))\n", "model" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Since the problem we are trying to solve is still the same (classifying ASL images), we will continue to use the same `loss_function` and `accuracy` metric." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 237, "status": "ok", "timestamp": 1715240559055, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "-BUIQ5COwsri" }, "outputs": [], "source": [ "loss_function = nn.CrossEntropyLoss()\n", "optimizer = Adam(model.parameters())" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 3, "status": "ok", "timestamp": 1715240559790, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "SniWnvc5NSkA" }, "outputs": [], "source": [ "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": { "id": "OBgbUNDH3ZZR" }, "source": [ "## 3.6 Training the Model" ] }, { "cell_type": "markdown", "metadata": { "id": "tsS9zDKh3ZZR" }, "source": [ "Despite the very different model architecture, the training looks exactly the same." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Exercise" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "These are the same `train` and `validate` functions as before, but they have been mixed up. Can you correctly name each function and replace the `FIXME`s?\n", "\n", "One of them should have `model.train` and the other should have `model.eval`. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 214, "status": "ok", "timestamp": 1715240562885, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "e9R0vJA8NQUW" }, "outputs": [], "source": [ "def FIXME():\n", " loss = 0\n", " accuracy = 0\n", "\n", " model.FIXME()\n", " with torch.no_grad():\n", " for x, y in FIXME:\n", " output = model(x)\n", "\n", " loss += loss_function(output, y).item()\n", " accuracy += get_batch_accuracy(output, y, valid_N)\n", " print('FIXME - Loss: {:.4f} Accuracy: {:.4f}'.format(loss, accuracy))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 212, "status": "ok", "timestamp": 1715240561357, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "wr-X8QkVv9I7" }, "outputs": [], "source": [ "def FIXME():\n", " loss = 0\n", " accuracy = 0\n", "\n", " model.FIXME()\n", " for x, y in FIXME:\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('FIXME - Loss: {:.4f} Accuracy: {:.4f}'.format(loss, accuracy))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Solution" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Click the two `...`s below for the solution." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "jupyter": { "source_hidden": true } }, "outputs": [], "source": [ "# SOLUTION\n", "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": "code", "execution_count": null, "metadata": { "jupyter": { "source_hidden": true } }, "outputs": [], "source": [ "# SOLUTION\n", "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": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 720 }, "executionInfo": { "elapsed": 430665, "status": "error", "timestamp": 1715240995537, "user": { "displayName": "Danielle Detering US", "userId": "15432464718872067879" }, "user_tz": 420 }, "id": "qOYsrlmUwyyI", "outputId": "ccbb497f-8f23-43c3-85c4-81f47c98728d" }, "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": "pVytGlnl3ZZR" }, "source": [ "### 3.6.1 Discussion of Results" ] }, { "cell_type": "markdown", "metadata": { "id": "Ukd8Kk8l3ZZR" }, "source": [ "It looks like this model is significantly improved! The training accuracy is very high, and the validation accuracy has improved as well. This is a great result, as all we had to do was swap in a new model.\n", "\n", "You may have noticed the validation accuracy jumping around. This is an indication that our model is still not generalizing perfectly. Fortunately, there's more that we can do. Let's talk about it in the next lecture." ] }, { "cell_type": "markdown", "metadata": { "id": "zsOHIy5F3ZZR" }, "source": [ "## 3.7 Summary" ] }, { "cell_type": "markdown", "metadata": { "id": "DcIRdSur3ZZR" }, "source": [ "In this section, we utilized several new kinds of layers to implement a CNN, which performed better than the more simple model used in the last section. Hopefully the overall process of creating and training a model with prepared data is starting to become even more familiar." ] }, { "cell_type": "markdown", "metadata": { "id": "o0wFCmbK3ZZS" }, "source": [ "### 3.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": "0Ul7wgax3ZZS" }, "outputs": [], "source": [ "import IPython\n", "app = IPython.Application.instance()\n", "app.kernel.do_shutdown(True)" ] }, { "cell_type": "markdown", "metadata": { "id": "4kMR2FOK3ZZS" }, "source": [ "### 3.7.2 Next" ] }, { "cell_type": "markdown", "metadata": { "id": "13FglbMX3ZZS" }, "source": [ "In the last several sections you have focused on the creation and training of models. In order to further improve performance, you will now turn your attention to *data augmentation*, a collection of techniques that will allow your models to train on more and better data than what you might have originally at your disposal." ] }, { "cell_type": "markdown", "metadata": { "id": "PEzcSC6x3ZZS" }, "source": [ "
\"Header\"
" ] } ], "metadata": { "colab": { "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 }