Skip to content

Guide · Open source

How to use pytorch-grad-cam: install and generate CAM heatmaps

Updated · written with AI from the project's own documentation and checked against our catalogue data

pytorch-grad-cam is a Python package of explainability methods for computer vision models built with PyTorch. It produces heatmaps (CAMs) that highlight the image regions that most influenced a model's output, such as a classification label or a detection result. This guide shows how to install it, choose a method, and produce a heatmap, so you can check whether a model is looking at sensible features.

pytorch-grad-camjacobgil/pytorch-grad-cam · ★ 13k · MIT

Quick start

  1. 1Check prerequisites. Make sure Python and PyTorch are installed in the environment you plan to use.
  2. 2Install the package. Run pip install grad-cam to install pytorch-grad-cam from PyPI.
  3. 3Load your model. Load a PyTorch image model and preprocess an input image into a tensor.
  4. 4Pick a method and target layer. Choose a CAM class such as GradCAM and select the layer whose activations you want to inspect.
  5. 5Set the target. Use ClassifierOutputTarget to choose the class index you want to explain.
  6. 6Overlay the heatmap. Call show_cam_on_image to draw the CAM over the original image and review where the model looks.

What pytorch-grad-cam does

The package provides a collection of pixel attribution methods for computer vision. It is designed for diagnosing model predictions, either in production or while developing models. The project also aims to serve as a benchmark of algorithms and metrics for researchers working on new explainability methods.

It works with classification, object detection, semantic segmentation and embedding-similarity use cases, and the README states it has been tested on many common CNNs and Vision Transformers.

  • Methods include GradCAM, HiResCAM, GradCAM++, XGradCAM, AblationCAM, ScoreCAM, EigenCAM, LayerCAM and others.
  • Smoothing methods are included to make the CAMs look cleaner.
  • Batches of images are supported in all methods.
  • Metrics are included for checking how far you can trust an explanation.

Install pytorch-grad-cam with pip

The package is installed from PyPI. You need Python and PyTorch available first. The README lists these as prerequisites.

Run the install command from the README in your terminal or environment.

pip install grad-cam

Choose a CAM method for your model

Each method trades off speed, resolution and what it measures. GradCAM is the standard starting point and weights the 2D activations by the average gradient. ScoreCAM and AblationCAM are perturbation-based and measure how the output drops when activations are removed or scaled. EigenCAM does not use class discrimination, so it shows strong activations regardless of the target class.

If you are unsure, start with GradCAM, then compare with one or two other methods on the same image. Agreement between methods is a useful sanity check, but the README does not claim any single method is always faithful.

  • GradCAM: weights activations by average gradient.
  • HiResCAM: element-wise multiplies activations with gradients.
  • AblationCAM: zeroes out activations and measures the output drop.
  • ScoreCAM: perturbs the image by scaled activations.
  • EigenCAM: first principal component of 2D activations, no class discrimination.

Generate a heatmap for a classifier

Import the CAM class you want, plus the helper for choosing the target class and the helper that overlays the heatmap on the image. The README usage example imports GradCAM, HiResCAM, ScoreCAM, GradCAMPlusPlus, AblationCAM, XGradCAM, EigenCAM and FullGrad from pytorch_grad_cam, ClassifierOutputTarget from pytorch_grad_cam.utils.model_targets, and show_cam_on_image from pytorch_grad_cam.utils.image.

Pass your model, the target layer(s) whose activations you want to inspect, and an input tensor. The target selects which output to explain, such as a specific class index. The full worked example is in the documentation linked from the README, so check it for the exact call pattern for your model.

  • Load a PyTorch model and a preprocessed image tensor.
  • Choose a target layer inside the network.
  • Wrap the target with ClassifierOutputTarget for the class you want to explain.
  • Overlay the resulting map on the original image with show_cam_on_image.
from pytorch_grad_cam import GradCAM, HiResCAM, ScoreCAM, GradCAMPlusPlus, AblationCAM, XGradCAM, EigenCAM, FullGrad from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget from pytorch_grad_cam.utils.image import show_cam_on_image

Use it for object detection and segmentation

The README shows examples for object detection, semantic segmentation, 3D medical segmentation, embedding similarity, Deep Feature Factorization and CLIP text prompts. These are presented as visual examples; the README's code section for these cases is not included in the source text used for this guide, so consult the documentation at https://jacobgil.github.io/pytorch-gradcam-book for the setup details.

Segmentation-specific methods such as SegEigenCAM are described in the README as designed for semantic segmentation.

What people use it for

  • Checking whether a dog classifier focuses on the dog rather than the background.
  • Comparing GradCAM, ScoreCAM and AblationCAM on the same image for research.
  • Debugging a Vision Transformer classifier by inspecting which regions drive its label.
  • Producing visual explanations for object detection or semantic segmentation outputs.

Frequently asked questions

How do I install pytorch-grad-cam?

Install it from PyPI with pip install grad-cam. The README lists Python and PyTorch as prerequisites, so make sure both are available in your environment first.

Is pytorch-grad-cam free to use?

The project is released under the MIT licence, as shown in the README. Check the licence file in the repository for the full terms.

What are the requirements for pytorch-grad-cam?

The package requires Python and PyTorch. The README does not list other requirements in the text provided here.

Does pytorch-grad-cam work with Vision Transformers?

Yes. The README says it has been tested on many common CNNs and Vision Transformers, and it shows GradCAM, AblationCAM and ScoreCAM examples for a DeiT Tiny model and a Swin Transformer.

What are alternatives to pytorch-grad-cam?

The project's comparable tools listed in our analysis are captum, tf-keras-vis and zennit. Captum is PyTorch-based, while tf-keras-vis targets TensorFlow and Keras models.

Can pytorch-grad-cam explain text or tabular models?

No. The README focuses on computer vision, so it is not the right tool for text or tabular models.

New agent skills, repos and AI tools — every week

The best new skills and open-source projects, the fastest-growing repos, and one free prompt. Five minutes to read. Unsubscribe anytime.

Our verdict

pytorch-grad-cam suits researchers comparing explainability methods, and engineers debugging CNN or Vision Transformer image models in PyTorch who are comfortable writing Python. It is not a fit for text or tabular models, for people who need a graphical interface, or for anyone needing a guarantee that an explanation is correct.

Install options & downloads