GradCAMExplainer<T>

Models & Types · AiDotNet.Interpretability.Explainers

Gradient-weighted Class Activation Mapping (Grad-CAM) explainer for CNNs.

Implements: ILocalExplainer<T, GradCAMExplanation<T>>

For Beginners

Grad-CAM creates visual explanations showing which parts of an image were most important for a CNN’s prediction. It produces a heatmap highlighting important regions.

How it works:

  1. Pass the image through the CNN
  2. Get the feature maps from a convolutional layer (typically the last one)
  3. Compute gradients of the target class score with respect to feature maps
  4. Weight each feature map by its average gradient (importance)
  5. Combine weighted feature maps and apply ReLU
  6. Resize the result to match input image size

Why Grad-CAM is useful:

  • Visual and intuitive: shows a heatmap over the image
  • Class-discriminative: different classes highlight different regions
  • Works with any CNN architecture (VGG, ResNet, etc.)
  • No modification to the model architecture needed

Example: For an image classified as “cat”:

  • The heatmap would highlight the cat’s face, body, ears
  • Areas like the background would have low activation

Grad-CAM++ is an improved version that handles multiple instances of the same object better.

Constructors

Constructor Summary
GradCAMExplainer(Func<Tensor<T>, Tensor<T>> predictFunction, Func<Tensor<T>, int, Tensor<T>> featureMapFunction, Func<Tensor<T>, int, int, Tensor<T>> gradientFunction, int[] inputShape, int[] featureMapShape, bool useGradCAMPlusPlus) Initializes a new Grad-CAM explainer.

Properties

Property Summary
bool SupportsGlobalExplanations { get; }
bool SupportsLocalExplanations { get; }
string MethodName { get; }

Methods

Method Summary
GradCAMExplanation<T> Explain(Vector<T> instance) Computes Grad-CAM heatmap for an input image.
GradCAMExplanation<T> ExplainTensor(Tensor<T> input, int targetClass, int layerIndex) Computes Grad-CAM heatmap for an input tensor.
GradCAMExplanation<T>[] ExplainBatch(Matrix<T> instances)