Chest X-Ray Diagnosis: Deep Learning for Medical Imaging
Train a neural network that detects pneumonia from chest X-rays with radiologist-level accuracy
A fine-tuned ResNet50 model achieving ~94% accuracy on the Kaggle Chest X-Ray dataset, with Grad-CAM heatmaps showing which lung regions triggered the diagnosis, deployed as a FastAPI endpoint that accepts image uploads and returns diagnosis + visual explanation
Skills you'll gain
Prerequisites
Tech stack
Medical Imaging AI Pipeline
Milestone 1
Setup & Data Loading
Create a reproducible environment, download the dataset, and build DataLoaders that correctly handle the class imbalance.
Create your project and install dependencies
src/, API code in api/, outputs in outputs/.# Create project structure
mkdir -p chest-xray-ai/{src,api,outputs,data}
cd chest-xray-ai
# Create virtual environment
python -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
requirements.txt with all pinned packages:# requirements.txt
torch==2.2.2
torchvision==0.17.2
timm==0.9.16
albumentations==1.4.6
matplotlib==3.9.0
scikit-learn==1.5.0
grad-cam==1.5.2
fastapi==0.111.0
uvicorn==0.29.0
python-multipart==0.0.9
Pillow==10.3.0
numpy==1.26.4
seaborn==0.13.2
tqdm==4.66.4
pip install -r requirements.txt
Download the dataset
Read this to understand why clinical images are stored as DICOM rather than JPEG, and what metadata each file carries that matters for preprocessing and regulatory compliance
NORMAL/ and PNEUMONIA/ subfolders.# Install Kaggle CLI and set up credentials
pip install kaggle
# Place your kaggle.json API token at ~/.kaggle/kaggle.json
kaggle datasets download -d paultimothymooney/chest-xray-pneumonia
unzip chest-xray-pneumonia.zip -d data/
data/ folder should look like this:data/chest_xray/
├── train/
│ ├── NORMAL/ # 1,341 images
│ └── PNEUMONIA/ # 3,875 images
├── val/
│ ├── NORMAL/ # 8 images
│ └── PNEUMONIA/ # 8 images
└── test/
├── NORMAL/ # 234 images
└── PNEUMONIA/ # 390 images
Build DataLoaders and inspect class distribution
Read this to understand why ImageNet pretrained weights dramatically accelerate medical imaging models — ResNet50 arrives already knowing how to detect edges, textures, and shapes before it sees a single X-ray
src/load_data.py:"""
src/load_data.py
Load the Chest X-Ray dataset using torchvision ImageFolder,
compute class statistics, and return DataLoader objects.
"""
import os
from pathlib import Path
from typing import Tuple
import torch
from torch.utils.data import DataLoader, WeightedRandomSampler
from torchvision import datasets, transforms
# ── Constants ──────────────────────────────────────────────────────────────────
DATA_ROOT = Path("data/chest_xray")
IMAGE_SIZE = 224 # ResNet50 expects 224×224
BATCH_SIZE = 32
NUM_WORKERS = 4 # Adjust based on your CPU cores
SEED = 42
torch.manual_seed(SEED)
def get_basic_transforms(split: str) -> transforms.Compose:
"""
Return torchvision transforms for a given split.
Training uses only normalization here — Albumentations handles augmentation.
Val/test use resize + center crop + normalize.
"""
imagenet_mean = [0.485, 0.456, 0.406]
imagenet_std = [0.229, 0.224, 0.225]
if split == "train":
return transforms.Compose([
transforms.Resize((IMAGE_SIZE, IMAGE_SIZE)),
transforms.ToTensor(),
transforms.Normalize(mean=imagenet_mean, std=imagenet_std),
])
else:
return transforms.Compose([
transforms.Resize((IMAGE_SIZE + 32, IMAGE_SIZE + 32)),
transforms.CenterCrop(IMAGE_SIZE),
transforms.ToTensor(),
transforms.Normalize(mean=imagenet_mean, std=imagenet_std),
])
def build_datasets() -> Tuple[datasets.ImageFolder, ...]:
"""Load train/val/test datasets using ImageFolder."""
train_ds = datasets.ImageFolder(
root=DATA_ROOT / "train",
transform=get_basic_transforms("train"),
)
val_ds = datasets.ImageFolder(
root=DATA_ROOT / "val",
transform=get_basic_transforms("val"),
)
test_ds = datasets.ImageFolder(
root=DATA_ROOT / "test",
transform=get_basic_transforms("test"),
)
return train_ds, val_ds, test_ds
def compute_class_weights(dataset: datasets.ImageFolder) -> torch.Tensor:
"""
Compute per-class weights inversely proportional to class frequency.
Minority class (NORMAL) gets higher weight so the model pays more attention to it.
"""
class_counts = [0] * len(dataset.classes)
for _, label in dataset.samples:
class_counts[label] += 1
total = sum(class_counts)
weights = [total / (len(class_counts) * count) for count in class_counts]
return torch.tensor(weights, dtype=torch.float)
def build_weighted_sampler(dataset: datasets.ImageFolder) -> WeightedRandomSampler:
"""
Return a WeightedRandomSampler so each batch sees roughly equal class distribution.
This is more effective than just weighting the loss — it controls what the model sees.
"""
class_weights = compute_class_weights(dataset)
sample_weights = [class_weights[label] for _, label in dataset.samples]
return WeightedRandomSampler(
weights=sample_weights,
num_samples=len(dataset),
replacement=True,
)
def build_dataloaders() -> Tuple[DataLoader, DataLoader, DataLoader]:
"""Build and return train/val/test DataLoaders."""
train_ds, val_ds, test_ds = build_datasets()
sampler = build_weighted_sampler(train_ds)
train_loader = DataLoader(
train_ds,
batch_size=BATCH_SIZE,
sampler=sampler, # WeightedRandomSampler replaces shuffle=True
num_workers=NUM_WORKERS,
pin_memory=True,
)
val_loader = DataLoader(
val_ds,
batch_size=BATCH_SIZE,
shuffle=False,
num_workers=NUM_WORKERS,
pin_memory=True,
)
test_loader = DataLoader(
test_ds,
batch_size=BATCH_SIZE,
shuffle=False,
num_workers=NUM_WORKERS,
pin_memory=True,
)
# Print class distribution — always verify before training
print("\n=== Dataset Statistics ===")
for split, ds in [("Train", train_ds), ("Val", val_ds), ("Test", test_ds)]:
counts = {}
for _, label in ds.samples:
counts[label] = counts.get(label, 0) + 1
print(f"\n{split} split ({len(ds)} images):")
for class_idx, class_name in enumerate(ds.classes):
n = counts.get(class_idx, 0)
pct = 100 * n / len(ds)
print(f" {class_name}: {n} images ({pct:.1f}%)")
class_weights = compute_class_weights(train_ds)
print(f"\nClass weights for loss function:")
for i, name in enumerate(train_ds.classes):
print(f" {name}: {class_weights[i]:.4f}")
return train_loader, val_loader, test_loader
if __name__ == "__main__":
train_loader, val_loader, test_loader = build_dataloaders()
# Quick sanity check — iterate one batch
images, labels = next(iter(train_loader))
print(f"\nBatch shape: {images.shape}") # [32, 3, 224, 224]
print(f"Label shape: {labels.shape}") # [32]
print(f"Unique labels in batch: {labels.unique()}")
# Visualize 8 random images (4 Normal, 4 Pneumonia)
import matplotlib.pyplot as plt
import torchvision.utils as vutils
train_ds, _, _ = build_datasets()
normal_imgs, pneumo_imgs = [], []
for img, label in train_ds:
if label == 0 and len(normal_imgs) < 4:
normal_imgs.append(img)
elif label == 1 and len(pneumo_imgs) < 4:
pneumo_imgs.append(img)
if len(normal_imgs) == 4 and len(pneumo_imgs) == 4:
break
fig, axes = plt.subplots(2, 4, figsize=(14, 7))
fig.suptitle("Chest X-Rays: Normal (top) vs Pneumonia (bottom)", fontsize=14, fontweight="bold")
imagenet_mean = torch.tensor([0.485, 0.456, 0.406]).view(3, 1, 1)
imagenet_std = torch.tensor([0.229, 0.224, 0.225]).view(3, 1, 1)
for i, img in enumerate(normal_imgs):
unnorm = img * imagenet_std + imagenet_mean
axes[0, i].imshow(unnorm.permute(1, 2, 0).clamp(0, 1), cmap="gray")
axes[0, i].set_title(f"Normal #{i+1}", color="green")
axes[0, i].axis("off")
for i, img in enumerate(pneumo_imgs):
unnorm = img * imagenet_std + imagenet_mean
axes[1, i].imshow(unnorm.permute(1, 2, 0).clamp(0, 1), cmap="gray")
axes[1, i].set_title(f"Pneumonia #{i+1}", color="red")
axes[1, i].axis("off")
plt.tight_layout()
plt.savefig("outputs/m1_sample_images.png", dpi=150, bbox_inches="tight")
print("\nSaved: outputs/m1_sample_images.png")
plt.show()python src/load_data.py--- Dataset Statistics ---\n\nTrain split (5216 images):\n NORMAL: 1341 images (25.7%)\n PNEUMONIA: 3875 images (74.3%)\n\nVal split (16 images):\n NORMAL: 8 images (50.0%)\n PNEUMONIA: 8 images (50.0%)\n\nTest split (624 images):\n NORMAL: 234 images (37.5%)\n PNEUMONIA: 390 images (62.5%)\n\nClass weights for loss function:\n NORMAL: 1.8817\n PNEUMONIA: 0.6519\n\nBatch shape: torch.Size([32, 3, 224, 224])\nLabel shape: torch.Size([32])\nUnique labels in batch: tensor([0, 1])\n\nSaved: outputs/m1_sample_images.png
uvicorn api.main:app --reload --port 8000INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\nINFO: Started reloader process\nINFO: Started server process\nINFO: Application startup complete.
python api/test_api.pyStarting API tests(…)\n\n[HEALTH] Status: healthy | Device: cuda\n\n[DIAGNOSE] person100_bacteria_474.jpeg\n Diagnosis: PNEUMONIA\n Confidence: 96.3%\n Normal: 3.7%\n Pneumonia: 96.3%\n Severity: High\n Inference: 47.2ms\n Disclaimer: ⚠️ RESEARCH ONLY — NOT FOR CLINICAL USE. This model(…)\n\n Grad-CAM saved to: outputs/m7_api_gradcam_response.png\n\n All assertions passed.\n\n✓ All tests passed.
- FastAPI's file upload endpoint with
UploadFileand content-type validation handles the preprocessing pipeline cleanly — validate file type, size, and format before any model inference - Grad-CAM heatmaps can be returned as base64-encoded PNG strings inline in a JSON response — no separate file serving required, and the client can decode and display them without additional requests
- DICOM is the standard medical imaging format in clinical practice — this API accepts JPEG/PNG previews, but production deployments need pydicom to handle windowing, DICOM metadata, and multi-frame images
- A medical disclaimer is not just legal boilerplate — it reflects the genuine gap between a research model and an FDA-cleared medical device; every team member involved in clinical AI deployment needs to understand this gap and the regulatory pathway to close it
#System Architecture
Medical Imaging AI System
Read this to understand how gradient-weighted class activation mapping generates the heatmaps that show exactly which image regions the CNN attended to when making its diagnosis — the mechanism that makes this model explainable to clinicians
#Clinical Context: FDA SaMD and Why Explainability Is Non-Negotiable
#What You Built
You built a complete end-to-end clinical AI system from scratch:
- A fine-tuned ResNet50 achieving ~94% accuracy and ~95% sensitivity on 5,216 chest X-ray images — matching or exceeding radiologist performance on this benchmark
- Clinically appropriate augmentation that respects the constraints of medical images — no vertical flips, no extreme rotations, exposure simulation only
- Class-weighted training that prioritizes sensitivity (catching sick patients) over raw accuracy — the right clinical trade-off
- Grad-CAM explainability that shows which lung regions drove each prediction — the critical safety layer that separates research-grade from deployment-grade medical AI
- A FastAPI endpoint that accepts image uploads and returns diagnosis, confidence, severity estimate, and a visual heatmap — all in one JSON response
The system you built is a real demonstration of how clinical AI works. It also demonstrates the humility required: the disclaimer on every API response is not noise. It is a reminder that this model has not been validated on diverse populations, scanner types, or prospective clinical cohorts. The technical accuracy is real. The regulatory work required to deploy it clinically is a completely separate and much larger undertaking.
#Extend This Project
Five directions to take this further:
-
Multi-class classification — expand the target from binary (Normal/Pneumonia) to three classes (Normal/Bacterial/Viral). The filename labels in the dataset already encode this distinction. This forces the model to learn the difference between lobar consolidation and diffuse bilateral infiltrates — a harder and more clinically meaningful task.
-
DICOM support — install
pydicomand extendpreprocess_image()to handle.dcmfiles. Real clinical systems never receive JPEG files. DICOM encodes windowing parameters (Window Level/Window Width) that determine which tissue densities are visible — ignoring these produces low-quality inputs. -
Ensemble predictions — train three separate ResNet50 models with different random seeds and different augmentation pipelines, then average their softmax outputs. Ensemble uncertainty (disagreement between models) is a better confidence signal than any single model's output, and it is clinically informative: high disagreement → flag for radiologist review.
-
Federated learning — train the same model architecture on X-rays from three different hospital datasets without sharing raw patient images. Use PySyft or Flower to orchestrate weight averaging. This is the privacy-preserving approach that makes clinical AI possible across institutions without HIPAA-violating data sharing.
-
FDA pathway overview — research the De Novo pathway for Computer-Aided Detection (CADe) devices. Understand the difference between CADe (flagging regions for radiologist review — lower risk) and CADx (characterizing disease — higher risk). Draft the intended use statement for this model. Understanding the regulatory path is as important as the engineering for any clinical AI career.
#Resume Bullet
Built chest X-ray pneumonia detection system using transfer learning (ResNet50) achieving 94% accuracy and 95% sensitivity on 5,216-image Kaggle dataset; implemented Grad-CAM explainability showing clinically relevant lung region activation; deployed as FastAPI image upload endpoint with base64 Grad-CAM response; applied discriminative fine-tuning, class-weighted loss, and WeightedRandomSampler to handle 2.9:1 class imbalance
Why does transfer learning from ImageNet work for chest X-rays, even though X-rays and natural photos look nothing alike?