Alterlab pyhealth

From NVlabs/Skill2Env · View interactive version

Alterlab pyhealth is an AI agent skill from the GitHub repository NVlabs/Skill2Env. 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, E

How to use this skill

Skill file

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:

Core Capabilities

PyHealth operates through a modular 5-stage pipeline optimized for healthcare AI:

  1. Data Loading: Access 10+ healthcare datasets with standardized interfaces
  2. Task Definition: Apply 20+ predefined clinical prediction tasks or create custom tasks
  3. Model Selection: Choose from 33+ models (baselines, deep learning, healthcare-specific)
  4. Training: Train with automatic checkpointing, monitoring, and evaluation
  5. 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:

Key Topics:

2. Medical Coding Translation

File: references/medical_coding.md

Read when:

Key Topics:

3. Clinical Prediction Tasks

File: references/tasks.md

Read when:

Key Topics:

4. Models and Architectures

File: references/models.md

Read when:

Key Topics:

5. Data Preprocessing

File: references/preprocessing.md

Read when:

Key Topics:

6. Training and Evaluation

File: references/training_evaluation.md

Read when:

Key Topics:

Installation

uv pip install "pyhealth==2.0.1"

Requirements (PyHealth 2.0.1):

Common Use Cases

Use Case 1: ICU Mortality Prediction

Objective: Predict patient mortality in intensive care unit

Approach:

  1. Load MIMIC-IV dataset → Read references/datasets.md
  2. Apply mortality prediction task → Read references/tasks.md
  3. Select interpretable model (RETAIN) → Read references/models.md
  4. Train and evaluate → Read references/training_evaluation.md
  5. 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:

  1. Load EHR dataset (MIMIC-IV or OMOP) → Read references/datasets.md
  2. Apply drug recommendation task → Read references/tasks.md
  3. Use SafeDrug model with DDI constraints → Read references/models.md
  4. Preprocess medication codes → Read references/medical_coding.md
  5. 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:

  1. Load multi-site EHR data (eICU or OMOP) → Read references/datasets.md
  2. Apply readmission prediction task → Read references/tasks.md
  3. Handle class imbalance in preprocessing → Read references/preprocessing.md
  4. Train Transformer model → Read references/models.md
  5. Calibrate predictions and assess fairness → Read references/training_evaluation.md

Use Case 4: Sleep Disorder Diagnosis

Objective: Classify sleep stages from EEG signals

Approach:

  1. Load sleep EEG dataset (SleepEDF, SHHS) → Read references/datasets.md
  2. Apply sleep staging task → Read references/tasks.md
  3. Preprocess EEG signals (filtering, segmentation) → Read references/preprocessing.md
  4. Train CNN or RNN model → Read references/models.md
  5. Evaluate per-stage performance → Read references/training_evaluation.md

Use Case 5: Medical Code Translation

Objective: Standardize diagnoses across different coding systems

Approach:

  1. Read references/medical_coding.md for comprehensive guidance
  2. Use CrossMap to translate between ICD-9, ICD-10, CCS
  3. Group codes into clinically meaningful categories
  4. Integrate with dataset processing

Use Case 6: Clinical Text to ICD Coding

Objective: Automatically assign ICD codes from clinical notes

Approach:

  1. Load MIMIC-III with clinical text → Read references/datasets.md
  2. Apply ICD coding task → Read references/tasks.md
  3. Preprocess clinical text → Read references/preprocessing.md
  4. Use TransformersModel (ClinicalBERT) → Read references/models.md
  5. Evaluate with multi-label metrics → Read references/training_evaluation.md

Best Practices

Data Handling

  1. Always split by patient: Prevent data leakage by ensuring no patient appears in multiple splits

```python

from pyhealth.datasets import split_by_patient

train, val, test = split_by_patient(dataset, [0.7, 0.1, 0.2])

```

  1. Check dataset statistics: Understand your data before modeling

```python

print(dataset.stats()) # Patients, visits, events, code distributions

```

  1. Use appropriate preprocessing: Match processors to data types (see references/preprocessing.md)

Model Development

  1. Start with baselines: Establish baseline performance with simple models
  1. Choose task-appropriate models:
  1. Monitor validation metrics: Use appropriate metrics for task and handle class imbalance. PyHealth metric strings (pass to Trainer(metrics=[...]) / monitor=):

Clinical Deployment

  1. Calibrate predictions: Ensure probabilities are reliable (see references/training_evaluation.md)
  1. Assess fairness: Evaluate across demographic groups to detect bias
  1. Quantify uncertainty: Provide confidence estimates for predictions
  1. Interpret predictions: Use attention weights, SHAP, or Chefer relevance for clinical trust
  1. Validate thoroughly: Use held-out test sets from different time periods or sites

Limitations and Considerations

Data Requirements

Clinical Validation

Computational Resources

Troubleshooting

Common Issues

ImportError for dataset:

Out of memory:

Poor performance:

Slow training:

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)
one = get_dataloader(test, 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:

Total comprehensive documentation: ~28,000 words across modular reference files.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.