A small network looks at a picture and answers “ring”. It is right on 998 of 1,000 test pictures it has never seen. But the network is a list of 6,148 numbers, and no one can read “ring” in them. Did it look at the ring, or at something else?
We cannot read a network’s reasons, but we can look at three things: the kernels it learned, the feature maps it computes, and the pixels its answer depends on (heat maps). This lesson does all three on one small network that we trained by code, so you can explore every number.
The network we look inside
Real CNNs for photographs are too large to explore on a phone, and photographs bring licensing questions. So we made a tiny world by code. Each picture is grey pixels (values 0 to 1, shape for one picture in PyTorch order, P5.1). It holds one shape at a random place: a plus, a cross (two diagonals), a ring (a square outline) or a filled square. It also holds a dim distractor blob that never touches the shape, and random noise. The label is the shape. The blob says nothing about the label, so a network that has learned the task should ignore it, and that gives us a check on every explanation below.
The network has three convolutional layers (P5.5, P5.6), each followed by ReLU, then an average over each final map and one linear layer (P4.5) that gives four class scores:
- Layer 1: 8 kernels of , padding 2, stride 1: 8 maps of .
- Layer 2: 16 kernels of , stride 2: 16 maps of .
- Layer 3: 32 kernels of , stride 2: 32 maps of .
- Average each map to one number, then a linear layer to 4 scores.
Stride 2 halves the size (P5.4). The four layers have 208, 1,168, 4,640 and 132 learned numbers, which is 6,148 in all. We trained it on 4,000 made-up pictures with Adam (P4.13) for 15 epochs, in the script scripts/p5-8-what-cnns-learn.py that also exports everything the widgets below show. On the 1,000 test pictures it is right 998 times; both mistakes are crosses read as pluses. Everything below describes this network. A network trained on photographs would show richer patterns, and where we say so, we quote the papers that looked at those.
Layer 1: the kernels, drawn as pictures
A first-layer kernel looks at the picture itself, so its weights sit in the same grid as the pixels they multiply. That means a kernel can be drawn as a small picture, with one square per weight: blue for a positive weight, pink for a negative one (the same colours as P5.3). By the dot-product reading of P5.3, a kernel gives its largest output where the patch under it looks like the picture of the kernel, so the drawing of a kernel is the pattern it looks for.
What do learned kernels look like? Krizhevsky, Sutskever and Hinton (2012) drew the 96 kernels of size in the first layer of AlexNet, trained on photographs, and describe “a variety of frequency- and orientation-selective kernels, as well as various colored blobs”. That is the picture P5.3 promised: many learned kernels resemble the oriented edge detectors that were once designed by hand. Kernels in deeper layers cannot be drawn this way, since they see feature maps, not pixels.
Our network is much smaller and its pictures have no photographic texture, so its kernels are rougher. Open the widget below, choose Layer 1 and tap each of the 8 tiles. Below the enlarged map you see the kernel that made it and the sum of its 25 weights. You will see:
- Maps 1 and 3 have mostly positive weights (sums and ). By the rule of P5.3 they respond to bright patches, like a blur, and not to edges.
- The other six kernels have sums between and , and mixed signs. Kernel 7 has a thin positive column between negative neighbours, which is a detector for a vertical line. Kernels 4 and 5 alternate in sign across the grid, which does not look like a simple edge. Several are small and hard to read.
So the honest summary is not “every kernel is an edge detector”. It is: the kernels are templates for the patterns this task needs, learned from random starting values, and they are noisier than hand-made ones. P5.3’s warning stands: learned kernels have no reason to sum to 0 or 1.
Feature maps and depth
A feature map is the output of one kernel on one picture (P5.2), after ReLU. A layer has one map per kernel. Pick Feature maps in the widget, choose a picture and a layer, and tap a tile to enlarge it.
Things to try:
- Switch from layer 1 to layer 2, then layer 3. The tiles get blockier: the maps have , then , then pixels, and each pixel now stands for a bigger part of the picture. One pixel of a layer 1, 2 or 3 map sees a , or patch of the picture (the rule is in P5.6: each layer adds times the step between neighbouring pixels in its input, and stride 2 doubles that step).
- In layer 3, many tiles are completely black. In this network 10 of the 32 layer-3 maps are 0 on all 1,000 test pictures, and about 63% of all layer-3 values are 0, because ReLU (P4.4) cuts negative values to 0. A black map means that the kernel’s pattern is absent from this picture. A map that is black on every test picture is a unit that never fires (a “dead” unit) and plays no part in the answer.
- Compare the same layer-3 map across the four classes (use a plus, a cross, a ring and a square). Map 7 is bright on the crosses (mean value over the crosses of the test set, at most over the other classes). Map 6 is bright on the squares (, against at most ). In layer 1 no map is that selective: a map of layer 1 answers “is there a stroke of this kind here?”, and a map of layer 3 answers closer to “is this the class?”.
That last step is the general pattern. Layers near the input respond to small, simple patterns at fine detail. Layers near the output respond to larger and more class-specific patterns at coarse detail. Zeiler and Fergus (2014) show this for a network trained on ImageNet photographs, by projecting strong activations back to pixels: they describe layer 2 as responding to “corners and other edge/color conjunctions”, layer 3 as capturing textures such as mesh patterns and text, layer 4 as more class-specific (dog faces, bird’s legs) and layer 5 as showing “entire objects with significant pose variation”. Our shapes are far simpler, so we see the same direction (simple to class-specific) but not faces or objects. That a network learns a hierarchy like this is also the reason the early layers of a trained network can be reused for a new task (P5.10).
Which pixels matter? Saliency
Now ask a different question: not what the layers compute, but which pixels the final answer depends on. Let be the score of class that the network gives to the picture , taken before the softmax. If we change pixel a little, the score changes by about times the change. This partial derivative is the number backpropagation computes anyway (P4.8), here taken with respect to the input instead of a weight. All the gradient numbers in this lesson are drawn in orange, as in the training lessons. The saliency map of Simonyan, Vedaldi and Zisserman (2014) is the size of that gradient at every pixel:
For a colour picture they take, at each pixel, the largest absolute gradient over the colour channels. Our pictures have one channel. A large means: this score moves fast when this pixel moves. It costs one forward and one backward pass. Simonyan et al. use the unnormalised class score and not the softmax probability. One reason is that a probability can rise because the other scores fall, which would hide what supports class .
A small example makes the numbers concrete. Take a picture whose left two columns are 0 and right two columns are 4, one convolution with the Sobel kernel (P5.3), a ReLU and a sum as the “score”. The score is 64, and the gradient of the score with respect to each pixel (computed by hand backpropagation and checked against finite differences in the Python section) is
Each pixel’s gradient adds up the kernel weights of the outputs that pixel feeds (P5.2). The middle rows matter more, since the corner pixels feed fewer outputs. And the gradient is negative on the dark side: making a dark pixel there brighter would lower this score, because it reduces the contrast. Saliency takes the absolute value, so a pixel that helps and a pixel that hurts look the same. That is a first limit to remember.
On the network, open Heat maps, choose Saliency and the trained network. You will see a bright cloud around the shape, but speckled with isolated pixels: the gradient of a ReLU network probably jumps from pixel to pixel because each pixel’s influence goes through many switches (the ReLUs), and the map shows the local slope. Averaged over the 1,000 test pictures, 43% of the saliency falls inside the box around the shape, which covers 19% of the picture, and 1.9% falls on the blob, which covers 1.6%. For comparison, the raw pixel brightness of the picture puts 44% inside the box and 5% on the blob (the blob is dim but not dark). So the 43% is no better than brightness alone, and saliency is better than brightness only in putting less weight on the blob.
Grad-CAM: a heat map from the last conv layer
Saliency starts at the pixels, so it is detailed but noisy. Grad-CAM (Selvaraju et al. 2017) starts from the feature maps of the last convolutional layer instead. Those maps are coarse but already specific to the class, and they still have positions. Grad-CAM asks: for class , which of these maps matter, and where are they active?
Write for the -th map of the last convolutional layer (after ReLU), with entries , and let be the number of pixels in one map (16 here). The method has three steps.
- Weights. For each map, take the gradient of the class score with respect to that map, and average it over all pixels of the map (a global average):
A positive says: more of map raises the score of class . A negative one says it lowers it.
- Weighted sum, then ReLU.
The ReLU keeps only the positions that push the score up, the evidence for the class. The paper applies it because only features with a positive influence on the class are of interest.
- Upsample the result (here ) to the size of the picture, for example by bilinear interpolation, so that it can be laid over the picture.
Worked example. Take three maps of size , so , and suppose the class score is with the mean of map (a network that averages the maps and then applies a linear layer, as ours does) and . The gradient with respect to every pixel of map is then , so
With maps
the weighted sum is , and
Map 3 has : it does not change the score and is ignored. Map 2 has a negative weight: where it is bright, the class is less likely, so the two right-hand pixels are removed by the ReLU. The surviving evidence is on the left. Upsampled to with bilinear interpolation, the heat falls smoothly from 0.5 at the top left to 0 at the right edge (the code below prints the numbers). The Python section checks every number against PyTorch’s autograd.
In the widget, choose Grad-CAM: the three layer-3 maps with the largest weights for the chosen class are shown with their . On the test set 43% of the Grad-CAM heat falls inside the shape’s box and 0.9% on the blob (which covers 1.6%). The two 43% figures are not a typo: saliency gives 0.4332 and Grad-CAM 0.4327 by coincidence. It is blurrier than saliency, because it is built from maps, but steadier. Use the class buttons to explain a wrong class and see where its evidence comes from.
Go deeper For this network, Grad-CAM is CAM
Our network averages the last maps and then applies a linear layer, so with . The derivative of with respect to every pixel of map is , so : the Grad-CAM weights are the linear layer’s weights divided by . The earlier method CAM (class activation mapping, Zhou et al. 2016) used exactly those weights; Selvaraju et al. show that Grad-CAM reduces to it for this architecture, and extends it to networks that do not end that way. Running the script confirms for all 32 maps, to (float rounding). The positions where is large are where the class evidence sits.
Occlusion: no gradients at all
Gradient methods look inside the network. Occlusion sensitivity treats it as a black box, as Zeiler and Fergus (2014) did with a grey square. Slide a small square over the picture, set the pixels under it to a neutral value, run the network, and record how much the probability of the class drops. Positions where the drop is large are positions the answer needs.
In our network the square is and the neutral value is 0, the background level. It visits positions on a picture (stride 1), so the cost is 196 forward passes, against one backward pass for saliency. Choose Occlusion in the widget (blue, because it is built from forward values and has no gradients). Blanking the whole shape box drops the probability of the predicted class from 0.997 (average) to 0.264 and changes the predicted class on 73% of the test pictures. Blanking the blob leaves the probability at 0.997 and changes the class on 0.2% (2 of 1,000). That is a direct, model-agnostic confirmation that the network uses the shape and not the blob, which a gradient map could only suggest.
Occlusion has its limits: the result depends on the square size and the neutral value, a blanked patch is a picture the network never saw in training, and covering one cue changes nothing if a second cue is left.
How far to trust a heat map
A heat map is easy to believe: it looks like an explanation. Three cautions.
1. A heat map can be produced by a network that learned nothing. The widget has a Random weights button: the same layers with random numbers instead of trained ones (it guesses one class, “square”, for every picture, 25.7% accuracy). Averaged over the test pictures, its Grad-CAM still puts 31% of its heat inside the shape’s box (against 19% for an even spread; for 176 of the 1,000 pictures the random network’s Grad-CAM is all zero, and those count as 0), probably because maps made by random kernels still light up where the picture is bright. Its saliency puts 23% inside the box. A heat map that looks sensible is therefore not proof that it reflects what was learned. Adebayo et al. (2018) turned this into a test: compare a method’s maps for the trained network with its maps for the network whose weights have been randomised (“the model parameter randomisation test”). If the maps hardly change, the method cannot be used to explain what the model learned. They report that plain gradients and Grad-CAM pass the test, while Guided Backpropagation and Guided Grad-CAM, two popular variations, are “invariant to higher layer parameters” and fail (Grad-CAM changed when the layers after the last convolution were randomised). Their test randomises ImageNet networks layer by layer from the top; ours randomises every layer of a toy network. On our network, the saliency maps of the trained and the random network have an average rank correlation of only 0.15, and the Grad-CAM maps about 0.37 (on the 824 pictures where it is defined; for the other 176 the random network’s map is all zero). The methods in this lesson do respond to the weights, as they should, but they respond to the picture too.
2. Different methods give different maps, because they measure different things: local slope, class evidence in coarse maps, and the effect of removing a patch. Agreement raises confidence; disagreement means: look closer. Resolution is limited too: Grad-CAM here is a map stretched to .
3. A heat map shows what the score depends on, not why. It is evidence about the model’s computation, not a reason that a person would give, and not a statement about the object. If a heat map lands on a corner of the picture instead of the object, the model may be using something that happens to go with the label (a shortcut). The map reveals the shortcut but does not tell you whether it is harmless. The wider tools for explaining model decisions are in P12.6.
Go deeper Making the network dream: activation maximisation
Instead of asking where in a given picture a unit responds, ask which picture makes it respond most. Start from a nearly empty picture and run gradient ascent on the pixels: change in the direction of the gradient of the target, , many times (the same step as gradient descent with the sign flipped). Simonyan et al. (2014) did this for class scores, with a penalty that keeps the picture small, starting from a zero picture. For a first-layer unit the answer is simple: among pictures of a given length, the dot product with a kernel is largest for the kernel itself (P1.B3, Cauchy–Schwarz). That is why drawing the kernel shows what it looks for.
For a class the result is less friendly. Here we maximised the score of a class minus the best other score, with a penalty of and pixels kept between 0 and 1.
The results are not pictures of shapes: the “cross” image is a checkerboard-like pattern repeated over the whole picture, the “ring” image is stripes, the “square” image is nearly all white, and the “plus” image is a few scattered bright pixels. One possible reason (not tested here) is that the network averages each last map over all positions, so repeating a pattern everywhere raises the average. The cross, ring and square pictures reach scores of 90.8, 253.1 and 482.6, while the highest score on any of the 1,000 test pictures is 48.2; the plus picture only reaches 17.2, so the optimiser found little for that class. Caveats: the result depends on the penalty, the starting picture and the constraints; it shows what raises the score, not what a typical member of the class looks like; and many pictures have a high score, of which gradient ascent finds one.
Depth: three ways to see it
Intuition
A trained CNN is a chain of pattern finders. Layer 1 asks small questions about patches (is there a stroke here?), and each later layer asks questions about the answers of the layer before, so each of its pixels covers a bigger patch of the picture and its question is more specific. The last layer’s maps are almost the answer, kept in a grid, and a final average and a linear layer turn them into scores.
The three heat maps are three ways of asking the same network “where?”. Saliency wiggles every pixel a little and asks how the score moves. Grad-CAM asks which late maps raise the score. Occlusion hides parts of the picture and asks if the answer changes. None reads the network’s mind: they report how the score responds.
Math
Scores are taken before the softmax. First-order change: , with . Saliency: (largest over colour channels).
Grad-CAM, with the maps of the last convolutional layer and :
For a head with : .
Occlusion at position with a square:
where is the softmax probability and the occluded picture has the square set to a neutral value. There are positions at stride 1.
Code
The two functions below are the ones in the script (PyTorch 2.9.1). The network net returns the class scores, and with maps=True it also returns the feature maps of the three layers. Shapes are : a picture is (1, 1, 16, 16) and the last maps are (1, 32, 4, 4). The output is a static copy from a local run on one test picture.
def saliency(net, x, c):
x = x.clone().requires_grad_(True)
net(x)[0, c].backward() # score of class c
return x.grad[0, 0].abs() # (16, 16)
def gradcam(net, x, c):
out, a1, a2, a3 = net(x, maps=True)
a3.retain_grad()
net.fc(a3.mean(dim=(2, 3)))[0, c].backward()
alpha = a3.grad.mean(dim=(2, 3)) # (1, 32)
cam = F.relu((alpha[:, :, None, None] * a3).sum(1))
up = F.interpolate(cam[:, None], size=16,
mode="bilinear",
align_corners=False)
return alpha, cam, up[0, 0]true: cross predicted: cross
saliency (16, 16) grad-cam (16, 16)
alpha (1, 32) cam (1, 4, 4)
alpha * 16 == fc weights: True
Grad-CAM peak at row 14 column 9
shape box rows 8-14, columns 4-10retain_grad() keeps the gradient of a non-leaf tensor (P2.6), here the last maps. The Grad-CAM peak lies inside the shape’s box. The Colab notebook trains the network and draws every figure of this lesson.
Try it in Python
The first cell is the Grad-CAM hand example: it computes the weights from gradient maps, the weighted sum, the ReLU and the upsampling to .
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Running the cell prints , the weighted sum , the map after ReLU, and a map whose first row is and last row . These agree with PyTorch’s autograd and F.interpolate.
The second cell compares the three ways of asking “which pixels matter?” on the toy of the saliency section: a picture, the Sobel kernel, ReLU and a sum. It computes the gradient by backpropagation, checks it against finite differences, and runs a occlusion.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Running the cell prints the score 64, the gradient matrix shown earlier, True for the finite-difference check, the saliency map, and the occlusion drops . The two maps disagree on the left: the gradient there is negative but not zero (brightening those pixels would lower the score), while occlusion sets them to 0, which they already are, and changes nothing.
Challenge. Change the picture to a flat grey (all values 3). What are the score and the gradient in the code? (Every output is exactly 0, so the code treats the ReLU as switched off: the score and the gradient are both 0. A flat picture has no edge to detect.)
Colab notebook
The Colab notebook P5.8-what-do-cnns-learn.ipynb (source on GitHub) generates the pictures, trains the network on a CPU in about a minute, draws the kernels and feature maps with Matplotlib (P2.4), computes the three heat maps and repeats the randomised-weights check. The numbers in this lesson come from the script scripts/p5-8-what-cnns-learn.py (PyTorch 2.9.1, CPU, 4 threads). Another machine or version trains a slightly different network, so expect numbers of the same size, not the same digits.
Common mistakes
Quiz
Check your understanding
In Grad-CAM, what is the weight of the -th feature map for class ?
Grad-CAM averages the gradient of the (pre-softmax) class score over the pixels of each map. A large positive value says that more of this map raises the score. The largest value in the map is a forward quantity, not a gradient; the kernel sum is what P5.3 used to tell blurs from edge kernels; and removing maps and measuring a training loss is a different (ablation) experiment.
A saliency map is large at a pixel. What does that say?
A gradient is a local slope, and the absolute value drops its sign, so the map shows sensitivity, not helpful versus harmful. It is not a statement about the object, nor about removing the pixel (a large change, which occlusion tests and the slope does not predict), and a large gradient does not require a bright pixel.
You need a heat map for a model you can only call, for example one behind a prediction service that returns probabilities. Which method still works?
Occlusion changes the input and reads the output probability, so it treats the model as a black box. Saliency and Grad-CAM need gradients with respect to the pixels or to an inside layer, which a returned class name or probability does not give. The claim that none works is wrong because occlusion does.
The same network with random weights gives a Grad-CAM map that looks reasonable on a picture. What should you conclude?
Random kernels can still respond to the bright parts of a picture, so a map can look sensible without reflecting learning. That is why Adebayo et al. compare the maps of trained and randomised networks. The method is not necessarily broken (it follows the picture), the random network is not claimed to be right, and heat is not always on the object.
Exercises
- Grad-CAM by hand. Two maps and have weights and . Compute the Grad-CAM map before upsampling.
Show answer
. After ReLU: . The negative entries are positions where map 2 argues against the class. - Layer 2 of the network has 16 kernels of with a bias each. How many learned numbers is that, and why can its kernels not be drawn as one picture each the way layer 1’s can?
Show answer
. A layer 2 kernel multiplies 8 feature maps, not a picture, so it has weights, and its meaning depends on what the 8 maps of layer 1 stand for. It is not a pattern of pixels. - Occlusion cost. How many forward passes does a occluder at stride 1 need on a picture? How many does a occluder at stride 8 need on a picture?
Show answer
and . One saliency map needs one forward and one backward pass. - A fourth layer ( kernel, stride 1) is added after layer 3. What patch of the picture does one pixel of its maps see?
Show answer
The jump after layer 3 is 4, so the receptive field grows by , from 11 to . - A Grad-CAM map for “cat” on a photo glows on the bottom-right corner, where a caption is printed, and not on the cat. What can you conclude, and what would you check?
Show answer
The cat score reacts to something in that corner, so the model may be using the caption (a shortcut) instead of or besides the animal. It does not prove the cause. Check with occlusion (cover the corner, see if the probability drops), try pictures without the caption, and look for the same pattern in the training data.