{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# For tips on running notebooks in Google Colab, see\n",
    "# https://docs.pytorch.org/tutorials/beginner/colab\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[Introduction](introyt1_tutorial.html) \\|\\|\n",
    "[Tensors](tensors_deeper_tutorial.html) \\|\\|\n",
    "[Autograd](autogradyt_tutorial.html) \\|\\| [Building\n",
    "Models](modelsyt_tutorial.html) \\|\\| [TensorBoard\n",
    "Support](tensorboardyt_tutorial.html) \\|\\| [Training\n",
    "Models](trainingyt.html) \\|\\| **Model Understanding**\n",
    "\n",
    "# Model Understanding with Captum\n",
    "\n",
    "Follow along with the video below or on\n",
    "[youtube](https://www.youtube.com/watch?v=Am2EF9CLu-g). Download the\n",
    "notebook and corresponding files\n",
    "[here](https://pytorch-tutorial-assets.s3.amazonaws.com/youtube-series/video7.zip).\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "59c11d18",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Run this cell to load the video\n",
    "\n",
    "from IPython.display import display, HTML\n",
    "html_code = \"\"\"\n",
    "<div style=\"margin-top:10px; margin-bottom:10px;\">\n",
    "  <iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/Am2EF9CLu-g\" frameborder=\"0\" allow=\"accelerometer; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe>\n",
    "</div>\n",
    "\"\"\"\n",
    "display(HTML(html_code))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "801f9759",
   "metadata": {},
   "source": [
    "\n",
    "\n",
    "[Captum](https://captum.ai/) (\"comprehension\" in Latin) is an open\n",
    "source, extensible library for model interpretability built on PyTorch.\n",
    "\n",
    "With the increase in model complexity and the resulting lack of\n",
    "transparency, model interpretability methods have become increasingly\n",
    "important. Model understanding is both an active area of research as\n",
    "well as an area of focus for practical applications across industries\n",
    "using machine learning. Captum provides state-of-the-art algorithms,\n",
    "including Integrated Gradients, to provide researchers and developers\n",
    "with an easy way to understand which features are contributing to a\n",
    "model's output.\n",
    "\n",
    "Full documentation, an API reference, and a suite of tutorials on\n",
    "specific topics are available at the [captum.ai](https://captum.ai/)\n",
    "website.\n",
    "\n",
    "## Introduction\n",
    "\n",
    "Captum's approach to model interpretability is in terms of\n",
    "*attributions.* There are three kinds of attributions available in\n",
    "Captum:\n",
    "\n",
    "-   **Feature Attribution** seeks to explain a particular output in\n",
    "    terms of features of the input that generated it. Explaining whether\n",
    "    a movie review was positive or negative in terms of certain words in\n",
    "    the review is an example of feature attribution.\n",
    "-   **Layer Attribution** examines the activity of a model's hidden\n",
    "    layer subsequent to a particular input. Examining the\n",
    "    spatially-mapped output of a convolutional layer in response to an\n",
    "    input image in an example of layer attribution.\n",
    "-   **Neuron Attribution** is analagous to layer attribution, but\n",
    "    focuses on the activity of a single neuron.\n",
    "\n",
    "In this interactive notebook, we'll look at Feature Attribution and\n",
    "Layer Attribution.\n",
    "\n",
    "Each of the three attribution types has multiple **attribution\n",
    "algorithms** associated with it. Many attribution algorithms fall into\n",
    "two broad categories:\n",
    "\n",
    "-   **Gradient-based algorithms** calculate the backward gradients of a\n",
    "    model output, layer output, or neuron activation with respect to the\n",
    "    input. **Integrated Gradients** (for features), **Layer Gradient \\*\n",
    "    Activation**, and **Neuron Conductance** are all gradient-based\n",
    "    algorithms.\n",
    "-   **Perturbation-based algorithms** examine the changes in the output\n",
    "    of a model, layer, or neuron in response to changes in the input.\n",
    "    The input perturbations may be directed or random. **Occlusion,**\n",
    "    **Feature Ablation,** and **Feature Permutation** are all\n",
    "    perturbation-based algorithms.\n",
    "\n",
    "We'll be examining algorithms of both types below.\n",
    "\n",
    "Especially where large models are involved, it can be valuable to\n",
    "visualize attribution data in ways that relate it easily to the input\n",
    "features being examined. While it is certainly possible to create your\n",
    "own visualizations with Matplotlib, Plotly, or similar tools, Captum\n",
    "offers enhanced tools specific to its attributions:\n",
    "\n",
    "-   The `captum.attr.visualization` module (imported below as `viz`)\n",
    "    provides helpful functions for visualizing attributions related to\n",
    "    images.\n",
    "\n",
    "This visualization toolset will be demonstrated throughout this\n",
    "notebook.\n",
    "\n",
    "## Installation\n",
    "\n",
    "Before you get started, you need to have a Python environment with:\n",
    "\n",
    "-   Python version 3.9 or higher\n",
    "-   PyTorch (the latest version is recommended)\n",
    "-   TorchVision (the latest version is recommended)\n",
    "-   Captum (the latest version is recommended)\n",
    "-   Matplotlib (the latest version is recommended)\n",
    "\n",
    "To install Captum in a virtual environment, use:\n",
    "\n",
    "``` sh\n",
    "pip install torch torchvision captum matplotlib\n",
    "```\n",
    "\n",
    "Restart this notebook in the environment you set up, and you're ready to\n",
    "go!\n",
    "\n",
    "## A First Example\n",
    "\n",
    "To start, let's take a simple, visual example. We'll start with a ResNet\n",
    "model pretrained on the ImageNet dataset. We'll get a test input, and\n",
    "use different **Feature Attribution** algorithms to examine how the\n",
    "input images affect the output, and see a helpful visualization of this\n",
    "input attribution map for some test images.\n",
    "\n",
    "First, some imports:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn.functional as F\n",
    "import torchvision.transforms as transforms\n",
    "import torchvision.models as models\n",
    "\n",
    "import captum\n",
    "from captum.attr import IntegratedGradients, Occlusion, LayerGradCam, LayerAttribution\n",
    "from captum.attr import visualization as viz\n",
    "\n",
    "import os, sys\n",
    "import json\n",
    "\n",
    "import numpy as np\n",
    "from PIL import Image\n",
    "import matplotlib.pyplot as plt\n",
    "from matplotlib.colors import LinearSegmentedColormap"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we'll use the TorchVision model library to download a pretrained\n",
    "ResNet. Since we're not training, we'll place it in evaluation mode for\n",
    "now.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "model = models.resnet18(weights='IMAGENET1K_V1')\n",
    "model = model.eval()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The place where you got this interactive notebook should also have an\n",
    "`img` folder with a file `cat.jpg` in it.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "test_img = Image.open('img/cat.jpg')\n",
    "test_img_data = np.asarray(test_img)\n",
    "plt.imshow(test_img_data)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Our ResNet model was trained on the ImageNet dataset, and expects images\n",
    "to be of a certain size, with the channel data normalized to a specific\n",
    "range of values. We'll also pull in the list of human-readable labels\n",
    "for the categories our model recognizes - that should be in the `img`\n",
    "folder as well.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# model expects 224x224 3-color image\n",
    "transform = transforms.Compose([\n",
    " transforms.Resize(224),\n",
    " transforms.CenterCrop(224),\n",
    " transforms.ToTensor()\n",
    "])\n",
    "\n",
    "# standard ImageNet normalization\n",
    "transform_normalize = transforms.Normalize(\n",
    "     mean=[0.485, 0.456, 0.406],\n",
    "     std=[0.229, 0.224, 0.225]\n",
    " )\n",
    "\n",
    "transformed_img = transform(test_img)\n",
    "input_img = transform_normalize(transformed_img)\n",
    "input_img = input_img.unsqueeze(0) # the model requires a dummy batch dimension\n",
    "\n",
    "labels_path = 'img/imagenet_class_index.json'\n",
    "with open(labels_path) as json_data:\n",
    "    idx_to_labels = json.load(json_data)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, we can ask the question: What does our model think this image\n",
    "represents?\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "output = model(input_img)\n",
    "output = F.softmax(output, dim=1)\n",
    "prediction_score, pred_label_idx = torch.topk(output, 1)\n",
    "pred_label_idx.squeeze_()\n",
    "predicted_label = idx_to_labels[str(pred_label_idx.item())][1]\n",
    "print('Predicted:', predicted_label, '(', prediction_score.squeeze().item(), ')')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We've confirmed that ResNet thinks our image of a cat is, in fact, a\n",
    "cat. But *why* does the model think this is an image of a cat?\n",
    "\n",
    "For the answer to that, we turn to Captum.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Feature Attribution with Integrated Gradients\n",
    "\n",
    "**Feature attribution** attributes a particular output to features of\n",
    "the input. It uses a specific input - here, our test image - to generate\n",
    "a map of the relative importance of each input feature to a particular\n",
    "output feature.\n",
    "\n",
    "[Integrated Gradients](https://captum.ai/api/integrated_gradients.html)\n",
    "is one of the feature attribution algorithms available in Captum.\n",
    "Integrated Gradients assigns an importance score to each input feature\n",
    "by approximating the integral of the gradients of the model's output\n",
    "with respect to the inputs.\n",
    "\n",
    "In our case, we're going to be taking a specific element of the output\n",
    "vector - that is, the one indicating the model's confidence in its\n",
    "chosen category - and use Integrated Gradients to understand what parts\n",
    "of the input image contributed to this output.\n",
    "\n",
    "Once we have the importance map from Integrated Gradients, we'll use the\n",
    "visualization tools in Captum to give a helpful representation of the\n",
    "importance map. Captum's `visualize_image_attr()` function provides a\n",
    "variety of options for customizing display of your attribution data.\n",
    "Here, we pass in a custom Matplotlib color map.\n",
    "\n",
    "Running the cell with the `integrated_gradients.attribute()` call will\n",
    "usually take a minute or two.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Initialize the attribution algorithm with the model\n",
    "integrated_gradients = IntegratedGradients(model)\n",
    "\n",
    "# Ask the algorithm to attribute our output target to \n",
    "attributions_ig = integrated_gradients.attribute(input_img, target=pred_label_idx, n_steps=200)\n",
    "\n",
    "# Show the original image for comparison\n",
    "_ = viz.visualize_image_attr(None, np.transpose(transformed_img.squeeze().cpu().detach().numpy(), (1,2,0)),\n",
    "                      method=\"original_image\", title=\"Original Image\")\n",
    "\n",
    "default_cmap = LinearSegmentedColormap.from_list('custom blue', \n",
    "                                                 [(0, '#ffffff'),\n",
    "                                                  (0.25, '#0000ff'),\n",
    "                                                  (1, '#0000ff')], N=256)\n",
    "\n",
    "_ = viz.visualize_image_attr(np.transpose(attributions_ig.squeeze().cpu().detach().numpy(), (1,2,0)),\n",
    "                             np.transpose(transformed_img.squeeze().cpu().detach().numpy(), (1,2,0)),\n",
    "                             method='heat_map',\n",
    "                             cmap=default_cmap,\n",
    "                             show_colorbar=True,\n",
    "                             sign='positive',\n",
    "                             title='Integrated Gradients')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the image above, you should see that Integrated Gradients gives us\n",
    "the strongest signal around the cat's location in the image.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Feature Attribution with Occlusion\n",
    "\n",
    "Gradient-based attribution methods help to understand the model in terms\n",
    "of directly computing out the output changes with respect to the input.\n",
    "*Perturbation-based attribution* methods approach this more directly, by\n",
    "introducing changes to the input to measure the effect on the output.\n",
    "[Occlusion](https://captum.ai/api/occlusion.html) is one such method. It\n",
    "involves replacing sections of the input image, and examining the effect\n",
    "on the output signal.\n",
    "\n",
    "Below, we set up Occlusion attribution. Similarly to configuring a\n",
    "convolutional neural network, you can specify the size of the target\n",
    "region, and a stride length to determine the spacing of individual\n",
    "measurements. We'll visualize the output of our Occlusion attribution\n",
    "with `visualize_image_attr_multiple()`, showing heat maps of both\n",
    "positive and negative attribution by region, and by masking the original\n",
    "image with the positive attribution regions. The masking gives a very\n",
    "instructive view of what regions of our cat photo the model found to be\n",
    "most \"cat-like\".\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "occlusion = Occlusion(model)\n",
    "\n",
    "attributions_occ = occlusion.attribute(input_img,\n",
    "                                       target=pred_label_idx,\n",
    "                                       strides=(3, 8, 8),\n",
    "                                       sliding_window_shapes=(3,15, 15),\n",
    "                                       baselines=0)\n",
    "\n",
    "\n",
    "_ = viz.visualize_image_attr_multiple(np.transpose(attributions_occ.squeeze().cpu().detach().numpy(), (1,2,0)),\n",
    "                                      np.transpose(transformed_img.squeeze().cpu().detach().numpy(), (1,2,0)),\n",
    "                                      [\"original_image\", \"heat_map\", \"heat_map\", \"masked_image\"],\n",
    "                                      [\"all\", \"positive\", \"negative\", \"positive\"],\n",
    "                                      show_colorbar=True,\n",
    "                                      titles=[\"Original\", \"Positive Attribution\", \"Negative Attribution\", \"Masked\"],\n",
    "                                      fig_size=(18, 6)\n",
    "                                     )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Again, we see greater significance placed on the region of the image\n",
    "that contains the cat.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Layer Attribution with Layer GradCAM\n",
    "\n",
    "**Layer Attribution** allows you to attribute the activity of hidden\n",
    "layers within your model to features of your input. Below, we'll use a\n",
    "layer attribution algorithm to examine the activity of one of the\n",
    "convolutional layers within our model.\n",
    "\n",
    "GradCAM computes the gradients of the target output with respect to the\n",
    "given layer, averages for each output channel (dimension 2 of output),\n",
    "and multiplies the average gradient for each channel by the layer\n",
    "activations. The results are summed over all channels. GradCAM is\n",
    "designed for convnets; since the activity of convolutional layers often\n",
    "maps spatially to the input, GradCAM attributions are often upsampled\n",
    "and used to mask the input.\n",
    "\n",
    "Layer attribution is set up similarly to input attribution, except that\n",
    "in addition to the model, you must specify a hidden layer within the\n",
    "model that you wish to examine. As above, when we call `attribute()`, we\n",
    "specify the target class of interest.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "layer_gradcam = LayerGradCam(model, model.layer3[1].conv2)\n",
    "attributions_lgc = layer_gradcam.attribute(input_img, target=pred_label_idx)\n",
    "\n",
    "_ = viz.visualize_image_attr(attributions_lgc[0].cpu().permute(1,2,0).detach().numpy(),\n",
    "                             sign=\"all\",\n",
    "                             title=\"Layer 3 Block 1 Conv 2\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We'll use the convenience method `interpolate()` in the\n",
    "[LayerAttribution](https://captum.ai/api/base_classes.html?highlight=layerattribution#captum.attr.LayerAttribution)\n",
    "base class to upsample this attribution data for comparison to the input\n",
    "image.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "upsamp_attr_lgc = LayerAttribution.interpolate(attributions_lgc, input_img.shape[2:])\n",
    "\n",
    "print(attributions_lgc.shape)\n",
    "print(upsamp_attr_lgc.shape)\n",
    "print(input_img.shape)\n",
    "\n",
    "_ = viz.visualize_image_attr_multiple(upsamp_attr_lgc[0].cpu().permute(1,2,0).detach().numpy(),\n",
    "                                      transformed_img.permute(1,2,0).numpy(),\n",
    "                                      [\"original_image\",\"blended_heat_map\",\"masked_image\"],\n",
    "                                      [\"all\",\"positive\",\"positive\"],\n",
    "                                      show_colorbar=True,\n",
    "                                      titles=[\"Original\", \"Positive Attribution\", \"Masked\"],\n",
    "                                      fig_size=(18, 6))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Visualizations such as this can give you novel insights into how your\n",
    "hidden layers respond to your input.\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "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.12.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
