alterlab-pyhealth — independently scanned and version-tracked by SaferSkills.
SaferSkills independently audited alterlab-pyhealth (Agent Skill) and scored it 100/100 (green). The audit ran 55 deterministic rules across Security, Supply Chain, Maintenance, Transparency, and Community; it found 0 high-severity and 0 lower-severity findings. The full rule-by-rule trace and per-finding evidence are below. Free, methodology-open.
Findings & checks · 0 flagged
Every scanned point with the score it earned and what moved between them.
First recorded scan — no prior version to compare against.
The primary manifest — the file an agent reads to learn what this artifact does.
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 (pinpyhealth==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-casemortality_prediction_mimic4_fnfunctions. Pass the instance todataset.set_task(task). - Datasets take an explicit `tables=[...]` list (e.g.tables=["diagnoses_icd", "procedures_icd", "prescriptions"]). - Models require `label_key=` in addition tofeature_keys=andmode=. 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*_samplesfamily (jaccard_samples,f1_samples,pr_auc_samples,ddi). Passmetrics=[...]to the `Trainer` constructor, andmonitor=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.
Invoke this skill when:
PyHealth operates through a modular 5-stage pipeline optimized for healthcare AI:
PyHealth 2.x uses a polars-backed data layer for fast, memory-efficient processing of large EHR tables.
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)This skill includes comprehensive reference documentation organized by functionality. Read specific reference files as needed:
File: references/datasets.md
Read when:
Key Topics:
File: references/medical_coding.md
Read when:
Key Topics:
File: references/tasks.md
Read when:
Key Topics:
File: references/models.md
Read when:
Key Topics:
File: references/preprocessing.md
Read when:
Key Topics:
File: references/training_evaluation.md
Read when:
Key Topics:
pyhealth.interpret.methods.CheferRelevance)uv pip install "pyhealth==2.0.1"Requirements (PyHealth 2.0.1):
>=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.Objective: Predict patient mortality in intensive care unit
Approach:
references/datasets.mdreferences/tasks.mdreferences/models.mdreferences/training_evaluation.mdreferences/training_evaluation.mdObjective: Recommend medications while avoiding drug-drug interactions
Approach:
references/datasets.mdreferences/tasks.mdreferences/models.mdreferences/medical_coding.mdreferences/training_evaluation.mdObjective: Identify patients at risk of 30-day readmission
Approach:
references/datasets.mdreferences/tasks.mdreferences/preprocessing.mdreferences/models.mdreferences/training_evaluation.mdObjective: Classify sleep stages from EEG signals
Approach:
references/datasets.mdreferences/tasks.mdreferences/preprocessing.mdreferences/models.mdreferences/training_evaluation.mdObjective: Standardize diagnoses across different coding systems
Approach:
references/medical_coding.md for comprehensive guidanceObjective: Automatically assign ICD codes from clinical notes
Approach:
references/datasets.mdreferences/tasks.mdreferences/preprocessing.mdreferences/models.mdreferences/training_evaluation.md from pyhealth.datasets import split_by_patient
train, val, test = split_by_patient(dataset, [0.7, 0.1, 0.2]) print(dataset.stats()) # Patients, visits, events, code distributionsreferences/preprocessing.md)Trainer(metrics=[...]) / monitor=):roc_auc, pr_auc (prefer pr_auc for rare events), f1, accuracyf1_macro, f1_weighted, accuracy, cohen_kappajaccard_samples, f1_samples, pr_auc_samples, ddimae, mse, r2references/training_evaluation.md)ImportError for dataset:
Out of memory:
max_seq_length)Poor performance:
pr_auc vs roc_auc)Slow training:
device="cuda")# 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!")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.
~30 seconds. Free. No account. Every finding cites a rule and a line of evidence.