Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 5: Computer Vision and CNNs

What do CNNs learn?

P5.840 min●●○ IntermediateReviewed Dec 3, 2026

Why this matters for machine learning

A trained network is a pile of numbers, and you cannot read it, but you can look at what its kernels and feature maps respond to and at which pixels its answer depends on. That is how you spot a model that has learned the wrong thing.

  • The first layers of a trained CNN hold general kernels, which is why they can be reused (frozen) when a pretrained network is fine-tuned on a new task. (P5.10: Transfer learning and fine-tuning)
  • The gradient of a score with respect to the input pixels, the tool behind saliency maps, is also the tool that builds adversarial examples. (P5.17: Adversarial examples and robustness)
  • Heat maps are a first check that a classifier looks at the object and not at the background, and they belong to the wider toolbox of explaining model decisions. (P12.6: Explainability, coming soon)

Before this: Kernels as feature detectors, Multi-channel convolutions and 1×1 convs, Pooling and receptive fields, Build a CNN, Backpropagation: step by step with numbers

After this lesson you can

  • Draw the kernels of a first convolutional layer as pictures, say what they tend to look like in networks trained on natural images, and read the weight sum as in P5.3
  • Describe how feature maps change with depth (fewer pixels, more channels, bigger receptive fields, more class-specific) and read a feature-map grid
  • Compute a saliency map (the absolute gradient of a class score with respect to the pixels) and a Grad-CAM heat map (by hand on a small example), and an occlusion map, and say what each one needs and costs
  • Name the limits of these explanations, run a randomised-weights sanity check, and say why a heat map is evidence about the model and not a reason in human terms

A small network looks at a 16×1616\times16 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 16×1616\times16 grey pixels (values 0 to 1, shape (1,16,16)(1,16,16) for one picture in PyTorch order, P5.1). It holds one 7×77\times7 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 2×22\times2 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 5×55\times5, padding 2, stride 1: 8 maps of 16×1616\times16.
  • Layer 2: 16 kernels of 3×3×83\times3\times8, stride 2: 16 maps of 8×88\times8.
  • Layer 3: 32 kernels of 3×3×163\times3\times16, stride 2: 32 maps of 4×44\times4.
  • 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 11×11×311\times11\times3 in the first layer of AlexNet, trained on 224×224224\times224 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 +2.81+2.81 and +3.49+3.49). 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 −1.12-1.12 and −0.45-0.45, 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.

Picture (16 by 16, made by code)

True class: plus. The trained network says plus (99.9%).

Layer 1: 8 maps, each 16×16 pixels. One pixel of a map sees a 5×5 patch of the picture (P5.6).

Input
Layer 1, map 1

Largest value in this map: 1.95. White is the largest value in layer 1 (1.95), black is 0 (after ReLU).

The kernel that made this map: 5×5 weights (blue positive, pink negative) Sum of the 25 weights: 2.81. Bias: −0.37.
A small CNN trained by code on made-up 16 by 16 pictures, with eight test pictures (✗ marks a mistake). Feature maps: pick a layer, tap a tile to enlarge it; layer 1 also shows the kernel and its weight sum. Heat maps: saliency, Grad-CAM or occlusion for any class, for the trained or a random-weights network, with the share of heat on the shape and on the blob. All numbers were computed by the training script.

Things to try:

  1. Switch from layer 1 to layer 2, then layer 3. The tiles get blockier: the maps have 16×1616\times16, then 8×88\times8, then 4×44\times4 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 5×55\times5, 7×77\times7 or 11×1111\times11 patch of the picture (the rule is in P5.6: each layer adds (k−1)(k-1) times the step between neighbouring pixels in its input, and stride 2 doubles that step).
  2. 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.
  3. 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 2.852.85 over the crosses of the test set, at most 0.760.76 over the other classes). Map 6 is bright on the squares (6.486.48, against at most 0.240.24). 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 sc(x)s_c(\mathbf{x}) be the score of class cc that the network gives to the picture x\mathbf{x}, taken before the softmax. If we change pixel xijx_{ij} a little, the score changes by about ∂sc∂xij\frac{\partial s_c}{\partial x_{ij}} 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:

