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:
- Pass the image through the CNN
- Get the feature maps from a convolutional layer (typically the last one)
- Compute gradients of the target class score with respect to feature maps
- Weight each feature map by its average gradient (importance)
- Combine weighted feature maps and apply ReLU
- 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) |