GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — GitHub - Ejihand/Auditable-CKD-Risk-Pipeline: A comprehensive, auditable machine learning pipeline for Chronic Kidney Disease (CKD) risk prediction with full traceability, explainability, and regulatory compliance. This project demonstrates end-to-end clinical AI evaluation practices, from data quality validation and model training to explainability assessment and production monitoring.

BranchesTags
Open more actions menu

Latest commit

 

History

1 Commit
1 Commit

Folders and files

NameName
Last commit message
Last commit date
data
data
 
 
.gitignore
.gitignore
 
 
.gitkeep
.gitkeep
 
 
README.md
README.md
 
 
REPORT_INTERPRETATION_GUIDE.md
REPORT_INTERPRETATION_GUIDE.md
 
 
app.py
app.py
 
 
drift_detector.py
drift_detector.py
 
 
explain_model.py
explain_model.py
 
 
explain_model.sh
explain_model.sh
 
 
generate_test_datasets.py
generate_test_datasets.py
 
 
requirements.txt
requirements.txt
 
 
run_dashboard.sh
run_dashboard.sh
 
 
schema_validator.py
schema_validator.py
 
 
train_ckd_classifier.py
train_ckd_classifier.py
 
 
train_ckd_classifier.sh
train_ckd_classifier.sh
 
 
tune_hyperparameters.py
tune_hyperparameters.py
 
 
tune_hyperparameters.sh
tune_hyperparameters.sh
 
 
view_deepchecks_report.sh
view_deepchecks_report.sh
 
 

Repository files navigation

Auditable CKD Risk Pipeline

A comprehensive, auditable machine learning pipeline for Chronic Kidney Disease (CKD) risk prediction with full traceability, explainability, and regulatory compliance. This project demonstrates end-to-end clinical AI evaluation practices, from data quality validation and model training to explainability assessment and production monitoring. Designed for healthcare applications where safety, interpretability, and regulatory compliance are critical.

Portfolio Focus: Clinical AI Evaluation Engineering - Validating, testing, and monitoring ML models for safe clinical deployment with full auditability.

Overview

This repository demonstrates Clinical AI Evaluation Engineering practices through a complete evaluation framework for CKD risk prediction. The system showcases industry-standard evaluation methodologies for validating, testing, and monitoring ML models in clinical settings.

Evaluation Framework Components

  • Data Quality Evaluation: Schema validation and statistical drift detection for data quality assurance
  • Model Performance Evaluation: Comprehensive training pipeline with cross-validation and hyperparameter optimization
  • Explainability Evaluation: SHAP and LIME analysis for model interpretability assessment
  • Clinical Safety Evaluation: Input validation, range checking, and error handling for safe deployment
  • Production Monitoring: Continuous drift detection and model reliability monitoring
  • Regulatory Compliance: Documentation and explainability features aligned with FDA/CE marking requirements

Clinical AI Evaluation Practices Demonstrated

  • Pre-deployment Validation: Data schema validation, model performance metrics, and explainability assessment
  • Post-deployment Monitoring: Drift detection, model reliability tracking, and continuous evaluation
  • Safety & Compliance: Human-in-the-Loop AI design, clinical input validation, and regulatory documentation
  • Interpretability Assessment: SHAP/LIME explanations for clinical decision support and trust building

The system follows Human-in-the-Loop AI design principles, ensuring that doctors remain in control of clinical decisions while leveraging AI for data-driven insights. All evaluation components are designed with clinical safety, regulatory compliance (FDA/CE marking), and interpretability assessment in mind.

Features

Core Components

  • šŸ“Š Data Validation & Monitoring:

    • Schema validation using pandera for data structure and type checking
    • Automated drift detection using deepchecks to monitor production data
    • Comprehensive HTML reports with visualizations and statistical analysis
  • šŸ¤– Machine Learning Pipeline:

    • XGBoost classifier training with clinical label generation
    • SMOTE oversampling for handling class imbalance
    • Bayesian hyperparameter optimization with Optuna
    • Comprehensive model evaluation with precision, recall, F1-score
  • šŸ”¬ Explainable AI (XAI):

    • SHAP (SHapley Additive exPlanations) for feature contribution analysis
    • LIME (Local Interpretable Model-agnostic Explanations) for local explanations
    • Global and local interpretability for both model behavior and individual predictions
  • šŸ’» Interactive Dashboard:

    • Streamlit web application for real-time CKD risk assessment
    • Plotly gauge charts for visual risk display
    • Real-time SHAP and LIME explanations
    • Customizable input fields for future feature expansion
  • šŸ“š Educational Content:

    • Extensive documentation explaining ML concepts in clinical context
    • Human-in-the-Loop AI design principles
    • Clinical safety and regulatory compliance guidance
    • Best practices for medical AI deployment

Key Highlights

  • Clinical Safety: Input validation, range checking, and error handling
  • Regulatory Compliance: Explainability features meet FDA/CE marking requirements
  • Production-Ready: Drift detection and monitoring for continuous reliability
  • User-Friendly: Helper scripts and clear documentation for easy execution
  • Educational: Comprehensive comments and explanations throughout codebase

Installation

  1. Clone this repository or download the script

  2. Create a virtual environment (recommended):

# Using uv (recommended)
uv venv

# Or using venv
python -m venv .venv
  1. Activate the virtual environment:
# On Linux/macOS
source .venv/bin/activate

# On Windows (PowerShell)
.venv\Scripts\Activate.ps1

# On Windows (Command Prompt)
.venv\Scripts\activate.bat
  1. Install dependencies:
# Using uv
uv pip install -r requirements.txt