Mij=∣∂sc∂xij∣.M_{ij}=\left|\frac{\partial s_c}{\partial x_{ij}}\right|.

For a colour picture they take, at each pixel, the largest absolute gradient over the colour channels. Our pictures have one channel. A large MijM_{ij} 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 cc.

A small example makes the numbers concrete. Take a 4×44\times4 picture whose left two columns are 0 and right two columns are 4, one convolution with the Sobel xx 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

(−1−111−3−333−3−333−1−111).\begin{pmatrix}-1&-1&1&1\\-3&-3&3&3\\-3&-3&3&3\\-1&-1&1&1\end{pmatrix}.

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 7×77\times7 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 cc, which of these maps matter, and where are they active?

Write AkA^k for the kk-th map of the last convolutional layer (after ReLU), with entries AijkA^k_{ij}, and let ZZ be the number of pixels in one map (16 here). The method has three steps.

  1. 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):
αk=1Z∑i,j∂sc∂Aijk.\alpha_k=\frac1Z\sum_{i,j}\frac{\partial s_c}{\partial A^k_{ij}}.

A positive αk\alpha_k says: more of map kk raises the score of class cc. A negative one says it lowers it.

  1. Weighted sum, then ReLU.
L=ReLU(∑kαkAk).L=\mathrm{ReLU}\Big(\sum_k\alpha_kA^k\Big).

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.

  1. Upsample the result (here 4×44\times4) 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 2×22\times2, so Z=4Z=4, and suppose the class score is s=w1Aˉ1+w2Aˉ2+w3Aˉ3s=w_1\bar A^1+w_2\bar A^2+w_3\bar A^3 with Aˉk\bar A^k the mean of map kk (a network that averages the maps and then applies a linear layer, as ours does) and w=(1,−2,0)\mathbf{w}=(1,-2,0). The gradient with respect to every pixel of map kk is then wk/4w_k/4, so

α1=14=0.25,α2=−24=−0.5,α3=0.\begin{aligned} \alpha_1&=\tfrac14=0.25,\\ \alpha_2&=-\tfrac24=-0.5,\\ \alpha_3&=0. \end{aligned}

With maps

A1=(2010),A2=(0103),A3=(1111)\begin{aligned} A^1&=\begin{pmatrix}2&0\\1&0\end{pmatrix},\\ A^2&=\begin{pmatrix}0&1\\0&3\end{pmatrix},\\ A^3&=\begin{pmatrix}1&1\\1&1\end{pmatrix} \end{aligned}

the weighted sum is 0.25A1−0.5A20.25A^1-0.5A^2, and

0.25A1−0.5A2=(0.5−0.50.25−1.5),ReLU→(0.500.250).\begin{aligned} 0.25A^1-0.5A^2&=\begin{pmatrix}0.5&-0.5\\0.25&-1.5\end{pmatrix},\\ \mathrm{ReLU}\to&\begin{pmatrix}0.5&0\\0.25&0\end{pmatrix}. \end{aligned}

