Why Your 98% Accurate ResNet Needs Grad-CAM to Win Over Radiologists
From the publisher’s feed, collected in the ZeroLabs newsroom.
End-to-End PipelineBenchmark accuracy on medical imaging datasets is easy to game. A model trained on a single-site MRI dataset, with images from one scanner, one patient population, and one acquisition protocol, will learn shortcuts for you never intended scanner frame artifacts, background intensity patterns, and even image borders. It hits 98% on the test set and fails silently the moment it sees a scan from a different hospital.The problem isn’t the accuracy number. It’s that accuracy tells you nothing about what the model learned to look at. For clinical deployment, that distinction is everything.This tutorial builds a complete Alzheimer’s MRI classification pipeline in PyTorch ResNet18, four-class staging, rigorous evaluation, and then applies Grad-CAM to verify that the model is attending to the right anatomy before you trust any number it produces. By the end, you will have working, runnable code for every step, and a framework for deciding whether a model is actually learning medicine or just memorizing noise.Prerequisites: Python, basic familiarity with PyTorch, and comfort reading a training loop. No medical imaging background needed.The Dataset and What Makes It TrickyWe use the Best Alzheimer MRI Dataset on Kaggle - 224x224 axial brain MRI scans across four classes:No Impairment (NI)Very Mild Impairment (VMI)Mild Impairment (MI)Moderate Impairment (MOD)The training split is balanced: 2,560 images per class. The test split is not — 640 No Impairment, 448 Very Mild, 179 Mild, and only 12 Moderate. That 53:1 ratio between the most and least common test classes is not an accident; it mirrors real clinical prevalence. It also means a model that always predicts “No Impairment” scores around 50% accuracy while being medically useless. Keep this asymmetry in mind for every evaluation decision that follows.The four-class staging task is also harder than it looks. Very Mild and No Impairment are genuinely difficult to separate on structural MRI; the cortical thinning is subtle, ventricular enlargement is slight, and hippocampal volume loss is measured in millimeters. Models that struggle at this boundary are not broken; they are hitting the same diagnostic challenge human neurologists face.Overall PipelineDownload the dataset and organize it as follows:data/ train/ MildDemented/ ModerateDemented/ NonDemented/ VeryMildDemented/ test/ MildDemented/ ModerateDemented/ NonDemented/ VeryMildDemented/1. Environment SetupInstall the full stack:pip install torch torchvision albumentations opencv-python \ scikit-learn matplotlib seaborn grad-camAll imports and constants in one place, every subsequent snippet assumes these are already loaded:import osimport numpy as npimport matplotlib.pyplot as pltimport seaborn as snsimport torchimport torch.nn as nnimport torch.optim as optimfrom torch.utils.data import DataLoader, WeightedRandomSamplerfrom torchvision import datasets, modelsimport albumentations as Afrom albumentations.pytorch import ToTensorV2from sklearn.metrics import f1_score, confusion_matrix, classification_reportfrom pytorch_grad_cam import GradCAMfrom pytorch_grad_cam.utils.model_targets import ClassifierOutputTargetfrom pytorch_grad_cam.utils.image import show_cam_on_image# Fixed seeds for reproducibility across runstorch.manual_seed(42)np.random.seed(42)DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")MEAN = [0.485, 0.456, 0.406]STD = [0.229, 0.224, 0.225]NUM_CLASSES = 4BATCH_SIZE = 322. Augmentation StrategyStandard image augmentation, random flips, crops, and color jitter are designed for natural photographs. MRI scans require a different philosophy.Brain MRI has no color information worth augmenting (it’s grayscale remapped to RGB). What varies between real scans is: patient positioning in the scanner (handled by rotation and translation), scanner gain and field inhomogeneity (handled by brightness and gamma), and subtle anatomical variation between individuals (handled by elastic deformation). Each augmentation below maps to a specific real-world variation source.train_transform = A.Compose([ A.Resize(224, 224), # Patient head rotation in the scanner — kept small (15 degrees) # because larger rotations lose diagnostic orientation A.Rotate(limit=15, p=0.5), A.HorizontalFlip(p=0.5), # Scanner intensity variation and field inhomogeneity A.RandomBrightnessContrast(brightness_limit=0.15, contrast_limit=0.15, p=0.4), A.RandomGamma(gamma_limit=(80, 120), p=0.3), # Anatomical variation between patients — elastic deformation # mimics the soft-tissue deformability of real brain tissue A.ElasticTransform(alpha=1, sigma=50, alpha_affine=10, p=0.2), # Simulated scanner noise — teaches noise-invariant feature extraction A.GaussNoise(var_limit=(5.0, 25.0), p=0.3), A.Normalize(mean=MEAN, std=STD), ToTensorV2(),])val_transform = A.Compose([ A.Resize(224, 224), A.Normalize(mean=MEAN, std=STD), ToTensorV2(),]) def __len__(self): return len(self.dataset)Notice the validation transform has no augmentation. This is an intentional augmentation that is a training-time regularizer, not a preprocessing step. Applying it at inference would introduce stochastic noise into your evaluation numbers.Bridging Albumentations and PyTorchAlbumentations operates on NumPy arrays; PyTorch’s ImageFolder returns PIL images. This wrapper handles the conversion:class MRIDataset(torch.utils.data.Dataset): def __init__(self, root, transform=None): self.dataset = datasets.ImageFolder(root) self.transform = transform self.classes = self.dataset.classesdef __len__(self): return len(self.dataset) def __getitem__(self, idx): img, label = self.dataset[idx] img = np.array(img) # PIL -> NumPy for Albumentations if self.transform: img = self.transform(image=img)["image"] return img, labelFixing the Class Imbalance ProblemA naive DataLoader samples proportional to class size. On this dataset, that means the model sees 53 No Impairment images for every Moderate Impairment image. WeightedRandomSampler inverts those frequencies so every class appears equally often during training:train_dataset = MRIDataset("data/train", transform=train_transform)val_dataset = MRIDataset("data/test", transform=val_transform)# Compute inverse-frequency weights per sampletargets = [label for _, label in train_dataset.dataset.samples]class_counts = np.bincount(targets)class_weights = 1.0 / class_countssample_weights = [class_weights[t] for t in targets]sampler = WeightedRandomSampler( weights=sample_weights, num_samples=len(sample_weights), replacement=True)train_loader = DataLoader(train_dataset, batch_size=BATCH_SIZE, sampler=sampler, num_workers=4, pin_memory=True)val_loader = DataLoader(val_dataset, batch_size=BATCH_SIZE, shuffle=False, num_workers=4, pin_memory=True)CLASS_NAMES = train_dataset.classesprint("Classes:", CLASS_NAMES)3. Why ResNet18 Outperforms Vision Transformers on Small Medical Datasets3. Why ResNet18 Outperforms Vision Transformers on Small Medical DatasetsArchitecture of ResNet18Before writing the model code, it is worth understanding why ResNet18 is the right architectural choice here because the answer is not obvious, and it matters for any future work you do on constrained medical datasets.Vision Transformers (ViT) learn global relationships across the entire image using self-attention. That power comes at a cost: ViT has no inductive bias about spatial locality. It needs to learn from data that nearby pixels are related to something a CNN gets for free through its convolutional structure. On ImageNet (1.2 million images), ViT can learn that locality from the data volume alone. On a 10,000-image medical dataset, it cannot, and performance degrades accordingly.In controlled benchmarks on this exact dataset, ResNet18 achieves 98.36% accuracy and 0.9877 macro-F1. ViT-B16 reaches 86.4%. DINO-ViT Small, despite self-supervised pretraining, reaches only 70.1%. The gap is not a tuning artifact it reflects a genuine structural mismatch between transformer architectures and small-data regimes.ResNet18 wins because the convolutional feature extraction is hierarchical, translation-equivariant, and local, which is inherently well-suited to the spatial structure of brain anatomy. The hippocampus is always in roughly the same location in an axial slice. Convolutional filters exploit that regularity; attention mechanisms must learn it from scratch.Build the modeldef build_resnet18(num_classes=NUM_CLASSES, pretrained=True): weights = "IMAGENET1K_V1" if pretrained else None model = models.resnet18(weights=weights)# Freeze backbone for Phase 1 training for param in model.parameters(): param.requires_grad = False # Replace 1000-class ImageNet head with our 4-class head # Dropout before the linear layer reduces overfitting on small data in_features = model.fc.in_features # 512 model.fc = nn.Sequential( nn.Dropout(p=0.3), nn.Linear(in_features, num_classes) ) return modelmodel = build_resnet18().to(DEVICE)trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)print(f"Trainable parameters (head only): {trainable:,}")4. Two-Phase Fine-TuningSingle-phase fine-tuning on a small dataset, unfreezing everything immediately and training end-to-end often degrades the pretrained ImageNet representations before the new classification head is stable enough to provide useful gradients. The result is worse performance than you would get from a more controlled approach.Training StrategyTwo-phase fine-tuning solves this. Phase 1 trains only the new head with the backbone frozen, giving it stable initial weights. Phase 2 unfreezes the entire network for full adaptation, with the head now providing a coherent gradient signal to the backbone.def train_one_epoch(model, loader, criterion, optimizer): model.train() total_loss, correct, total = 0.0, 0, 0 for images, labels in loader: images, labels = images.to(DEVICE), labels.to(DEVICE) optimizer.zero_grad() loss = criterion(model(images), labels) loss.backward() optimizer.step() with torch.no_grad(): preds = model(images).argmax(1) correct += preds.eq(labels).sum().item() total_loss += loss.item() * images.size(0) total += labels.size(0) return total_loss / total, correct / total def evaluate(model, loader, criterion): model.eval() all_preds, all_labels, total_loss, total = [], [], 0.0, 0 with torch.no_grad(): for images, labels in loader: images, labels = images.to(DEVICE), labels.to(DEVICE) outputs = model(images) total_loss += criterion(outputs, labels).item() * images.size(0) preds = outputs.argmax(1) all_preds.extend(preds.cpu().numpy()) all_labels.extend(labels.cpu().numpy()) total += labels.size(0) acc = sum(p == l for p, l in zip(all_preds, all_labels)) / total macro_f1 = f1_score(all_labels, all_preds, average="macro") return total_loss / total, acc, macro_f1def train_two_phase(model, train_loader, val_loader, phase1_epochs=3, phase2_epochs=7, lr=1e-4):criterion = nn.CrossEntropyLoss() best_f1, best_ckpt = 0.0, None # ── Phase 1: head warm-up ───────────────────────────────────────── optimizer = optim.Adam( filter(lambda p: p.requires_grad, model.parameters()), lr=lr) scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=5, gamma=0.1) print("=== Phase 1: head warm-up ===") for epoch in range(1, phase1_epochs + 1): tr_loss, tr_acc = train_one_epoch(model, train_loader, criterion, optimizer) va_loss, va_acc, va_f1 = evaluate(model, val_loader, criterion) scheduler.step() print(f" [{epoch}/{phase1_epochs}] " f"train_loss={tr_loss:.4f} train_acc={tr_acc:.4f} | " f"val_acc={va_acc:.4f} macro_f1={va_f1:.4f}") # ── Phase 2: full fine-tuning ───────────────────────────────────── for param in model.parameters(): param.requires_grad = True optimizer = optim.Adam(model.parameters(), lr=lr) scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=5, gamma=0.1) print("\n=== Phase 2: full fine-tuning ===") for epoch in range(1, phase2_epochs + 1): tr_loss, tr_acc = train_one_epoch(model, train_loader, criterion, optimizer) va_loss, va_acc, va_f1 = evaluate(model, val_loader, criterion) scheduler.step() tag = " best_f1 else "" if va_f1 > best_f1: best_f1 = va_f1 best_ckpt = {k: v.clone() for k, v in model.state_dict().items()} print(f" [{epoch}/{phase2_epochs}] " f"train_loss={tr_loss:.4f} train_acc={tr_acc:.4f} | " f"val_acc={va_acc:.4f} macro_f1={va_f1:.4f}{tag}") model.load_state_dict(best_ckpt) torch.save(best_ckpt, "resnet18_alzheimer_best.pth") print(f"\nSaved best model. Macro-F1: {best_f1:.4f}") return modelmodel = train_two_phase(model, train_loader, val_loader)The StepLR scheduler cuts the learning rate by 90% every 5 epochs. The effect is deliberate: early epochs make large parameter updates to capture coarse disease patterns; later epochs make fine-grained adjustments to resolve the hard boundary between Very Mild and No Impairment the most clinically consequential confusion this model makes.5. Evaluation: Why Accuracy Is the Wrong Headline MetricWith 640 No Impairment and 12 Moderate Impairment test samples, overall accuracy is structurally biased toward the majority class. A model that predicts “No Impairment” for every input achieves roughly 50% accuracy. That is not a hypothetical failure mode, it is the default behavior of an undertrained model on imbalanced data, and it will look acceptable if you only report accuracy.Macro-F1 computes F1 independently for each class, then averages them with equal weight. A model that ignores Moderate Impairment entirely gets a Macro-F1 near 0.75 at best, a number that clearly signals the problem, where accuracy would mask it.def full_evaluation(model, loader, class_names, save_path="confusion_matrix.png"): model.eval() all_preds, all_labels = [], [] with torch.no_grad(): for images, labels in loader: preds = model(images.to(DEVICE)).argmax(1) all_preds.extend(preds.cpu().numpy()) all_labels.extend(labels.numpy()) print(classification_report(all_labels, all_preds, target_names=class_names, digits=4))cm = confusion_matrix(all_labels, all_preds) plt.figure(figsize=(7, 6)) sns.heatmap(cm, annot=True, fmt="d", cmap="Blues", xticklabels=class_names, yticklabels=class_names) plt.title("Confusion Matrix - ResNet18 Alzheimer Classification") plt.ylabel("True Label") plt.xlabel("Predicted Label") plt.tight_layout() plt.savefig(save_path, dpi=150) plt.show() return cmcm = full_evaluation(model, val_loader, CLASS_NAMES)Reading the confusion matrix for clinical meaningThe confusion matrix reveals something accuracy never will: where the model fails and whether those failures are clinically acceptable.Errors at adjacent severity boundaries, Very Mild misclassified as No Impairment, Mild misclassified as Very Mild , are expected. These classes are genuinely ambiguous on 2D axial MRI; even experienced neurologists disagree on staging at these boundaries. A model making these errors is not broken.Errors that jump multiple severity levels, Moderate classified as No Impairment, are a serious red flag. They suggest the model has not learned the clinical gradient of disease severity and is instead pattern-matching on some confounding feature. On a well-trained ResNet18, the confusion matrix should show near-zero off-diagonal mass beyond one step from the diagonal.In the benchmark results on this dataset, ResNet18 correctly classifies all 12 Moderate Impairment cases and misclassifies only 14 of 448 Very Mild cases. The model’s errors are concentrated exactly where the clinical ambiguity is highest.6. Grad-CAM: From Accuracy to Trustworthy PredictionsHow Grad-CAM worksA 98% accuracy number on a Kaggle dataset does not tell you whether the model learned hippocampal atrophy patterns or learned that scans in one severity class happened to be slightly brighter on average due to scanner drift. Grad-CAM answers that question directly.The mechanism: during inference, Grad-CAM computes the gradient of the predicted class score with respect to the feature maps in the final convolutional layer. Channels whose activations most influence the prediction receive a higher weight. The weighted sum of those channels, upsampled to input resolution and overlaid on the original image, produces a spatial attention map a heatmap showing which regions drove the decision.Why the final convolutional layer specifically? Because by that point in the network, low-level features (edges, textures) have been abstracted into high-level semantic representations (cortical patterns, tissue boundaries). Earlier layers would highlight generic image features; the last layer highlights disease-relevant anatomy.def get_gradcam_overlay(model, image_tensor, pred_class_idx, display_image_np): """ model : trained ResNet18, on DEVICE, in eval mode image_tensor : (1, 3, 224, 224) normalized tensor on DEVICE pred_class_idx : integer — the class index to explain display_image_np : (224, 224, 3) float32 in [0, 1] — denormalized for display """ target_layers = [model.layer4[-1]] # last residual block of Layer 4with GradCAM(model=model, target_layers=target_layers) as cam: grayscale_cam = cam( input_tensor=image_tensor, targets=[ClassifierOutputTarget(pred_class_idx)] )[0] # shape: (224, 224)overlay = show_cam_on_image(display_image_np, grayscale_cam, use_rgb=True) return overlay, grayscale_camdef visualize_gradcam(model, dataset, class_names, num_samples=4, save_path="gradcam_results.png"): model.eval() fig, axes = plt.subplots(num_samples, 3, figsize=(11, num_samples * 3.2))indices = np.random.choice(len(dataset), num_samples, replace=False)for row, idx in enumerate(indices): image_tensor, true_label = dataset[idx] inp = image_tensor.unsqueeze(0).to(DEVICE)with torch.no_grad(): pred_label = model(inp).argmax(1).item() # Reverse the normalization to recover the displayable pixel range orig = image_tensor.cpu().numpy().transpose(1, 2, 0) orig = np.array(STD) * orig + np.array(MEAN) orig = np.clip(orig, 0, 1).astype(np.float32) overlay, heatmap = get_gradcam_overlay(model, inp, pred_label, orig) is_correct = pred_label == true_label axes[row, 0].imshow(orig, cmap="gray") axes[row, 0].set_title(f"Input | True: {class_names[true_label]}", fontsize=9) axes[row, 0].axis("off") axes[row, 1].imshow(heatmap, cmap="jet") axes[row, 1].set_title("Grad-CAM activation", fontsize=9) axes[row, 1].axis("off") label_color = "green" if is_correct else "red" status = "Correct" if is_correct else "WRONG" axes[row, 2].imshow(overlay) axes[row, 2].set_title( f"Pred: {class_names[pred_label]} [{status}]", fontsize=9, color=label_color) axes[row, 2].axis("off") plt.suptitle("Grad-CAM Explanations - ResNet18 Alzheimer Classifier", fontsize=12, y=1.01) plt.tight_layout() plt.savefig(save_path, dpi=150, bbox_inches="tight") plt.show()visualize_gradcam(model, val_dataset, CLASS_NAMES, num_samples=4)7. Interpreting Grad-CAM Output for Clinical ValidityRunning Grad-CAM is the easy part. The harder part is knowing what you are looking for and what constitutes a failure.What good activation patterns look likeA clinically valid Alzheimer’s classifier should focus on regions with established neurodegeneration biomarkers. In order of expected significance:Medial temporal structures: The hippocampus and entorhinal cortex are the earliest sites of tau tangle formation and volume loss. Activation here in early-stage cases (Very Mild, Mild) is the strongest positive signal that the model learned meaningful anatomy.Lateral ventricles: These fluid-filled cavities enlarge as surrounding brain tissue shrinks. In moderate-to-severe cases, ventricular enlargement is one of the most visually prominent MRI features, and models reliably attend to it.Temporal and parietal cortex: Cortical thinning progresses from medial temporal to lateral temporal to parietal regions. Activation spreading across these areas in advanced cases is expected and appropriate.What bad activation patterns look like and what to do about themActivation concentrated at image borders or outside brain tissue: The model found a shortcut. Possible sources: scanner manufacturer watermarks embedded in certain severity classes, consistent padding artifacts, or slice selection that is confounded with staging. Fix: apply aggressive border cropping before training, and audit whether image preprocessing was consistent across classes.Activation focused on the skull or scalp: The model may be using skull thickness or scalp tissue distribution as a proxy, which can be correlated with age rather than disease stage. This is a demographic shortcut, not a diagnostic one. Fix: skull-strip your MRI images using FSL’s BET or ANTs before training.Diffuse, low-intensity activations spread uniformly: The model is uncertain or has learned no useful spatial features. This is typical of DINO-ViT Small on this dataset size. The self-supervised pretraining objective does not align well with fine-grained medical staging, and the resulting attention maps lack focal specificity.Activation patterns that flip between correct and incorrect predictions in the same class: The model is memorizing rather than generalizing. This typically indicates insufficient augmentation, overfitting, or that the dataset has systematic label noise in that class.The gap between benchmark and deploymentA model that passes Grad-CAM inspection on a held-out test set from the same distribution as training is necessary but not sufficient for clinical deployment. Real deployment introduces distribution shift: different scanner manufacturers, different field strengths (1.5T vs 3T), different slice thicknesses, different patient demographics. None of these are represented in a single-site Kaggle dataset.The responsible path forward requires external validation on a second dataset (ADNI or OASIS are publicly available), multi-site testing, and prospective evaluation alongside radiologist judgment. Grad-CAM is a tool for building confidence and catching obvious failure modes early not a substitute for that validation work.What You Built and Where to Take It NextComponent Decision Reasoning Augmentation MRI-specific: elastic, gamma, Gaussian noise Maps to real scanner variation sources Class balancing WeightedRandomSampler on training Prevents majority-class dominance without duplicating data Architecture ResNet18 over ViT Convolutional inductive bias wins at small dataset scale Fine-tuning Two-phase: head then full network Prevents catastrophic forgetting of ImageNet representations Evaluation Macro-F1 as headline metric Imbalanced test set makes accuracy unreliable Explainability Grad-CAM on layer4[-1] Last convolutional layer has highest semantic specificityThree concrete next steps if you want to push this further:Replace CrossEntropyLoss with focal loss to further penalize misclassification of the rare Moderate class, the standard loss still treats a Moderate error identically to a No Impairment error despite the clinical difference.Add a second explainability pass using SHAP with a background distribution sampled from the training set. Grad-CAM is gradient-based and class-specific; SHAP is perturbation-based and feature-additive. Where they agree, you have high-confidence attribution. Where they disagree, the feature importance is ambiguous and worth investigating.Swap the backbone for EfficientNet-B3 and compare Grad-CAM maps alongside accuracy. The architectural differences in how EfficientNet scales depth, width, and resolution can produce meaningfully different attention patterns even at similar accuracy levels, which matters if clinical interpretability, not just performance, is your deployment criterion.Why Your 98% Accurate ResNet Needs Grad-CAM to Win Over Radiologists was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.