Visualizing What CNNs Learn
Feature visualization, deconvolution, network dissection and their caveats.
Ask a trained CNN what it has learned and it answers with millions of numbers. Visualization methods turn them into pictures: what a unit responds to, where the evidence for a class lies, which human concept a channel tracks. The pictures have diagnosed real flaws and fueled whole research programs, and some of them turned out to show more about the input, or about the method, than about the network.
What you’ll learn
- Read first-layer filters, top-activating patches and occlusion maps, and explain how the deconvnet projects a unit back to pixels.
- Show that gradients, the deconvnet and guided backpropagation differ only in their backward rule at ReLUs, and explain what that implies.
- Derive class activation maps from global average pooling and prove that Grad-CAM's channel weights reduce to CAM's for such networks.
- Formulate activation maximization as regularized optimization, and explain transformation robustness, Fourier preconditioning and DeepDream.
- Compute network dissection's unit–concept IoU, interpret its rotation experiment, and weigh the evidence on the reliability of these methods.
Filters, top patches and the deconvnet
The first layer is the one place where weights are pictures. AlexNet's 96 filters of size came out of training as frequency- and orientation-selective edge detectors and colored blobs (Krizhevsky, Sutskever & Hinton, 2012), close relatives of the Gabor-like filters of classical image processing. Deeper filters live in a space of 64 to 512 channels and cannot be read off as images, so every other method on this page asks a question about behavior instead.
The simplest question: which inputs excite a unit most? Zeiler & Fergus (2014) ran the validation images through an AlexNet-style network, kept the nine image patches with the strongest activation of each feature map, and projected each activation back to pixel space with a deconvnet that undoes the layers in reverse order:
- unpool, using "switches" recorded in the forward pass that say where each max-pooling maximum came from;
- rectify, passing the reconstruction through a ReLU so it stays positive;
- filter with the transposed filters, that is, the same kernels flipped vertically and horizontally.
The projections showed a hierarchy: layer 2 responds to corners and edge–color conjunctions, layer 3 to textures such as meshes and text, layer 4 to class-specific parts such as dog faces and bird legs, and layer 5 to whole objects across poses. They were also a debugging tool. AlexNet's first layer mixed very high and very low frequencies with little in between and had "dead" filters, and its second-layer projections showed aliasing from the stride-4 first layer; a modified network with first-layer filters and stride 2 removed both, and beat AlexNet's single-model top-5 error by 1.7 points.
A third, model-agnostic probe is occlusion: slide a gray square over the image and record the probability of the true class at every position. If the probability collapses when the dog's face is covered, the face carries the evidence, which rules out the worry that the network is reading the background.
Three backward passes
A saliency map asks which pixels the class score is most sensitive to (Simonyan, Vedaldi & Zisserman, 2014): compute by one backward pass and display . They used the unnormalized score rather than the softmax probability, because the probability can also be raised by pushing the other scores down. They also showed that the deconvnet is almost the same computation.
Through a convolution , all three methods propagate a signal backward with the flipped kernel , and through max pooling all three route it to the recorded argmax: the "switch" is just the subgradient of the max.
They differ only at a ReLU . The gradient masks by the sign of the forward input; the deconvnet rectifies the backward signal and ignores the forward pass; guided backpropagation (Springenberg et al., 2015) applies both masks:
Discarding every negative backward signal at every layer means the map no longer reflects evidence against the unit, and positive contributions pile up wherever the input has strong local structure. That is why guided maps look crisp, and also why they say less about the network than they appear to.
Which backward rule ignores the forward activations entirely when it passes a ReLU, so that it no longer depends on which units were active for this image?
- The plain gradient
- Guided backpropagation
- The deconvnet
- None of them: all three mask by the forward activation
Show the answer
C. The deconvnet
The deconvnet applies a ReLU to the backward signal itself, . The image enters only through the max-pooling switches, which is why it fails without them (Springenberg et al. found that guided backpropagation, which keeps the forward mask, works with or without switches).
Class activation maps and Grad-CAM
Gradients are noisy and pixel-level. A coarser question is better posed: where in the image is the evidence for class ? Networks that end with global average pooling answer it almost for free (Zhou et al., 2016). Let the last convolutional layer output maps with positions, pooled to , and let the class score be .
Exchange the two sums. The score is the spatial average of a map, the class activation map , which says how much each position contributes:
Grad-CAM (Selvaraju et al., 2017) drops the architectural requirement: for any differentiable head, weight each map by its spatially averaged gradient, combine, and keep the positive part:
For the pooled linear head above, is linear in with at every position. The average of a constant is the constant:
So Grad-CAM is CAM, up to a positive constant and the ReLU, wherever CAM applies. Elsewhere is the weight of a first-order linearization of everything downstream of , which is why it extends to captioning and question-answering heads. The ReLU keeps regions that raise ; without it the maps also light up evidence for other classes.
import torch
import torch.nn.functional as F
def grad_cam(features, classifier, x, c):
"""Grad-CAM for a network: features -> global average pool -> linear classifier."""
A = features(x) # (1, K, h, w) last conv feature maps
y = classifier(A.mean(dim=(2, 3)))[0, c] # class score before the softmax
(dA,) = torch.autograd.grad(y, A) # dy/dA, same shape as A
alpha = dA.mean(dim=(2, 3), keepdim=True) # channel weights: averaged gradients
cam = F.relu((alpha * A).sum(dim=1)) # (1, h, w) coarse map
return F.interpolate(cam[None], size=x.shape[-2:], mode='bilinear')[0]The map has the resolution of the last convolutional layer, for VGG at input, and is upsampled for display. Guided Grad-CAM multiplies it pointwise with a guided-backpropagation map for sharper detail, inheriting that method's weakness.
The payoff is weakly supervised localization. Trained only with image labels, a GAP network's thresholded CAMs reached 37.1% top-5 localization error on ILSVRC 2014, close to the 34.2% of a network trained with bounding boxes (Zhou et al., 2016). The limits are just as concrete: a map is only as fine as the last feature grid, Grad-CAM maps get worse at earlier layers (their receptive fields are small and their features less semantic), and a map says where, never what: it cannot tell you whether the network used the dog's shape or the texture of its fur.
Activation maximization and feature visualization
Instead of explaining one image, synthesize the image a unit "prefers" (Erhan et al., 2009): gradient ascent on the input,
where is a feature's activation (a neuron, a whole channel, or a class logit) and a regularizer. Simonyan et al. (2014) used on class scores. Unregularized, the optimizer finds high-frequency noise that drives the unit hard but looks like nothing: a cousin of adversarial examples, encouraged by strided convolutions and pooling, whose gradients have checkerboard structure.
| Ingredient | What it does | Cost |
|---|---|---|
| Frequency penalties (total variation, blurring) | suppress the high-frequency noise | also suppress genuine sharp edges |
| Transformation robustness (random jitter, rotation, scaling at each step) | keep only patterns that activate the unit robustly | more optimization steps |
| Learned priors (a generative model's latent space) | the most natural-looking images | hard to tell the unit's preference from the prior's |
| Preconditioning: optimize in a decorrelated color space and a Fourier basis scaled so all frequencies carry equal energy | the same steepest-ascent objective, under a metric that favors natural-image statistics | none at run time |
| A diversity term between several images | reveals different facets of one unit, such as several kinds of balls | several images per unit |
DeepDream turns the objective around: start from a photograph and ascend for a whole layer (Mordvintsev, Olah & Tyka, 2015). The gradient amplifies whatever the layer already detects, a feedback loop that grows eyes and dog faces out of clouds.
Network dissection and the unit question
Network dissection (Bau et al., 2017) replaces pictures with a number. It uses Broden, a merger of densely labeled datasets in which pixels carry labels from 1,197 concepts across six categories: colors, materials, textures, parts, objects and scenes. For each convolutional unit :
- choose the threshold exceeded by its top 0.5% of activations over the whole dataset, ;
- upsample the unit's activation map to image resolution and threshold it into a binary mask ;
- score it against every concept's mask with a dataset-wide intersection over union, and call the unit a detector for if .
Across the dataset, a unit's thresholded masks cover 12,000 pixels, the "dog" masks cover 20,000 pixels, and the two overlap on 4,000 pixels. What is ?
Show the answer
0.14
The union is pixels, so , well above the threshold: this unit counts as a dog detector, although it fires on many non-dog pixels and misses most dog pixels.
The most telling experiment rotates the representation. Take AlexNet's conv5 trained on scene recognition and apply a random orthogonal matrix to its 256 units. A network that undoes the rotation in its next layer computes exactly the same function, so discriminative power is unchanged, yet the number of unique detectors fell by 80%. Interpretability of individual units is therefore axis-aligned: training places concepts on single units more often than chance would, but it is not a consequence of performance. Batch normalization also lowered interpretability significantly at similar accuracy (the authors suggest that it lets training rotate the axes cheaply), and object and part detectors appeared at higher layers and texture and color detectors at lower ones.
Units need not be monosemantic, either. Olah et al. (2017) found a GoogLeNet neuron that responds to two kinds of animal faces and to car bodies, and concluded that neurons are not necessarily the right units of analysis. Why networks mix unrelated features in one unit, and how to recover cleaner features with sparse dictionaries, is the subject of Interpretability: Looking Inside Networks and Dictionary Learning at Scale.
Key takeaways
- First-layer filters can be viewed directly; deeper units are studied through behavior: top-activating patches, deconvnet projections, occlusion maps. Visualization revealed real flaws, such as AlexNet's aliased first layer.
- Gradients, the deconvnet and guided backpropagation share one backward pass and differ only at ReLUs; dropping negative signals makes guided maps crisp but largely insensitive to the model's weights.
- For a global-average-pooling head, the class score is the average of the class activation map , and Grad-CAM's weights reduce to ; elsewhere they linearize the head.
- Activation maximization needs regularizers, transformation robustness and a decorrelated Fourier parameterization; even so, natural exemplars can be more informative, and visualizations can be manipulated.
- Network dissection scores units against 1,197 labeled concepts by IoU; its rotation experiment shows that unit-level interpretability is axis-aligned and separate from performance, and polysemantic units show that neurons may be the wrong units of analysis.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A CNN ends with global average pooling over positions and a linear layer with weights . What are Grad-CAM's channel weights for class ?
- divided by
- multiplied by
- The maximum gradient over positions
- They depend on the image, so they cannot be expressed through
Show the answer
A. divided by
The score is linear in the maps with at every position, and averaging a constant returns it. So Grad-CAM equals CAM up to the factor and the final ReLU.
Why can guided backpropagation produce crisp, object-shaped maps even for a network whose top layers have been re-randomized?
- Because re-randomizing weights does not change a network's predictions
- Because it discards all negative signals going backward, so the map is dominated by the input's local structure, a partial image reconstruction
- Because it uses the max-pooling switches, which store the trained network's knowledge
- It cannot: guided backpropagation always changes when the weights change
Show the answer
B. Because it discards all negative signals going backward, so the map is dominated by the input's local structure, a partial image reconstruction
With both ReLU masks at every layer only positive contributions survive, and they accumulate where the image has edges. Adebayo et al. (2018) found guided maps nearly invariant to randomizing higher layers, and Nie, Zhang & Patel (2018) showed the method performs partial image recovery.
You maximize a class's softmax probability by gradient ascent on the input, with no regularizer. What do you most likely get?
- A clear, natural-looking image of the class
- A blank gray image, since nothing is regularized
- High-frequency noise that scores highly, often reached partly by suppressing the other classes
- The average training image of the class
Show the answer
C. High-frequency noise that scores highly, often reached partly by suppressing the other classes
Unconstrained ascent finds adversarial-like patterns, and with a softmax the probability can rise because rival logits fall. Feature visualization therefore maximizes logits and adds frequency penalties, transformation robustness and a decorrelated parameterization.
Bau et al. applied a random rotation to the 256 units of a layer, leaving the network's accuracy unchanged, and the number of concept detectors fell by 80%. What does this show?
- Rotations damage the information stored in the layer
- Interpretability of single units is an axis-aligned property, not a consequence of discriminative power
- The original units were random, and the rotation revealed it
- Network dissection measures accuracy, not interpretability
Show the answer
B. Interpretability of single units is an axis-aligned property, not a consequence of discriminative power
A rotated layer followed by the inverse rotation computes the same function, so all the information remains. Yet far fewer single units align with labeled concepts: training happens to place concepts on individual units, more than a random basis would.
Further reading
- M. D. Zeiler & R. Fergus, "Visualizing and understanding convolutional networks," ECCV (2014).
- R. R. Selvaraju, M. Cogswell, A. Das, R. Vedantam, D. Parikh & D. Batra, "Grad-CAM: Visual explanations from deep networks via gradient-based localization," ICCV (2017).
- C. Olah, A. Mordvintsev & L. Schubert, "Feature visualization," Distill (2017), distill.pub/2017/feature-visualization.
- D. Bau, B. Zhou, A. Khosla, A. Oliva & A. Torralba, "Network dissection: Quantifying interpretability of deep visual representations," CVPR (2017).
- J. Adebayo, J. Gilmer, M. Muelly, I. Goodfellow, M. Hardt & B. Kim, "Sanity checks for saliency maps," NeurIPS (2018).