Map 3 has α3=0\alpha_3=0: 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 4×44\times4 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 α\alpha. 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 4×44\times4 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 sc=∑kwc,k Aˉks_c=\sum_k w_{c,k}\,\bar A^k with Aˉk=1Z∑i,jAijk\bar A^k=\frac1Z\sum_{i,j}A^k_{ij}. The derivative of scs_c with respect to every pixel of map kk is wc,k/Zw_{c,k}/Z, so αk=wc,k/Z\alpha_k=w_{c,k}/Z: the Grad-CAM weights are the linear layer’s weights divided by ZZ. 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 16 αk=wc,k16\,\alpha_k=w_{c,k} for all 32 maps, to 6×10−86\times10^{-8} (float rounding). The positions where ∑kwc,kAk\sum_kw_{c,k}A^k 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 3×33\times3 and the neutral value is 0, the background level. It visits 14×14=19614\times14=196 positions on a 16×1616\times16 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 7×77\times7 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 2×22\times2 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 4×44\times4 map stretched to 16×1616\times16.

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 x\mathbf{x} in the direction of the gradient of the target, x←x+η ∂s/∂x\mathbf{x}\leftarrow\mathbf{x}+\eta\,\partial s/\partial\mathbf{x}, many times (the same step as gradient descent with the sign flipped). Simonyan et al. (2014) did this for class scores, with a penalty λ∥x∥22\lambda\lVert\mathbf{x}\rVert_2^2 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 0.02∥x∥20.02\lVert\mathbf{x}\rVert^2 and pixels kept between 0 and 1.

  • plus: 17.2
  • cross: −4.8
  • ring: −5.2
  • square: −11

The network’s highest score is for plus. On the 1,000 real test pictures the highest score averages 19.3 and the largest is 48.2. This score is within that range, but the picture still looks nothing like a real shape.

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 sc(x)s_c(\mathbf{x}) are taken before the softmax. First-order change: sc(x+δ)≈sc(x)+g⋅δs_c(\mathbf{x}+\boldsymbol\delta)\approx s_c(\mathbf{x})+\mathbf{g}\cdot\boldsymbol\delta, with g=∇xsc\mathbf{g}=\nabla_{\mathbf{x}}s_c. Saliency: Mij=∣gij∣M_{ij}=|g_{ij}| (largest over colour channels).

Grad-CAM, with Ak∈Rh×wA^k\in\mathbb{R}^{h\times w} the maps of the last convolutional layer and Z=hwZ=hw:

αkc=1Z∑i,j∂sc∂Aijk,Lc=ReLU(∑kαkcAk).\begin{aligned} \alpha_k^c&=\frac1Z\sum_{i,j}\frac{\partial s_c}{\partial A^k_{ij}},\\ L^c&=\mathrm{ReLU}\Big(\sum_k\alpha^c_kA^k\Big). \end{aligned}

For a head sc=∑kwc,kAˉks_c=\sum_kw_{c,k}\bar A^k with Aˉk=1Z∑i,jAijk\bar A^k=\frac1Z\sum_{i,j}A^k_{ij}: αkc=wc,k/Z\alpha_k^c=w_{c,k}/Z.

Occlusion at position (r,c)(r,c) with a q×qq\times q square:

Dr,c=pc(x)−pc(xoccluded),D_{r,c}=p_c(\mathbf{x})-p_c(\mathbf{x}_{\text{occluded}}),

where pcp_c is the softmax probability and the occluded picture has the square set to a neutral value. There are (H−q+1)(W−q+1)(H-q+1)(W-q+1) 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 (N,C,H,W)(N,C,H,W): 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-10

retain_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 4×44\times4.

Grad-CAM on three 2 by 2 maps

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Running the cell prints α=(0.25,−0.5,0)\alpha=(0.25,-0.5,0), the weighted sum (0.5−0.50.25−1.5)\begin{pmatrix}0.5&-0.5\\0.25&-1.5\end{pmatrix}, the map (0.500.250)\begin{pmatrix}0.5&0\\0.25&0\end{pmatrix} after ReLU, and a 4×44\times4 map whose first row is 0.5, 0.375, 0.125, 00.5,\ 0.375,\ 0.125,\ 0 and last row 0.25, 0.188, 0.062, 00.25,\ 0.188,\ 0.062,\ 0. 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 4×44\times4 picture, the Sobel xx kernel, ReLU and a sum. It computes the gradient by backpropagation, checks it against finite differences, and runs a 2×22\times2 occlusion.

