Simple Algorithm
Deep Learning · Emergence · 26 min

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 11×11×311\times11\times3 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 7×77\times7 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 ScS_c is most sensitive to (Simonyan, Vedaldi & Zisserman, 2014): compute w=∂Sc/∂I\mathbf w=\partial S_c/\partial I by one backward pass and display Mij=max⁡channels∣wij∣M_{ij}=\max_{\text{channels}}\abs{w_{ij}}. 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.

DerivationSame pass, three rules at the ReLU
  1. Rn=Rn+1⋆K^n,Rn(s)=Rn+1(p) 1[s=arg max⁡q∈Ω(p)Xn(q)]R_n=R_{n+1}\star\hat K_n,\qquad R_n(s)=R_{n+1}(p)\,\mathbf 1\Big[s=\argmax_{q\in\Omega(p)}X_n(q)\Big]

    Through a convolution Xn+1=Xn⋆KnX_{n+1}=X_n\star K_n, all three methods propagate a signal RR backward with the flipped kernel K^n\hat K_n, and through max pooling all three route it to the recorded argmax: the "switch" is just the subgradient of the max.

  2. Rn=Rn+1⊙1[Xn>0]⏟gradientRn=Rn+1⊙1[Rn+1>0]⏟deconvnetRn=Rn+1⊙1[Xn>0]⊙1[Rn+1>0]⏟guided backpropagation\underbrace{R_n=R_{n+1}\odot\mathbf 1[X_n>0]}_{\text{gradient}}\qquad\underbrace{R_n=R_{n+1}\odot\mathbf 1[R_{n+1}>0]}_{\text{deconvnet}}\qquad\underbrace{R_n=R_{n+1}\odot\mathbf 1[X_n>0]\odot\mathbf 1[R_{n+1}>0]}_{\text{guided backpropagation}}

    They differ only at a ReLU Xn+1=max⁡(Xn,0)X_{n+1}=\max(X_n,0). 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:

  3. guided map≈a weighted reconstruction of the input’s edges\text{guided map}\approx\text{a weighted reconstruction of the input's edges}

    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.

Check your understanding

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?

  1. The plain gradient
  2. Guided backpropagation
  3. The deconvnet
  4. 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, Rn=max⁡(Rn+1,0)R_n=\max(R_{n+1},0). 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 cc? Networks that end with global average pooling answer it almost for free (Zhou et al., 2016). Let the last convolutional layer output KK maps Ak∈Ru×vA^k\in\R^{u\times v} with Z=uvZ=uv positions, pooled to Fk=1Z∑i,jAijkF^k=\frac1Z\sum_{i,j}A^k_{ij}, and let the class score be yc=∑kwkcFky^c=\sum_kw^c_kF^k.

DerivationFrom CAM to Grad-CAM
  1. yc=∑kwkc 1Z∑i,jAijk=1Z∑i,j∑kwkcAijk⏟Mijcy^c=\sum_kw^c_k\,\frac1Z\sum_{i,j}A^k_{ij}=\frac1Z\sum_{i,j}\underbrace{\sum_kw^c_kA^k_{ij}}_{M^c_{ij}}

    Exchange the two sums. The score is the spatial average of a map, the class activation map McM^c, which says how much each position contributes:

  2. αkc=1Z∑i,j∂yc∂Aijk,LGrad-CAMc=ReLU⁡(∑kαkcAk)\alpha^c_k=\frac1Z\sum_{i,j}\frac{\partial y^c}{\partial A^k_{ij}},\qquad L^c_{\text{Grad-CAM}}=\operatorname{ReLU}\Big(\sum_k\alpha^c_kA^k\Big)

    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:

  3. αkc=wkcZ⟹LGrad-CAMc=1ZReLU⁡(Mc)\alpha^c_k=\frac{w^c_k}{Z}\quad\Longrightarrow\quad L^c_{\text{Grad-CAM}}=\frac1Z\operatorname{ReLU}\big(M^c\big)

    For the pooled linear head above, ycy^c is linear in AA with ∂yc/∂Aijk=wkc/Z\partial y^c/\partial A^k_{ij}=w^c_k/Z at every position. The average of a constant is the constant:

  4. yc(A)≈yc(A0)+∑k,i,j∂yc∂Aijk(Aijk−A0,ijk)y^c(A)\approx y^c(A_0)+\sum_{k,i,j}\frac{\partial y^c}{\partial A^k_{ij}}\big(A^k_{ij}-A^k_{0,ij}\big)

    So Grad-CAM is CAM, up to a positive constant and the ReLU, wherever CAM applies. Elsewhere αkc\alpha^c_k is the weight of a first-order linearization of everything downstream of AA, which is why it extends to captioning and question-answering heads. The ReLU keeps regions that raise ycy^c; without it the maps also light up evidence for other classes.

python
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, 14×1414\times14 for VGG at 224×224224\times224 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,

x⋆=arg max⁡x ak(x)−λ R(x),\mathbf x^\star=\argmax_{\mathbf x}\ a_k(\mathbf x)-\lambda\,\mathcal R(\mathbf x),

where aka_k is a feature's activation (a neuron, a whole channel, or a class logit) and R\mathcal R a regularizer. Simonyan et al. (2014) used R=∥x∥22\mathcal R=\norm{\mathbf x}_2^2 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.

IngredientWhat it doesCost
Frequency penalties (total variation, blurring)suppress the high-frequency noisealso suppress genuine sharp edges
Transformation robustness (random jitter, rotation, scaling at each step)keep only patterns that activate the unit robustlymore optimization steps
Learned priors (a generative model's latent space)the most natural-looking imageshard 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 energythe same steepest-ascent objective, under a metric that favors natural-image statisticsnone at run time
A diversity term between several imagesreveals different facets of one unit, such as several kinds of ballsseveral images per unit
After Olah, Mordvintsev & Schubert (2017). They also found that maximizing the pre-softmax logit gives cleaner images than maximizing a class probability. The usual explanation is that the easiest way to raise a probability is to make the alternatives unlikely; they note that the softmax may also simply be harder to optimize through.

DeepDream turns the objective around: start from a photograph and ascend 12∥aℓ(x)∥2\tfrac12\norm{\mathbf a_\ell(\mathbf x)}^2 for a whole layer ℓ\ell (Mordvintsev, Olah & Tyka, 2015). The gradient Jℓ(x)⊤aℓ(x)J_\ell(\mathbf x)^\top\mathbf a_\ell(\mathbf x) 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 kk:

  1. choose the threshold TkT_k exceeded by its top 0.5% of activations over the whole dataset, P(ak>Tk)=0.005P(a_k>T_k)=0.005;
  2. upsample the unit's activation map to image resolution and threshold it into a binary mask Mk(x)M_k(\mathbf x);
  3. score it against every concept's mask Lc(x)L_c(\mathbf x) with a dataset-wide intersection over union, and call the unit a detector for cc if IoUk,c>0.04\mathrm{IoU}_{k,c}>0.04.
IoUk,c=∑x∣Mk(x)∩Lc(x)∣∑x∣Mk(x)∪Lc(x)∣\mathrm{IoU}_{k,c}=\frac{\sum_{\mathbf x}\abs{M_k(\mathbf x)\cap L_c(\mathbf x)}}{\sum_{\mathbf x}\abs{M_k(\mathbf x)\cup L_c(\mathbf x)}}
Sums run over the images that carry labels of cc's category. The interpretability of a layer is reported as its number of unique concepts with a detector.
Predict before you look

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 IoUk,dog\mathrm{IoU}_{k,\text{dog}}?

Show the answer

0.14

The union is 12,000+20,000−4,000=28,00012{,}000+20{,}000-4{,}000=28{,}000 pixels, so IoU=4,000/28,000≈0.14\mathrm{IoU}=4{,}000/28{,}000\approx0.14, well above the 0.040.04 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 QQ 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 Mc=∑kwkcAkM^c=\sum_kw^c_kA^k, and Grad-CAM's weights αkc\alpha^c_k reduce to wkc/Zw^c_k/Z; 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.

Question 1

A CNN ends with global average pooling over ZZ positions and a linear layer with weights wkcw^c_k. What are Grad-CAM's channel weights αkc\alpha^c_k for class cc?

  1. wkcw^c_k divided by ZZ
  2. wkcw^c_k multiplied by ZZ
  3. The maximum gradient over positions
  4. They depend on the image, so they cannot be expressed through wkcw^c_k
Show the answer

A. wkcw^c_k divided by ZZ

The score is linear in the maps with ∂yc/∂Aijk=wkc/Z\partial y^c/\partial A^k_{ij}=w^c_k/Z at every position, and averaging a constant returns it. So Grad-CAM equals CAM up to the factor 1/Z1/Z and the final ReLU.

Question 2

Why can guided backpropagation produce crisp, object-shaped maps even for a network whose top layers have been re-randomized?

  1. Because re-randomizing weights does not change a network's predictions
  2. Because it discards all negative signals going backward, so the map is dominated by the input's local structure, a partial image reconstruction
  3. Because it uses the max-pooling switches, which store the trained network's knowledge
  4. 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.

Question 3

You maximize a class's softmax probability by gradient ascent on the input, with no regularizer. What do you most likely get?

  1. A clear, natural-looking image of the class
  2. A blank gray image, since nothing is regularized
  3. High-frequency noise that scores highly, often reached partly by suppressing the other classes
  4. 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.

Question 4

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?

  1. Rotations damage the information stored in the layer
  2. Interpretability of single units is an axis-aligned property, not a consequence of discriminative power
  3. The original units were random, and the rotation revealed it
  4. 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).