Back to paper library
Paper notesarXiv 2015CVPR 2016

CAM

Where Is the Model Looking?

Original paper

Learning Deep Features for Discriminative Localization

Paper authors

Bolei Zhou · Aditya Khosla · Agata Lapedriza · Aude Oliva · Antonio Torralba

Publication
CVPR 2016Conference
First submitted to arXiv
arXiv:1512.04150
Cite this paper · BibTeX

The citation identifies the linked source version. It cites the original paper and its authors.

@misc{classiccnnscam2015,
  title = {{Learning Deep Features for Discriminative Localization}},
  author = {Bolei Zhou and Aditya Khosla and Agata Lapedriza and Aude Oliva and Antonio Torralba},
  year = {2015},
  eprint = {1512.04150},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/1512.04150}
}
On this page

Does a classification network that has only ever seen class labels know where the object is?

In work from the year before, Bolei Zhou and colleagues at MIT found that the answer is mostly yes. In a convolutional network trained for scene classification, the convolutional units in various layers behave much like object detectors, even though nobody told the network where the objects were during training. But this ability disappears at the fully connected layers. The output of a convolutional layer still keeps spatial positions; once it's flattened and fed into fully connected layers, “where” and “what” get mixed together and can no longer be pulled apart.

In December 2015, the same group (Bolei Zhou, Aditya Khosla, Agata Lapedriza, Aude Oliva, and Antonio Torralba) released this paper. They turned their attention to global average pooling, proposed in NiN and also used in GoogLeNet.

Defining the Problem

This paper tackles weakly supervised object localization, where training has only image-level class labels, yet at test time the model has to put a box around the object.

Several approaches already existed. Some covered up the image piece by piece to see where occlusion made the response drop most; some combined multiple-instance learning with convolutional features; some ran the network once on each of a large number of overlapping patches. None of these were trained end to end, and they required many forward passes, which made them hard to use on large-scale data.

The closest was the method of Oquab et al., which localizes objects with global max pooling. It can only find a single point on the object's boundary and can't tell you how far the object extends.

Another related line of work is visualizing convolutional networks. ZFNet used a deconvnet to see what pattern each unit looks for, and Zhou et al.'s own earlier work found object detectors inside scene networks; all of this research analyzed only the convolutional layers and skipped the fully connected ones.

The authors wanted the network to tell you, with a single forward pass, which regions of the image it used to decide on this class.

Solving the Problem

Splitting the Score Back Over Space

The authors use a network structure similar to NiN and GoogLeNet, with mostly convolutional layers up front, global average pooling after the last convolutional layer, then one fully connected layer, then a softmax.

Let fk(x,y)f_k(x, y) be the activation of the kk-th unit of the last convolutional layer at position (x,y)(x, y). Global average pooling squeezes each feature map into a single number:

Fk=∑x,yfk(x,y)F_k = \sum_{x,y} f_k(x, y)

The paper writes this as a plain sum and leaves out the division by the number of positions; the two differ by a constant, which doesn't affect the derivation that follows.

The score for class cc is a weighted sum of these numbers:

Sc=∑kwkcFkS_c = \sum_k w_k^c F_k

wkcw_k^c is a weight of the fully connected layer, representing how important the kk-th feature map is for class cc. The authors set the softmax bias to 0, saying it has almost no effect on classification.

Next comes the key to the whole paper. Substitute FkF_k and swap the order of the two sums:

Sc=∑kwkc∑x,yfk(x,y)=∑x,y∑kwkcfk(x,y)S_c = \sum_k w_k^c \sum_{x,y} f_k(x, y) = \sum_{x,y} \sum_k w_k^c f_k(x, y)

The inner sum ∑kwkcfk(x,y)\sum_k w_k^c f_k(x, y) still carries the position (x,y)(x, y). The authors define it as the class activation map (CAM) for class cc:

Mc(x,y)=∑kwkcfk(x,y)M_c(x, y) = \sum_k w_k^c f_k(x, y)

