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.
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.
- 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
- 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.
-
š Data Validation & Monitoring:
- Schema validation using
panderafor data structure and type checking - Automated drift detection using
deepchecksto monitor production data - Comprehensive HTML reports with visualizations and statistical analysis
- Schema validation using
-
š¤ 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
- 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
-
Clone this repository or download the script
-
Create a virtual environment (recommended):
# Using uv (recommended) uv venv # Or using venv python -m venv .venv
- 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
- Install dependencies:
# Using uv uv pip install -r requirements.txt # Or using pip pip install -r requirements.txt
- To deactivate the virtual environment when you're done:
deactivate
Follow these steps in order to build and deploy the CKD prediction system:
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)
| 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.
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 developmentdata/new_production_dataset.csv: Production data for drift detection (Step 8)
Generate Test Data (if needed):
python generate_test_datasets.py
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.
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.shAlternative 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:
- Loads training data from
data/training_dataset.csv - Generates CKD labels using clinical thresholds (creatinine, eGFR, urea)
- Applies SMOTE to handle class imbalance
- Trains XGBoost classifier on balanced data
- Evaluates model with comprehensive metrics
- 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 parametersreports/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
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:
- Optimizes hyperparameters:
learning_rate,max_depth,n_estimators - Uses Bayesian optimization (more efficient than grid search)
- Performs 5-fold cross-validation for robust evaluation
- Maximizes ROC-AUC for best classification performance
- Saves best model with optimized parameters
Output Files:
models/ckd_xgboost_optimized_*.pkl: Best model with optimized hyperparametersmodels/ckd_xgboost_optimized_metadata_*.json: Optimization results and best parametersreports/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
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:
- Loads trained model (defaults to latest optimized model)
- Calculates SHAP values for test set
- Generates SHAP plots:
- Summary Plot: Global feature importance across all patients
- Waterfall Plot: Local explanation for one specific patient
- Generates LIME explanation: Local linear approximation for one patient
- Saves plots in both PNG and PDF formats
Output Files:
reports/explainability/shap_summary_plot_*.png/pdf: Global feature importancereports/explainability/shap_waterfall_plot_patient*_*.png/pdf: Local SHAP explanationreports/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)
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:
- Interactive Patient Input: Enter lab values via sidebar form
- Real-time Risk Prediction: Get instant CKD probability (0-100%)
- Visual Risk Display: Plotly gauge chart showing risk level
- SHAP Explanations: Waterfall plot showing feature contributions
- LIME Explanations: Local interpretable model explanation
- Model Selection: Choose which trained model to use
- 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:
- Select model from dropdown (defaults to latest optimized model)
- Enter patient lab values in sidebar
- (Optional) Enable custom fields to collect additional data
- Click "Assess Risk" button
- 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.
Purpose: Monitor data drift between training and production datasets.
Command:
- Open
drift_detector.pyand 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
- 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:
- Text Summary (
drift_summary_*.txt) - Always works, no dependencies - Standalone HTML Report (
drift_report_standalone_*.html) - Works offline - 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):
- Start an HTTP server:
cd reports python3 -m http.server 8000 - Open in browser:
http://localhost:8000/drift_report_YYYYMMDD_HHMMSS.html - 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
š For a comprehensive guide on interpreting reports, see REPORT_INTERPRETATION_GUIDE.md
- 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
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.
This project implements two complementary validation layers:
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
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
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.shWhy 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:
- Load training data from
data/training_dataset.csv - Generate CKD labels using clinical thresholds (creatinine, eGFR, urea)
- Apply SMOTE to handle class imbalance
- Train XGBoost classifier on balanced data
- Evaluate model with comprehensive metrics
- 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 parametersreports/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
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:
- Optimizes hyperparameters:
learning_rate,max_depth,n_estimators - Uses Bayesian optimization: More efficient than grid search
- Cross-validation: 5-fold CV for robust evaluation
- Maximizes ROC-AUC: Optimizes for the best classification performance
- Saves best model: Trains and saves model with optimized parameters
Output Files:
models/ckd_xgboost_optimized_*.pkl: Best model with optimized hyperparametersmodels/ckd_xgboost_optimized_metadata_*.json: Optimization results and best parametersreports/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.
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:
- Loads trained model (defaults to latest optimized model)
- Calculates SHAP values for test set
- Generates SHAP plots:
- Summary Plot: Global feature importance across all patients
- Waterfall Plot: Local explanation for one specific patient
- Generates LIME explanation: Local linear approximation for one patient
- Saves plots in both PNG and PDF formats
Output Files:
reports/explainability/shap_summary_plot_*.png/pdf: Global feature importancereports/explainability/shap_waterfall_plot_patient*_*.png/pdf: Local SHAP explanationreports/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)
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:
- Interactive Patient Input: Enter lab values via sidebar form
- Real-time Risk Prediction: Get instant CKD probability (0-100%)
- Visual Risk Display: Plotly gauge chart showing risk level
- SHAP Explanations: Waterfall plot showing feature contributions
- LIME Explanations: Local interpretable model explanation
- Model Selection: Choose which trained model to use
- 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:
- Select model from dropdown (defaults to latest optimized model)
- 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
- (Optional) Enable custom fields to collect additional data
- Click "Assess Risk" button
- 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
- Confidence Score: Tells doctors when to trust the model
Technical Details:
- Uses
@st.cache_resourcefor efficient model loading - Uses
@st.cache_datafor background data caching - Integrates with existing
explain_model.pyfunctions - 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.
Purpose: Monitor data drift between training and production datasets.
Command:
- Open
drift_detector.pyand 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
- 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:
- Text Summary (
drift_summary_*.txt) - Always works, no dependencies - Standalone HTML Report (
drift_report_standalone_*.html) - Works offline - 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):
- Start an HTTP server:
cd reports python3 -m http.server 8000 - Open in browser:
http://localhost:8000/drift_report_YYYYMMDD_HHMMSS.html - 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
- Patient Safety: Silent model degradation can lead to incorrect diagnoses
- Regulatory Compliance: FDA and CE marking require continuous monitoring
- Clinical Trust: Healthcare providers need reliable, consistent AI tools
- Early Detection: Catch issues before they cause patient harm
- Legal Responsibility: Documentation of monitoring is crucial for liability protection
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
pandera >= 0.18.0: Schema validation library for data structure and type checkingdeepchecks >= 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 predictionimbalanced-learn >= 0.11.0: SMOTE implementation for handling class imbalancescikit-learn >= 1.3.0: Machine learning utilities (metrics, train_test_split)joblib >= 1.3.0: Model serialization and persistenceoptuna >= 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 visualizationstreamlit >= 1.28.0: Web application framework for interactive dashboardplotly >= 5.17.0: Interactive gauge charts and visualizationspandas >= 2.0.0: Data manipulation and CSV loadingnumpy >= 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.
- Ensure CSV file paths are correct
- Check that files exist at the specified locations
- Use absolute paths if relative paths don't work
- Ensure both datasets have the same column names
- Check for typos in column names
- Remove any extra columns from one dataset if needed
- 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
panderaimport fails, ensure it's installed:pip install pandera>=0.18.0
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.pyfor ranges) - Fix data quality issues before proceeding with drift detection
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 installis 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.
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-samplesfor 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 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
If the deepchecks HTML report shows a blank page:
-
Check you're using HTTP, not file://
- ā
Correct:
http://localhost:8000/drift_report_*.html - ā Wrong:
file:///path/to/drift_report_*.html
- ā
Correct:
-
Verify the HTTP server is running:
# Check if server is running lsof -i :8000 # Or start it: cd reports && python3 -m http.server 8000
-
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
-
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
-
Use the standalone HTML report instead:
- The
drift_report_standalone_*.htmlfile works offline - It contains all drift scores and visualizations
- Open it directly without needing HTTP server
- The
-
Investigate Root Causes:
- Check for data collection changes
- Review preprocessing pipelines
- Examine population demographics
-
Assess Impact:
- Evaluate model performance on drifted data
- Check if predictions are still reliable
-
Take Action:
- Retrain model with updated data if drift is significant
- Adjust preprocessing to handle new distributions
- Document findings for regulatory compliance
-
Monitor Continuously:
- Run this script regularly (e.g., weekly/monthly)
- Set up automated alerts for high drift scores
- Maintain a drift detection log
This script is provided as-is for educational and research purposes. Ensure compliance with healthcare data regulations (HIPAA, GDPR) when handling patient data.
Feel free to submit issues or pull requests to improve this tool.
- Deepchecks Documentation
- FDA Guidance on AI/ML in Medical Devices
- Clinical AI Safety Best Practices