# Or using pip
pip install -r requirements.txt
  1. To deactivate the virtual environment when you're done:
deactivate

Execution Order

Follow these steps in order to build and deploy the CKD prediction system:

Quick Start Guide

1. Installation (Setup)
   ↓
2. Prepare Data
   ↓
3. Schema Validation (Optional but Recommended)
   ↓
4. Train Model
   ↓
5. Hyperparameter Tuning (Optional but Recommended)
   ↓
6. Model Explainability
   ↓
7. Interactive Dashboard (For Real-time Predictions)
   ↓
8. Drift Detection (For Production Monitoring)

Quick Reference Table

Step Script/Command Purpose Required? Output
1 python generate_test_datasets.py Generate test data Optional CSV files in data/
2 python schema_validator.py Validate data structure Recommended Validation report
3 ./train_ckd_classifier.sh Train XGBoost model Required Model in models/
4 ./tune_hyperparameters.sh Optimize hyperparameters Recommended Optimized model
5 ./explain_model.sh --shap --lime Generate explanations Recommended SHAP/LIME plots
6 ./run_dashboard.sh Launch web dashboard Optional Web interface
7 python drift_detector.py Monitor data drift For production Drift reports

Note: Steps 3-5 are the core workflow. Steps 1-2 prepare data, Step 6 is for interactive use, and Step 7 is for production monitoring.


Step-by-Step Execution Guide

Step 1: Prepare Your Data

Purpose: Ensure you have properly formatted CSV files with the required features.

Action: Create or obtain CSV files with the following 7 columns:

  • age (integer, 18-120)
  • sodium (float, 130-150 mmol/L)
  • potassium (float, 3.0-6.0 mmol/L)
  • chloride (float, 95-110 mmol/L)
  • bicarbonate (float, 15-32 mmol/L)
  • urea (float, 2.0-15.0 mmol/L)
  • creatinine (float, 0.5-5.0 mg/dL)

Required Files:

  • data/training_dataset.csv: Training data for model development
  • data/new_production_dataset.csv: Production data for drift detection (Step 8)

Generate Test Data (if needed):

python generate_test_datasets.py

Step 2: Schema Validation (Optional but Recommended)

Purpose: Validate data structure and quality before model training.

Command:

python schema_validator.py

What it does:

  • āœ… Checks that all required columns are present
  • āœ… Validates data types (integers for age, floats for lab values)
  • āœ… Ensures values are within clinical ranges
  • āœ… Catches data quality issues early

Example Output:

======================================================================
Validating Training Dataset: data/training_dataset.csv
======================================================================
āœ… Schema validation passed - data structure and types are correct
   Validated 1000 rows

Why Run This First?

  • Fast: Runs in milliseconds (vs seconds for model training)
  • Catches 80% of data quality issues: Missing columns, wrong types, impossible values
  • Prevents pipeline failures: Stops errors before they crash your model
  • Clinical safety: Rejects invalid clinical values (e.g., negative creatinine, age 200)

When to Skip: If you're confident your data is clean and properly formatted.


Step 3: Train CKD Prediction Model

Purpose: Train an XGBoost classifier to predict CKD from clinical lab values.

Command:

# Recommended: Use the helper script (handles Python path automatically)
./train_ckd_classifier.sh

