Explainable AI in Medical Imaging: Implementing Grad-CAM with PyTorch
A deep dive into Gradient-weighted Class Activation Mapping (Grad-CAM) to make deep neural networks verifiable in medical diagnostics like Netra AI.
The Black-Box Problem in Clinical Deep Learning
Convolutional neural networks (CNNs) have achieved superhuman benchmark performance on image classification tasks, including retinal fundus photograph screening for diabetic retinopathy. However, deploying these models in actual healthcare settings faces a fundamental roadblock: clinical distrust of "black-box" systems.
When an ophthalmologist is presented with an automated prediction of "Severe Non-Proliferative Diabetic Retinopathy", their immediate reaction is: why did the model make this call? Did it detect microaneurysms near the macula, or did it latch onto an artifact from the camera flash or lens dust?
How Grad-CAM Computes Visual Attribution
Grad-CAM (Gradient-weighted Class Activation Mapping) solves this by using the gradients of any target concept flowing into the final convolutional layer of a CNN. Because convolutional layers naturally retain 2D spatial information that gets flattened in dense layers, the final feature maps contain the richest combination of high-level visual features and spatial location.
To generate the localization map, we compute the gradient of the class score with respect to feature map activations of the last convolutional layer. These gradients are global-average-pooled to obtain importance weights for each feature map.
import torch
import torch.nn.functional as F
class GradCAM:
def __init__(self, model, target_layer):
self.model = model
self.target_layer = target_layer
self.gradients = None
self.activations = None
# Register forward and backward hooks
self.target_layer.register_forward_hook(self.save_activation)
self.target_layer.register_full_backward_hook(self.save_gradient)
def save_activation(self, module, input, output):
self.activations = output.detach()
def save_gradient(self, module, grad_input, grad_output):
self.gradients = grad_output[0].detach()
def generate_heatmap(self, input_tensor, target_class):
self.model.zero_grad()
output = self.model(input_tensor)
score = output[0, target_class]
score.backward()
# Global average pool the gradients
weights = torch.mean(self.gradients, dim=(2, 3), keepdim=True)
# Weight the activation maps
cam = torch.sum(weights * self.activations, dim=1).squeeze()
# ReLU to focus on positive correlations
cam = F.relu(cam)
cam = cam - cam.min()
cam = cam / (cam.max() + 1e-8)
return cam.cpu().numpy()Deploying Explainability in Netra AI
In Netra AI (our Technomaster 2026 winning project), Grad-CAM wasn't just an academic exercise—it was the cornerstone of clinical utility. By normalizing the heatmap to the original 512x512 retina image using a Jet colormap overlay, doctors could immediately see whether the model highlighted hard exudates or cotton wool spots.
Making AI explainable transforms the technology from a questionable replacement into a powerful, verifiable diagnostic assistant.