# Alterlab Pyhealth

> 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 healt…

- **Type:** Skill
- **Install:** `agentstack add skill-alterlab-ieu-alterlab-academic-skills-alterlab-pyhealth`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [AlterLab-IEU](https://agentstack.voostack.com/s/alterlab-ieu)
- **Installs:** 0
- **Category:** [AI & ML](https://agentstack.voostack.com/c/ai-and-ml)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [AlterLab-IEU](https://github.com/AlterLab-IEU)
- **Source:** https://github.com/AlterLab-IEU/AlterLab-Academic-Skills/tree/main/skills/clinical-research/alterlab-pyhealth
- **Website:** https://alterlab-ieu.github.io/AlterLab-Academic-Skills/

## Install

```sh
agentstack add skill-alterlab-ieu-alterlab-academic-skills-alterlab-pyhealth
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# 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, 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:

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

```python
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

```bash
uv pip install "pyhealth==2.0.1"
```

**Requirements (PyHealth 2.0.1):**
- Python **3.12 or 3.13** (`>=3.12, {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.

## Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [AlterLab-IEU](https://github.com/AlterLab-IEU)
- **Source:** [AlterLab-IEU/AlterLab-Academic-Skills](https://github.com/AlterLab-IEU/AlterLab-Academic-Skills)
- **License:** MIT
- **Homepage:** https://alterlab-ieu.github.io/AlterLab-Academic-Skills/

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** no
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** no
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/skill-alterlab-ieu-alterlab-academic-skills-alterlab-pyhealth
- Seller: https://agentstack.voostack.com/s/alterlab-ieu
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