Alternative methods (if helper script doesn't work):

# Option 2: Direct Python execution (only if packages are installed in venv)
python train_ckd_classifier.py

# Option 3: With PYTHONPATH set (if packages are in user site-packages)
PYTHONPATH=/home/ejiaka/.local/lib/python3.10/site-packages:$PYTHONPATH python train_ckd_classifier.py

What it does:

  1. Loads training data from data/training_dataset.csv
  2. Generates CKD labels using clinical thresholds (creatinine, eGFR, urea)
  3. Applies SMOTE to handle class imbalance
  4. Trains XGBoost classifier on balanced data
  5. Evaluates model with comprehensive metrics
  6. Saves model and metadata to models/ directory

Output Files:

  • models/ckd_xgboost_model_*.pkl: Trained model (saved with joblib)
  • models/ckd_xgboost_model_metadata_*.json: Model metadata and parameters
  • reports/classification_report_*.txt: Detailed evaluation metrics

Example Output:

Label distribution:
  Healthy (0): 448 (44.8%)
  CKD (1): 552 (55.2%)

Classification Report:
              precision    recall  f1-score   support
     Healthy       0.98      0.96      0.97        90
         CKD       0.96      0.98      0.97       110

Note: If you get ModuleNotFoundError: No module named 'imblearn', see the Troubleshooting section below.

Key Concepts Explained in Code:

  • Accuracy Paradox: Why high accuracy can be misleading in imbalanced medical datasets
  • SMOTE Algorithm: How synthetic oversampling works to balance classes
  • Precision vs Recall Trade-off: Clinical implications of false positives vs false negatives

Step 4: Hyperparameter Tuning (Optional but Recommended)

Purpose: Optimize XGBoost hyperparameters for better performance.

Command:

# Option 1: Using the helper script (recommended)
./tune_hyperparameters.sh

# Option 2: Direct Python execution (if packages are in venv)
python tune_hyperparameters.py

# Option 3: With PYTHONPATH set (if packages are in user site-packages)
PYTHONPATH=/home/ejiaka/.local/lib/python3.10/site-packages:$PYTHONPATH python tune_hyperparameters.py

What it does:

  1. Optimizes hyperparameters: learning_rate, max_depth, n_estimators
  2. Uses Bayesian optimization (more efficient than grid search)
  3. Performs 5-fold cross-validation for robust evaluation
  4. Maximizes ROC-AUC for best classification performance
  5. Saves best model with optimized parameters

Output Files:

  • models/ckd_xgboost_optimized_*.pkl: Best model with optimized hyperparameters
  • models/ckd_xgboost_optimized_metadata_*.json: Optimization results and best parameters
  • reports/optuna_summary_*.txt: Summary of optimization trials

Example Output:

Best Cross-Validation ROC-AUC: 0.9987
Best Hyperparameters:
  learning_rate: 0.0357
  max_depth: 10
  n_estimators: 233
Test Set ROC-AUC: 0.9950

Note: Hyperparameter tuning can take 10-30 minutes depending on number of trials (default: 50). Reduce N_TRIALS in the script for faster testing.

When to Skip: If you're satisfied with the baseline model performance from Step 3.

Key Concepts Explained in Code:

  • Bayesian Optimization: How Optuna intelligently searches hyperparameter space
  • Grid Search vs Bayesian: Why Bayesian optimization is more efficient
  • max_depth and Overfitting: How tree depth affects model generalization

Step 5: Model Explainability (SHAP and LIME)

Purpose: Generate interpretable explanations for individual patient predictions.

Command:

# Option 1: Using the helper script (recommended) - Generate both SHAP and LIME
./explain_model.sh --shap --lime

# Option 2: Generate only SHAP explanations
./explain_model.sh --shap

# Option 3: Generate only LIME explanations
./explain_model.sh --lime

# Option 4: Specify patient index for local explanations
./explain_model.sh --shap --lime --patient-index 5

# Option 5: Specify custom model path
./explain_model.sh --shap --lime --model-path models/custom_model.pkl

What it does:

  1. Loads trained model (defaults to latest optimized model)
  2. Calculates SHAP values for test set
  3. Generates SHAP plots:
    • Summary Plot: Global feature importance across all patients
    • Waterfall Plot: Local explanation for one specific patient
  4. Generates LIME explanation: Local linear approximation for one patient
  5. Saves plots in both PNG and PDF formats

Output Files:

  • reports/explainability/shap_summary_plot_*.png/pdf: Global feature importance
  • reports/explainability/shap_waterfall_plot_patient*_*.png/pdf: Local SHAP explanation
  • reports/explainability/lime_explanation_patient*_*.png/pdf: Local LIME explanation

Example Output:

SHAP Explanation for Patient 0:
  Creatinine: +0.35 (biggest contributor)
  Urea: +0.15
  Age: +0.05
  ...

LIME Explanation for Patient 0:
  1.18 < creatinine <= 1.57: +0.5422
  4.10 < urea <= 5.38: -0.1120
  ...
Predicted Probability (CKD): 0.9978

Key Concepts Explained in Code:

  • Game Theory Origin: How Shapley values from cooperative game theory apply to ML
  • SHAP Color Interpretation: What red/blue colors mean in summary plots
  • Why Global Importance is Insufficient: Why we need local explanations for individual patients
  • LIME Algorithm: How local linear approximations work

Clinical Significance:

  • Trust: Doctors understand why model made a specific prediction
  • Debugging: Identify when model uses wrong features
  • Personalized Care: Understand which factors matter for THIS patient
  • Regulatory Compliance: Demonstrate interpretability (FDA/CE marking requirement)

Step 6: Interactive Dashboard (For Real-time Predictions)

Purpose: Launch an interactive web application for real-time CKD risk assessment.

Command:

# Option 1: Using the helper script (recommended)
./run_dashboard.sh

# Option 2: Direct Streamlit command
streamlit run app.py

The dashboard will automatically open in your default web browser at http://localhost:8501.

Prerequisites:

  • Must have completed Steps 3-5 (at minimum Step 3) to have a trained model

What it does:

  1. Interactive Patient Input: Enter lab values via sidebar form
  2. Real-time Risk Prediction: Get instant CKD probability (0-100%)
  3. Visual Risk Display: Plotly gauge chart showing risk level
  4. SHAP Explanations: Waterfall plot showing feature contributions
  5. LIME Explanations: Local interpretable model explanation
  6. Model Selection: Choose which trained model to use
  7. Custom Input Fields: Optional fields for future feature expansion

Key Features:

  • Tabbed Interface: Patient Input, Risk Assessment, Explanations
  • Input Validation: Automatic range checking with clinical reference ranges
  • Customizable Input Fields: Optional fields for data collection (up to 5 fields)
  • Model Selection: Dropdown to select from available trained models
  • Educational Content: Human-in-the-Loop AI explanations and confidence score guidance

Example Workflow:

  1. Select model from dropdown (defaults to latest optimized model)
  2. Enter patient lab values in sidebar
  3. (Optional) Enable custom fields to collect additional data
  4. Click "Assess Risk" button
  5. View results in tabs:
    • Risk Assessment Tab: Gauge chart showing CKD risk percentage
    • Explanations Tab: SHAP waterfall plot and LIME explanation

Note: The dashboard requires a trained model to function. Make sure you've completed Steps 3-5 before using the dashboard.


Step 7: Drift Detection (For Production Monitoring)

Purpose: Monitor data drift between training and production datasets.

Command:

  1. Open drift_detector.py and modify the configuration section at the top if needed:
TRAINING_CSV_PATH = "data/training_dataset.csv"  # Your training data path
PRODUCTION_CSV_PATH = "data/new_production_dataset.csv"  # Your production data path
OUTPUT_REPORT_PATH = "reports"  # Where to save HTML reports
TARGET_COLUMN = None  # Optional: name of your target/label column
  1. Run the drift detection:
python drift_detector.py

What it does:

  • Compares training dataset with production dataset
  • Detects covariate shift (feature drift)
  • Generates comprehensive HTML reports with visualizations
  • Provides statistical test results and recommendations

Output Files:

  1. Text Summary (drift_summary_*.txt) - Always works, no dependencies
  2. Standalone HTML Report (drift_report_standalone_*.html) - Works offline
  3. Deepchecks HTML Report (drift_report_*.html) - Full-featured with interactive visualizations (requires internet)

Viewing Reports:

Standalone HTML Report (Recommended for offline use):

# Double-click the file, or:
xdg-open reports/drift_report_standalone_*.html

Deepchecks HTML Report (Full features):

  1. Start an HTTP server:
    cd reports
    python3 -m http.server 8000
  2. Open in browser: http://localhost:8000/drift_report_YYYYMMDD_HHMMSS.html
  3. Or use helper script:
    ./view_deepchecks_report.sh

Important Notes:

  • āœ… DO use: http://localhost:8000/...
  • āŒ DON'T use: file:///... (won't work due to browser security restrictions)
  • The deepchecks report requires an internet connection to load CDN resources

