Advanced AI Explainability for computer vision. Support for CNNs, Vision Transformers, Classification, Object detection, Segmentation, Image similarity and mor
Advanced AI Explainability for computer vision. Support for CNNs, Vision Transformers, Classification, Object detection, Segmentation, Image similarity and mor
pip install grad-cam
Documentation with advanced tutorials: https://jacobgil.github.io/pytorch-gradcam-book
This is a package with state of the art methods for Explainable AI for computer vision. This can be used for diagnosing model predictions, either in production or while developing models. The aim is also to serve as a benchmark of algorithms and metrics for research of new explainability methods.
⭐ Comprehensive collection of Pixel Attribution methods for Computer Vision.
⭐ Tested on many Common CNN Networks and Vision Transformers.
⭐ Advanced use cases: Works with Classification, Object Detection, Semantic Segmentation, Embedding-similarity and more.
⭐ Includes smoothing methods to make the CAMs look nice.
⭐ High performance: full support for batches of images in all methods.
⭐ Includes metrics for checking if you can trust the explanations, and tuning them for best performance.
| Method | What it does |
|---|---|
| GradCAM | Weight the 2D activations by the average gradient |
| HiResCAM | Like GradCAM but element-wise multiply the activations with the gradients; provably guaranteed faithfulness for certain models |
| GradCAMElementWise | Like GradCAM but element-wise multiply the activations with the gradients then apply a ReLU operation before summing |
| GradCAM++ | Like GradCAM but uses second order gradients |
| XGradCAM | Like GradCAM but scale the gradients by the normalized activations |
| AblationCAM | Zero out activations and measure how the output drops (this repository includes a fast batched implementation) |
| ScoreCAM | Perbutate the image by the scaled activations and measure how the output drops |
| EigenCAM | Takes the first principle component of the 2D Activations (no class discrimination, but seems to give great results) |
| EigenGradCAM | Like EigenCAM but with class discrimination: First principle component of Activations*Grad. Looks like GradCAM, but cleaner |
| LayerCAM | Spatially weight the activations by positive gradients. Works better especially in lower layers |
| FullGrad | Computes the gradients of the biases from all over the network, and then sums them |
| Deep Feature Factorizations | Non Negative Matrix Factorization on the 2D activations |
| KPCA-CAM | Like EigenCAM but with Kernel PCA instead of PCA |
| FEM | A gradient free method that binarizes activations by an activation > mean + k * std rule. |
| ShapleyCAM | Weight the activations using the gradient and Hessian-vector product. |
| FinerCAM | Improves fine-grained classification by comparing similar classes, suppressing shared features and highlighting discriminative details. |
| SegEigenCAM | Like EigenCAM but with gradient weighting (absolute gradients ⊙ activations) before SVD and sign correction to fix SVD sign ambiguity; designed for semantic segmentation |
| RefineCAM | A meta-method that computes a CAM at multiple layers, and then it combines them to ubtain a higher resolution and better focused CAM. It can be used with any of the other CAM methods. |
| SESS | A meta-method that computes CAMs for sliding window patches taken at multiple scales, and fuses them with score based channel weights and a spatial weighted average. Makes the CAM robust to scale variance, multiple occurrences of the object and distractors. It can be used with any of the other CAM methods. |
| What makes the network think the image label is 'pug, pug-dog' | What makes the network think the image label is 'tabby, tabby cat' | Combining Grad-CAM with Guided Backpropagation for the 'pug, pug-dog' class |
|---|---|---|
| Object Detection | Semantic Segmentation |
|---|---|
| 3D Medical Semantic Segmentation |
|---|
| Explaining the text prompt "a dog" | Explaining the text prompt "a cat" |
|---|---|
| Category | Image | GradCAM | AblationCAM | ScoreCAM |
|---|---|---|---|---|
| Dog | ||||
| Cat |
| Category | Image | GradCAM | AblationCAM | ScoreCAM |
|---|---|---|---|---|
| Dog | ||||
| Cat |
| Category | Image | GradCAM | AblationCAM | ScoreCAM |
|---|---|---|---|---|
| Dog | ||||
| Cat |
…cam.py has a more detailed usage example.
You need to choose the target layer to compute the CAM for. Some common choices are:
If you pass a list with several layers, the CAM will be averaged accross them. This can be useful if you're not sure what layer will perform best.
Methods like GradCAM were designed for and were originally mostly applied on classification models, and specifically CNN classification models. However you can also use this package on new architectures like Vision Transformers, and on non classification tasks like Object Detection or Semantic Segmentation.
The be able to adapt to non standard cases, we have two concepts.
In a CNN the intermediate activations in the model are a mult-channel image that have the dimensions channel x rows x cols, and the various explainabiltiy methods work with these to produce a new image.
In case of another architecture, like the Vision Transformer, the shape might be different, like (rows x cols + 1) x channels, or something else. The reshape transform converts the activations back into a multi-channel image, for example by removing the class token in a vision transformer. For examples, check here
The model target is just a callable that is able to get the model output, and filter it out for the specific scalar output we want to explain.
For classification tasks, the model target will typically be the output from a specific category.
The targets parameter passed to the CAM method can then use ClassifierOutputTarget:
targets = [ClassifierOutputTarget(281)]However for more advanced cases, you might want a different behaviour. Check here for more examples.
Here you can find detailed examples of how to use this for various custom use cases like object detection:
These point to the new documentation jupter-book for fast rendering. The jupyter notebooks themselves can be found under the tutorials folder in the git repository.
Notebook tutorial: XAI Recipes for the HuggingFace Image Classification Models
Notebook tutorial: Deep Feature Factorizations for better model explainability
Notebook tutorial: Class Activation Maps for Object Detection with Faster-RCNN
Notebook tutorial: Class Activation Maps for Semantic Segmentation
Notebook tutorial: Adapting pixel attribution methods for embedding outputs from models
Notebook tutorial: May the best explanation win. CAM Metrics and Tuning
from pytorch_grad_cam import GuidedBackpropReLUModel
from pytorch_grad_cam.utils.image import (
show_cam_on_image, deprocess_image, preprocess_image
)
gb_model = GuidedBackpropReLUModel(model=model, device=model.device())
gb = gb_model(input_tensor, target_category=None)
cam_mask = cv2.merge([grayscale_cam, grayscale_cam, grayscale_cam])
cam_gb = deprocess_image(cam_mask * gb)
result = deprocess_image(gb)…To reduce noise in the CAMs, and make it fit better on the objects, two smoothing methods are supported:
aug_smooth=True
Test time augmentation: increases the run time by x6.
Applies a combination of horizontal flips, and mutiplying the image by [1.0, 1.1, 0.9].
This has the effect of better centering the CAM around the objects.
eigen_smooth=True
First principle component of activations*weights
This has the effect of removing a lot of noise.
| AblationCAM | aug smooth | eigen smooth | aug+eigen smooth |
|---|---|---|---|
SESS is a method agnostic wrapper around any of the other CAM methods.
It resizes the image to several scales, slides a window over every scale, and fuses
the CAM of every patch back into the original image coordinates, weighted by the
score the model gives that patch.
This makes the CAM robust to scale variance, to multiple occurrences of the object
and to distractors, at the cost of running the base method once per patch.
from pytorch_grad_cam import SESS, GradCAM
with SESS(model=model,
target_layers=target_layers,
base_method=GradCAM) asUsage of opencv-python-headless
AttributeError: 'list' object has no attribute 'cpu'
ShapleyCAM HVP term silently collapses to zero on ReLU networks
how can i adapt pytorch-grad-cam to Transformers VQA Models?
gradcam applied in regression tasks
How use gradcam in a multitask network
Can I use this framework for drawing heatmap of Qwen2.5-VL?
Could you give me some guidance on how I can adapt this to vllm like llava?
How can i use this for vit-based clip?
Can GradCAM be used in Transformer?