pytorch-grad-cam README

The project's README from github.com/jacobgil/pytorch-grad-cam. As one markdown file: README.md.

License: MIT Build Status Downloads Downloads

Advanced AI explainability for PyTorch

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.

visualization

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.

Visual Examples

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 and Semantic Segmentation

Object Detection Semantic Segmentation
3D Medical Semantic Segmentation

Explaining similarity to other images / embeddings

Deep Feature Factorization

CLIP

Explaining the text prompt "a dog" Explaining the text prompt "a cat"

Classification

Resnet50:

Category Image GradCAM AblationCAM ScoreCAM
Dog
Cat

Vision Transfomer (Deit Tiny):

Category Image GradCAM AblationCAM ScoreCAM
Dog
Cat

Swin Transfomer (Tiny window:7 patch:4 input-size:224):

Category Image GradCAM AblationCAM ScoreCAM
Dog
Cat

Metrics and Evaluation for XAI


Usage examples

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
from torchvision.models import resnet50, ResNet50_Weights

model = resnet50(weights=ResNet50_Weights.DEFAULT)
target_layers = [model.layer4[-1]]
input_tensor = # Create an input tensor image for your model..
# Note: input_tensor can be a batch tensor with several images!

# We have to specify the target we want to generate the CAM for.
targets = [ClassifierOutputTarget(281)]

# Construct the CAM object once, and then re-use it on many images.
with GradCAM(model=model, target_layers=target_layers) as cam:
  # You can also pass aug_smooth=True and eigen_smooth=True, to apply smoothing.
  grayscale_cam = cam(input_tensor=input_tensor, targets=targets)
  # In this example grayscale_cam has only one image in the batch:
  grayscale_cam = grayscale_cam[0, :]
  visualization = show_cam_on_image(rgb_img, grayscale_cam, use_rgb=True)
  # You can also get the model outputs without having to redo inference
  model_outputs = cam.outputs

cam.py has a more detailed usage example.


Choosing the layer(s) to extract activations from

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.


Adapting for new architectures and tasks

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.

The reshape_transform argument

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 argument

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.


Tutorials

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.


Guided backpropagation

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)

Metrics and evaluating the explanations

from pytorch_grad_cam.utils.model_targets import ClassifierOutputSoftmaxTarget
from pytorch_grad_cam.metrics.cam_mult_image import CamMultImageConfidenceChange
# Create the metric target, often the confidence drop in a score of some category
metric_target = ClassifierOutputSoftmaxTarget(281)
scores, batch_visualizations = CamMultImageConfidenceChange()(input_tensor, 
  inverse_cams, targets, model, return_visualization=True)
visualization = deprocess_image(batch_visualizations[0, :])

# State of the art metric: Remove and Debias
from pytorch_grad_cam.metrics.road import ROADMostRelevantFirst, ROADLeastRelevantFirst
cam_metric = ROADMostRelevantFirst(percentile=75)
scores, perturbation_visualizations = cam_metric(input_tensor, 
  grayscale_cams, targets, model, return_visualization=True)

# You can also average across different percentiles, and combine
# (LeastRelevantFirst - MostRelevantFirst) / 2
from pytorch_grad_cam.metrics.road import ROADMostRelevantFirstAverage,
                                          ROADLeastRelevantFirstAverage,
                                          ROADCombined
cam_metric = ROADCombined(percentiles=[20, 40, 60, 80])
scores = cam_metric(input_tensor, grayscale_cams, targets, model)

# You can also use aggregate metrics such as ARCC
from pytorch_grad_cam.metrics.ARCC import ARCC

cam_metric = ARCC(base_method=cam)
arcc_score = cam_metric(input_tensor, grayscale_cams, targets, model)

Smoothing to get nice looking CAMs

To reduce noise in the CAMs, and make it fit better on the objects, two smoothing methods are supported:

AblationCAM aug smooth eigen smooth aug+eigen smooth

Enhancing the CAM with scaling and sliding (SESS)

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) as cam:
    grayscale_cam = cam(input_tensor=input_tensor, targets=targets)

The run time is controlled by the number of scales and by the sliding window stride:

cam = SESS(model=model,
           target_layers=target_layers,
           base_method=GradCAM,
           num_scales=4,      # The image is resized to 4 scales instead of 12
           step_size=224,     # Non overlapping windows
           pre_filter_ratio=0.5,  # Skip the 50% lowest scoring patches
           batch_size=32)