When to Run:

  • After deploying model to production
  • Regularly (weekly/monthly) to monitor data quality
  • When you suspect data distribution changes

Understanding the Results

šŸ“– For a comprehensive guide on interpreting reports, see REPORT_INTERPRETATION_GUIDE.md

Quick Reference: Drift Scores

  • Low scores (< 0.2): āœ… Minimal drift detected - feature distribution is stable
  • Medium scores (0.2 - 0.5): āš ļø Moderate drift - investigate the cause
  • High scores (> 0.5): 🚨 Significant drift - consider retraining your model

Types of Drift

The script detects Covariate Shift (feature drift), which occurs when:

  • The distribution of input features P(X) changes between training and production
  • But the relationship P(X|Y) between features and target remains the same

Example: Your model was trained on data from Hospital A, but production data comes from Hospital B with different patient demographics.


Additional Information

Schema Validation vs Statistical Validation

This project implements two complementary validation layers:

1. Schema Validation (Pandera) - First Line of Defense

What it checks:

  • Data structure (all required columns present)
  • Data types (integers vs floats, no strings where numbers expected)
  • Value ranges (age 0-120, creatinine > 0)
  • Missing values

When it runs: FIRST - Before any processing

Speed: Very fast (milliseconds)

Use: python schema_validator.py

2. Statistical Validation (DeepChecks) - Second Layer

What it checks:

  • Distribution shifts (drift)
  • Statistical anomalies
  • Pattern changes
  • Correlation changes

When it runs: SECOND - After schema validation passes (Step 7)

Speed: Slower (seconds to minutes)

Use: python drift_detector.py

Recommended Validation Pipeline

1. Schema Validation (Pandera) → Fast, catches structure/type issues
   ↓ (if passes)
2. Statistical Validation (DeepChecks) → Slower, catches distribution issues
   ↓ (if passes)
3. Model Inference → Only if both validations pass

Train an XGBoost classifier to predict CKD from clinical lab values:

# Recommended: Use the helper script (handles Python path automatically)
./train_ckd_classifier.sh

Why use the helper script?

  • Automatically sets up the correct Python path
  • Works regardless of where packages are installed (venv or user site-packages)
  • No need to manually configure PYTHONPATH
  • Simplest and most reliable method

