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 I0 be the input image and Sc(I) the score for class c.
Start with the linear model that motivates the idea. Suppose that, with the image I flattened into a single vector, the score for class c is given by:
Sc(I)=wc⊤I+bc(2)
In this case, the magnitude of each element of the weight wc directly gives the importance of the corresponding pixel. The score Sc(I) of a deep CNN is not linear, but near the image I0 it can be approximated by a linear expression through a first-order Taylor expansion.
Sc(I)≈w⊤I+b,w=∂I∂ScI0(3),(4)
The gradient saliency map treats this w as the importance of each pixel. The steps are as follows.
Feed the image I0 to the model and compute the score Sc for class c. Use the value of Scbefore the softmax.
Compute the gradient w of Sc with respect to the input image (Eq. 4) by backpropagation. The model weights are not updated.
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).
Display the resulting map M (the same height m × width n as the input) next to or on top of the image.
Mij=kmaxwh(i,j,k)(5)
Here, h(i,j,k) is the index in the vector w of channel k of the pixel in row i and column j. 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 c 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 Sc 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.
Item
Details
Model
A 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 map
A map is computed for each of 10 images made by cropping and horizontal flipping, and the maps are averaged
Localization procedure
The 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 result
A 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 I0. 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.
Method
What it uses
Map resolution
Computation
Main weakness
Gradient saliency map
Absolute value of the gradient with respect to the input image
Feature maps of the last convolutional layer and their gradients
Coarse (feature map size)
1 backward pass
Cannot 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 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.