{"slug":"alterlab-pyhealth","title":"alterlab-pyhealth","summary":"Develops, tests, and validates clinical machine learning models with the PyHealth 2.x healthcare AI toolkit. Use when working with electronic health records (EHR), clinical prediction tasks (mortality, readmission, length of stay, drug recommendation), medical coding systems (ICD","platform":"Claude","tags":[],"authorName":"LLM Mart","authorSlug":"llm-mart","score":0,"source":"github","price":null,"verified":false,"createdAt":"2026-09-23T18:57:01.115221Z","repo":{"url":"https://github.com/AlterLab-IEU/AlterLab-Academic-Skills","stars":68,"forks":13,"license":"MIT","updatedAt":"2026-09-23T13:42:59Z"},"bodyHtml":"<hr>\n<h2>name: alterlab-pyhealth\ndescription: Develops, tests, and validates clinical machine learning models with the PyHealth 2.x healthcare AI toolkit. Use when working with electronic health records (EHR), clinical prediction tasks (mortality, readmission, length of stay, drug recommendation), medical coding systems (ICD, NDC, ATC, CCS), physiological signals (EEG, ECG), healthcare datasets (MIMIC-III/IV, eICU, OMOP), or implementing deep learning models for healthcare (RETAIN, SafeDrug, GAMENet, Transformer, GAT/GCN). Part of the AlterLab Academic Skills suite.\nlicense: MIT\nallowed-tools: Read Write Edit Bash(python:*)\ncompatibility: \"Self-contained — runs under <code>uv run python</code> with PyHealth &gt;= 2.0.2 (Python 3.12-3.13) in its own environment; no API key required. MIMIC-III/IV and eICU data need the user's own PhysioNet credentialed access.\"\nmetadata:\nskill-author: AlterLab\nversion: \"1.2.0\"\nlast_updated: \"2026-09-23\"</h2>\n<h1>PyHealth: Healthcare AI Toolkit</h1>\n<h2>Overview</h2>\n<p>PyHealth is a Python library for healthcare AI that provides datasets, task definitions, models, trainers, and medical-code utilities for clinical machine learning. Use this skill when developing healthcare prediction models, processing clinical data, working with medical coding systems, or validating models before any clinical use.</p>\n<blockquote>\n<p><strong>Version gotcha (read first).</strong> This skill targets <strong>PyHealth 2.x</strong> (current release 2.0.2, Sept 2026). The 2.0 rewrite changed the API in ways most tutorials and pre-2025 snippets get wrong:</p>\n<ul>\n<li><strong>Tasks are classes you instantiate</strong>, e.g. <code>MortalityPredictionMIMIC4()</code>, <code>DrugRecommendationMIMIC3()</code> — not the old snake-case <code>mortality_prediction_mimic4_fn</code> functions. Pass the instance to <code>dataset.set_task(task)</code>.</li>\n<li><strong>Datasets take an explicit table list.</strong> Single-source loaders use <code>root=</code> + <code>tables=[...]</code> (<code>MIMIC3Dataset</code>, <code>MIMIC4EHRDataset</code>, <code>eICUDataset</code>, <code>OMOPDataset</code>); the multimodal <code>MIMIC4Dataset</code> uses <code>ehr_root=</code> + <code>ehr_tables=[...]</code> (plus optional <code>note_root</code>/<code>cxr_root</code>).</li>\n<li><strong>Models take only the <code>SampleDataset</code> plus hyperparameters</strong>, e.g. <code>Transformer(dataset=samples, embedding_dim=128)</code>. Feature keys, label key, and mode are read from the task's <code>input_schema</code> / <code>output_schema</code>; the 1.x <code>feature_keys=</code> / <code>label_key=</code> / <code>mode=</code> arguments raise <code>TypeError</code>.</li>\n<li><strong>Metric names have no <code>_score</code> suffix</strong>: <code>pr_auc</code>, <code>roc_auc</code>, <code>f1</code>; multilabel/drug-rec use the <code>*_samples</code> family (<code>jaccard_samples</code>, <code>f1_samples</code>, <code>pr_auc_samples</code>). Pass <code>metrics=[...]</code> to the <strong><code>Trainer</code> constructor</strong> and <code>monitor=</code> one of those names.</li>\n<li>Checkpoints use <code>trainer.save_ckpt(path)</code> / <code>trainer.load_ckpt(path)</code> (there is no <code>trainer.save</code>).</li>\n<li>2.0.2 requires <strong>Python 3.12 or 3.13</strong> and pins its own stack (numpy 2.2, pandas 2.3, torch 2.7, transformers 4.53), so install it in a dedicated environment rather than next to pandas 3 / transformers 5.</li>\n</ul>\n<p>When unsure of a class or argument name, check the installed source rather than trusting older snippets.</p>\n</blockquote>\n<h2>When to Use This Skill</h2>\n<p>Invoke this skill when:</p>\n<ul>\n<li><strong>Working with healthcare datasets</strong>: MIMIC-III, MIMIC-IV, eICU, OMOP, sleep EEG data, medical images</li>\n<li><strong>Clinical prediction tasks</strong>: Mortality prediction, hospital readmission, length of stay, drug recommendation</li>\n<li><strong>Medical coding</strong>: Translating between ICD-9/10, NDC, RxNorm, ATC, CCS coding systems</li>\n<li><strong>Processing clinical data</strong>: Sequential events, physiological signals, clinical text, medical images</li>\n<li><strong>Implementing healthcare models</strong>: RETAIN, SafeDrug, GAMENet, StageNet, Transformer for EHR</li>\n<li><strong>Evaluating clinical models</strong>: Fairness metrics, calibration, interpretability, uncertainty quantification</li>\n</ul>\n<h3>Does NOT Trigger</h3>\n<table>\n<thead>\n<tr>\n<th>Scenario</th>\n<th>Use Instead</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Cleaning a raw ECG/EEG/EDA trace and computing HRV or SCR features (no model training)</td>\n<td><code>alterlab-neurokit2</code></td>\n</tr>\n<tr>\n<td>Reading, anonymizing, or converting DICOM image files</td>\n<td><code>alterlab-pydicom</code></td>\n</tr>\n<tr>\n<td>Kaplan-Meier / Cox time-to-event modeling on a tabular clinical dataset</td>\n<td><code>alterlab-scikit-survival</code></td>\n</tr>\n<tr>\n<td>Biomarker-stratified cohort report with GRADE-graded treatment recommendations</td>\n<td><code>alterlab-clinical-decision</code></td>\n</tr>\n<tr>\n<td>General tabular ML on non-EHR data (scikit-learn pipelines)</td>\n<td><code>alterlab-scikit-learn</code></td>\n</tr>\n</tbody>\n</table>\n<h2>Core Capabilities</h2>\n<p>PyHealth operates through a modular 5-stage pipeline:</p>\n<ol>\n<li><strong>Data Loading</strong>: Standardized loaders for EHR, signal, imaging, and text datasets</li>\n<li><strong>Task Definition</strong>: Predefined clinical prediction tasks (task classes) or custom <code>BaseTask</code> subclasses</li>\n<li><strong>Model Selection</strong>: Baselines, general deep learning, and healthcare-specific models</li>\n<li><strong>Training</strong>: <code>Trainer</code> with best-checkpoint selection, monitoring, and evaluation</li>\n<li><strong>Validation</strong>: Calibration, conformal prediction, fairness metrics, and interpretability methods</li>\n</ol>\n<p>PyHealth 2.x uses a <strong>polars-backed</strong> data layer and caches task samples, which keeps large EHR tables memory-efficient.</p>\n<h2>Quick Start Workflow</h2>\n<pre><code>from pyhealth.datasets import MIMIC4EHRDataset, split_by_patient, get_dataloader\nfrom pyhealth.tasks import MortalityPredictionMIMIC4\nfrom pyhealth.models import Transformer\nfrom pyhealth.trainer import Trainer\n\n# 1. Load dataset (declare the tables the task needs) and set the task (a class instance)\ndataset = MIMIC4EHRDataset(\n    root=\"/path/to/mimic-iv/2.2\",\n    tables=[\"diagnoses_icd\", \"procedures_icd\", \"prescriptions\"],\n)\nsample_dataset = dataset.set_task(MortalityPredictionMIMIC4())\n\n# 2. Split data by patient (no leakage across splits)\ntrain, val, test = split_by_patient(sample_dataset, [0.7, 0.1, 0.2], seed=42)\n\n# 3. Create data loaders\ntrain_loader = get_dataloader(train, batch_size=64, shuffle=True)\nval_loader = get_dataloader(val, batch_size=64, shuffle=False)\ntest_loader = get_dataloader(test, batch_size=64, shuffle=False)\n\n# 4. Initialize the model: inputs, label (\"mortality\"), and mode (\"binary\")\n#    all come from the task schema, so only hyperparameters are passed\nmodel = Transformer(dataset=sample_dataset, embedding_dim=128)\n\ntrainer = Trainer(model=model, metrics=[\"pr_auc\", \"roc_auc\", \"f1\"])  # device auto-detected\ntrainer.train(\n    train_dataloader=train_loader,\n    val_dataloader=val_loader,\n    epochs=50,\n    monitor=\"pr_auc\",            # AUPRC — robust for the rare-mortality class\n    monitor_criterion=\"max\",\n)\n\n# 5. Evaluate (uses the metrics passed to the Trainer)\nresults = trainer.evaluate(test_loader)\n</code></pre>\n<h2>Detailed Documentation</h2>\n<p>Read the reference file that matches the step you are on:</p>\n<table>\n<thead>\n<tr>\n<th>File</th>\n<th>Read when</th>\n<th>Key topics</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>references/datasets.md</code></td>\n<td>Loading MIMIC/eICU/OMOP/signal datasets, splitting data</td>\n<td>Patient/Event structures, loaders, <code>split_by_patient</code> / <code>split_by_visit</code> / <code>split_by_sample</code></td>\n</tr>\n<tr>\n<td><code>references/medical_coding.md</code></td>\n<td>Translating or grouping ICD, NDC, RxNorm, ATC, CCS codes</td>\n<td><code>InnerMap</code> lookups and hierarchy, <code>CrossMap</code> translation</td>\n</tr>\n<tr>\n<td><code>references/tasks.md</code></td>\n<td>Choosing a predefined task or writing a custom one</td>\n<td>2.x task classes, <code>input_schema</code> / <code>output_schema</code>, custom <code>BaseTask</code></td>\n</tr>\n<tr>\n<td><code>references/models.md</code></td>\n<td>Selecting and configuring a model</td>\n<td>Baselines, RNN/CNN/Transformer, RETAIN, SafeDrug, GAMENet, StageNet, GAT/GCN</td>\n</tr>\n<tr>\n<td><code>references/preprocessing.md</code></td>\n<td>Understanding how raw events become tensors</td>\n<td>Schema-string processors (<code>\"sequence\"</code>, <code>\"timeseries\"</code>, <code>\"binary\"</code>, ...)</td>\n</tr>\n<tr>\n<td><code>references/training_evaluation.md</code></td>\n<td>Training, metrics, calibration, uncertainty, interpretability</td>\n<td><code>Trainer</code>, metric strings, conformal prediction, Chefer/IG attributions</td>\n</tr>\n</tbody>\n</table>\n<h2>Installation</h2>\n<pre><code>uv venv --python 3.13 .venv-pyhealth      # PyHealth 2.0.2 supports Python 3.12-3.13\nsource .venv-pyhealth/bin/activate\nuv pip install \"pyhealth&gt;=2.0.2\"\n</code></pre>\n<p><strong>Requirements (PyHealth 2.0.2):</strong></p>\n<ul>\n<li>Python <strong>3.12 or 3.13</strong> (<code>&gt;=3.12,&lt;3.14</code>) — if your default interpreter is 3.14, create the environment with <code>--python 3.13</code>.</li>\n<li>PyTorch, polars, pandas, scikit-learn, and transformers are installed as pinned dependencies — keep PyHealth in its own environment so these pins don't collide with other projects.</li>\n<li>A <code>2.1</code> alpha line exists on PyPI; stay on the 2.0.x releases unless you need an alpha-only feature.</li>\n</ul>\n<h2>Common Use Cases</h2>\n<h3>Use Case 1: ICU Mortality Prediction</h3>\n<p><strong>Objective</strong>: Predict patient mortality in intensive care unit</p>\n<p><strong>Approach:</strong></p>\n<ol>\n<li>Load MIMIC-IV dataset → Read <code>references/datasets.md</code></li>\n<li>Apply mortality prediction task → Read <code>references/tasks.md</code></li>\n<li>Select an interpretable model (RETAIN) or an attribution-friendly one (Transformer) → Read <code>references/models.md</code></li>\n<li>Train and evaluate → Read <code>references/training_evaluation.md</code></li>\n<li>Interpret predictions for clinical review → Read <code>references/training_evaluation.md</code></li>\n</ol>\n<h3>Use Case 2: Safe Medication Recommendation</h3>\n<p><strong>Objective</strong>: Recommend medications while avoiding drug-drug interactions</p>\n<p><strong>Approach:</strong></p>\n<ol>\n<li>Load EHR dataset (MIMIC-III/IV, eICU, or OMOP) → Read <code>references/datasets.md</code></li>\n<li>Apply a <code>DrugRecommendation*</code> task → Read <code>references/tasks.md</code></li>\n<li>Use SafeDrug or GAMENet, which build their DDI graphs from the dataset → Read <code>references/models.md</code></li>\n<li>Preprocess medication codes → Read <code>references/medical_coding.md</code></li>\n<li>Evaluate with multi-label metrics (<code>jaccard_samples</code>, <code>f1_samples</code>, <code>pr_auc_samples</code>) → Read <code>references/training_evaluation.md</code></li>\n</ol>\n<h3>Use Case 3: Hospital Readmission Prediction</h3>\n<p><strong>Objective</strong>: Identify patients at risk of readmission</p>\n<p><strong>Approach:</strong></p>\n<ol>\n<li>Load multi-site EHR data (eICU or OMOP) → Read <code>references/datasets.md</code></li>\n<li>Apply a <code>ReadmissionPrediction*</code> task → Read <code>references/tasks.md</code></li>\n<li>Handle class imbalance (report AUPRC, not only AUROC) → Read <code>references/training_evaluation.md</code></li>\n<li>Train a Transformer or RNN model → Read <code>references/models.md</code></li>\n<li>Calibrate predictions and assess fairness → Read <code>references/training_evaluation.md</code></li>\n</ol>\n<h3>Use Case 4: Sleep Staging</h3>\n<p><strong>Objective</strong>: Classify sleep stages from EEG signals</p>\n<p><strong>Approach:</strong></p>\n<ol>\n<li>Load a sleep EEG dataset (SleepEDF, SHHS, ISRUC) → Read <code>references/datasets.md</code></li>\n<li>Apply sleep staging (<code>SleepStagingSleepEDF</code> or the legacy <code>sleep_staging_*_fn</code> functions) → Read <code>references/tasks.md</code></li>\n<li>Preprocess EEG signals (filtering, segmentation) → Read <code>references/preprocessing.md</code></li>\n<li>Train a CNN, SparcNet, or ContraWR model → Read <code>references/models.md</code></li>\n<li>Evaluate per-stage performance (<code>f1_macro</code>, <code>cohen_kappa</code>) → Read <code>references/training_evaluation.md</code></li>\n</ol>\n<h3>Use Case 5: Medical Code Translation</h3>\n<p><strong>Objective</strong>: Standardize diagnoses across different coding systems</p>\n<p><strong>Approach:</strong></p>\n<ol>\n<li>Read <code>references/medical_coding.md</code> for comprehensive guidance</li>\n<li>Use <code>CrossMap</code> to translate between ICD-9, ICD-10, and CCS</li>\n<li>Group codes into clinically meaningful categories</li>\n<li>Integrate with dataset processing</li>\n</ol>\n<h3>Use Case 6: Clinical Text to ICD Coding</h3>\n<p><strong>Objective</strong>: Automatically assign ICD codes from clinical notes</p>\n<p><strong>Approach:</strong></p>\n<ol>\n<li>Load MIMIC-III with clinical notes → Read <code>references/datasets.md</code></li>\n<li>Apply the <code>MIMIC3ICD9Coding</code> task → Read <code>references/tasks.md</code></li>\n<li>Preprocess clinical text → Read <code>references/preprocessing.md</code></li>\n<li>Use <code>TransformersModel(dataset=..., model_name=\"emilyalsentzer/Bio_ClinicalBERT\")</code> → Read <code>references/models.md</code></li>\n<li>Evaluate with multi-label metrics → Read <code>references/training_evaluation.md</code></li>\n</ol>\n<h2>Best Practices</h2>\n<h3>Data Handling</h3>\n<ol>\n<li><p><strong>Always split by patient</strong>: Prevent data leakage by ensuring no patient appears in multiple splits</p>\n<pre><code>from pyhealth.datasets import split_by_patient\ntrain, val, test = split_by_patient(sample_dataset, [0.7, 0.1, 0.2], seed=42)\n</code></pre>\n</li>\n<li><p><strong>Check dataset statistics</strong>: Understand your data before modeling</p>\n<pre><code>dataset.stats()  # prints patient and event counts (returns None)\n</code></pre>\n</li>\n<li><p><strong>Use appropriate preprocessing</strong>: Match processors to data types (see <code>references/preprocessing.md</code>)</p>\n</li>\n</ol>\n<h3>Model Development</h3>\n<ol>\n<li><p><strong>Start with baselines</strong>: Establish baseline performance with simple models</p>\n<ul>\n<li><code>LogisticRegression</code> for binary/multi-class tasks</li>\n<li><code>MLP</code> for an initial deep learning baseline</li>\n</ul>\n</li>\n<li><p><strong>Choose task-appropriate models</strong>:</p>\n<ul>\n<li>Interpretability needed → RETAIN, AdaCare (by design); Transformer (post-hoc attributions)</li>\n<li>Drug recommendation → SafeDrug, GAMENet</li>\n<li>Long sequences → Transformer</li>\n<li>Graph relationships → GAT / GCN</li>\n</ul>\n</li>\n<li><p><strong>Monitor validation metrics</strong>: Use appropriate metrics for the task and handle class imbalance. PyHealth metric strings (pass to <code>Trainer(metrics=[...])</code> / <code>monitor=</code>):</p>\n<ul>\n<li>Binary: <code>roc_auc</code>, <code>pr_auc</code> (prefer <code>pr_auc</code> for rare events), <code>f1</code>, <code>accuracy</code></li>\n<li>Multi-class: <code>f1_macro</code>, <code>f1_weighted</code>, <code>accuracy</code>, <code>cohen_kappa</code></li>\n<li>Multi-label / drug-rec: <code>jaccard_samples</code>, <code>f1_samples</code>, <code>pr_auc_samples</code>, <code>ddi</code> (reported as <code>ddi_score</code>)</li>\n<li>Regression: <code>mae</code>, <code>mse</code>, <code>kl_divergence</code></li>\n</ul>\n</li>\n</ol>\n<h3>Clinical Validation</h3>\n<ol>\n<li><strong>Calibrate predictions</strong>: Ensure probabilities are reliable (see <code>references/training_evaluation.md</code>)</li>\n<li><strong>Assess fairness</strong>: Evaluate across demographic groups to detect bias</li>\n<li><strong>Quantify uncertainty</strong>: Provide confidence estimates for predictions (conformal prediction sets)</li>\n<li><strong>Interpret predictions</strong>: Attention/relevance maps, SHAP, or integrated gradients for clinician review</li>\n<li><strong>Validate thoroughly</strong>: Use held-out test sets from different time periods or sites</li>\n<li><strong>Report transparently</strong>: Follow TRIPOD+AI (BMJ 2024;385:e078378) when publishing a clinical prediction model</li>\n</ol>\n<h2>Limitations and Considerations</h2>\n<h3>Data Requirements</h3>\n<ul>\n<li><strong>Large datasets</strong>: Deep learning models require sufficient data (thousands of patients)</li>\n<li><strong>Data quality</strong>: Missing data and coding errors impact performance</li>\n<li><strong>Temporal consistency</strong>: Ensure train/test split respects temporal ordering when needed</li>\n<li><strong>Access</strong>: MIMIC and eICU require PhysioNet credentialing and a data use agreement; never copy restricted records into prompts, notebooks, or repositories that the agreement does not cover</li>\n</ul>\n<h3>Clinical Validation</h3>\n<ul>\n<li><strong>External validation</strong>: Test on data from different hospitals/systems</li>\n<li><strong>Prospective evaluation</strong>: Validate in real clinical settings before deployment</li>\n<li><strong>Clinical review</strong>: Have clinicians review predictions and interpretations</li>\n<li><strong>Decision support, not diagnosis</strong>: Present model outputs as research-grade risk estimates for qualified clinicians; deployment as a medical device falls under device regulation (e.g. FDA SaMD, EU MDR)</li>\n<li><strong>Ethical considerations</strong>: Address privacy (HIPAA/GDPR), fairness, and safety</li>\n</ul>\n<h3>Computational Resources</h3>\n<ul>\n<li><strong>GPU recommended</strong>: For training deep learning models efficiently</li>\n<li><strong>Memory requirements</strong>: Large datasets may require 16GB+ RAM</li>\n<li><strong>Storage</strong>: Healthcare datasets can be 10s-100s of GB, plus the task-sample cache</li>\n</ul>\n<h2>Troubleshooting</h2>\n<h3>Common Issues</h3>\n<p><strong><code>TypeError: ... unexpected keyword argument 'feature_keys'</code> (or <code>'root'</code>)</strong>:</p>\n<ul>\n<li>You are using a 1.x-style call. Pass only <code>dataset=</code> and hyperparameters to models; use <code>MIMIC4EHRDataset(root=..., tables=...)</code> or <code>MIMIC4Dataset(ehr_root=..., ehr_tables=...)</code></li>\n</ul>\n<p><strong>ImportError or missing tables</strong>:</p>\n<ul>\n<li>Ensure dataset files are downloaded and the root path points at the versioned folder</li>\n<li>Confirm the table names exist in the dataset's YAML config</li>\n</ul>\n<p><strong>Out of memory</strong>:</p>\n<ul>\n<li>Reduce batch size</li>\n<li>Reduce sequence length (<code>max_seq_len</code> on <code>Transformer</code>)</li>\n<li>Pass <code>dev=True</code> to the dataset loader (e.g. <code>MIMIC4EHRDataset(..., dev=True)</code>) to prototype on the first 1,000 patients</li>\n<li>Process data in chunks</li>\n</ul>\n<p><strong>Poor performance</strong>:</p>\n<ul>\n<li>Check class imbalance and use appropriate metrics (<code>pr_auc</code> vs <code>roc_auc</code>)</li>\n<li>Verify preprocessing (normalization, missing data handling)</li>\n<li>Increase model capacity or training epochs</li>\n<li>Check for data leakage in the train/test split</li>\n</ul>\n<p><strong>Slow training</strong>:</p>\n<ul>\n<li>Use a GPU (<code>Trainer(..., device=\"cuda\")</code>)</li>\n<li>Increase batch size (if memory allows)</li>\n<li>Reduce sequence length</li>\n<li>Use a lighter model (CNN or RNN instead of Transformer)</li>\n</ul>\n<h3>Getting Help</h3>\n<ul>\n<li><strong>Documentation</strong>: <a href=\"https://pyhealth.readthedocs.io/\">https://pyhealth.readthedocs.io/</a></li>\n<li><strong>GitHub Issues</strong>: <a href=\"https://github.com/sunlabuiuc/PyHealth/issues\">https://github.com/sunlabuiuc/PyHealth/issues</a></li>\n<li><strong>Examples/notebooks</strong>: <a href=\"https://github.com/sunlabuiuc/PyHealth/tree/master/examples\">https://github.com/sunlabuiuc/PyHealth/tree/master/examples</a></li>\n</ul>\n<h2>Example: Complete Workflow</h2>\n<pre><code># Complete mortality prediction pipeline (PyHealth 2.0.x)\nimport torch\nfrom pyhealth.datasets import MIMIC4EHRDataset, split_by_patient, get_dataloader\nfrom pyhealth.tasks import MortalityPredictionMIMIC4\nfrom pyhealth.models import Transformer\nfrom pyhealth.trainer import Trainer\nfrom pyhealth.interpret.methods import CheferRelevance\n\n# 1. Load dataset (declare the tables the task needs)\ndataset = MIMIC4EHRDataset(\n    root=\"/data/mimic-iv/2.2\",\n    tables=[\"diagnoses_icd\", \"procedures_icd\", \"prescriptions\"],\n)\ndataset.stats()\n\n# 2. Define task (instantiate the task class)\nsample_dataset = dataset.set_task(MortalityPredictionMIMIC4())\nprint(f\"Generated {len(sample_dataset)} samples\")\n\n# 3. Split data (by patient to prevent leakage)\ntrain_ds, val_ds, test_ds = split_by_patient(sample_dataset, [0.7, 0.1, 0.2], seed=42)\n\n# 4. Create data loaders\ntrain_loader = get_dataloader(train_ds, batch_size=64, shuffle=True)\nval_loader = get_dataloader(val_ds, batch_size=64)\ntest_loader = get_dataloader(test_ds, batch_size=64)\n\n# 5. Initialize the model (schema-driven; swap in RETAIN(dataset=sample_dataset,\n#    embedding_dim=128) for a model that is interpretable by design)\nmodel = Transformer(dataset=sample_dataset, embedding_dim=128, heads=2, num_layers=2)\n\n# 6. Train, keeping the best checkpoint by validation AUPRC\ntrainer = Trainer(model=model, metrics=[\"accuracy\", \"pr_auc\", \"roc_auc\", \"f1\"])\ntrainer.train(\n    train_dataloader=train_loader,\n    val_dataloader=val_loader,\n    epochs=50,\n    optimizer_class=torch.optim.Adam,\n    optimizer_params={\"lr\": 1e-3},\n    weight_decay=1e-5,\n    monitor=\"pr_auc\",          # AUPRC for the imbalanced (rare-mortality) outcome\n    monitor_criterion=\"max\",\n    patience=5,                # early stopping\n)\n\n# 7. Evaluate on the test set (uses the metrics passed to the Trainer)\nfor metric, value in trainer.evaluate(test_loader).items():\n    print(f\"  {metric}: {value:.4f}\")\n\n# 8. Predictions with patient IDs: inference() returns (y_true, y_prob, loss),\n#    extended with patient_ids when return_patient_ids=True\ny_true, y_prob, loss, patient_ids = trainer.inference(test_loader, return_patient_ids=True)\npositive_prob = y_prob if y_prob.ndim == 1 else y_prob[..., -1]\nhigh_risk_idx = int(positive_prob.argmax())\nprint(f\"Highest-risk patient: {patient_ids[high_risk_idx]} ({float(positive_prob[high_risk_idx]):.3f})\")\n\n# 9. Token-level relevance (Chefer; supported by Transformer and StageAttentionNet)\nrelevance = CheferRelevance(model)\nbatch = next(iter(get_dataloader(test_ds, batch_size=1, shuffle=False)))\nfor feature_key, rel in relevance.attribute(**batch).items():\n    print(f\"{feature_key}: top tokens -&gt; {rel[0].topk(min(5, rel.shape[-1])).indices.tolist()}\")\n\n# 10. Save the trained weights\ntrainer.save_ckpt(\"./models/mortality_transformer.pt\")\n</code></pre>\n<h2>Resources</h2>\n<p>For detailed information on each component, see the reference files in <code>references/</code>: <code>datasets.md</code>, <code>medical_coding.md</code>, <code>tasks.md</code>, <code>models.md</code>, <code>preprocessing.md</code>, and <code>training_evaluation.md</code> (see the table under <strong>Detailed Documentation</strong> for when to read each).</p>\n<p>Part of the AlterLab Academic Skills suite.</p>\n","files":[{"path":"evals/evals.json","sizeBytes":6353,"isText":true},{"path":"references/datasets.md","sizeBytes":6466,"isText":true},{"path":"references/medical_coding.md","sizeBytes":9171,"isText":true},{"path":"references/models.md","sizeBytes":16133,"isText":true},{"path":"references/preprocessing.md","sizeBytes":15407,"isText":true},{"path":"references/tasks.md","sizeBytes":14031,"isText":true},{"path":"references/training_evaluation.md","sizeBytes":20874,"isText":true},{"path":"SKILL.md","sizeBytes":19326,"isText":true}],"reviewScore":null,"reviewSummary":null,"trust":{"provenance":"trusted-source-unreviewed","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow.","bodySource":null},"bodyLocked":false,"purchaseUrl":null,"sourceUrl":null,"report":{"provenance":"trusted-source-unreviewed","screen":{"ran":true,"outcome":"clean","suspicious":0,"notes":0,"hiddenCharacters":false},"virusScan":{"engine":"clamav","status":"clean","scannedAt":"2026-09-23T18:58:28.593476Z","sha256":"480E230A82F974A1E2414B8501801A9910057D8B9C739D8821756BCD93636126","sizeBytes":39434},"review":null,"source":{"repositoryUrl":"https://github.com/AlterLab-IEU/AlterLab-Academic-Skills","path":"skills/clinical-research/alterlab-pyhealth","license":"MIT","commit":"e4836c08a20da195a11f30f203a8cf23ec30aa95","subtreeSha":"008FD0B54D2F68CFE8D80D2A86F87CB3EE491A21A6D163CD9F6B6A008C15E8BF","lastSyncedAt":"2026-09-23T18:56:52.297238Z"},"reviewedAt":"2026-09-23T19:01:10.355126Z","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow."},"install":[{"target":"skills-cli","command":"npx skills add https://github.com/AlterLab-IEU/AlterLab-Academic-Skills/tree/main/skills/clinical-research/alterlab-pyhealth"},{"target":"claude-code","command":"claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install alterlab-ieu-alterlab-academic-skills@llmmart"},{"target":"git","command":"git clone https://github.com/AlterLab-IEU/AlterLab-Academic-Skills.git"}]}