Alternative methods (if helper script doesn't work):

# Option 2: Direct Python execution (only if packages are installed in venv)
python train_ckd_classifier.py

# Option 3: With PYTHONPATH set (if packages are in user site-packages)
PYTHONPATH=/home/ejiaka/.local/lib/python3.10/site-packages:$PYTHONPATH python train_ckd_classifier.py

Note: If you get ModuleNotFoundError: No module named 'imblearn', see the Troubleshooting section below.

This script will:

  1. Load training data from data/training_dataset.csv
  2. Generate CKD labels using clinical thresholds (creatinine, eGFR, urea)
  3. Apply SMOTE to handle class imbalance
  4. Train XGBoost classifier on balanced data
  5. Evaluate model with comprehensive metrics
  6. Save model and metadata to models/ directory

Output Files:

  • models/ckd_xgboost_model_*.pkl: Trained model (saved with joblib)
  • models/ckd_xgboost_model_metadata_*.json: Model metadata and parameters
  • reports/classification_report_*.txt: Detailed evaluation metrics

Key Features:

  • Clinical Label Generation: Automatically creates binary labels (CKD/Healthy) based on clinical thresholds
  • SMOTE Oversampling: Handles class imbalance by creating synthetic minority samples
  • Comprehensive Evaluation: Generates precision, recall, F1-score, and confusion matrix
  • Educational Content: Explains why accuracy is misleading in medical ML and the precision/recall trade-off

Example Output:

Label distribution:
  Healthy (0): 448 (44.8%)
  CKD (1): 552 (55.2%)

Classification Report:
              precision    recall  f1-score   support
     Healthy       0.98      0.96      0.97        90
         CKD       0.96      0.98      0.97       110

Important Concepts Explained in Code:

  • Accuracy Paradox: Why high accuracy can be misleading in imbalanced medical datasets
  • SMOTE Algorithm: How synthetic oversampling works to balance classes
  • Precision vs Recall Trade-off: Clinical implications of false positives vs false negatives

Step 3: Hyperparameter Tuning (Optional but Recommended)

Optimize XGBoost hyperparameters using Bayesian optimization with Optuna:

# Option 1: Using the helper script (recommended)
./tune_hyperparameters.sh

# Option 2: Direct Python execution (if packages are in venv)
python tune_hyperparameters.py

# Option 3: With PYTHONPATH set (if packages are in user site-packages)
PYTHONPATH=/home/ejiaka/.local/lib/python3.10/site-packages:$PYTHONPATH python tune_hyperparameters.py

What it does:

  1. Optimizes hyperparameters: learning_rate, max_depth, n_estimators
  2. Uses Bayesian optimization: More efficient than grid search
  3. Cross-validation: 5-fold CV for robust evaluation
  4. Maximizes ROC-AUC: Optimizes for the best classification performance
  5. Saves best model: Trains and saves model with optimized parameters

Output Files:

  • models/ckd_xgboost_optimized_*.pkl: Best model with optimized hyperparameters
  • models/ckd_xgboost_optimized_metadata_*.json: Optimization results and best parameters
  • reports/optuna_summary_*.txt: Summary of optimization trials

Key Features:

  • Bayesian Optimization: Uses Optuna's TPE sampler for efficient search
  • Cross-Validation: Ensures robust evaluation and prevents overfitting
  • Educational Content: Explains Bayesian optimization vs grid search, and max_depth/overfitting relationship

Example Output:

Best Cross-Validation ROC-AUC: 0.9987
Best Hyperparameters:
  learning_rate: 0.0357
  max_depth: 10
  n_estimators: 233
Test Set ROC-AUC: 0.9950

Important Concepts Explained in Code:

  • Bayesian Optimization: How Optuna intelligently searches hyperparameter space
  • Grid Search vs Bayesian: Why Bayesian optimization is more efficient
  • max_depth and Overfitting: How tree depth affects model generalization

Note: Hyperparameter tuning can take 10-30 minutes depending on number of trials (default: 50). Reduce N_TRIALS in the script for faster testing.

Step 4: Model Explainability (SHAP and LIME)

Generate interpretable explanations for individual patient predictions:

# Option 1: Using the helper script (recommended)
./explain_model.sh --shap --lime

# Option 2: Generate both SHAP and LIME explanations
PYTHONPATH=/home/ejiaka/.local/lib/python3.10/site-packages:$PYTHONPATH python explain_model.py --shap --lime

# Option 3: Generate only SHAP explanations
./explain_model.sh --shap

# Option 4: Generate only LIME explanations
./explain_model.sh --lime

# Option 5: Specify patient index for local explanations
./explain_model.sh --shap --lime --patient-index 5

# Option 6: Specify custom model path
./explain_model.sh --shap --lime --model-path models/custom_model.pkl

What it does:

  1. Loads trained model (defaults to latest optimized model)
  2. Calculates SHAP values for test set
  3. Generates SHAP plots:
    • Summary Plot: Global feature importance across all patients
    • Waterfall Plot: Local explanation for one specific patient
  4. Generates LIME explanation: Local linear approximation for one patient
  5. Saves plots in both PNG and PDF formats

Output Files:

  • reports/explainability/shap_summary_plot_*.png/pdf: Global feature importance
  • reports/explainability/shap_waterfall_plot_patient*_*.png/pdf: Local SHAP explanation
  • reports/explainability/lime_explanation_patient*_*.png/pdf: Local LIME explanation

Key Features:

  • SHAP (SHapley Additive exPlanations): Game theory-based feature contributions
  • LIME (Local Interpretable Model-agnostic Explanations): Local linear approximations
  • Global and Local Explanations: Understand both overall model behavior and individual predictions
  • Educational Content: Explains Game Theory origin, color interpretation, and why local explanations matter

Example Output:

SHAP Explanation for Patient 0:
  Creatinine: +0.35 (biggest contributor)
  Urea: +0.15
  Age: +0.05
  ...

LIME Explanation for Patient 0:
  1.18 < creatinine <= 1.57: +0.5422
  4.10 < urea <= 5.38: -0.1120
  ...
Predicted Probability (CKD): 0.9978

Important Concepts Explained in Code:

  • Game Theory Origin: How Shapley values from cooperative game theory apply to ML
  • SHAP Color Interpretation: What red/blue colors mean in summary plots
  • Why Global Importance is Insufficient: Why we need local explanations for individual patients
  • LIME Algorithm: How local linear approximations work

Clinical Significance:

  • Trust: Doctors understand why model made a specific prediction
  • Debugging: Identify when model uses wrong features
  • Personalized Care: Understand which factors matter for THIS patient
  • Regulatory Compliance: Demonstrate interpretability (FDA/CE marking requirement)

Step 5: Kidney Risk Assessor Dashboard (Streamlit)

Launch an interactive web application for real-time CKD risk assessment:

# Option 1: Using the helper script (recommended)
./run_dashboard.sh

# Option 2: Direct Streamlit command
streamlit run app.py

The dashboard will automatically open in your default web browser at http://localhost:8501.

What it does:

  1. Interactive Patient Input: Enter lab values via sidebar form
  2. Real-time Risk Prediction: Get instant CKD probability (0-100%)
  3. Visual Risk Display: Plotly gauge chart showing risk level
  4. SHAP Explanations: Waterfall plot showing feature contributions
  5. LIME Explanations: Local interpretable model explanation
  6. Model Selection: Choose which trained model to use
  7. Custom Input Fields: Optional fields for future feature expansion

Key Features:

  • Tabbed Interface:

    • Patient Input Tab: View all entered lab values and custom fields
    • Risk Assessment Tab: Gauge chart, risk category, and clinical interpretation
    • Explanations Tab: SHAP waterfall plot and LIME explanation side-by-side
  • Input Validation:

    • Automatic range checking for all lab values
    • Clinical reference ranges displayed
    • Color-coded validation (green=normal, yellow=borderline, red=abnormal)
    • Helpful tooltips with clinical context
  • Customizable Input Fields:

    • Enable/disable custom fields via checkbox
    • Add up to 5 custom fields (name, value, unit)
    • Custom fields stored for data collection (not used in prediction)
    • Useful for future model expansion or research data collection
  • Model Selection:

    • Dropdown to select from available trained models
    • Automatically finds latest optimized model by default
    • Displays model metadata (training date, performance metrics)
    • Cached model loading for fast switching
  • Educational Content:

    • Human-in-the-Loop AI: Explains why doctors stay in control
    • Confidence Scores: When to trust the model vs. rely on clinical judgment
    • Explanations: Why SHAP/LIME are essential for clinical AI
    • Regulatory Compliance: How explainability meets FDA/CE marking requirements

UI Layout:

ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│  Kidney Risk Assessor                    [Model Select] │
ā”œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¤
│           │  [Tabs: Input | Results | Explanations]     │
│  SIDEBAR  │                                             │
│           │  Tab 1: Patient Input                       │
│  Age: [__]│    - Standard 7 features                    │
│  Sodium:  │    - [āœ“] Enable Custom Fields               │
│  [____]   │      └─ Custom Field 1: [Name] [Value] [Unit]│
│  ...      │    - [Assess Risk] button                  │
│           │                                             │
│  [Custom] │  Tab 2: Risk Assessment                    │
│  Fields]  │    - Plotly Gauge chart (0-100%)            │
│           │    - Risk category (Low/Moderate/High)       │
│           │    - Confidence score                       │
│           │                                             │
│           │  Tab 3: Explanations                       │
│           │    - SHAP Waterfall plot                    │
│           │    - LIME explanation                       │
│           │    - Feature contributions                  │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”“ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜

