AI Logic

Explainability (XAI)

CAM (Class Activation Mapping)

Updated:

Diagram of CAM. The left side shows the flow of a CNN that supports CAM (input image, convolutional layers, feature maps of the last convolutional layer, global average pooling, a single fully connected layer, score of class c). The right side shows an example in which 3 feature maps are summed with the fully connected layer's weights to form a heatmap, which is overlaid on an input image of abstract shapes

What is CAM?

CAM (Class Activation Mapping) is a method that shows, as a heatmap computed from the feature maps of the last convolutional layer and the weights of the fully connected layer, "which parts of the image an image-classification CNN relied on when deciding on a class". Zhou et al. proposed it in 2016.

CAM applies to CNNs in which the last convolutional layer is followed only by global average pooling (GAP) and a single fully connected layer. In this architecture, the class score is "the feature maps summed with the weights of the fully connected layer", so summing the feature maps with the same weights reveals how much each location in the image contributed to the score.

The computation is only one forward pass and a weighted sum of the feature maps. No backpropagation is needed. Because each class has different weights, different locations light up for "dome" and "palace" even in the same image.

The key finding of CAM is that a CNN trained only with the class labels attached to images can also indicate object locations fairly accurately. Without ever using ground-truth bounding boxes around objects, it achieved an error rate on ImageNet object localization close to that of AlexNet, which was trained with bounding boxes. Locating objects without location labels in this way is called weakly supervised object localization.

Computation steps

The explanation follows the equations in Section 2 of Zhou et al. (2016), who proposed the method. Let fk(x,y)f_k(x, y) be the value at location (x,y)(x, y) of the kk-th channel of the last convolutional layer.

  1. Feed the image into the model and obtain the feature maps fk(x,y)f_k(x, y) (k=1,…,Kk = 1, \dots, K) of the last convolutional layer.
  2. Use global average pooling to reduce each channel to a single value Fk=∑x,yfk(x,y)F_k = \sum_{x,y} f_k(x, y).
  3. Use the fully connected layer to compute the score of class cc, Sc=∑kwkcFkS_c = \sum_k w^c_k F_k. ScS_c is the value before the softmax, and wkcw^c_k is a weight representing "how important the kk-th feature is for class cc". The bias is set to 0.
  4. Sum the feature maps with the same weights wkcw^c_k to obtain the heatmap McM_c for class cc (Eq. 2).
  5. Upsample McM_c (which has the same size as the feature maps) to the size of the input image and overlay it on the image.

Combining steps 2 and 3 and swapping the order of summation gives Eq. 1.

Sc=∑kwkc∑x,yfk(x,y)=∑x,y∑kwkcfk(x,y)(1)S_c = \sum_k w^c_k \sum_{x,y} f_k(x, y) = \sum_{x,y} \sum_k w^c_k f_k(x, y) \qquad (1)

CAM is this inner sum taken out for each location.

Mc(x,y)=∑kwkcfk(x,y)(2)M_c(x, y) = \sum_k w^c_k f_k(x, y) \qquad (2)

From Eq. 1 and Eq. 2, Sc=∑x,yMc(x,y)S_c = \sum_{x,y} M_c(x, y) holds. In other words, CAM is the class score split into a share for each location in the image. The larger Mc(x,y)M_c(x, y) is, the more the features at that location push up the score of class cc.

The paper writes FkF_k as the sum ∑x,yfk(x,y)\sum_{x,y} f_k(x, y). Actual global average pooling divides this by the number of locations to obtain the mean. The divisor is the same for every channel, so the shape of the heatmap does not change; only its overall magnitude is scaled by a constant.

The right side of the top figure is an example with 3 feature maps (K=3K = 3) of size 4 × 4. The weights of the fully connected layer are wc=(0.90, 0.20, −0.60)w^c = (0.90,\ 0.20,\ -0.60): 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. The weighted sum is positive at the circle's location and negative at the triangle's location. Unlike Grad-CAM, the CAM formula has no ReLU, so negative values are kept as they are.

Why locations can be found: the role of global average pooling

Global average pooling was originally used in Network In Network (Lin et al., 2014) to prevent overfitting and reduce the number of parameters. The CAM paper showed that this layer has another advantage: it can be used for classification while preserving object locations.