So Sc=∑x,yMc(x,y)S_c = \sum_{x,y} M_c(x, y). The class score is simply the sum of the CAM over all positions, and Mc(x,y)M_c(x, y) tells you directly how much position (x,y)(x, y) contributes to that score.

In other words, classification averages first and weights second; CAM reverses the order, weighting first and keeping the spatial layout instead of averaging. Weighting and averaging are both linear, so swapping their order leaves the class score unchanged. CAM uses no new parameters and doesn't need another pass through the network; it simply “projects” the already-learned fully connected weights back onto the last convolutional layer's feature maps.

The top half is the network: a photo of a boy holding a dog passes through a series of convolutional layers, and the feature maps of the last convolutional layer go through GAP and connect to the class Australian terrier with weights w1, w2, through wn. The bottom half is titled Class Activation Mapping: w1, w2, and wn each multiply their corresponding feature map, and the results are summed into a heat map overlaid on the original image, brightest over the dog
Figure 2 from the paper, excerpted from page 3 of the v1 PDF. The predicted class score is mapped back to the previous convolutional layer to produce the class activation map.

The bottom half of the figure is the computation of McM_c. Each feature map detects some visual pattern of its own, with some lighting up on the dog's head and others on the body below. Multiply them by the weights for the class “Australian terrier” and add them up, and you get this class's heat map. The last convolutional layer has very low resolution (13×1313\times13 or 14×1414\times14 in the paper); upsample the CAM to the size of the input image, and you can see which regions of the image are most relevant to this class.

For the same image, a different class means a different set of weights, and the CAM changes with it:

Top left is a nighttime photo of a domed building, labeled dome. The other five panels show the CAMs and scores for the top five predicted classes: palace 0.459 lights up on the wide palace building below; dome 0.195 on the dome above; church 0.146, altar 0.091, and monastery 0.051 concentrate their bright spots around the lower left of the building and the spire
Figure 4 from the paper, excerpted from page 4 of the v1 PDF. The true class is dome; the other five panels are the CAMs of the top five predictions, each labeled at the top with its class and score.

Palace lights up on the flat main building below, and dome on the dome above. To judge the two classes, the network looks at different parts of the same image.

Average vs. Max: What's the Difference?

Since Oquab et al. used global max pooling, the authors take care to explain why they use the average.

They reason that with an average, the best way to raise the score is to find all the discriminative parts of the object, since a low activation anywhere drags the average down; with a maximum, only the strongest position counts, and whether the other positions are high or low makes no difference.

The difference shows most clearly in backpropagation. On a 4×44\times4 feature map, average pooling spreads the gradient evenly over the 16 positions, 1/16 each, so every position gets trained; max pooling sends the gradient only to the largest cell, and the other 15 learn nothing from this step. Later experiments check whether this intuition holds up for localization.

Raising the Resolution of the Last Layer

The authors modify three networks, AlexNet, VGGnet, and GoogLeNet, removing the final fully connected layers and replacing them with GAP followed by a fully connected softmax layer.

They found that the higher the spatial resolution of the last convolutional layer before GAP, the better the localization. The authors call this resolution the mapping resolution. To raise it, they also removed a few more layers:

  • AlexNet: remove all layers after conv5, giving 13×1313\times13.
  • VGGnet: remove all layers after conv5-3, giving 14×1414\times14.
  • GoogLeNet: remove all layers after inception4e, giving 14×1414\times14.

Each network then gets one more convolutional layer, 3×33\times3 with stride 1, padding 1, and 1024 units, followed by GAP and softmax, and is fine-tuned for 1000-class classification on ILSVRC's 1.3 million training images. The resulting networks are called AlexNet-GAP, VGGnet-GAP, and GoogLeNet-GAP. The authors mention in a footnote that training from scratch gives similar results.

From Heat Map to Box

ILSVRC's localization evaluation wants a box, and the authors cut it out of the CAM in three steps:

  1. Upsample the CAM to the image size.
  2. Keep the regions whose values exceed 20% of the maximum.
  3. Take the largest connected region and draw its bounding box.