Example Workflow:

  1. Select model from dropdown (defaults to latest optimized model)
  2. Enter patient lab values in sidebar:
    • Age: 65
    • Sodium: 142 mmol/L
    • Potassium: 4.5 mmol/L
    • Chloride: 105 mmol/L
    • Bicarbonate: 22 mmol/L
    • Urea: 8.5 mmol/L
    • Creatinine: 1.8 mg/dL
  3. (Optional) Enable custom fields to collect additional data
  4. Click "Assess Risk" button
  5. View results:
    • Risk Assessment Tab: See gauge chart showing 78% CKD risk (High Risk)
    • Explanations Tab: See SHAP showing creatinine (+35%) and urea (+15%) as main contributors

Important Concepts Explained:

  • Human-in-the-Loop AI Design Principle:

    • AI provides suggestions, doctors make final decisions
    • Doctors can override AI predictions based on clinical judgment
    • AI augments, doesn't replace, clinical expertise
    • Builds trust through transparency and explanations
  • Why Show Confidence Score and Explanation:

    • Confidence Score: Tells doctors when to trust the model
      • High confidence (90-100%): Model is certain, but doctor should still review
      • Medium confidence (60-90%): Model is somewhat certain, be cautious
      • Low confidence (<60%): Model is uncertain, rely more on clinical judgment
    • Explanation: Shows which features drove the prediction
      • Transparency: Doctors see the reasoning
      • Trust: Verify reasoning matches clinical knowledge
      • Error Detection: Catch when model uses wrong features
      • Regulatory: Required for FDA/CE marking (explainability mandate)
      • Safety: Prevent blind trust in AI systems

Technical Details:

  • Uses @st.cache_resource for efficient model loading
  • Uses @st.cache_data for background data caching
  • Integrates with existing explain_model.py functions
  • Supports both TreeExplainer and KernelExplainer (automatic fallback)
  • Generates SHAP waterfall plots using matplotlib
  • Generates LIME explanations with configurable number of features

Output:

  • Real-time predictions displayed in browser
  • Interactive Plotly gauge charts
  • SHAP and LIME visualizations
  • All results displayed in the web interface (no files saved)

Note: The dashboard requires a trained model to function. Make sure you've completed Steps 3-5 before using the dashboard.


Step 7: Drift Detection (For Production Monitoring)

Purpose: Monitor data drift between training and production datasets.

Command:

  1. Open drift_detector.py and modify the configuration section at the top if needed:
TRAINING_CSV_PATH = "data/training_dataset.csv"  # Your training data path
PRODUCTION_CSV_PATH = "data/new_production_dataset.csv"  # Your production data path
OUTPUT_REPORT_PATH = "reports"  # Where to save HTML reports
TARGET_COLUMN = None  # Optional: name of your target/label column
  1. Run the drift detection:
python drift_detector.py

What it does:

  • Compares training dataset with production dataset
  • Detects covariate shift (feature drift)
  • Generates comprehensive HTML reports with visualizations
  • Provides statistical test results and recommendations

Output Files:

  1. Text Summary (drift_summary_*.txt) - Always works, no dependencies
  2. Standalone HTML Report (drift_report_standalone_*.html) - Works offline
  3. Deepchecks HTML Report (drift_report_*.html) - Full-featured with interactive visualizations (requires internet)

Viewing Reports:

Standalone HTML Report (Recommended for offline use):

# Double-click the file, or:
xdg-open reports/drift_report_standalone_*.html

Deepchecks HTML Report (Full features):

  1. Start an HTTP server:
    cd reports
    python3 -m http.server 8000
  2. Open in browser: http://localhost:8000/drift_report_YYYYMMDD_HHMMSS.html
  3. Or use helper script:
    ./view_deepchecks_report.sh

Important Notes:

  • āœ… DO use: http://localhost:8000/...
  • āŒ DON'T use: file:///... (won't work due to browser security restrictions)
  • The deepchecks report requires an internet connection to load CDN resources

