AI Logic

Explainability (XAI)

Gradient Saliency Map

Updated:

Diagram of the gradient saliency map. Left: the flow of a classification CNN (input image, convolutional layers, fully connected layers, score for class c). Right: a worked example in which the score is backpropagated to an input image of abstract shapes to obtain R, G and B gradients, a per-pixel map is formed by taking the maximum absolute value across channels, and the map is overlaid on the image

What is a gradient saliency map?

A gradient saliency map is a method that, for a CNN that has classified an image, shows "which pixels of the image matter most for that class score" through the magnitude of the gradient of the score with respect to the input image. It was proposed by Simonyan, Vedaldi and Zisserman in 2013.

The computation simply differentiates the class score with respect to the input image using backpropagation. A single backward pass is enough, and the trained model is used as is. The result is a map of the same size as the input image, in which pixels on the object tend to appear brighter.

This method became the starting point for later pixel-level explanation methods. SmoothGrad, which reduces the noise in the gradient, and Integrated Gradients, which integrates the gradient along a path, are both refinements of this gradient map.

The magnitude of the gradient expresses "how much the score changes if this pixel is changed slightly." The paper rephrases this as "the pixels that need to be changed the least to affect the class score the most." Because pixels on the object tend to affect the score more, the map often reveals where the object is.

How it is computed

This section follows the equations in Section 3 of Simonyan et al. (2013), who proposed the method. Let I0I_0 be the input image and Sc(I)S_c(I) the score for class cc.

Start with the linear model that motivates the idea. Suppose that, with the image II flattened into a single vector, the score for class cc is given by:

Sc(I)=wc⊤I+bc(2)S_c(I) = w_c^{\top} I + b_c \qquad (2)

In this case, the magnitude of each element of the weight wcw_c directly gives the importance of the corresponding pixel. The score Sc(I)S_c(I) of a deep CNN is not linear, but near the image I0I_0 it can be approximated by a linear expression through a first-order Taylor expansion.

Sc(I)≈w⊤I+b,w=∂Sc∂I∣I0(3), (4)S_c(I) \approx w^{\top} I + b, \qquad w = \left. \frac{\partial S_c}{\partial I} \right|_{I_0} \qquad (3),\ (4)

The gradient saliency map treats this ww as the importance of each pixel. The steps are as follows.

  1. Feed the image I0I_0 to the model and compute the score ScS_c for class cc. Use the value of ScS_c before the softmax.
  2. Compute the gradient ww of ScS_c with respect to the input image (Eq. 4) by backpropagation. The model weights are not updated.
  3. Reduce the absolute values of the gradient to one value per pixel. For a grayscale image, use the absolute value of that pixel's gradient directly. For an RGB image, use the largest of the absolute values across the three channels (Eq. 5).
  4. Display the resulting map MM (the same height mm × width nn as the input) next to or on top of the image.
Mij=max⁡k∣wh(i,j,k)∣(5)M_{ij} = \max_{k} \left| w_{h(i,j,k)} \right| \qquad (5)

Here, h(i,j,k)h(i,j,k) is the index in the vector ww of channel kk of the pixel in row ii and column jj. The equation number (5) was added in this article to refer to it in the text.

The right side of the diagram at the top shows an example of this computation. The circle is an object of class cc and the triangle is an object of another class. The gradient is large on the circle, but its sign varies from pixel to pixel. Taking absolute values and the maximum across channels makes the position of the circle stand out.

The reason for not using the probability after the softmax is that the probability can increase simply by lowering the scores of other classes. The paper uses the unnormalized score ScS_c to keep the explanation focused on the class itself.

Object localization and results in the paper

A gradient saliency map is built from a classification model trained only with class labels. It uses no bounding boxes or object region information. Since it still reveals where the object is, the paper showed that it can be used for weakly supervised object localization.

The paper reports the following.

ItemDetails
ModelA CNN trained on ImageNet (ILSVRC-2013, 1.2 million images, 1000 classes). Its architecture is similar to AlexNet, with top-1/top-5 error rates of 39.7%/17.7% on the validation data
Building the mapA map is computed for each of 10 images made by cropping and horizontal flipping, and the maps are averaged
Localization procedureThe top 5% of pixels in the map are used as foreground cues and the bottom 30% as background cues; a method that segments regions based on color continuity (GraphCut) finds the object region, and the box enclosing it is returned
Localization resultA top-5 error rate of 46.4% on the ILSVRC-2013 test data

This 46.4% falls short of that year's winning method (29.9%), which was trained using location information. On the other hand, it is lower than the 50.0% the same authors achieved the previous year with a method trained using location information.

There is a reason the map is not simply binarized but instead grown into regions using color continuity. A gradient saliency map may strongly highlight only the most class-discriminative part of an object, so thresholding alone cannot enclose the whole object.

The paper also shows that backpropagating the gradient to the input is nearly the same computation as the visualization by DeconvNet of Zeiler and Fergus (2013). The only difference is the handling of ReLU: backpropagation passes the gradient at positions where the forward input was positive, while DeconvNet passes it at positions where the value coming back is positive.

Caveats in practice