Gradient, finite differences and 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 (016320244801632)\begin{pmatrix}0&16&32\\0&24&48\\0&16&32\end{pmatrix}. 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

  1. In Grad-CAM, what is the weight αk\alpha_k of the kk-th feature map for class cc?

  2. A saliency map Mij=∣∂sc/∂xij∣M_{ij}=|\partial s_c/\partial x_{ij}| is large at a pixel. What does that say?

  3. 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?

  4. The same network with random weights gives a Grad-CAM map that looks reasonable on a picture. What should you conclude?

Exercises

  1. Grad-CAM by hand. Two maps A1=(1002)A^1=\begin{pmatrix}1&0\\0&2\end{pmatrix} and A2=(0310)A^2=\begin{pmatrix}0&3\\1&0\end{pmatrix} have weights α1=0.5\alpha_1=0.5 and α2=−0.25\alpha_2=-0.25. Compute the Grad-CAM map before upsampling.
    Show answer0.5A1−0.25A2=(0.5−0.75−0.251)0.5A^1-0.25A^2=\begin{pmatrix}0.5&-0.75\\-0.25&1\end{pmatrix}. After ReLU: (0.5001)\begin{pmatrix}0.5&0\\0&1\end{pmatrix}. The negative entries are positions where map 2 argues against the class.
  2. Layer 2 of the network has 16 kernels of 3×3×83\times3\times8 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 answer16⋅(3⋅3⋅8+1)=16⋅73=116816\cdot(3\cdot3\cdot8+1)=16\cdot73=1168. A layer 2 kernel multiplies 8 feature maps, not a picture, so it has 8×3×38\times3\times3 weights, and its meaning depends on what the 8 maps of layer 1 stand for. It is not a pattern of pixels.
  3. Occlusion cost. How many forward passes does a 3×33\times3 occluder at stride 1 need on a 16×1616\times16 picture? How many does a 16×1616\times16 occluder at stride 8 need on a 224×224224\times224 picture?
    Show answer14×14=19614\times14=196 and (224−168+1)2=272=729\left(\frac{224-16}{8}+1\right)^2=27^2=729. One saliency map needs one forward and one backward pass.
  4. A fourth layer (3×33\times3 kernel, stride 1) is added after layer 3. What patch of the picture does one pixel of its maps see?
    Show answerThe jump after layer 3 is 4, so the receptive field grows by (3−1)⋅4=8(3-1)\cdot4=8, from 11 to 1919.
  5. 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 answerThe 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.

Key takeaways

  • First-layer kernels see pixels, so they can be drawn as pictures. On photographs they often look like oriented edge detectors and colour blobs (Krizhevsky et al. 2012). The kernels of this lesson's small network are rougher: two act like blurs (weight sums +2.8+2.8 and +3.5+3.5), the rest are small and mixed.
  • Deeper layers have more channels but fewer pixels per map (16×1616\times16, 8×88\times8, 4×44\times4 here), each pixel sees a larger patch of the picture (5×55\times5, 7×77\times7, 11×1111\times11), and the patterns get more class-specific.
  • A saliency map is ∣∂sc/∂xij∣|\partial s_c/\partial x_{ij}|, the size of the gradient of the class score (before the softmax) with respect to each pixel (Simonyan et al. 2014). It costs one backward pass and is speckled.
  • Grad-CAM (Selvaraju et al. 2017) weights each map AkA^k of the last conv layer by αk=1Z∑i,j∂sc/∂Aijk\alpha_k=\frac1Z\sum_{i,j}\partial s_c/\partial A^k_{ij}, adds them up, applies ReLU and upsamples. It is coarse but class-specific.
  • Occlusion blanks a patch at every position and records the drop in the class probability. It needs no gradients and works for any model, at one forward pass per position.
  • Heat maps are evidence about the model, not human reasons. Methods disagree, a random network can still give maps that look sensible, and a randomisation test (Adebayo et al. 2018) checks a method before you trust it.
Found a mistake? Tell us