When to Run:

  • After deploying model to production
  • Regularly (weekly/monthly) to monitor data quality
  • When you suspect data distribution changes

Why Drift Detection Matters in Clinical AI

  1. Patient Safety: Silent model degradation can lead to incorrect diagnoses
  2. Regulatory Compliance: FDA and CE marking require continuous monitoring
  3. Clinical Trust: Healthcare providers need reliable, consistent AI tools
  4. Early Detection: Catch issues before they cause patient harm
  5. Legal Responsibility: Documentation of monitoring is crucial for liability protection

Project Structure

explainable-ckd-engine/
ā”œā”€ā”€ schema_validator.py            # Schema validation script (Project 1.2)
ā”œā”€ā”€ drift_detector.py              # Main drift detection script (Project 1.1)
ā”œā”€ā”€ train_ckd_classifier.py         # XGBoost classifier training (Project 2)
ā”œā”€ā”€ train_ckd_classifier.sh         # Helper script to run training (recommended)
ā”œā”€ā”€ tune_hyperparameters.py         # Optuna hyperparameter optimization (Project 3)
ā”œā”€ā”€ tune_hyperparameters.sh         # Helper script to run tuning (recommended)
ā”œā”€ā”€ explain_model.py                # SHAP and LIME explainability (Project 4)
ā”œā”€ā”€ explain_model.sh                # Helper script to run explainability (recommended)
ā”œā”€ā”€ app.py                          # Streamlit dashboard (Project 5 - Capstone)
ā”œā”€ā”€ run_dashboard.sh                # Helper script to run Streamlit dashboard (recommended)
ā”œā”€ā”€ generate_test_datasets.py      # Script to generate test datasets
ā”œā”€ā”€ view_deepchecks_report.sh      # Helper script to view deepchecks HTML report
ā”œā”€ā”€ requirements.txt               # Python dependencies
ā”œā”€ā”€ README.md                      # This file
ā”œā”€ā”€ REPORT_INTERPRETATION_GUIDE.md # Comprehensive guide for interpreting reports
ā”œā”€ā”€ data/                          # Your CSV datasets
│   ā”œā”€ā”€ training_dataset.csv
│   └── new_production_dataset.csv
ā”œā”€ā”€ models/                        # Trained models (created automatically)
│   ā”œā”€ā”€ ckd_xgboost_model_*.pkl    # Trained XGBoost model
│   ā”œā”€ā”€ ckd_xgboost_model_metadata_*.json  # Model metadata
│   ā”œā”€ā”€ ckd_xgboost_optimized_*.pkl  # Optimized model (from tuning)
│   └── ckd_xgboost_optimized_metadata_*.json  # Optimization metadata
└── reports/                       # Generated reports (created automatically)
    ā”œā”€ā”€ drift_summary_*.txt        # Text summary (always works)
    ā”œā”€ā”€ drift_report_standalone_*.html  # Standalone HTML (works offline)
    ā”œā”€ā”€ drift_report_*.html        # Deepchecks HTML (requires HTTP server)
    ā”œā”€ā”€ classification_report_*.txt # Model evaluation metrics
    ā”œā”€ā”€ optuna_summary_*.txt        # Hyperparameter optimization summary
    └── explainability/              # Model explainability plots (created automatically)
        ā”œā”€ā”€ shap_summary_plot_*.png/pdf      # SHAP global importance
        ā”œā”€ā”€ shap_waterfall_plot_*.png/pdf    # SHAP local explanation
        └── lime_explanation_*.png/pdf       # LIME local explanation

Dependencies

  • pandera >= 0.18.0: Schema validation library for data structure and type checking
  • deepchecks >= 0.17.0, < 1.0.0: Data validation and drift detection library (Python 3.10 compatible)
  • xgboost >= 2.0.0: Gradient boosting classifier for CKD prediction
  • imbalanced-learn >= 0.11.0: SMOTE implementation for handling class imbalance
  • scikit-learn >= 1.3.0: Machine learning utilities (metrics, train_test_split)
  • joblib >= 1.3.0: Model serialization and persistence
  • optuna >= 3.0.0: Hyperparameter optimization framework (Bayesian optimization)
  • shap >= 0.42.0: SHAP value calculation and visualization (model explainability)
  • lime >= 0.2.0.1: LIME explanations (local interpretability)
  • matplotlib >= 3.5.0: Plotting and visualization
  • streamlit >= 1.28.0: Web application framework for interactive dashboard
  • plotly >= 5.17.0: Interactive gauge charts and visualizations
  • pandas >= 2.0.0: Data manipulation and CSV loading
  • numpy >= 1.24.0, < 2.0.0: Numerical operations (NumPy 2.0+ not compatible with deepchecks 0.x)
  • setuptools >= 65.0.0: Required for deepchecks (provides pkg_resources)
  • anywidget >= 0.5.0: Required for HTML report generation with interactive widgets

Note: Deepchecks 1.0.0+ requires Python 3.11+. For Python 3.10, use deepchecks 0.x versions.

Troubleshooting

File Not Found Error

  • Ensure CSV file paths are correct
  • Check that files exist at the specified locations
  • Use absolute paths if relative paths don't work

Column Mismatch Warning

  • Ensure both datasets have the same column names
  • Check for typos in column names
  • Remove any extra columns from one dataset if needed

Import Errors

  • Make sure all dependencies are installed: pip install -r requirements.txt
  • Check your Python version (3.8+ recommended, but Python 3.10 is required for deepchecks 0.x)
  • If pandera import fails, ensure it's installed: pip install pandera>=0.18.0