If the CAM has two responses, one large and one small, both may pass the threshold, but the final box surrounds only the largest region. That is also this method's limitation: when an image contains two objects, only one of them gets a box. For top-5 localization, the procedure is run once for each of the five top predicted classes.

Discussion

How Much Does Classification Suffer Without the Fully Connected Layers?

Table: Excerpted from Table 1 of the paper, ILSVRC validation set, in percent; the rows have been reordered for easier comparison with the original networks.
NetworkTop-1 errorTop-5 error
AlexNet42.619.5
AlexNet-GAP51.126.3
AlexNet*-GAP44.920.9
VGGnet31.211.4
VGGnet-GAP33.412.2
GoogLeNet31.911.3
GoogLeNet-GAP35.013.2
GoogLeNet-GMP35.613.9
NIN41.919.6

After VGGnet and GoogLeNet lose a few layers, their top-1 error rises by 2.2 and 3.1 percentage points, respectively, and top-5 by less than 2 points for both. AlexNet is hit hardest, with top-1 error going from 42.6% to 51.1%; when the authors add two more convolutional layers before GAP, the resulting AlexNet*-GAP is about as good as the original AlexNet. GAP and GMP also perform similarly on classification, as expected.

Classification can't afford to get much worse, because the localization evaluation requires both the class and the box to be right.

Weakly Supervised Localization

Table: Excerpted from Table 2 of the paper: localization error on the ILSVRC validation set, sorted by top-5. Backprop means using the backpropagation saliency maps of Simonyan et al. instead of CAM.
MethodTop-1 errorTop-5 error
GoogLeNet-GAP56.4043.00
VGGnet-GAP57.2045.14
GoogLeNet-GMP57.7845.26
GoogLeNet60.0949.34
AlexNet*-GAP63.7549.53
Backprop on GoogLeNet61.3150.55
Backprop on VGGnet61.1251.46
AlexNet-GAP67.1952.16
Backprop on AlexNet65.1752.64
NIN65.4754.19

The table breaks down into three comparisons.

  • CAM vs. backpropagation: on GoogLeNet and VGGnet, CAM's top-5 error is more than 6 percentage points lower than backpropagation's; on AlexNet the two are close (52.16 vs. 52.64), and on top-1 backpropagation actually comes out slightly ahead.
  • GoogLeNet-GAP vs. GoogLeNet: the original GoogLeNet classifies better but localizes worse than the trimmed GoogLeNet-GAP. The authors attribute this to the original GoogLeNet's last layer being only 7×77\times7, too low a resolution.
  • GAP vs. GMP: similar on classification, but for localization GAP's top-5 error is 2.26 percentage points lower, supporting the earlier intuition about average pooling.
Two groups, left and right. a) Four examples, each with an original image and a CAM: American alligator, maze, Shetland sheepdog, and grasshopper; on the original images, green boxes are the annotations and red boxes are inferred from the CAM, and the two roughly overlap. b) The top two examples are GoogLeNet-GAP localizing a snowmobile and an apron, with the heat concentrated on the object; the bottom two are results of backpropagation on AlexNet, where the heat map is scattered dots and the inferred boxes are too large
Figure 6 from the paper, excerpted from page 6 of the v1 PDF. a) Localization examples from GoogLeNet-GAP; b) the top two examples are GoogLeNet-GAP and the bottom two are backpropagation on AlexNet. Green boxes are annotations; red boxes are inferred from the heat maps.

The comparison on the right is easy to read. The backpropagation saliency map is a spread of scattered bright dots, so after thresholding the box comes out too large; CAM's hot region is concentrated, and its box fits the object more closely.

On the test set, the authors switch to a different box-selection strategy, taking one tight box and one loose box for each of the top two classes and one loose box for the third. This heuristic was tuned on the validation set.

Table: Excerpted from Table 3 of the paper, ILSVRC test set.
MethodSupervisionTop-5 test error
GoogLeNet-GAP (heuristic box selection)Weak37.1
GoogLeNet-GAPWeak42.9
BackpropWeak46.4
GoogLeNetFull26.7
OverFeatFull29.9
AlexNetFull34.2

