PyHealth: Healthcare AI Toolkit
Overview
PyHealth is a comprehensive Python library for healthcare AI that provides specialized tools, models, and datasets for clinical machine learning. Use this skill when developing healthcare prediction models, processing clinical data, working with medical coding systems, or deploying AI solutions in healthcare settings.
Version gotcha (read first). This skill targets PyHealth 2.x (pin pyhealth==2.0.1). The 2.0 rewrite changed the API in ways the wider web (and pre-2024 tutorials) get wrong:
- Tasks are classes you instantiate, e.g.
MortalityPredictionMIMIC4(), DrugRecommendationMIMIC3() — not the old snake-case mortality_prediction_mimic4_fn functions. Pass the instance to dataset.set_task(task).
- Datasets take an explicit
tables=[...] list (e.g. tables=["diagnoses_icd", "procedures_icd", "prescriptions"]).
- Models require
label_key= in addition to feature_keys= and mode=. Common feature keys for EHR tasks are "conditions", "procedures", "drugs".
- Metric names have no
_score suffix: pr_auc, roc_auc, f1; multilabel/drug-rec use the *_samples family (jaccard_samples, f1_samples, pr_auc_samples, ddi). Pass metrics=[...] to the Trainer constructor, and monitor= one of those names.
- 2.0.1 requires Python 3.12 or 3.13 (
>=3.12,<3.14).
When unsure of a class/arg name, check the current source rather than trusting older snippets.
When to Use This Skill
Invoke this skill when:
- Working with healthcare datasets: MIMIC-III, MIMIC-IV, eICU, OMOP, sleep EEG data, medical images
- Clinical prediction tasks: Mortality prediction, hospital readmission, length of stay, drug recommendation
- Medical coding: Translating between ICD-9/10, NDC, RxNorm, ATC coding systems
- Processing clinical data: Sequential events, physiological signals, clinical text, medical images
- Implementing healthcare models: RETAIN, SafeDrug, GAMENet, StageNet, Transformer for EHR
- Evaluating clinical models: Fairness metrics, calibration, interpretability, uncertainty quantification
Core Capabilities
PyHealth operates through a modular 5-stage pipeline optimized for healthcare AI:
- Data Loading: Access 10+ healthcare datasets with standardized interfaces
- Task Definition: Apply 20+ predefined clinical prediction tasks or create custom tasks
- Model Selection: Choose from 33+ models (baselines, deep learning, healthcare-specific)
- Training: Train with automatic checkpointing, monitoring, and evaluation
- Deployment: Calibrate, interpret, and validate for clinical use
PyHealth 2.x uses a polars-backed data layer for fast, memory-efficient processing of large EHR tables.
Quick Start Workflow
from pyhealth.datasets import MIMIC4Dataset, split_by_patient, get_dataloader
from pyhealth.tasks import MortalityPredictionMIMIC4
from pyhealth.models import Transformer
from pyhealth.trainer import Trainer
# 1. Load dataset (declare the tables you need) and set the task (a class instance)
dataset = MIMIC4Dataset(
root="/path/to/data",
tables=["diagnoses_icd", "procedures_icd", "prescriptions"],
)
sample_dataset = dataset.set_task(MortalityPredictionMIMIC4())
# 2. Split data by patient (no leakage across splits)
train, val, test = split_by_patient(sample_dataset, [0.7, 0.1, 0.2])
# 3. Create data loaders
train_loader = get_dataloader(train, batch_size=64, shuffle=True)
val_loader = get_dataloader(val, batch_size=64, shuffle=False)
test_loader = get_dataloader(test, batch_size=64, shuffle=False)
# 4. Initialize and train (feature_keys + label_key + mode all required)
model = Transformer(
dataset=sample_dataset,
feature_keys=["conditions", "procedures", "drugs"],
label_key="mortality",
mode="binary",
embedding_dim=128,
)
trainer = Trainer(model=model, metrics=["pr_auc", "roc_auc", "f1"]) # device auto-detected
trainer.train(
train_dataloader=train_loader,
val_dataloader=val_loader,
epochs=50,
monitor="pr_auc", # AUPRC — robust for the rare-mortality class
monitor_criterion="max",
)
# 5. Evaluate (uses the metrics passed to the Trainer)
results = trainer.evaluate(test_loader)
Detailed Documentation
This skill includes comprehensive reference documentation organized by functionality. Read specific reference files as needed:
1. Datasets and Data Structures
File: references/datasets.md
Read when:
- Loading healthcare datasets (MIMIC, eICU, OMOP, sleep EEG, etc.)
- Understanding Event, Patient, Visit data structures
- Processing different data types (EHR, signals, images, text)
- Splitting data for training/validation/testing
- Working with SampleDataset for task-specific formatting
Key Topics:
- Core data structures (Event, Patient, Visit)
- 10+ available datasets (EHR, physiological signals, imaging, text)
- Data loading and iteration
- Train/val/test splitting strategies
- Performance optimization for large datasets
2. Medical Coding Translation
File: references/medical_coding.md
Read when:
- Translating between medical coding systems
- Working with diagnosis codes (ICD-9-CM, ICD-10-CM, CCS)
- Processing medication codes (NDC, RxNorm, ATC)
- Standardizing procedure codes (ICD-9-PROC, ICD-10-PROC)
- Grouping codes into clinical categories
- Handling hierarchical drug classifications
Key Topics:
- InnerMap for within-system lookups
- CrossMap for cross-system translation
- Supported coding systems (ICD, NDC, ATC, CCS, RxNorm)
- Code standardization and hierarchy traversal
- Medication classification by therapeutic class
- Integration with datasets
3. Clinical Prediction Tasks
File: references/tasks.md
Read when:
- Defining clinical prediction objectives
- Using predefined tasks (mortality, readmission, drug recommendation)
- Working with EHR, signal, imaging, or text-based tasks
- Creating custom prediction tasks
- Setting up input/output schemas for models
- Applying task-specific filtering logic
Key Topics:
- 20+ predefined clinical tasks
- EHR tasks (mortality, readmission, length of stay, drug recommendation)
- Signal tasks (sleep staging, EEG analysis, seizure detection)
- Imaging tasks (COVID-19 chest X-ray classification)
- Text tasks (medical coding, specialty classification)
- Custom task creation patterns
4. Models and Architectures
File: references/models.md
Read when:
- Selecting models for clinical prediction
- Understanding model architectures and capabilities
- Choosing between general-purpose and healthcare-specific models
- Implementing interpretable models (RETAIN, AdaCare)
- Working with medication recommendation (SafeDrug, GAMENet)
- Using graph neural networks for healthcare
- Configuring model hyperparameters
Key Topics:
- 33+ available models
- General-purpose: Logistic Regression, MLP, CNN, RNN, Transformer, GNN
- Healthcare-specific: RETAIN, SafeDrug, GAMENet, StageNet, AdaCare
- Model selection by task type and data type
- Interpretability considerations
- Computational requirements
- Hyperparameter tuning guidelines
5. Data Preprocessing
File: references/preprocessing.md
Read when:
- Preprocessing clinical data for models
- Handling sequential events and time-series data
- Processing physiological signals (EEG, ECG)
- Normalizing lab values and vital signs
- Preparing labels for different task types
- Building feature vocabularies
- Managing missing data and outliers
Key Topics:
- 15+ processor types
- Sequence processing (padding, truncation)
- Signal processing (filtering, segmentation)
- Feature extraction and encoding
- Label processors (binary, multi-class, multi-label, regression)
- Text and image preprocessing
- Common preprocessing workflows
6. Training and Evaluation
File: references/training_evaluation.md
Read when:
- Training models with the Trainer class
- Evaluating model performance
- Computing clinical metrics
- Assessing model fairness across demographics
- Calibrating predictions for reliability
- Quantifying prediction uncertainty
- Interpreting model predictions
- Preparing models for clinical deployment
Key Topics:
- Trainer class (train, evaluate, inference)
- Metrics for binary, multi-class, multi-label, regression tasks
- Fairness metrics for bias assessment
- Calibration methods (Platt scaling, temperature scaling)
- Uncertainty quantification (conformal prediction, MC dropout)
- Interpretability tools (attention visualization, SHAP, Chefer relevance via
pyhealth.interpret.methods.CheferRelevance)
- Complete training pipeline example
Installation
uv pip install "pyhealth==2.0.1"
Requirements (PyHealth 2.0.1):
- Python 3.12 or 3.13 (
>=3.12,<3.14) — note this machine's default uv Python is 3.14, which is outside the supported range; create the env with uv venv --python 3.13 for PyHealth work.
- PyTorch (pulled in as a dependency)
- NumPy, pandas, polars, scikit-learn
Common Use Cases
Use Case 1: ICU Mortality Prediction
Objective: Predict patient mortality in intensive care unit
Approach:
- Load MIMIC-IV dataset → Read
references/datasets.md
- Apply mortality prediction task → Read
references/tasks.md
- Select interpretable model (RETAIN) → Read
references/models.md
- Train and evaluate → Read
references/training_evaluation.md
- Interpret predictions for clinical use → Read
references/training_evaluation.md
Use Case 2: Safe Medication Recommendation
Objective: Recommend medications while avoiding drug-drug interactions
Approach:
- Load EHR dataset (MIMIC-IV or OMOP) → Read
references/datasets.md
- Apply drug recommendation task → Read
references/tasks.md
- Use SafeDrug model with DDI constraints → Read
references/models.md
- Preprocess medication codes → Read
references/medical_coding.md
- Evaluate with multi-label metrics → Read
references/training_evaluation.md
Use Case 3: Hospital Readmission Prediction
Objective: Identify patients at risk of 30-day readmission
Approach:
- Load multi-site EHR data (eICU or OMOP) → Read
references/datasets.md
- Apply readmission prediction task → Read
references/tasks.md
- Handle class imbalance in preprocessing → Read
references/preprocessing.md
- Train Transformer model → Read
references/models.md
- Calibrate predictions and assess fairness → Read
references/training_evaluation.md
Use Case 4: Sleep Disorder Diagnosis
Objective: Classify sleep stages from EEG signals
Approach:
- Load sleep EEG dataset (SleepEDF, SHHS) → Read
references/datasets.md
- Apply sleep staging task → Read
references/tasks.md
- Preprocess EEG signals (filtering, segmentation) → Read
references/preprocessing.md
- Train CNN or RNN model → Read
references/models.md
- Evaluate per-stage performance → Read
references/training_evaluation.md
Use Case 5: Medical Code Translation
Objective: Standardize diagnoses across different coding systems
Approach:
- Read
references/medical_coding.md for comprehensive guidance
- Use CrossMap to translate between ICD-9, ICD-10, CCS
- Group codes into clinically meaningful categories
- Integrate with dataset processing
Use Case 6: Clinical Text to ICD Coding
Objective: Automatically assign ICD codes from clinical notes
Approach:
- Load MIMIC-III with clinical text → Read
references/datasets.md
- Apply ICD coding task → Read
references/tasks.md
- Preprocess clinical text → Read
references/preprocessing.md
- Use TransformersModel (ClinicalBERT) → Read
references/models.md
- Evaluate with multi-label metrics → Read
references/training_evaluation.md
Best Practices
Data Handling
Always split by patient: Prevent data leakage by ensuring no patient appears in multiple splits
from pyhealth.datasets import split_by_patient
train, val, test = split_by_patient(dataset, [0.7, 0.1, 0.2])
Check dataset statistics: Understand your data before modeling
print(dataset.stats()) # Patients, visits, events, code distributions
Use appropriate preprocessing: Match processors to data types (see references/preprocessing.md)
Model Development
Start with baselines: Establish baseline performance with simple models
- Logistic Regression for binary/multi-class tasks
- MLP for initial deep learning baseline
Choose task-appropriate models:
- Interpretability needed → RETAIN, AdaCare
- Drug recommendation → SafeDrug, GAMENet
- Long sequences → Transformer
- Graph relationships → GNN
Monitor validation metrics: Use appropriate metrics for task and handle class imbalance. PyHealth metric strings (pass to Trainer(metrics=[...]) / monitor=):
- Binary:
roc_auc, pr_auc (prefer pr_auc for rare events), f1, accuracy
- Multi-class:
f1_macro, f1_weighted, accuracy, cohen_kappa
- Multi-label / drug-rec:
jaccard_samples, f1_samples, pr_auc_samples, ddi
- Regression:
mae, mse, r2
Clinical Deployment
Calibrate predictions: Ensure probabilities are reliable (see references/training_evaluation.md)
Assess fairness: Evaluate across demographic groups to detect bias
Quantify uncertainty: Provide confidence estimates for predictions
Interpret predictions: Use attention weights, SHAP, or Chefer relevance for clinical trust
Validate thoroughly: Use held-out test sets from different time periods or sites
Limitations and Considerations
Data Requirements
- Large datasets: Deep learning models require sufficient data (thousands of patients)
- Data quality: Missing data and coding errors impact performance
- Temporal consistency: Ensure train/test split respects temporal ordering when needed
Clinical Validation
- External validation: Test on data from different hospitals/systems
- Prospective evaluation: Validate in real clinical settings before deployment
- Clinical review: Have clinicians review predictions and interpretations
- Ethical considerations: Address privacy (HIPAA/GDPR), fairness, and safety
Computational Resources
- GPU recommended: For training deep learning models efficiently
- Memory requirements: Large datasets may require 16GB+ RAM
- Storage: Healthcare datasets can be 10s-100s of GB
Troubleshooting
Common Issues
ImportError for dataset:
- Ensure dataset files are downloaded and path is correct
- Check PyHealth version compatibility
Out of memory:
- Reduce batch size
- Reduce sequence length (
max_seq_length)
- Use gradient accumulation
- Process data in chunks
Poor performance:
- Check class imbalance and use appropriate metrics (
pr_auc vs roc_auc)
- Verify preprocessing (normalization, missing data handling)
- Increase model capacity or training epochs
- Check for data leakage in train/test split
Slow training:
- Use GPU (
device="cuda")
- Increase batch size (if memory allows)
- Reduce sequence length
- Use more efficient model (CNN vs Transformer)
Getting Help
Example: Complete Workflow
# Complete mortality prediction pipeline
from pyhealth.datasets import MIMIC4Dataset, split_by_patient, get_dataloader
from pyhealth.tasks import MortalityPredictionMIMIC4
from pyhealth.models import RETAIN
from pyhealth.trainer import Trainer
# 1. Load dataset (declare the tables the task needs)
print("Loading MIMIC-IV dataset...")
dataset = MIMIC4Dataset(
root="/data/mimic4",
tables=["diagnoses_icd", "procedures_icd", "prescriptions"],
)
print(dataset.stats())
# 2. Define task (instantiate the task class)
print("Setting mortality prediction task...")
sample_dataset = dataset.set_task(MortalityPredictionMIMIC4())
print(f"Generated {len(sample_dataset)} samples")
# 3. Split data (by patient to prevent leakage)
print("Splitting data...")
train_ds, val_ds, test_ds = split_by_patient(
sample_dataset, ratios=[0.7, 0.1, 0.2], seed=42
)
# 4. Create data loaders
train_loader = get_dataloader(train_ds, batch_size=64, shuffle=True)
val_loader = get_dataloader(val_ds, batch_size=64)
test_loader = get_dataloader(test_ds, batch_size=64)
# 5. Initialize interpretable model (label_key is required)
print("Initializing RETAIN model...")
model = RETAIN(
dataset=sample_dataset,
feature_keys=["conditions", "procedures", "drugs"],
label_key="mortality",
mode="binary",
embedding_dim=128,
)
# 6. Train model
print("Training model...")
import torch
trainer = Trainer(
model=model,
metrics=["accuracy", "pr_auc", "roc_auc", "f1"],
)
trainer.train(
train_dataloader=train_loader,
val_dataloader=val_loader,
epochs=50,
optimizer_class=torch.optim.Adam,
optimizer_params={"lr": 1e-3, "weight_decay": 1e-5},
monitor="pr_auc", # Use AUPRC for the imbalanced (rare-mortality) outcome
monitor_criterion="max",
)
# 7. Evaluate on test set (uses the metrics passed to the Trainer)
print("Evaluating on test set...")
test_results = trainer.evaluate(test_loader)
print("\nTest Results:")
for metric, value in test_results.items():
print(f" {metric}: {value:.4f}")
# 8. Get predictions for analysis.
# inference() returns (y_true, y_prob, loss) by default; requesting extras
# extends the tuple to (y_true, y_prob, loss, additional_outputs, patient_ids).
y_true, y_prob, loss, extra, patient_ids = trainer.inference(
test_loader,
additional_outputs=["attention_weights"],
return_patient_ids=True,
)
# 9. Flag the highest-risk patient
positive_prob = y_prob if y_prob.ndim == 1 else y_prob[..., -1]
high_risk_idx = int(positive_prob.argmax())
print(f"\nHighest-risk patient: {patient_ids[high_risk_idx]}")
print(f"Risk score: {float(positive_prob[high_risk_idx]):.3f}")
# 10. Feature-level interpretation via Chefer relevance (works on attention models)
from pyhealth.interpret.methods import CheferRelevance
relevance = CheferRelevance(model) batch_size=1, shuffle=False)
scores = relevance.get_relevance_matrix(**next(iter(one)))
for feature_key, rel in scores.items():
print(f"{feature_key}: top tokens -> {rel[0].topk(5).indices.tolist()}")
# 11. Save the trained model
trainer.save("./models/mortality_retain_final.pt")
print("\nModel saved successfully!")
Resources
For detailed information on each component, refer to the comprehensive reference files in the references/ directory:
- datasets.md: Data structures, loading, and splitting (4,500 words)
- medical_coding.md: Code translation and standardization (3,800 words)
- tasks.md: Clinical prediction tasks and custom task creation (4,200 words)
- models.md: Model architectures and selection guidelines (5,100 words)
- preprocessing.md: Data processors and preprocessing workflows (4,600 words)
- training_evaluation.md: Training, metrics, calibration, interpretability (5,900 words)
Total comprehensive documentation: ~28,000 words across modular reference files.
1---2name: alterlab-pyhealth3description: Develops, tests, and deploys clinical machine learning models with the PyHealth healthcare AI toolkit. Use when working with electronic health records (EHR), clinical prediction tasks (mortality, readmission, drug recommendation), medical coding systems (ICD, NDC, ATC), physiological signals (EEG, ECG), healthcare datasets (MIMIC-III/IV, eICU, OMOP), or implementing deep learning models for healthcare (RETAIN, SafeDrug, Transformer, GNN). Part of the AlterLab Academic Skills suite.4license: MIT5---67# PyHealth: Healthcare AI Toolkit89## Overview1011PyHealth is a comprehensive Python library for healthcare AI that provides specialized tools, models, and datasets for clinical machine learning. Use this skill when developing healthcare prediction models, processing clinical data, working with medical coding systems, or deploying AI solutions in healthcare settings.1213> **Version gotcha (read first).** This skill targets **PyHealth 2.x** (pin `pyhealth==2.0.1`). The 2.0 rewrite changed the API in ways the wider web (and pre-2024 tutorials) get wrong:14> - **Tasks are classes you instantiate**, e.g. `MortalityPredictionMIMIC4()`, `DrugRecommendationMIMIC3()` — *not* the old snake-case `mortality_prediction_mimic4_fn` functions. Pass the instance to `dataset.set_task(task)`.15> - **Datasets take an explicit `tables=[...]`** list (e.g. `tables=["diagnoses_icd", "procedures_icd", "prescriptions"]`).16> - **Models require `label_key=`** in addition to `feature_keys=` and `mode=`. Common feature keys for EHR tasks are `"conditions"`, `"procedures"`, `"drugs"`.17> - **Metric names have no `_score` suffix**: `pr_auc`, `roc_auc`, `f1`; multilabel/drug-rec use the `*_samples` family (`jaccard_samples`, `f1_samples`, `pr_auc_samples`, `ddi`). Pass `metrics=[...]` to the **`Trainer` constructor**, and `monitor=` one of those names.18> - 2.0.1 requires **Python 3.12 or 3.13** (`>=3.12,<3.14`).19> When unsure of a class/arg name, check the current source rather than trusting older snippets.2021## When to Use This Skill2223Invoke this skill when:2425- **Working with healthcare datasets**: MIMIC-III, MIMIC-IV, eICU, OMOP, sleep EEG data, medical images26- **Clinical prediction tasks**: Mortality prediction, hospital readmission, length of stay, drug recommendation27- **Medical coding**: Translating between ICD-9/10, NDC, RxNorm, ATC coding systems28- **Processing clinical data**: Sequential events, physiological signals, clinical text, medical images29- **Implementing healthcare models**: RETAIN, SafeDrug, GAMENet, StageNet, Transformer for EHR30- **Evaluating clinical models**: Fairness metrics, calibration, interpretability, uncertainty quantification3132## Core Capabilities3334PyHealth operates through a modular 5-stage pipeline optimized for healthcare AI:35361. **Data Loading**: Access 10+ healthcare datasets with standardized interfaces372. **Task Definition**: Apply 20+ predefined clinical prediction tasks or create custom tasks383. **Model Selection**: Choose from 33+ models (baselines, deep learning, healthcare-specific)394. **Training**: Train with automatic checkpointing, monitoring, and evaluation405. **Deployment**: Calibrate, interpret, and validate for clinical use4142PyHealth 2.x uses a **polars-backed** data layer for fast, memory-efficient processing of large EHR tables.4344## Quick Start Workflow4546```python47from pyhealth.datasets import MIMIC4Dataset, split_by_patient, get_dataloader48from pyhealth.tasks import MortalityPredictionMIMIC449from pyhealth.models import Transformer50from pyhealth.trainer import Trainer5152# 1. Load dataset (declare the tables you need) and set the task (a class instance)53dataset = MIMIC4Dataset(54 root="/path/to/data",55 tables=["diagnoses_icd", "procedures_icd", "prescriptions"],56)57sample_dataset = dataset.set_task(MortalityPredictionMIMIC4())5859# 2. Split data by patient (no leakage across splits)60train, val, test = split_by_patient(sample_dataset, [0.7, 0.1, 0.2])6162# 3. Create data loaders63train_loader = get_dataloader(train, batch_size=64, shuffle=True)64val_loader = get_dataloader(val, batch_size=64, shuffle=False)65test_loader = get_dataloader(test, batch_size=64, shuffle=False)6667# 4. Initialize and train (feature_keys + label_key + mode all required)68model = Transformer(69 dataset=sample_dataset,70 feature_keys=["conditions", "procedures", "drugs"],71 label_key="mortality",72 mode="binary",73 embedding_dim=128,74)7576trainer = Trainer(model=model, metrics=["pr_auc", "roc_auc", "f1"]) # device auto-detected77trainer.train(78 train_dataloader=train_loader,79 val_dataloader=val_loader,80 epochs=50,81 monitor="pr_auc", # AUPRC — robust for the rare-mortality class82 monitor_criterion="max",83)8485# 5. Evaluate (uses the metrics passed to the Trainer)86results = trainer.evaluate(test_loader)87```8889## Detailed Documentation9091This skill includes comprehensive reference documentation organized by functionality. Read specific reference files as needed:9293### 1. Datasets and Data Structures9495**File**: `references/datasets.md`9697**Read when:**98- Loading healthcare datasets (MIMIC, eICU, OMOP, sleep EEG, etc.)99- Understanding Event, Patient, Visit data structures100- Processing different data types (EHR, signals, images, text)101- Splitting data for training/validation/testing102- Working with SampleDataset for task-specific formatting103104**Key Topics:**105- Core data structures (Event, Patient, Visit)106- 10+ available datasets (EHR, physiological signals, imaging, text)107- Data loading and iteration108- Train/val/test splitting strategies109- Performance optimization for large datasets110111### 2. Medical Coding Translation112113**File**: `references/medical_coding.md`114115**Read when:**116- Translating between medical coding systems117- Working with diagnosis codes (ICD-9-CM, ICD-10-CM, CCS)118- Processing medication codes (NDC, RxNorm, ATC)119- Standardizing procedure codes (ICD-9-PROC, ICD-10-PROC)120- Grouping codes into clinical categories121- Handling hierarchical drug classifications122123**Key Topics:**124- InnerMap for within-system lookups125- CrossMap for cross-system translation126- Supported coding systems (ICD, NDC, ATC, CCS, RxNorm)127- Code standardization and hierarchy traversal128- Medication classification by therapeutic class129- Integration with datasets130131### 3. Clinical Prediction Tasks132133**File**: `references/tasks.md`134135**Read when:**136- Defining clinical prediction objectives137- Using predefined tasks (mortality, readmission, drug recommendation)138- Working with EHR, signal, imaging, or text-based tasks139- Creating custom prediction tasks140- Setting up input/output schemas for models141- Applying task-specific filtering logic142143**Key Topics:**144- 20+ predefined clinical tasks145- EHR tasks (mortality, readmission, length of stay, drug recommendation)146- Signal tasks (sleep staging, EEG analysis, seizure detection)147- Imaging tasks (COVID-19 chest X-ray classification)148- Text tasks (medical coding, specialty classification)149- Custom task creation patterns150151### 4. Models and Architectures152153**File**: `references/models.md`154155**Read when:**156- Selecting models for clinical prediction157- Understanding model architectures and capabilities158- Choosing between general-purpose and healthcare-specific models159- Implementing interpretable models (RETAIN, AdaCare)160- Working with medication recommendation (SafeDrug, GAMENet)161- Using graph neural networks for healthcare162- Configuring model hyperparameters163164**Key Topics:**165- 33+ available models166- General-purpose: Logistic Regression, MLP, CNN, RNN, Transformer, GNN167- Healthcare-specific: RETAIN, SafeDrug, GAMENet, StageNet, AdaCare168- Model selection by task type and data type169- Interpretability considerations170- Computational requirements171- Hyperparameter tuning guidelines172173### 5. Data Preprocessing174175**File**: `references/preprocessing.md`176177**Read when:**178- Preprocessing clinical data for models179- Handling sequential events and time-series data180- Processing physiological signals (EEG, ECG)181- Normalizing lab values and vital signs182- Preparing labels for different task types183- Building feature vocabularies184- Managing missing data and outliers185186**Key Topics:**187- 15+ processor types188- Sequence processing (padding, truncation)189- Signal processing (filtering, segmentation)190- Feature extraction and encoding191- Label processors (binary, multi-class, multi-label, regression)192- Text and image preprocessing193- Common preprocessing workflows194195### 6. Training and Evaluation196197**File**: `references/training_evaluation.md`198199**Read when:**200- Training models with the Trainer class201- Evaluating model performance202- Computing clinical metrics203- Assessing model fairness across demographics204- Calibrating predictions for reliability205- Quantifying prediction uncertainty206- Interpreting model predictions207- Preparing models for clinical deployment208209**Key Topics:**210- Trainer class (train, evaluate, inference)211- Metrics for binary, multi-class, multi-label, regression tasks212- Fairness metrics for bias assessment213- Calibration methods (Platt scaling, temperature scaling)214- Uncertainty quantification (conformal prediction, MC dropout)215- Interpretability tools (attention visualization, SHAP, Chefer relevance via `pyhealth.interpret.methods.CheferRelevance`)216- Complete training pipeline example217218## Installation219220```bash221uv pip install "pyhealth==2.0.1"222```223224**Requirements (PyHealth 2.0.1):**225- Python **3.12 or 3.13** (`>=3.12,<3.14`) — note this machine's default `uv` Python is 3.14, which is *outside* the supported range; create the env with `uv venv --python 3.13` for PyHealth work.226- PyTorch (pulled in as a dependency)227- NumPy, pandas, polars, scikit-learn228229## Common Use Cases230231### Use Case 1: ICU Mortality Prediction232233**Objective**: Predict patient mortality in intensive care unit234235**Approach:**2361. Load MIMIC-IV dataset → Read `references/datasets.md`2372. Apply mortality prediction task → Read `references/tasks.md`2383. Select interpretable model (RETAIN) → Read `references/models.md`2394. Train and evaluate → Read `references/training_evaluation.md`2405. Interpret predictions for clinical use → Read `references/training_evaluation.md`241242### Use Case 2: Safe Medication Recommendation243244**Objective**: Recommend medications while avoiding drug-drug interactions245246**Approach:**2471. Load EHR dataset (MIMIC-IV or OMOP) → Read `references/datasets.md`2482. Apply drug recommendation task → Read `references/tasks.md`2493. Use SafeDrug model with DDI constraints → Read `references/models.md`2504. Preprocess medication codes → Read `references/medical_coding.md`2515. Evaluate with multi-label metrics → Read `references/training_evaluation.md`252253### Use Case 3: Hospital Readmission Prediction254255**Objective**: Identify patients at risk of 30-day readmission256257**Approach:**2581. Load multi-site EHR data (eICU or OMOP) → Read `references/datasets.md`2592. Apply readmission prediction task → Read `references/tasks.md`2603. Handle class imbalance in preprocessing → Read `references/preprocessing.md`2614. Train Transformer model → Read `references/models.md`2625. Calibrate predictions and assess fairness → Read `references/training_evaluation.md`263264### Use Case 4: Sleep Disorder Diagnosis265266**Objective**: Classify sleep stages from EEG signals267268**Approach:**2691. Load sleep EEG dataset (SleepEDF, SHHS) → Read `references/datasets.md`2702. Apply sleep staging task → Read `references/tasks.md`2713. Preprocess EEG signals (filtering, segmentation) → Read `references/preprocessing.md`2724. Train CNN or RNN model → Read `references/models.md`2735. Evaluate per-stage performance → Read `references/training_evaluation.md`274275### Use Case 5: Medical Code Translation276277**Objective**: Standardize diagnoses across different coding systems278279**Approach:**2801. Read `references/medical_coding.md` for comprehensive guidance2812. Use CrossMap to translate between ICD-9, ICD-10, CCS2823. Group codes into clinically meaningful categories2834. Integrate with dataset processing284285### Use Case 6: Clinical Text to ICD Coding286287**Objective**: Automatically assign ICD codes from clinical notes288289**Approach:**2901. Load MIMIC-III with clinical text → Read `references/datasets.md`2912. Apply ICD coding task → Read `references/tasks.md`2923. Preprocess clinical text → Read `references/preprocessing.md`2934. Use TransformersModel (ClinicalBERT) → Read `references/models.md`2945. Evaluate with multi-label metrics → Read `references/training_evaluation.md`295296## Best Practices297298### Data Handling2993001. **Always split by patient**: Prevent data leakage by ensuring no patient appears in multiple splits301 ```python302 from pyhealth.datasets import split_by_patient303 train, val, test = split_by_patient(dataset, [0.7, 0.1, 0.2])304 ```3053062. **Check dataset statistics**: Understand your data before modeling307 ```python308 print(dataset.stats()) # Patients, visits, events, code distributions309 ```3103113. **Use appropriate preprocessing**: Match processors to data types (see `references/preprocessing.md`)312313### Model Development3143151. **Start with baselines**: Establish baseline performance with simple models316 - Logistic Regression for binary/multi-class tasks317 - MLP for initial deep learning baseline3183192. **Choose task-appropriate models**:320 - Interpretability needed → RETAIN, AdaCare321 - Drug recommendation → SafeDrug, GAMENet322 - Long sequences → Transformer323 - Graph relationships → GNN3243253. **Monitor validation metrics**: Use appropriate metrics for task and handle class imbalance. PyHealth metric strings (pass to `Trainer(metrics=[...])` / `monitor=`):326 - Binary: `roc_auc`, `pr_auc` (prefer `pr_auc` for rare events), `f1`, `accuracy`327 - Multi-class: `f1_macro`, `f1_weighted`, `accuracy`, `cohen_kappa`328 - Multi-label / drug-rec: `jaccard_samples`, `f1_samples`, `pr_auc_samples`, `ddi`329 - Regression: `mae`, `mse`, `r2`330331### Clinical Deployment3323331. **Calibrate predictions**: Ensure probabilities are reliable (see `references/training_evaluation.md`)3343352. **Assess fairness**: Evaluate across demographic groups to detect bias3363373. **Quantify uncertainty**: Provide confidence estimates for predictions3383394. **Interpret predictions**: Use attention weights, SHAP, or Chefer relevance for clinical trust3403415. **Validate thoroughly**: Use held-out test sets from different time periods or sites342343## Limitations and Considerations344345### Data Requirements346347- **Large datasets**: Deep learning models require sufficient data (thousands of patients)348- **Data quality**: Missing data and coding errors impact performance349- **Temporal consistency**: Ensure train/test split respects temporal ordering when needed350351### Clinical Validation352353- **External validation**: Test on data from different hospitals/systems354- **Prospective evaluation**: Validate in real clinical settings before deployment355- **Clinical review**: Have clinicians review predictions and interpretations356- **Ethical considerations**: Address privacy (HIPAA/GDPR), fairness, and safety357358### Computational Resources359360- **GPU recommended**: For training deep learning models efficiently361- **Memory requirements**: Large datasets may require 16GB+ RAM362- **Storage**: Healthcare datasets can be 10s-100s of GB363364## Troubleshooting365366### Common Issues367368**ImportError for dataset**:369- Ensure dataset files are downloaded and path is correct370- Check PyHealth version compatibility371372**Out of memory**:373- Reduce batch size374- Reduce sequence length (`max_seq_length`)375- Use gradient accumulation376- Process data in chunks377378**Poor performance**:379- Check class imbalance and use appropriate metrics (`pr_auc` vs `roc_auc`)380- Verify preprocessing (normalization, missing data handling)381- Increase model capacity or training epochs382- Check for data leakage in train/test split383384**Slow training**:385- Use GPU (`device="cuda"`)386- Increase batch size (if memory allows)387- Reduce sequence length388- Use more efficient model (CNN vs Transformer)389390### Getting Help391392- **Documentation**: https://pyhealth.readthedocs.io/393- **GitHub Issues**: https://github.com/sunlabuiuc/PyHealth/issues394- **Examples/notebooks**: https://github.com/sunlabuiuc/PyHealth/tree/master/examples395396## Example: Complete Workflow397398```python399# Complete mortality prediction pipeline400from pyhealth.datasets import MIMIC4Dataset, split_by_patient, get_dataloader401from pyhealth.tasks import MortalityPredictionMIMIC4402from pyhealth.models import RETAIN403from pyhealth.trainer import Trainer404405# 1. Load dataset (declare the tables the task needs)406print("Loading MIMIC-IV dataset...")407dataset = MIMIC4Dataset(408 root="/data/mimic4",409 tables=["diagnoses_icd", "procedures_icd", "prescriptions"],410)411print(dataset.stats())412413# 2. Define task (instantiate the task class)414print("Setting mortality prediction task...")415sample_dataset = dataset.set_task(MortalityPredictionMIMIC4())416print(f"Generated {len(sample_dataset)} samples")417418# 3. Split data (by patient to prevent leakage)419print("Splitting data...")420train_ds, val_ds, test_ds = split_by_patient(421 sample_dataset, ratios=[0.7, 0.1, 0.2], seed=42422)423424# 4. Create data loaders425train_loader = get_dataloader(train_ds, batch_size=64, shuffle=True)426val_loader = get_dataloader(val_ds, batch_size=64)427test_loader = get_dataloader(test_ds, batch_size=64)428429# 5. Initialize interpretable model (label_key is required)430print("Initializing RETAIN model...")431model = RETAIN(432 dataset=sample_dataset,433 feature_keys=["conditions", "procedures", "drugs"],434 label_key="mortality",435 mode="binary",436 embedding_dim=128,437)438439# 6. Train model440print("Training model...")441import torch442trainer = Trainer(443 model=model,444 metrics=["accuracy", "pr_auc", "roc_auc", "f1"],445)446trainer.train(447 train_dataloader=train_loader,448 val_dataloader=val_loader,449 epochs=50,450 optimizer_class=torch.optim.Adam,451 optimizer_params={"lr": 1e-3, "weight_decay": 1e-5},452 monitor="pr_auc", # Use AUPRC for the imbalanced (rare-mortality) outcome453 monitor_criterion="max",454)455456# 7. Evaluate on test set (uses the metrics passed to the Trainer)457print("Evaluating on test set...")458test_results = trainer.evaluate(test_loader)459460print("\nTest Results:")461for metric, value in test_results.items():462 print(f" {metric}: {value:.4f}")463464# 8. Get predictions for analysis.465# inference() returns (y_true, y_prob, loss) by default; requesting extras466# extends the tuple to (y_true, y_prob, loss, additional_outputs, patient_ids).467y_true, y_prob, loss, extra, patient_ids = trainer.inference(468 test_loader,469 additional_outputs=["attention_weights"],470 return_patient_ids=True,471)472473# 9. Flag the highest-risk patient474positive_prob = y_prob if y_prob.ndim == 1 else y_prob[..., -1]475high_risk_idx = int(positive_prob.argmax())476print(f"\nHighest-risk patient: {patient_ids[high_risk_idx]}")477print(f"Risk score: {float(positive_prob[high_risk_idx]):.3f}")478479# 10. Feature-level interpretation via Chefer relevance (works on attention models)480from pyhealth.interpret.methods import CheferRelevance481relevance = CheferRelevance(model)482one = get_dataloader(test, batch_size=1, shuffle=False)483scores = relevance.get_relevance_matrix(**next(iter(one)))484for feature_key, rel in scores.items():485 print(f"{feature_key}: top tokens -> {rel[0].topk(5).indices.tolist()}")486487# 11. Save the trained model488trainer.save("./models/mortality_retain_final.pt")489print("\nModel saved successfully!")490```491492## Resources493494For detailed information on each component, refer to the comprehensive reference files in the `references/` directory:495496- **datasets.md**: Data structures, loading, and splitting (4,500 words)497- **medical_coding.md**: Code translation and standardization (3,800 words)498- **tasks.md**: Clinical prediction tasks and custom task creation (4,200 words)499- **models.md**: Model architectures and selection guidelines (5,100 words)500- **preprocessing.md**: Data processors and preprocessing workflows (4,600 words)501- **training_evaluation.md**: Training, metrics, calibration, interpretability (5,900 words)502503**Total comprehensive documentation**: ~28,000 words across modular reference files.504