Running the example script:

Usage: python cam.py --image-path <path_to_image> --method <method> --output-dir <output_dir_path>

To use with a specific device, like cpu, cuda, cuda:0, mps or hpu: python cam.py --image-path <path_to_image> --device cuda --output-dir <output_dir_path>


You can choose between:

GradCAM , HiResCAM, ScoreCAM, GradCAMPlusPlus, AblationCAM, XGradCAM , LayerCAM, FullGrad, EigenCAM, ShapleyCAM, FinerCAM, SegEigenCAM and RefineCAM.

Some methods like ScoreCAM and AblationCAM require a large number of forward passes, and have a batched implementation.

You can control the batch size with cam.batch_size =


Citation

If you use this for research, please cite. Here is an example BibTeX entry:

@misc{jacobgilpytorchcam,
  title={PyTorch library for CAM methods},
  author={Jacob Gildenblat and contributors},
  year={2021},
  publisher={GitHub},
  howpublished={\url{https://github.com/jacobgil/pytorch-grad-cam}},
}

References

https://arxiv.org/abs/1610.02391
Grad-CAM: Visual Explanations from Deep Networks via Gradient-based Localization Ramprasaath R. Selvaraju, Michael Cogswell, Abhishek Das, Ramakrishna Vedantam, Devi Parikh, Dhruv Batra

https://arxiv.org/abs/2011.08891
Use HiResCAM instead of Grad-CAM for faithful explanations of convolutional neural networks Rachel L. Draelos, Lawrence Carin

https://arxiv.org/abs/1710.11063
Grad-CAM++: Improved Visual Explanations for Deep Convolutional Networks Aditya Chattopadhyay, Anirban Sarkar, Prantik Howlader, Vineeth N Balasubramanian

https://arxiv.org/abs/1910.01279
Score-CAM: Score-Weighted Visual Explanations for Convolutional Neural Networks Haofan Wang, Zifan Wang, Mengnan Du, Fan Yang, Zijian Zhang, Sirui Ding, Piotr Mardziel, Xia Hu

https://ieeexplore.ieee.org/abstract/document/9093360/
`Ablation-cam: Visual explanations for deep convolutional network via gradient-free localizati

pytorch-grad-cam (jacobgil/pytorch-grad-cam)

Searching Database…

这是什么?一个 Python 包,实现了许多先进的可解释人工智能(XAI)像素归因方法(即类激活图 CAM),适用于计算机视觉模型,可以可视化模型在图像中关注哪些区域。
这是库还是独立应用?它是一个 PyTorch 库,需要导入到你自己的代码中(另附一个 cam.py 示例脚本),而不是图形界面应用。
我该怎么安装和使用?使用 'pip install grad-cam' 安装,在模型中选择一个目标层,然后对输入张量运行某个 CAM 类(例如 GradCAM),或者运行自带的 cam.py 脚本,并传入 --image-path 和 --method 参数。
能否开箱即用于任意模型结构?CNN 可以直接使用,但视觉 Transformer 和非 CNN 架构需要自定义 'reshape_transform',把激活值转换为空间图像;而且你必须手动为模型选择正确的目标层。
除了分类,它还支持哪些任务?它还支持目标检测、语义分割,以及对嵌入或图像相似度输出的解释,而不仅限于普通分类。
它包含多少种 CAM 方法?它包含约 20 种方法,例如 GradCAM、HiResCAM、GradCAM++、XGradCAM、AblationCAM、ScoreCAM、EigenCAM、LayerCAM、FullGrad、ShapleyCAM、FinerCAM、SegEigenCAM 和 RefineCAM 等。
我能为 CAM 选择多个层吗?可以。如果传入多个层的列表,CAM 输出会在这些层之间取平均,如果你不确定哪一层效果最好,这一点很有用。
怎样让热力图看起来更干净?支持两种平滑选项:aug_smooth(使用翻转和亮度缩放的测试时增强)和 eigen_smooth(使用激活权重的第一主成分),用来减少噪点。
README 里提到的 SESS 方法是什么?SESS 是一个与具体方法无关的封装器:它把图像缩放到多个尺度,在每个尺度上滑动窗口,再把每个小块的 CAM 融合回去。这样结果对尺度变化和干扰信息更稳健,代价是增加额外的计算量。
Creator
jacobgil
Size
143 MB
Stars
13K
Updated
CommitAug 13
Age
9y
Commits · 90 Days