A high-sensitivity deep learning vision model for 4-stage Alzheimer's disease classification and 512-dimensional latent feature extraction from structural brain MRI scans.
β οΈ Clinical Research Disclaimer: This model is distributed strictly for scientific, academic research, and educational purposes. It is not an FDA/CE-cleared medical device and should never replace clinical evaluations, expert neurological consultations, or standard diagnostic workups (such as MMSE, MoCA, PET, or CSF biomarkers).
Early diagnosis of Alzheimer's disease (AD) is critical for timely therapeutic interventions, clinical trial enrollment, and personalized patient care. This model uses transfer learning via a customized ResNet-18 architecture fine-tuned on 86,437 brain MRI slices.
The model serves two primary modalities:
Input: Brain MRI Scan (224 Γ 224 Γ 3 RGB)
β
βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β ResNet-18 Feature Backbone β
β (7x7 Conv, BatchNorm, MaxPool, Residual Blocks 1-4) β
β 11,176,512 Parameters β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Adaptive Average Pooling Layer β
β Output: 512-dimensional vector β
β β
Exportable for Case Similarity Search β
β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Fully Connected Classifier Head β
β Linear(in: 512, out: 4) β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
Softmax Probabilities:
[Mild Dementia, Moderate Dementia, Non Demented, Very Mild Dementia]
torchvision.models.resnet18 (ImageNet-1K pre-trained backbone)3 Γ 224 Γ 224 pixels (normalized to ImageNet mean/standard deviation)avgpool output)The model stratifies scans into four standard diagnostic classes:
| Class ID | Diagnosis Label | Clinical Manifestation & Radiological Correlates |
|---|---|---|
| 0 | Mild Dementia | Noticeable cognitive impairment; moderate hippocampal and temporal lobe atrophy visible on structural T1-weighted images. |
| 1 | Moderate Dementia | Marked memory loss, impaired executive function; generalized cortical thinning, prominent sulcal widening, and ventricular enlargement. |
| 2 | Non Demented | Normal age-appropriate brain volume; preserved cortical thickness without localized atrophy. |
| 3 | Very Mild Dementia | Early Prodromal / Mild Cognitive Impairment (MCI); subtle medial temporal lobe volume changes often challenging for unassisted visual inspection. |
Trained across 15 epochs on NVIDIA Tesla T4 hardware using WeightedRandomSampler and CrossEntropyLoss(label_smoothing=0.1).
| Epoch | Training Loss | Validation Accuracy | Status |
|---|---|---|---|
| 1 | 0.8931 | 71.83% | Best checkpoint |
| 3 | 0.7782 | 72.21% | Best checkpoint |
| 5 | 0.7611 | 73.10% | Best checkpoint |
| 6 | 0.7585 | 75.15% | Best checkpoint |
| 9 | 0.7557 | 75.94% | Best checkpoint |
| 11 | 0.7510 | 79.55% | π Global Best Checkpoint |
| 15 | 0.7355 | 76.68% | Converged |
========================================================================
PRECISION RECALL F1-SCORE SUPPORT (COUNT)
========================================================================
Mild Dementia 0.32 0.84 0.47 1,022
Moderate Dementia 0.27 0.97 0.42 121
Non Demented 0.94 0.81 0.87 13,390
Very Mild Dementia 0.55 0.53 0.54 2,755
------------------------------------------------------------------------
Accuracy 0.77 17,288
Macro Average 0.52 0.79 0.57 17,288
Weighted Average 0.83 0.77 0.79 17,288
========================================================================
PREDICTED
Mild Mod Non VeryMild β Total (Actual)
ACTUAL βββββββββ¬βββββββ¬ββββββββ¬ββββββββββββ
Mild β 855 β 27 β 85 β 55 ββ 1,022
Moderate β 3 β 117 β 0 β 1 ββ 121
Non Demented β 1,220 β 199 β10,818 β 1,153 ββ 13,390
Very Mild β 562 β 92 β 635 β 1,466 ββ 2,755
βββββββββ΄βββββββ΄ββββββββ΄ββββββββββββ
pip install torch torchvision pillow requests
import torch
import torch.nn as nn
from torchvision import models, transforms
from PIL import Image
# Setup device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Initialize architecture matching the trained model
model = models.resnet18(weights=None)
model.fc = nn.Linear(model.fc.in_features, 4)
# Load checkpoint
model_path = "resnet18_alzheimer_best.pth"
model.load_state_dict(torch.load(model_path, map_location=device))
model.to(device)
model.eval()
# Preprocessing transforms (ImageNet standard)
transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]
)
])
classes = [
"Mild Dementia",
"Moderate Dementia",
"Non Demented",
"Very Mild Dementia"
]
# Run prediction
img = Image.open("sample_brain_mri.png").convert("RGB")
tensor = transform(img).unsqueeze(0).to(device)
with torch.no_grad():
logits = model(tensor)
probs = torch.softmax(logits, dim=1)[0].cpu().numpy()
pred_idx = torch.argmax(logits, dim=1).item()
print(f"Top Prediction: {classes[pred_idx]} ({probs[pred_idx]*100:.2f}%)")
print("\nClass Probabilities:")
for label, p in zip(classes, probs):
print(f" β’ {label:20s}: {p*100:.2f}%")
# Strip the final classification layer to extract 512-d feature vectors
feature_extractor = nn.Sequential(*list(model.children())[:-1])
feature_extractor.eval()
with torch.no_grad():
# Returns shape: (1, 512)
embedding = feature_extractor(tensor).squeeze().cpu().numpy()
print(f"Extracted embedding dimension: {embedding.shape}")
# You can now compute cosine similarity against a database of MRI scans!
| Hyperparameter | Configuration |
|---|---|
| Dataset Size | 86,437 total images |
| Train / Validation Split | 80% (69,149 images) / 20% (17,288 images), seeded at 42 |
| Batch Size | 32 (optimized for GPU memory throughput) |
| Optimizer | AdamW(lr=1e-3, weight_decay=1e-4) |
| Learning Rate Schedule | ReduceLROnPlateau(mode='max', patience=2, factor=0.5) |
| Loss Function | CrossEntropyLoss(label_smoothing=0.1) |
| Sampling Technique | WeightedRandomSampler (inverse class frequency balancing) |
| Data Augmentation | RandomRotation(degrees=10), RandomHorizontalFlip(p=0.5) |
WeightedRandomSampler to boost minority-class detection sensitivity.If you use this model or its weights in your research or application, please cite:
@misc{alzheimers_mri_resnet18,
title={Alzheimer's Disease MRI Multi-Stage Classifier and Feature Extractor using ResNet-18},
author={Alzheimer's Early Detection AI Team},
year={2026},
publisher={Hugging Face},
howpublished={\url{https://huggingface.co}}
}
Made with β€οΈ for neuroscience and early Alzheimer's awareness.