Lesson 5 of 7 · 2 min
Where does it look
Grad-CAM shows the areas that pushed the decision. If it lights up the skull edge or printed text, the model has learned a shortcut.
# run locally: cam.py
import torch, torch.nn.functional as F
def gradcam(net, x, target):
feats, grads = [], []
layer = net.features[-1]
a = layer.register_forward_hook(lambda m, i, o: feats.append(o))
b = layer.register_full_backward_hook(lambda m, i, o: grads.append(o[0]))
net.zero_grad()
net(x)[0, target].backward()
a.remove(); b.remove()
weight = grads[0].mean((2, 3), keepdim=True)
cam = F.relu((weight * feats[0]).sum(1, keepdim=True))
cam = F.interpolate(cam, x.shape[-2:], mode="bilinear")[0, 0]
return (cam / (cam.max() + 1e-8)).detach().cpu()