End-to-end EHR predictive modeling pipeline with PyHealth, covering dataset loading, task definition, model training, evaluation, calibration, and clinical interpretation.
npx skills add https://github.com/BioTender-max/awesome-bio-agent-skills --skill ehr-analysis
Reference examples assume:
pyhealth 1.1.6+ (stable) or 2.0+ (latest, requires Python ≥ 3.12)torch 2.0+pandas 2.0+Verify the runtime first:
python -c "import pyhealth; print(pyhealth.__version__)"pip show pyhealthUse this skill when the user needs to:
pyhealth.datasets class, then set_task.SampleBaseDataset, then follow the same pipeline.pyhealth.medcode independently without the full pipeline.pyhealth.metrics independently on existing predictions.references/technical_reference.md for dataset branching rules, task schema details, model selection guidance, and calibration caveats.references/commands_and_thresholds.md for concrete PyHealth code patterns, recommended thresholds, and output file conventions.SKILL.md as the main execution path and load reference files only when the task or failure mode needs the extra detail.split_by_patient over random splits that can leak patient data.diagnoses_icd, procedures_icd, prescriptions)results/model_checkpoint.pthresults/test_metrics.jsonresults/predictions.tsvqc/dataset_stats.tsvfigures/calibration_curve.pdffigures/feature_importance.pdfpyhealth.datasets — MIMIC3Dataset, MIMIC4Dataset, eICUDataset, OMOPDataset, SampleBaseDatasetpyhealth.tasks — MortalityPrediction, ReadmissionPrediction, DrugRecommendation, LengthOfStayPrediction, and custom task functionspyhealth.models — RNN, LSTM, GRU, Transformer, RETAIN, SafeDrug, GAMENet, AdaCare, ConCare, StageNetpyhealth.trainer — Trainerpyhealth.metrics — binary, multiclass, multilabel, fairness, interpretability metricspyhealth.medcode — InnerMap, CrossMap for ontology lookup and code mappingpyhealth.tokenizer — Tokenizer for code-to-index transformationspyhealth.calib — calibration and prediction set constructionfrom pyhealth.datasets import MIMIC3Dataset
from pyhealth.tasks import drug_recommendation_mimic3_fn
from pyhealth.datasets import split_by_patient, get_dataloader
from pyhealth.models import Transformer
from pyhealth.trainer import Trainer
# Step 1: load dataset
dataset = MIMIC3Dataset(
root="/path/to/mimic3/",
tables=["DIAGNOSES_ICD", "PROCEDURES_ICD", "PRESCRIPTIONS"],
code_mapping={"NDC": ("ATC", {"target_kwargs": {"level": 3}})},
)
# Step 2: define task
samples = dataset.set_task(task_fn=drug_recommendation_mimic3_fn)
# Step 3: split and build dataloaders
train_ds, val_ds, test_ds = split_by_patient(samples, [0.8, 0.1, 0.1])
train_loader = get_dataloader(train_ds, batch_size=32, shuffle=True)
val_loader = get_dataloader(val_ds, batch_size=32, shuffle=False)
test_loader = get_dataloader(test_ds, batch_size=32, shuffle=False)
# Step 4: initialize model
model = Transformer(
dataset=samples,
feature_keys=["conditions", "procedures"],
label_key="drugs",
mode="multilabel",
)
# Step 5: train
trainer = Trainer(model=model)
trainer.train(
train_dataloader=train_loader,
val_dataloader=val_loader,
epochs=50,
monitor="pr_auc_samples",
)
# Step 6: evaluate
metrics = trainer.evaluate(test_loader)
print(metrics)
Confirm the EHR source is accessible and the required tables are present. Inspect patient counts, visit counts, and code distributions before building tasks.
pyhealth.datasetsUse the appropriate dataset class. Apply code mappings at load time so downstream tasks and models operate on a consistent vocabulary. Record which tables and mappings were used.
Choose a predefined task function or write a custom one. Confirm the input schema (feature keys and types) and output schema (label key and mode: binary, multiclass, or multilabel) match the clinical question.
Always split by patient, not by visit or row, to prevent patient-level data leakage. Use split_by_patient and get_dataloader from pyhealth.datasets.
Select an architecture matched to the task and data size. Configure feature_keys, label_key, and mode explicitly. Use Trainer for training, validation monitoring, and checkpoint saving.
Compute task-appropriate metrics using pyhealth.metrics. For binary tasks report AUROC and AUPRC. For multilabel tasks report Jaccard and PR-AUC. Export a metrics JSON and a predictions TSV alongside the model checkpoint.
Apply calibration from pyhealth.calib when predicted probabilities will be used for clinical decision support. Use pyhealth.interpret for feature-level or visit-level attribution when the use case requires explainability.
results/
├── model_checkpoint.pth
├── test_metrics.json
└── predictions.tsv
qc/
├── dataset_stats.tsv
└── split_summary.tsv
figures/
├── calibration_curve.pdf
└── feature_importance.pdf
| Parameter | Typical value | Notes |
|---|---|---|
| batch_size | 32 | reduce for large visit sequences or memory-constrained environments |
| epochs | 50 | use early stopping via monitor metric |
| monitor | "pr_auc_samples" for multilabel; "roc_auc" for binary | task-dependent |
| split_by_patient ratios | [0.8, 0.1, 0.1] | always split by patient not by visit |
| code mapping level | ATC level 3 for drug codes | balance specificity and sparsity |
| n_top_genes (HVG analog) | N/A for EHR; use vocabulary filtering | filter rare codes with min_count |
Machine Learning For OmicsMulti-Omics IntegrationPathway AnalysisReporting And Figure Exportpyhealth.medcode for standalone code mappingpyhealth.calib for post-hoc calibrationpyhealth.interpret for interpretabilityCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.
Access NCBI GEO for gene expression/genomics data. Search/download microarray and RNA-seq datasets (GSE, GSM, GPL), retrieve SOFT/Matrix files, for transcriptomics and expression analysis.
Bayesian modeling with PyMC. Build hierarchical models, MCMC (NUTS), variational inference, LOO/WAIC comparison, posterior checks, for probabilistic programming and inference.
Multi-objective optimization framework. NSGA-II, NSGA-III, MOEA/D, Pareto fronts, constraint handling, benchmarks (ZDT, DTLZ), for engineering design and optimization problems.
Statistical modeling toolkit. OLS, GLM, logistic, ARIMA, time series, hypothesis tests, diagnostics, AIC/BIC, for rigorous statistical inference and econometric analysis.
Add unsigned integer (uint) type support to PyTorch operators by updating AT_DISPATCH macros. Use when adding support for uint16, uint32, uint64 types to operators, kernels, or when user mentions enabling unsigned types, barebones unsigned types, or uint support.
Convert PyTorch AT_DISPATCH macros to AT_DISPATCH_V2 format in ATen C++ code. Use when porting AT_DISPATCH_ALL_TYPES_AND*, AT_DISPATCH_FLOATING_TYPES*, or other dispatch macros to the new v2 API. For ATen kernel files, CUDA kernels, and native operator implementations.
Write docstrings for PyTorch functions and methods following PyTorch conventions. Use when writing or updating docstrings in PyTorch code.
Take biotender-max/ehr-analysis from the repository into ~/.claude/skills for personal
use, or into .claude/skills inside a project.
The agent identifies a skill by the name field in its header. Two skills with the
same name cannot sit side by side — one of them will be ignored.