37.1% is already close to the fully supervised AlexNet (34.2%), and GoogLeNet-GAP never saw a single box during training. The authors also acknowledge that the gap is still large. With the same GoogLeNet architecture, full supervision reaches 26.7%.

Moving to Other Tasks

The authors also wanted to know whether these localization-capable features could be used directly on other datasets. To find out, they freeze GoogLeNet-GAP, train a linear SVM on the GAP output, and compute the CAM with the SVM weights in place of the original softmax weights.

As generic image features, GoogLeNet-GAP performs about the same as the features from the original GoogLeNet's average pooling layer on eight datasets, including SUN397, MIT Indoor67, and Caltech256, and is mostly well ahead of AlexNet's fc7.

The fine-grained CUB-200-2011 bird dataset is more interesting. It has 200 bird species, 5,994 training images, and 5,794 test images, and it comes with bounding boxes for the birds.

Table: Selected rows excerpted from Table 4 of the paper.
MethodAnnotations used in training/testingAccuracy
GoogLeNet-GAP, whole imageNone63.0%
GoogLeNet-GAP, boxes inferred from CAMNone67.8%
GoogLeNet-GAP, annotated boxesBoxes70.5%
PANDA R-CNNBoxes + parts76.4%

Boxing the bird with CAM first and then re-extracting features from inside the box raises accuracy from 63.0% to 67.8%, without any annotation. Under the IoU 0.5 criterion, 41.0% of the boxes inferred from CAM are correct, against 5.5% for random guessing. Fine-grained differences often come down to a few details, so focusing on the bird first clearly helps.

The last set of experiments is about “pattern discovery,” checking whether the CAM lights up on a concept shared by a group of images. One of the examples concerns text detection:

The top row has six street-view photos of storefronts, and the bottom row shows the corresponding CAMs. The hot regions all fall on the text of the shop signs, such as store names on awnings and signs above doorways
Figure 11 from the paper, excerpted from page 8 of the v1 PDF. A weakly supervised text detector: the network wasn't trained with text or any boxes, yet the CAM still lights up on the text.

The positive set is 350 Google Street View images containing text, from the SVT dataset, and the negative set is outdoor scenes randomly sampled from the SUN dataset. With nothing but a binary label for “does this image contain text,” the CAM lands on the text of the signs. The paper also tries localizing informative objects in scenes and concepts described by short phrases, and interpreting the answers of visual question answering models.

The authors also used the weights after GAP to rank the units of the last convolutional layer by their importance for a given class, which shows directly which units matter most when judging that class. For example, the units important for the lakeland terrier (a dog breed) detect dog faces and body fur; the ones important for living room detect sofas, tables, and fireplaces.

Conclusion

CAM itself is a one-line formula that multiplies the classification layer's weights back onto the last layer's feature maps. It works because GAP is followed by only one linear layer, so the class score can be split back over every position. That is also its precondition, which means the network must have a “convolutions, GAP, one fully connected layer” structure. Other networks have to be re-architected and fine-tuned first, and their classification accuracy may drop as a result.

Experimentally, CAM reaches 37.1% top-5 error on ILSVRC weakly supervised localization, close to the fully supervised AlexNet but still some distance from the fully supervised GoogLeNet with the same architecture. Taking only the box of the largest connected region per image also makes it better suited to images with one main object.

CAM's architectural constraint was soon addressed. Grad-CAM, from October 2016, uses gradients to set each feature map's weight, with no need to switch to a GAP architecture or retrain.

As for the heat maps themselves, don't take them too seriously. They mark the most discriminative parts, such as an animal's head, and often cover only part of the object.

CAM's barrier to entry is low, though. As long as the network ends in GAP followed by one fully connected layer, a few lines of code will compute it. The now-common ResNet has exactly this structure, so the next time your model gives an unexpected answer, try drawing a CAM first to see where it's actually looking.