Schema Validation Errors

If schema validation fails:

  • Check error messages for specific column/range issues
  • Ensure all 7 required columns are present: age, sodium, potassium, chloride, bicarbonate, urea, creatinine
  • Verify data types match (age should be integer, others should be float)
  • Check that values are within clinical ranges (see schema_validator.py for ranges)
  • Fix data quality issues before proceeding with drift detection

Model Training Errors

If model training fails:

  • Ensure training data exists and is properly formatted
  • Check that label generation creates sufficient samples in both classes
  • Verify SMOTE parameters are appropriate for your class distribution
  • If all samples are in one class, adjust clinical thresholds in train_ckd_classifier.py
  • Ensure all dependencies are installed: pip install -r requirements.txt

If model performance is poor:

  • Review classification report for precision/recall balance
  • Consider adjusting SMOTE sampling strategy
  • Check feature importance to identify most predictive features
  • Verify clinical thresholds match your data distribution
  • Consider feature engineering or hyperparameter tuning

If you get ModuleNotFoundError: No module named 'imblearn':

  • This happens when packages are installed in user site-packages (~/.local/lib/python3.10/site-packages/) but the virtual environment can't find them
  • Solution 1 (Recommended): Use the helper script: ./train_ckd_classifier.sh
    • The helper script automatically sets PYTHONPATH to include user site-packages
    • This is the simplest solution and works in most cases
  • Solution 2: Set PYTHONPATH manually:
    export PYTHONPATH=/home/ejiaka/.local/lib/python3.10/site-packages:$PYTHONPATH
    python train_ckd_classifier.py
  • Solution 3: Install packages directly in venv (if venv has pip):
    source .venv/bin/activate
    pip install xgboost imbalanced-learn scikit-learn joblib
  • Why this happens: When pip install is run without an activated venv, or when venv's pip isn't working, packages get installed to user site-packages instead of the venv. The helper script works around this by explicitly adding user site-packages to Python's search path.

Explainability Errors

If SHAP calculation fails:

  • SHAP may automatically fall back to KernelExplainer (slower but more compatible)
  • This is normal if TreeExplainer has compatibility issues with XGBoost version
  • KernelExplainer produces the same results but takes longer
  • Reduce --shap-samples for faster execution during testing (e.g., --shap-samples 10)

If LIME explanation fails:

  • Ensure training data is available (LIME needs background distribution)
  • Check that patient index is within test set range (0 to test_size-1)
  • Verify model can make predictions: python -c "import joblib; m=joblib.load('models/ckd_xgboost_optimized_*.pkl'); print(m.predict_proba([[50,140,4,100,24,5,1]])[0])"

If plots are not generated:

  • Check that matplotlib backend is working: python -c "import matplotlib; matplotlib.use('Agg'); import matplotlib.pyplot as plt; plt.figure(); plt.savefig('test.png'); print('OK')"
  • Ensure output directory is writable: reports/explainability/
  • Check file permissions: ls -la reports/explainability/

Python Version Compatibility

  • Python 3.10: Use deepchecks >= 0.17.0, < 1.0.0 (as specified in requirements.txt)
  • Python 3.11+: Can use deepchecks >= 1.0.0 (newer versions)
  • If you encounter version conflicts, ensure your Python version matches the deepchecks requirements

HTML Report Not Displaying

If the deepchecks HTML report shows a blank page:

  1. Check you're using HTTP, not file://

    • āœ… Correct: http://localhost:8000/drift_report_*.html
    • āŒ Wrong: file:///path/to/drift_report_*.html
  2. Verify the HTTP server is running:

    # Check if server is running
    lsof -i :8000
    # Or start it:
    cd reports && python3 -m http.server 8000
  3. Check internet connection:

    • The deepchecks report needs internet to load CDN resources
    • Test: curl -I https://unpkg.com/@jupyter-widgets/[email protected]/dist/index.js
  4. Check browser console for errors:

    • Press F12 to open Developer Tools
    • Look for red error messages in the Console tab
    • Check the Network tab for failed resource loads
  5. Use the standalone HTML report instead:

    • The drift_report_standalone_*.html file works offline
    • It contains all drift scores and visualizations
    • Open it directly without needing HTTP server

Next Steps After Detecting Drift

  1. Investigate Root Causes:

    • Check for data collection changes
    • Review preprocessing pipelines
    • Examine population demographics
  2. Assess Impact:

    • Evaluate model performance on drifted data
    • Check if predictions are still reliable
  3. Take Action:

    • Retrain model with updated data if drift is significant
    • Adjust preprocessing to handle new distributions
    • Document findings for regulatory compliance
  4. Monitor Continuously:

    • Run this script regularly (e.g., weekly/monthly)
    • Set up automated alerts for high drift scores
    • Maintain a drift detection log

License

This script is provided as-is for educational and research purposes. Ensure compliance with healthcare data regulations (HIPAA, GDPR) when handling patient data.

Contributing

Feel free to submit issues or pull requests to improve this tool.

References

  • Deepchecks Documentation
  • FDA Guidance on AI/ML in Medical Devices
  • Clinical AI Safety Best Practices

About

A comprehensive, auditable machine learning pipeline for Chronic Kidney Disease (CKD) risk prediction with full traceability, explainability, and regulatory compliance. This project demonstrates end-to-end clinical AI evaluation practices, from data quality validation and model training to explainability assessment and production monitoring.

Resources

Readme
Activity

Stars

0 stars

Watchers

0 watching

Forks

0 forks
Report repository

Releases

Packages

Contributors

Languages

You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800Ɨ600. No cookies required.