In CNNs that stack several fully connected layers, once the feature maps are flattened into a single vector, the information about which value came from which location in the image gets mixed. In contrast, with only global average pooling and a single fully connected layer, the score splits into a sum over locations as in Eq. 1, so location information can be traced all the way to the end.

The paper also examines the difference between global average pooling (average) and global max pooling (max).

  • Average: every location of the feature map contributes to the average, so the score rises by finding all the discriminative parts of the object. As a result, the full extent of the object tends to be shown.
  • Max: only the single strongest location contributes to the score, so it tends to show only part of the object.

In the experiments, too, the two had nearly the same classification error, but average pooling gave better localization (see the table in the next section).

Results in the paper

The paper modified AlexNet, VGG, and GoogLeNet into architectures that support CAM and evaluated them on ImageNet (ILSVRC). The modification removes the last few layers and the fully connected layers, adds a 3 × 3 convolutional layer (1024 channels), global average pooling, and a softmax fully connected layer, and retrains the network. The feature map size is 13 × 13 for AlexNet and 14 × 14 for VGG and GoogLeNet.

To build a bounding box from the heatmap, the locations above 20% of the maximum value are extracted, and the box is drawn around the largest connected region among them.

In classification error (ILSVRC validation set, top-1/top-5, %), the modification causes a slight drop in performance.

ModelOriginal architectureArchitecture for CAM (GAP)
VGG31.2/11.433.4/12.2
GoogLeNet31.9/11.335.0/13.2
AlexNet42.6/19.551.1/26.3 (44.9/20.9 with 2 extra convolutional layers)

The localization error (ILSVRC validation set, top-1/top-5, %) is as follows. The gradient saliency map ("Gradient" in the table) is the result of building boxes from the maps of the gradient saliency map.

Methodtop-1top-5
GoogLeNet-GAP (CAM)56.4043.00
VGG-GAP (CAM)57.2045.14
GoogLeNet-GMP (global max pooling)57.7845.26
Gradient (GoogLeNet)61.3150.55
Original GoogLeNet60.0949.34

On the test set, the top-5 error of GoogLeNet-GAP was 42.9%, and 37.1% with a refined box-selection strategy. This is close to the 34.2% of AlexNet trained with ground-truth boxes. However, there is still a gap from GoogLeNet with the same architecture trained with ground-truth boxes (26.7%).

The paper also reports that, on a dataset for distinguishing 200 bird species (CUB-200-2011), re-extracting features from regions cropped by CAM raises accuracy from 63.0% to 67.8%, and that CAM can show the locations of text and the regions that support answers to questions about an image.

Caveats in practice

CAM has the following limitations.

  • It requires a specific architecture: it applies only to models in which the last convolutional layer is followed only by global average pooling and a single fully connected layer. Other models must be modified and retrained, which can lower classification accuracy, as in the table above.
  • It is coarse: the heatmap size is fixed by the size of the last convolutional layer (for example, 14 × 14), so it cannot accurately show the locations of small objects or thin parts. In the paper, too, localization improved with larger feature maps, so layers were removed to keep the size large.
  • It can be biased toward the most discriminative parts: instead of the whole object, the part most useful for distinguishing the class (such as the head of an animal) may be highlighted most strongly.

Keep the following points in mind as well.

  • Take the weights from the fully connected layer before the softmax: wkcw^c_k are the weights of the fully connected layer that produces the score ScS_c.
  • Normalize the values for display: McM_c also contains negative values. When overlaying it on the image, decide how to display it, for example by scaling it to 0–1 using the minimum and maximum values.
  • ResNet and similar models work as is: models such as ResNet, which end with global average pooling and a single fully connected layer, can compute CAM without modification.

Comparison with other visualization methods

The table compares CAM with visualization methods it is often compared with, from the same viewpoints.

MethodWhat it usesHeatmap resolutionModel changesAmount of computation
CAMFully connected layer weights and feature mapsCoarse (feature map size)Requires a specific architecture; otherwise modify and retrain1 forward pass
Grad-CAMGradients and feature mapsCoarse (feature map size)None1 forward and 1 backward pass
Gradient saliency mapGradient with respect to the input imageFine (per pixel)None1 forward and 1 backward pass

