Activations, filters, Grad-CAM and occlusion maps of a ResNet-50.
title: Visualizing What ConvNets Learn
description: Four techniques for understanding what convolutional neural networks learn, intermediate activations, filter visualization, Grad-CAM, and occlusion sensitivity using PyTorch and ResNet-50.
Convolutional neural networks are often called “black boxes”, but there are principled techniques to inspect what they have learned. This section demonstrates four complementary interpretability methods using a pretrained ResNet-50 on ImageNet.
Technique
Question answered
Tool
Intermediate activations
What does each layer “see”?
Forward hooks
Filter visualization
What pattern maximally excites each filter?
Gradient ascent
Grad-CAM
Which image regions drive the prediction?
Gradient-weighted class activation map
Occlusion sensitivity
Which pixels matter most?
Systematic patch occlusion
All four methods use PyTorch hooks, no model modification required.
Device: cudaDownloading: "https://download.pytorch.org/models/resnet50-11ad3fa6.pth" to /home/vscode/.cache/torch/hub/checkpoints/resnet50-11ad3fa6.pth
# --- Technique 2: Filter visualization via gradient ascent ---## Start from random noise and update the input so that one specific# convolutional filter's mean activation is maximised.## ResNet-50 does not have a flat Sequential backbone like VGG.# We hook into specific layers and run a full forward pass.def visualize_filter(model, target_layer, filter_idx: int, n_steps=60, lr=0.05, size=128) -> np.ndarray: """Return a (size, size, 3) uint8 image that maximally excites filter_idx.""" x = torch.randn(1, 3, size, size, device=DEVICE) * 0.1 x.requires_grad_(True) captured = {} def fwd_hook(module, inp, out): captured['act'] = out hook = target_layer.register_forward_hook(fwd_hook) for _ in range(n_steps): if x.grad is not None: x.grad.zero_() model(x) # full forward pass loss = -captured['act'][0, filter_idx].mean() loss.backward() x.data += lr * x.grad / (x.grad.std() + 1e-8) hook.remove() img = x.detach().squeeze(0).permute(1, 2, 0).cpu().numpy() img -= img.min() mx = img.max() if mx > 0: img /= mx return (img * 255).astype(np.uint8)# 4 filters from conv1 (early edges) and 4 from layer3 (high-level textures)configs = [ (model.conv1, 0, 'conv1'), (model.conv1, 8, 'conv1'), (model.conv1, 16, 'conv1'), (model.conv1, 32, 'conv1'), (model.layer3[-1].conv3, 0, 'layer3'), (model.layer3[-1].conv3, 64, 'layer3'), (model.layer3[-1].conv3, 128, 'layer3'), (model.layer3[-1].conv3, 256, 'layer3'),]fig, axes = plt.subplots(2, 4, figsize=(10, 5))for ax, (layer, filt_idx, label) in zip(axes.flat, configs): vis = visualize_filter(model, layer, filt_idx) ax.imshow(vis, rasterized=True) ax.set_title(f'{label} f{filt_idx}', fontsize=8) ax.axis('off')fig.suptitle('Filter visualization, gradient ascent (top: conv1, bottom: layer3)')plt.tight_layout()plt.savefig('filter_visualization.png', dpi=120, bbox_inches='tight')plt.show()
Code
# --- Technique 3: Grad-CAM ---## Gradient-weighted Class Activation Mapping (Selvaraju et al., 2017).# Weights each feature-map channel by the global average of its gradient# w.r.t. the target class score, then applies ReLU and upsamples.def grad_cam(model, img_tensor: torch.Tensor, target_class: int, target_layer) -> np.ndarray: """Return a (224, 224) heat map in [0, 1].""" fmaps, grads = {}, {} def fwd_hook(m, inp, out): fmaps['A'] = out def bwd_hook(m, grad_in, grad_out): grads['dA'] = grad_out[0] h1 = target_layer.register_forward_hook(fwd_hook) h2 = target_layer.register_full_backward_hook(bwd_hook) out = model(img_tensor) model.zero_grad() out[0, target_class].backward() h1.remove() h2.remove() # alpha_k = global-average gradient per channel alpha = grads['dA'][0].mean(dim=(1, 2), keepdim=True) # (C, 1, 1) cam = torch.relu((alpha * fmaps['A'][0]).sum(0)) # (H, W) cam = F.interpolate( cam.unsqueeze(0).unsqueeze(0), size=(224, 224), mode='bilinear', align_corners=False ).squeeze().detach().cpu().numpy() cam -= cam.min() if cam.max() > 0: cam /= cam.max() return cam# Disable inplace ReLU, required for register_full_backward_hook to workfor m in model.modules(): if isinstance(m, torch.nn.ReLU): m.inplace = False# Last residual block of ResNet-50: layer4[-1]heatmap = grad_cam(model, img_tensor, TARGET_CLASS, model.layer4[-1])rgb = np.array(pil_img.resize((224, 224))).astype(np.float32) / 255.0colormap = plt.get_cmap('jet')(heatmap)[..., :3]overlay = (0.55 * rgb + 0.45 * colormap).clip(0, 1)fig, axes = plt.subplots(1, 3, figsize=(12, 4))axes[0].imshow(rgb, rasterized=True); axes[0].set_title('Input'); axes[0].axis('off')axes[1].imshow(heatmap, cmap='jet', rasterized=True); axes[1].set_title('Grad-CAM'); axes[1].axis('off')axes[2].imshow(overlay, rasterized=True); axes[2].set_title('Overlay'); axes[2].axis('off')fig.suptitle(f'Grad-CAM, target class: "{LABELS[TARGET_CLASS]}"')plt.tight_layout()plt.savefig('gradcam.png', dpi=120, bbox_inches='tight')plt.show()
Code
# --- Technique 4: Occlusion sensitivity ---## Slide a grey patch across the image and record how much the# target-class confidence drops at each position.# Large drops indicate regions that were important to the prediction.def occlusion_sensitivity(model, img_tensor: torch.Tensor, target_class: int, patch: int = 40, stride: int = 20) -> np.ndarray: """Return a (H, W) map of confidence drop when each patch is occluded.""" _, _, H, W = img_tensor.shape with torch.no_grad(): base_prob = F.softmax(model(img_tensor), dim=1)[0, target_class].item() sensitivity = np.zeros((H, W), dtype=np.float32) counts = np.zeros((H, W), dtype=np.float32) for y in range(0, H - patch + 1, stride): for x in range(0, W - patch + 1, stride): occluded = img_tensor.clone() occluded[:, :, y:y+patch, x:x+patch] = 0.0 # mid-grey in normalised space with torch.no_grad(): prob = F.softmax(model(occluded), dim=1)[0, target_class].item() drop = base_prob - prob sensitivity[y:y+patch, x:x+patch] += drop counts[y:y+patch, x:x+patch] += 1.0 counts = np.where(counts == 0, 1, counts) return sensitivity / countsprint('Running occlusion sensitivity (patch=40, stride=20) ...')sens_map = occlusion_sensitivity(model, img_tensor, TARGET_CLASS, patch=40, stride=20)rgb = np.array(pil_img.resize((224, 224)))fig, axes = plt.subplots(1, 2, figsize=(9, 4))axes[0].imshow(rgb, rasterized=True)axes[0].set_title('Input')axes[0].axis('off')vmax = np.abs(sens_map).max()im = axes[1].imshow(sens_map, cmap='RdBu_r', vmin=-vmax, vmax=vmax, rasterized=True)axes[1].set_title('Occlusion sensitivity\n(red = high confidence drop)')axes[1].axis('off')plt.colorbar(im, ax=axes[1], fraction=0.046, pad=0.04)fig.suptitle(f'Occlusion sensitivity, target: "{LABELS[TARGET_CLASS]}"')plt.tight_layout()plt.savefig('occlusion.png', dpi=120, bbox_inches='tight')plt.show()