Grad-CAM (Gradient-weighted Class Activation Mapping) is a method that shows as a heatmap "which parts of the image a CNN relied on when deciding on a class." It was proposed by Selvaraju et al. in 2017.
For example, for an image containing a cat and a dog, computing Grad-CAM for the "cat" score highlights the area around the cat, and computing it for the "dog" score highlights the dog. Being able to show different locations for each class in this way is its defining feature.
Grad-CAM is computed by combining the following two things.
The feature maps output by the last convolutional layer (which features responded at which positions in the image)
The gradients of the class score with respect to the feature maps (how much each feature contributed to the class decision)
A major advantage is that it can be applied as is to an already trained model. There is no need to change the model architecture or retrain, and it works for CNNs with fully connected layers such as VGG, as well as for image captioning and visual question answering models.
A Grad-CAM heatmap shows where the model looked to make its decision, not whether the decision is correct. Looking at Grad-CAM for a misclassification can sometimes reveal that the model relies on the wrong cues, such as the background or text in the image. It is useful as a tool for finding model failures and dataset bias.
Background: removing the restrictions of CAM
Grad-CAM builds on CAM by Zhou et al. (2016). CAM can only be used with models whose last convolutional feature maps are reduced to single values by global average pooling and then immediately mapped to class scores by a fully connected layer, because it uses the weights wkc of that fully connected layer directly as the weights of the feature maps.
Therefore, using CAM with a model such as VGG, where several fully connected layers follow the convolutional layers, required changing the architecture and retraining, which could lower classification accuracy. In the paper's comparison, modifying VGG-16 for CAM raised the ImageNet top-1 error from 30.38% to 33.40%.
Grad-CAM removes this restriction by computing the weights from gradients instead of the fully connected layer weights. The paper also shows that, for models with an architecture where CAM can be used, the Grad-CAM weights match the CAM weights up to a constant factor. In other words, Grad-CAM is a generalization of CAM.
Computation steps
The steps to produce the Grad-CAM heatmap for class c are as follows.
Feed the image into the model and obtain the feature maps Ak of the last convolutional layer (k=1,…,K, where K is the number of channels) and the score yc for class c.
yc is the value before the softmax function.
Compute the gradients ∂yc/∂Aijk of yc with respect to the feature maps by backpropagation. The model weights are not updated.
Average the gradients over the height and width of the feature map (global average pooling) to obtain a weight αkc for each channel (Equation 1).
Sum the feature maps weighted by αkc, and set negative values to 0 with ReLU (Equation 2).
Upsample the resulting heatmap (the same size as the feature maps) to the input image size with bilinear interpolation, and overlay it on the image.
Here, Aijk is the value of the k-th feature map at row i and column j, and Z is the number of pixels in the feature map (height × width). αkc represents "how much the k-th feature raises the score of class c."
The right side of the figure at the top shows an example with three feature maps (K=3) of size 4 × 4. The weights obtained by averaging the gradients are αc=(0.50,0.25,−0.50): the first feature map, which responds to the circle, has the largest weight, and the third, which responds to the triangle, has a negative weight. After the weighted sum, the triangle's position becomes negative and is set to 0 by ReLU, so only the circle's position remains in the heatmap.
ReLU is applied because only the positions that work to increase the score of class c are of interest. Positions with negative values are likely to belong to other classes; the paper reports that removing ReLU highlights regions outside the target class as well and lowers localization performance.
The last convolutional layer is used because deeper layers capture meaningful features such as "ears" and "wheels," and convolutional layers, unlike fully connected layers, retain spatial information. According to the paper, the earlier the layer used, the lower the quality of the heatmap.
Combining with fine-grained visualization, and the paper's results
A Grad-CAM heatmap is only as large as the feature maps. For the last convolutional layer of VGG-16 this is 14 × 14, so when overlaid on a 224 × 224 image, each cell covers 16 × 16 pixels, producing a coarse map. It shows the rough location of an object, but not fine cues such as "stripes" or "pointed ears."
The paper therefore also proposes Guided Grad-CAM, which combines Grad-CAM with Guided Backpropagation (Springenberg et al., 2015), a visualization that draws the gradient with respect to the input image pixel by pixel (a relative of gradient saliency maps). The Grad-CAM heatmap is upsampled to the input size and multiplied pixel-wise with the Guided Backpropagation result. This yields a visualization that distinguishes locations by class while also showing fine patterns.
Examples of results reported in the paper:
Human evaluation: in an experiment where people were shown visualizations of images containing two classes and asked which class was being explained, accuracy was 44.44% for Guided Backpropagation versus 61.23% for Guided Grad-CAM.
Object localization: in an experiment building bounding boxes from the heatmap (ImageNet, VGG-16), the top-1 localization error was 56.51%, lower than CAM (57.20%). Unlike CAM, this result was obtained without lowering classification accuracy.
In addition, negating the gradients in Equation 1 shows "regions that, if absent, would make the model more confident that the image is class c." The paper calls these counterfactual explanations.
Comparison with other visualization methods, and caveats
The table below compares Grad-CAM with commonly compared visualization methods from the same perspectives.
Method
What it uses
Heatmap resolution
Model changes
Class discrimination
CAM
Fully connected layer weights and feature maps
Coarse (feature map size)
Requires a specific architecture; otherwise modify and retrain
Yes
Grad-CAM
Gradients and feature maps
Coarse (feature map size)
None
Yes
Guided Backpropagation
Gradient with respect to the input image (negative gradients blocked in the backward pass)
Integral of gradients from a baseline input to the actual input
Fine (per pixel)
None
Yes
Rules of thumb for choosing:
To quickly check which part of the image a CNN is looking at: use Grad-CAM. It needs only one backward pass and works directly on a trained model.
To see fine patterns: use Guided Grad-CAM.
To quantify each pixel's contribution in a way that satisfies theoretical properties: use Integrated Gradients.
Grad-CAM has the following limitations.
Coarse: the heatmap size is determined by the size of the last convolutional layer, so it cannot accurately locate small objects or thin parts.
Assumes convolutional layers: it uses feature maps that carry spatial information, so as is, it is a method for CNNs. When applying it to ViT and similar models, you must decide which layer's output to treat as the feature map.
Weak with multiple objects of the same class: when several objects of the same class appear in the image, only some of them may be strongly highlighted. Grad-CAM++ (Chattopadhyay et al., 2018) is a method that improves on this.
PyTorch example
▶Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
'''
Train a small CNN on MNIST data and compute Grad-CAM for a test image
'''
# Hyperparameters
batch_size = 64 # batch size
epochs = 1 # number of epochs
learning_rate = 1e-3 # learning rate
# 'cuda' if CUDA is available, 'mps' on Apple Silicon, otherwise 'cpu'
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
test_dataset = datasets.MNIST(root='./data', train=False, download=True, transform=transform)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
class SmallCNN(nn.Module):
def __init__(self, num_classes=10):
super().__init__()
self.conv = nn.Sequential(
nn.Conv2d(1, 32, kernel_size=3, padding=1), # [B, 1, 28, 28] -> [B, 32, 28, 28]
nn.ReLU(),
nn.MaxPool2d(2), # -> [B, 32, 14, 14]
nn.Conv2d(32, 64, kernel_size=3, padding=1), # last convolutional layer -> [B, 64, 14, 14]
nn.ReLU(),
)
self.head = nn.Sequential(
nn.MaxPool2d(2), # -> [B, 64, 7, 7]
nn.Flatten(),
nn.Linear(64 * 7 * 7, num_classes),
)
def forward(self, x):
feats = self.conv(x) # feature maps A^k
return self.head(feats), feats # scores y (before softmax) and A^k
def grad_cam(model, image, target_class=None):
# image: [1, 1, 28, 28]. Returns a heatmap (0-1) of the same size as the input, and the class
model.eval()
scores, feats = model(image)
if target_class is None:
target_class = scores.argmax(dim=1).item()
# Step 2: differentiate the class-c score with respect to the feature maps (weights are not updated)
grads = torch.autograd.grad(scores[0, target_class], feats)[0] # [1, K, 14, 14]
# Step 3 (Eq. 1): average the gradients over height and width to get per-channel weights α_k^c
alpha = grads.mean(dim=(2, 3), keepdim=True) # [1, K, 1, 1]
# Step 4 (Eq. 2): take the weighted sum and apply ReLU
cam = F.relu((alpha * feats).sum(dim=1, keepdim=True)) # [1, 1, 14, 14]
# Step 5: upsample to the input size with bilinear interpolation and normalize to 0-1 for display
cam = F.interpolate(cam, size=image.shape[-2:], mode='bilinear', align_corners=False)
cam = cam / (cam.max() + 1e-8)
return cam[0, 0].detach(), target_class
# Training
model = SmallCNN().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
for epoch in range(epochs):
model.train()
for images, labels in train_loader:
images, labels = images.to(device), labels.to(device)
optimizer.zero_grad()
scores, _ = model(images)
loss = criterion(scores, labels)
loss.backward()
optimizer.step()
# Grad-CAM for one test image
image, label = test_dataset[0]
heatmap, predicted = grad_cam(model, image.unsqueeze(0).to(device))
print(f"Label: {label}, Predicted: {predicted}")
print(heatmap.shape) # torch.Size([28, 28])
# With matplotlib, it can be overlaid on the image:
# import matplotlib.pyplot as plt
# plt.imshow(image[0], cmap='gray'); plt.imshow(heatmap.cpu(), cmap='jet', alpha=0.5); plt.show()
FAQ
Q. Which layer's feature maps should be used?
A.
Usually the last convolutional layer, because it has both meaningful features and spatial information. The paper reports that the earlier the layer used, the lower the quality of the heatmap.
Q. Why use the score before softmax?
A.
Because the paper defines Grad-CAM as differentiating the pre-softmax score y^c. Post-softmax probabilities also depend on the scores of other classes, so the pre-softmax value is used to see the evidence for the class itself.
Q. Can it be used beyond image classification?
A.
Yes. Any differentiable output can be chosen as y^c, and the paper also applies it to image captioning and visual question answering models.