Gradient saliency maps have the following limitations.

  • High noise: The map often looks like fine speckles, and pixels unrelated to the object also light up. The SmoothGrad paper names the gradient's sharp fluctuation under small input changes as one cause.
  • Zero under saturation: Where the output has plateaued with respect to changes in the input, the gradient is close to 0 even if the feature is important. The Integrated Gradients paper presents this property as an example of failing the "sensitivity" axiom.
  • Local explanation: The gradient describes only the direction of change very close to the image I0I_0. It does not capture the effect of large pixel changes or of combinations of pixels.

Keep the following points in mind as well.

  • Use the score before the softmax: Differentiating the probability mixes in the influence of other classes. Most classification models in PyTorch output the pre-softmax values (logits), which can be used directly.
  • The display method changes the appearance: Whether absolute values are taken, whether signs are kept, and how channels are combined greatly change how the map looks. When comparing maps, use the same reduction.
  • It does not show whether a decision is correct: The map shows which pixels the model is sensitive to, not whether its decision is correct.

Comparison with other visualization methods

The table below compares the gradient saliency map with visualization methods it is often compared against, from the same perspectives.

MethodWhat it usesMap resolutionComputationMain weakness
Gradient saliency mapAbsolute value of the gradient with respect to the input imageFine (per pixel)1 backward passHigh noise; zero under saturation
SmoothGradAverage of gradients over noisy copies of the imageFine (per pixel)Tens of backward passesNoise level and number of samples must be chosen
Integrated GradientsIntegral of gradients from a baseline input to the actual inputFine (per pixel)Tens to hundreds of backward passesResults depend on the choice of baseline
CAMFeature maps of the last convolutional layer and fully connected layer weightsCoarse (feature map size)1 forward passOnly works for models with a specific architecture
Grad-CAMFeature maps of the last convolutional layer and their gradientsCoarse (feature map size)1 backward passCannot show small objects or thin parts

Rough guidelines for choosing:

  • To quickly see per-pixel sensitivity: Use a gradient saliency map. It takes only a few lines to implement.
  • To make a per-pixel map easier to read: Use SmoothGrad. It only adds noise and averaging to the gradient saliency map.
  • To quantify per-pixel contributions in a way that satisfies theoretical properties: Use Integrated Gradients.
  • To see the rough location of objects, separately for each class: Use Grad-CAM.

PyTorch example

Show code
python
import torch
from torchvision import models

'''
Compute the gradient saliency map of one image with a pretrained ResNet-18
(Simonyan et al. 2013, Section 3.1: M_ij = max_c |∂S_c/∂I|)
'''

device = 'cuda' if torch.cuda.is_available() else 'cpu'
model = models.resnet18(weights=models.ResNet18_Weights.DEFAULT).to(device)
model.eval()  # Put Dropout and BatchNorm in inference mode (gradients can still be computed)


def saliency_map(model, image, target_class=None):
  # image: [1, 3, H, W] (normalized). Returns an [H, W] map and the class
  image = image.clone().requires_grad_(True)   # Differentiate with respect to the input image
  scores = model(image)                        # Scores S_c before the softmax
  if target_class is None:
    target_class = scores.argmax(dim=1).item()
  model.zero_grad()
  # Step 2 (Eq. 4): differentiate S_c with respect to the input image. Model weights are not updated
  scores[0, target_class].backward()
  grad = image.grad[0]                         # [3, H, W]
  # Step 3 (Eq. 5): take the maximum absolute value across channels
  saliency = grad.abs().amax(dim=0)            # [H, W]
  return saliency.detach(), target_class


# Example: a random image (in practice, use an image normalized with transforms)
image = torch.randn(1, 3, 224, 224, device=device)
saliency, predicted = saliency_map(model, image)
print(predicted, saliency.shape)  # torch.Size([224, 224])
# Display example:
# import matplotlib.pyplot as plt
# plt.imshow(saliency.cpu(), cmap='gray'); plt.show()

FAQ

Q. Is the sign of the gradient not used?
A.

The map in the original paper uses the absolute value of the gradient. The sign indicates "whether brightening the pixel raises or lowers the score," but in an RGB image the sign can differ across channels of the same pixel, which makes it hard to combine. Some uses display the map with signs kept, but that yields a different map from the original paper.

Q. How does it differ from Guided Backpropagation?
A.

Guided Backpropagation (Springenberg et al., 2015) is a method that, at each ReLU during the backward pass, blocks not only positions where the forward input was negative but also positions where the gradient coming back is negative, before propagating to the input. It tends to show finer patterns than the plain gradient, but the result is no longer the gradient itself. The gradient saliency map uses the gradient ∂Sc/∂I\partial S_c / \partial I obtained by ordinary backpropagation as is.

Q. Can it be used for data other than images?
A.

Yes. It can be computed for any model whose score is differentiable with respect to the input. For example, in text models, the magnitude of the gradient with respect to word embeddings is sometimes used as the importance of each word.

References

  1. K. Simonyan, A. Vedaldi, and A. Zisserman, "Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps," arXiv:1312.6034, 2013.
  2. M. D. Zeiler and R. Fergus, "Visualizing and Understanding Convolutional Networks," arXiv:1311.2901, 2013.
  3. D. Smilkov, N. Thorat, B. Kim, F. Viégas, and M. Wattenberg, "SmoothGrad: removing noise by adding noise," arXiv:1706.03825, 2017.
  4. M. Sundararajan, A. Taly, and Q. Yan, "Axiomatic Attribution for Deep Networks," ICML, 2017(arXiv:1703.01365).