{ "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": {}, "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": {}, "source": [ "# 5a. Pre-Trained Models" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Though it is often necessary to have a large, well annotated dataset to solve a deep learning challenge, there are many freely available pre-trained models that we can use right out of the box. As you decide to take on your own deep learning project, it is a great idea to start by looking for existing models online that can help you achieve your goal. A great place to explore available models is [NGC](https://ngc.nvidia.com/catalog/models). There are also many models hosted on GitHub that you can find through searching on Google. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5a.1 Objectives" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Use TorchVision to load a very well-trained pretrained model\n", "* Preprocess our own images to work with the pretrained model\n", "* Use the pretrained model to perform accurate inference on your own images" ] }, { "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 data/imagenet_class_index.json data/doggy_door_images/happy_dog.jpg data/doggy_door_images/brown_bear.jpg data/doggy_door_images/sleepy_cat.jpg; 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 matplotlib; 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": {}, "outputs": [], "source": [ "import torch\n", "import torchvision.transforms.v2 as transforms\n", "import torchvision.io as tv_io\n", "\n", "import json\n", "\n", "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", "torch.cuda.is_available()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5a.2 An Automated Doggy Door" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this section, we will be creating a doggy door that only lets dogs (and not other animals) in and out. We can keep our cats inside, and other animals outside where they belong. Using the techniques covered so far, we would need a very large dataset with pictures of many dogs, as well as other animals. Luckily, there is a readily available model that has been trained on a massive dataset, including lots of animals. \n", "\n", "The [ImageNet challenge](https://en.wikipedia.org/wiki/ImageNet#History_of_the_ImageNet_challenge) has produced many state-of-the-art models that can be used for image classification. They are trained on millions of images, and can accurately classify images into 1000 different categories. Many of those categories are animals, including breeds of dogs and cats. This is a perfect model for our doggy door." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5a.3 Loading the Model" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We will start by downloading the model. Trained ImageNet models are available to download directly within the TorchVision library. We can see the available models and their details [here](https://pytorch.org/vision/stable/models.html). Any of these models would work for our exercise. We will pick a commonly used one called [VGG16](https://pytorch.org/vision/stable/models/vgg.html) and use the [default weights](https://pytorch.org/vision/stable/models/generated/torchvision.models.vgg19.html#torchvision.models.VGG19_Weights)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from torchvision.models import vgg16\n", "from torchvision.models import VGG16_Weights\n", "\n", "# load the VGG16 network *pre-trained* on the ImageNet dataset\n", "weights = VGG16_Weights.DEFAULT\n", "model = vgg16(weights=weights)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now that it is loaded, let us look at the model. It looks a lot like our convolutional model from the sign language exercise." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "model.to(device)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 5a.3.1 Input dimensions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As with our earlier exercises, our images should match the input dimensions that the model expects. Because PyTorch models are dynamically built, the model itself does not know what its input shape should be. Thankfully, the pretrained `weights` come with their own transforms." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pre_trans = weights.transforms()\n", "pre_trans" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is eqiuvalent to the following:\n", "\n", "```Python\n", "IMG_WIDTH, IMG_HEIGHT = (224, 224)\n", "\n", "pre_trans = transforms.Compose([\n", " transforms.ToDtype(torch.float32, scale=True), # Converts [0, 255] to [0, 1]\n", " transforms.Resize((IMG_WIDTH, IMG_HEIGHT)),\n", " transforms.Normalize(\n", " mean=[0.485, 0.456, 0.406],\n", " std=[0.229, 0.224, 0.225],\n", " ),\n", " transforms.CenterCrop(224)\n", "])\n", "```\n", "\n", "One new Transform here is [Normalize](https://pytorch.org/vision/main/generated/torchvision.transforms.Normalize.html) which will recolor an image based on a provided [mean](https://en.wikipedia.org/wiki/Mean) and [standard deviation](https://en.wikipedia.org/wiki/Standard_deviation). The other new Transform is [CenterCrop](https://pytorch.org/vision/stable/generated/torchvision.transforms.v2.CenterCrop.html#torchvision.transforms.v2.CenterCrop), which removes the edges of the image. We can apply these transforms to any image tensor we'd like to use with the VGG16 model." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 5a.3.2 Output dimensions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also see that the model will return a prediction of shape 1000. Remember that in our first exercise the output shape of our model was 10, corresponding to the 10 different digits. In our second exercise we had a shape of 24, corresponding to the 24 letters of the sign language alphabet that could be captured in a still image. Here, we have 1000 possible categories that the image will be placed in. Though the full ImageNet dataset has over 20,000 categories, the competition and resulting pre-trained models just use a subset of 1000 of these categories. We can take a look at all of these [possible categories here](https://gist.github.com/yrevar/942d3a0ac09ec9e5eb3a). \n", "\n", "Many of the categories are animals, including many types of dogs and cats. The dogs are categories 151 through 268. The cats are categories 281 through 285. We will be able to use these categories to tell our doggy door what type of animal is at our door, and whether we should let them in or not." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5a.4 Loading an Image\n", "We will start by loading in an image and displaying it, as we have done in previous exercises." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "import matplotlib.image as mpimg\n", "\n", "def show_image(image_path):\n", " image = mpimg.imread(image_path)\n", " plt.imshow(image)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "show_image(\"data/doggy_door_images/happy_dog.jpg\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 5a.4.1 Preprocessing the Image" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Next, we will preprocess the image so that it is ready to be sent into the model. This is just like what we did in our last exercise when we predicted on the sign language images. Remember that in this case, the final shape of the image should be (1, 3, 224, 224). We will use the Transforms provided by `weights` to so this." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def load_and_process_image(file_path):\n", " # Print image's original shape, for reference\n", " print('Original image shape: ', mpimg.imread(file_path).shape)\n", " \n", " image = tv_io.read_image(file_path).to(device)\n", " image = pre_trans(image) # weights.transforms()\n", " image = image.unsqueeze(0) # Turn into a batch\n", " return image" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's practice on our happy dog photo and see if it worked:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "processed_image = load_and_process_image(\"data/doggy_door_images/happy_dog.jpg\")\n", "print(\"Processed image shape: \", processed_image.shape)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The shape is correct, but how does it look? Let's print an image to verify:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import torchvision.transforms.functional as F\n", "\n", "plot_image = F.to_pil_image(torch.squeeze(processed_image))\n", "plt.imshow(plot_image, cmap='gray')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "That's a psychadelic effect, but if we squint our eyes, we can still see our happy dog. The strange coloring is due to the `Normalize` Transform, and the photo appears a little zoomed in because of `CenterCrop`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5a.5 Make a Prediction" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now that we have our image in the right format, we can pass it into our model and get a prediction. We are expecting an output of an array of 1000 elements, which is going to be difficult to read. We have a list of all the classes in [json](https://www.json.org/json-en.html) format, which is similar to a combination of python lists and dictionaries. In fact, let's load it into a combination of lists and dictionaries." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "vgg_classes = json.load(open(\"data/imagenet_class_index.json\"))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This file uses strings of numbers for each of the classes:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "vgg_classes[\"0\"]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's create a function to make a prediction from the VGG model human readable. This is similar to our `predict_letter` function from the previous lesson. This time, we will use the [torch.topk](https://pytorch.org/docs/stable/generated/torch.topk.html) function to give us the top `3` predictions." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "def readable_prediction(image_path):\n", " # Show image\n", " show_image(image_path)\n", " # Load and pre-process image\n", " image = load_and_process_image(image_path)\n", " # Make predictions\n", " output = model(image)[0] # Unbatch\n", " predictions = torch.topk(output, 3)\n", " indices = predictions.indices.tolist()\n", " # Print predictions in readable form\n", " out_str = \"Top results: \"\n", " pred_classes = [vgg_classes[str(idx)][1] for idx in indices]\n", " out_str += \", \".join(pred_classes)\n", " print(out_str)\n", "\n", " return predictions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Try it out on a few animals to see the results! Also feel free to upload your own images and categorize them just to see how well it works. Please see the [data/doggy_door_images/README.md](data/doggy_door_images/README.md) for attribution." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "readable_prediction(\"data/doggy_door_images/happy_dog.jpg\") # By Plank" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "readable_prediction(\"data/doggy_door_images/brown_bear.jpg\") # By Danielle Detering" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "readable_prediction(\"data/doggy_door_images/sleepy_cat.jpg\") # By TBD" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5a.6 Only Dogs" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now that we are making predictions with our model, we can use our categories to only let dogs in and out and keep cats inside. The dogs are categories 151 through 268 and cats are categories 281 through 285." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Exercise" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We used this [argmax](https://numpy.org/doc/stable/reference/generated/numpy.argmax.html) function in the previous lesson. Do you remember which dimension we are pulling indexes from?\n", "\n", "**Hint**: The first dimension is the batch dimension." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def doggy_door(image_path):\n", " show_image(image_path)\n", " image = load_and_process_image(image_path)\n", " idx = model(image).argmax(dim=FIXME).item()\n", " print(\"Predicted index:\", idx)\n", " if 151 <= idx <= 268:\n", " print(\"Doggy come on in!\")\n", " elif 281 <= idx <= 285:\n", " print(\"Kitty stay inside!\")\n", " else:\n", " print(\"You're not a dog! Stay outside!\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Solution" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Click on the `...` below to see the solution." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "jupyter": { "source_hidden": true }, "tags": [] }, "outputs": [], "source": [ "# SOLUTION\n", "import numpy as np\n", "\n", "def doggy_door(image_path):\n", " show_image(image_path)\n", " image = load_and_process_image(image_path)\n", " idx = model(image).argmax(dim=1).item()\n", " print(\"Predicted index:\", idx)\n", " if 151 <= idx <= 268:\n", " print(\"Doggy come on in!\")\n", " elif 281 <= idx <= 285:\n", " print(\"Kitty stay inside!\")\n", " else:\n", " print(\"You're not a dog! Stay outside!\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "doggy_door(\"data/doggy_door_images/brown_bear.jpg\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "doggy_door(\"data/doggy_door_images/happy_dog.jpg\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "doggy_door(\"data/doggy_door_images/sleepy_cat.jpg\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Summary" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Great work! Using a powerful pre-trained model, we have created a functional doggy door in just a few lines of code. We hope you are excited to take advantage of deep learning without a lot of up-front work. The best part is, as the deep learning community moves forward, more models will become available for you to use on your own projects." ] }, { "cell_type": "markdown", "metadata": {}, "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": {}, "outputs": [], "source": [ "import IPython\n", "app = IPython.Application.instance()\n", "app.kernel.do_shutdown(True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Next" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Using pretrained models is incredibly powerful, but sometimes they are not a perfect fit for your data. In the next section you will learn about another powerful technique, *transfer learning*, which allows you to tailer pretrained models to make good predictions for your data.\n", "\n", "Continue to the next section: [*Pretrained Models*](./05b_corgi_door.ipynb)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\"Header\"
" ] } ], "metadata": { "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 }