Instead of the fully connected layer weights used by CAM, Grad-CAM uses as weights the gradients averaged over the height and width of the feature maps. The Grad-CAM paper shows that, for models with an architecture that supports CAM, these weights match the CAM weights up to a constant factor. In other words, Grad-CAM generalizes CAM so that it can be used with any CNN.

Rough guidelines for choosing:

  • The model ends with GAP and a single fully connected layer: use CAM. It needs no backpropagation and is the simplest.
  • The model architecture should stay unchanged: use Grad-CAM.
  • A fine, pixel-level map is needed: use the gradient saliency map, or its improvements SmoothGrad and Integrated Gradients.

PyTorch example

Show code
python
import torch
import torch.nn.functional as F
from torchvision import models

'''
Compute CAM with a pretrained ResNet-18 (ends with global average pooling -> a single fully connected layer)
(Eq. 2 of Zhou et al. 2016: M_c(x, y) = Σ_k w_k^c f_k(x, y))
'''

device = 'cuda' if torch.cuda.is_available() else 'cpu'
model = models.resnet18(weights=models.ResNet18_Weights.DEFAULT).to(device)
model.eval()  # put BatchNorm in inference mode

# Receive the output of the last convolutional layer (feature maps f_k) with a hook
features = {}
model.layer4.register_forward_hook(lambda m, inp, out: features.__setitem__('f', out))


@torch.no_grad()  # CAM needs no backpropagation
def cam(model, image, target_class=None):
  # image: [1, 3, H, W] (normalized). Returns a heatmap (0-1) of the same size as the input, and the class
  scores = model(image)                          # scores S_c before the softmax
  if target_class is None:
    target_class = scores.argmax(dim=1).item()
  f = features['f'][0]                           # [K, 7, 7] (K = 512)
  w = model.fc.weight[target_class]              # fully connected layer weights w_k^c: [K]
  # step 4 (Eq. 2): weighted sum, without ReLU
  m = torch.einsum('k,kxy->xy', w, f)            # [7, 7]
  # step 5: upsample to the input size and scale to 0-1 for display
  m = F.interpolate(m[None, None], size=image.shape[-2:], mode='bilinear', align_corners=False)[0, 0]
  m = (m - m.min()) / (m.max() - m.min() + 1e-8)
  return m, target_class


# Example: a random image (in practice, use an image normalized with transforms)
image = torch.randn(1, 3, 224, 224, device=device)
heatmap, predicted = cam(model, image)
print(predicted, heatmap.shape)  # torch.Size([224, 224])

FAQ

Q. Can it be used with models such as VGG that have several fully connected layers?
A.

Not as is, because CAM assumes an architecture in which the score is a weighted sum of the feature maps. The paper removes the last layers, replaces them with global average pooling and a single fully connected layer, and retrains. To keep the architecture unchanged, use Grad-CAM, which derives the weights from gradients.

Q. Why use global average pooling instead of global max pooling?
A.

With averaging, every location of the feature map contributes to the score, so training learns to find the full extent of the object. With max pooling, only the single strongest location contributes, so the map tends to show only part of the object. In the paper's experiments, classification error was nearly the same, but localization was better with averaging (top-5 errors of 43.00% vs. 45.26%).

Q. What does a negative CAM value at a location mean?
A.

It means the features at that location work to lower the score of class cc. As in Eq. 1, summing McM_c over all locations gives the score ScS_c, so negative locations are the shares that pulled the score down.

References

  1. B. Zhou, A. Khosla, A. Lapedriza, A. Oliva, and A. Torralba, "Learning Deep Features for Discriminative Localization," CVPR, 2016(arXiv:1512.04150).
  2. M. Lin, Q. Chen, and S. Yan, "Network In Network," arXiv:1312.4400, 2013.
  3. R. R. Selvaraju, M. Cogswell, A. Das, R. Vedantam, D. Parikh, and D. Batra, "Grad-CAM: Visual Explanations from Deep Networks via Gradient-Based Localization," arXiv:1610.02391, 2016.
  4. K. Simonyan, A. Vedaldi, and A. Zisserman, "Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps," arXiv:1312.6034, 2013.