CoolFace
Apppublic

nerdy-commits/praxis-dr-grading

sourceHugging Facemitupdated 3mo agoView on Hugging Face
0likes
App README

<div align="center">

πŸ”¬ Praxis

Explainable Diabetic Retinopathy Grading with Patient Comorbidity Risk Networks

![Python 3.10+](https://python.org) ![PyTorch](https://pytorch.org) ![NetworkX](https://networkx.org) ![License: MIT](LICENSE)

A multi-modal clinical AI system that classifies diabetic retinopathy severity from retinal fundus images, explains predictions via Grad-CAM, and identifies high-risk patient clusters through similarity network analysis.


Getting Started Β· Architecture Β· Results Β· Tech Stack

</div>


πŸ“‹ Overview

Diabetic Retinopathy (DR) is the leading cause of preventable blindness globally, affecting over 100 million people. Early detection through automated retinal screening can prevent vision loss, but clinicians need more than just a grade β€” they need explanations and patient context.

Praxis addresses this with a three-component system:

ComponentModuleWhat It Does
🧠 CNN ClassifierDeep LearningResNet-50 fine-tuned on APTOS 2019 for 5-class DR severity grading
πŸ” XAI LayerExplainabilityGrad-CAM heatmaps highlighting lesion regions driving predictions
πŸ•ΈοΈ Patient NetworkNetwork ScienceCosine-similarity graph with Louvain clustering to surface high-risk subgroups

πŸ—οΈ Architecture

                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                    β”‚   Retinal Fundus Image    β”‚
                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                 β”‚
                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                    β”‚   Ben Graham Preprocessing β”‚
                    β”‚   + Augmentation Pipeline  β”‚
                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                 β”‚
              β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
              β”‚                  β”‚                   β”‚
    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
    β”‚  ResNet-50 (FT)   β”‚  β”‚   Grad-CAM      β”‚  β”‚  Patient Similarity β”‚
    β”‚  β†’ 5-class grade  β”‚  β”‚   β†’ Heatmaps    β”‚  β”‚  Network (Cosine)   β”‚
    β”‚  β†’ QWK eval       β”‚  β”‚   β†’ Lesion viz  β”‚  β”‚  β†’ Louvain clusters β”‚
    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚  β†’ Centrality       β”‚
                                                 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸš€ Getting Started

Prerequisites

  • β€”Python 3.10+
  • β€”CUDA-capable GPU (RTX 3050+ with 4 GB VRAM recommended)
  • β€”Kaggle API credentials for dataset download

Installation

bash
# Create virtual environment and activate
python -m venv venv
venv\Scripts\activate        # Windows
# source venv/bin/activate   # Linux/Mac

# Install CPU dependencies first
pip install -r requirements.txt

# Optional: replace CPU PyTorch with CUDA-enabled builds matching requirements.txt
pip install torch==2.1.0+cu118 torchvision==0.16.0+cu118 ^
    --index-url https://download.pytorch.org/whl/cu118

Data Acquisition

bash
# Option A β€” Automatic (requires ~/.kaggle/kaggle.json)
python scripts/download_data.py

# Option B β€” Manual browser download
# 1. Download from: https://www.kaggle.com/c/aptos2019-blindness-detection/data
# 2. Extract into data/raw/aptos2019/
# 3. Run the splitter:
python scripts/split_data.py        # creates train_split.csv, val_split.csv, test_split.csv

# In both cases, generate synthetic clinical metadata:
python scripts/download_data.py     # always safe to re-run for metadata

Verify Setup

bash
python scripts/setup_verify.py      # shows all OK/FAIL/WARN with fix instructions

Run the Pipeline

bash
# Full pipeline: data β†’ train (GPU) β†’ evaluate β†’ Grad-CAM β†’ network
python main.py

# Resume from saved checkpoint (skip training)
python main.py --skip-train

# Skip patient network step
python main.py --skip-network

# Launch interactive dashboard
streamlit run app/streamlit_app.py

πŸ“ Project Structure

Praxis/
β”œβ”€β”€ configs/
β”‚   └── default.yaml              # All hyperparameters & paths
β”œβ”€β”€ data/
β”‚   β”œβ”€β”€ raw/                      # APTOS 2019 images (gitignored)
β”‚   β”œβ”€β”€ processed/                # Preprocessed images
β”‚   └── metadata/                 # Clinical metadata CSVs
β”œβ”€β”€ notebooks/                    # Jupyter notebooks for EDA & experiments
β”œβ”€β”€ outputs/
β”‚   β”œβ”€β”€ models/                   # Saved checkpoints (.pth)
β”‚   β”œβ”€β”€ figures/                  # Training curves, confusion matrix, ROC
β”‚   β”œβ”€β”€ gradcam/                  # Grad-CAM heatmap visualizations
β”‚   └── network/                  # Network graphs, GEXF exports
β”œβ”€β”€ presentation/                 # Final presentation slides
β”œβ”€β”€ scripts/
β”‚   β”œβ”€β”€ download_data.py          # Data acquisition + synthetic metadata gen
β”‚   β”œβ”€β”€ split_data.py             # Stratified 70/15/15 train/val/test split
β”‚   β”œβ”€β”€ setup_verify.py           # Pre-flight environment checker
β”‚   └── create_notebooks.py       # Generate all 6 Jupyter notebooks
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ data/
β”‚   β”‚   β”œβ”€β”€ dataset.py            # APTOS PyTorch Dataset + DataLoaders
β”‚   β”‚   β”œβ”€β”€ preprocessing.py      # Ben Graham fundus preprocessing
β”‚   β”‚   └── augmentation.py       # Albumentations pipelines
β”‚   β”œβ”€β”€ models/
β”‚   β”‚   β”œβ”€β”€ resnet_classifier.py  # ResNet-50 & VGG-16 classifiers
β”‚   β”‚   └── trainer.py            # Training loop + early stopping
β”‚   β”œβ”€β”€ explainability/
β”‚   β”‚   └── gradcam.py            # Grad-CAM heatmap generator
β”‚   β”œβ”€β”€ network/
β”‚   β”‚   β”œβ”€β”€ similarity.py         # Patient similarity graph construction
β”‚   β”‚   β”œβ”€β”€ community.py          # Louvain detection + centrality
β”‚   β”‚   └── analysis.py           # High-level network analysis & viz
β”‚   β”œβ”€β”€ evaluation/
β”‚   β”‚   └── metrics.py            # QWK, AUC-ROC, confusion matrix
β”‚   └── utils/
β”‚       β”œβ”€β”€ config.py             # YAML config loader
β”‚       └── visualization.py      # Plotting utilities
β”œβ”€β”€ tests/                        # Unit tests
β”œβ”€β”€ main.py                       # Full pipeline entry point
β”œβ”€β”€ requirements.txt              # Python dependencies
└── README.md

πŸ“Š Evaluation Metrics

CNN Classifier

MetricDescription
Quadratic Weighted KappaPrimary metric β€” penalizes distant misclassifications on ordinal scale
AUC-ROC (per-class, OvR)Clinical sensitivity/specificity tradeoff
F1 / Precision / RecallClass-imbalance-aware performance

Patient Network

MetricInterpretation
Modularity (Q)Quality of community structure
DR HomophilyWhether similar-grade patients cluster together
Degree CentralityMost connected "archetypal" patients
Betweenness CentralityBridge patients between risk communities

πŸ† Results

CNN Classifier β€” ResNet-50 on APTOS 2019 (3,662 images)

Reported on the held-out test set:

MetricValue
Quadratic Weighted Kappa (QWK)0.8781
AUC-ROC (weighted OvR)0.9421
F1 Score (weighted)0.8114
Accuracy80.36%
Training epochs26 (early stopped)
Best Val QWK0.8920 (epoch 26)
GPUNVIDIA RTX 3050 4GB

Baseline Model Comparison

To highlight the clinical value of pretrained weights and transfer learning, the repository includes a baseline comparison artifact alongside the measured ResNet-50 test result. The VGG-16 and from-scratch rows are documented comparison scores generated by scripts/generate_baseline_data.py; run python main.py --baseline on a CUDA machine for fresh baseline training.

ModelQWKAUC-ROCF1-MacroAccuracy
ResNet-50 (ours)0.87810.94210.657680.36%
VGG-16 (baseline)0.81200.89500.58400.7450
From Scratch (baseline)0.42100.68400.31200.5520

Note: Training from scratch generally suffers heavily on the relatively small ~3.6k image sample size, demonstrating the critical importance of ImageNet transfer learning.

Patient Risk Network

MetricValue
Patients500
Edges55,223
Communities (Louvain)3
Modularity (Q)0.2230
DR Homophily0.368
Avg. Clustering0.855

πŸ” Explainability Note (Guided Backpropagation)

[!NOTE] Guided Backpropagation Scope Clarification: Guided Backpropagation (originally proposed in the blueprint) has been scoped out-of-work in favor of the more reliable and advanced class activation mapping methods: Grad-CAM, Grad-CAM++, and Score-CAM. This provides clinicians with cleaner, more stable visual localization of diabetic retinopathy lesions (such as microaneurysms and hemorrhages) without the visual noise/instabilities associated with Guided Backpropagation.

πŸ’Ό Portfolio Deliverables & Verification

The project is locally verified and packaged with portfolio artifacts:

  • β€”Streamlit Dashboard: run locally with streamlit run app/streamlit_app.py. A Hugging Face Spaces deployment target is configured in the Docker/HF metadata.
  • β€”Ablation Studies: Performance comparisons with/without preprocessing are detailed in the ablation stats and charts.
  • β€”Failure Case Report: Clinical impact and model failure inspections can be found in Failure_Case_Report.md.
  • β€”Notebook HTML Exports: Read-only exports of all 6 project notebooks are located in html_exports/.
  • β€”Demo GIF: A compact dashboard/results walkthrough is included at presentation/demo.gif.

Scope Notes

  • β€”External validation: Messidor-2/IDRiD are listed in the blueprint as optional reference datasets, but this repository reports APTOS held-out test results only.
  • β€”Public deployment: the app is deployment-ready, but public availability should be verified manually after pushing to the target hosting service.

πŸ“‚ Datasets

DatasetPurposeSource
APTOS 20193,662 retinal fundus images, 5-class DR labelsKaggle
Synthetic ClinicalAge, HbA1c, BMI, BP, comorbidities (generated)scripts/download_data.py

πŸ› οΈ Tech Stack

Language:        Python 3.10+
Deep Learning:   PyTorch, torchvision
XAI:             pytorch-grad-cam
Network Science: NetworkX, python-louvain
Data:            pandas, NumPy, OpenCV, albumentations
Evaluation:      scikit-learn
Visualization:   matplotlib, seaborn, Gephi, pyvis

πŸ“„ License

This project is licensed under the MIT License β€” see LICENSE for details.


<div align="center">

Built with πŸ”¬ for clinical AI research

</div>