Ehr analysis

From zongtingwei/Bioclaw_Skills_Hub · View interactive version

Ehr analysis is an AI agent skill from the GitHub repository zongtingwei/Bioclaw_Skills_Hub. End-to-end EHR predictive modeling pipeline with PyHealth, covering dataset loading, task definition, model training, evaluation, calibration, and clinical interpretation.

How to use this skill

Skill file

EHR Analysis

Version Compatibility

Reference examples assume:

Verify the runtime first:

Overview

Use this skill when the user needs to:

When To Use This Skill

Quick Route

Progressive Disclosure

Default Rules

Expected Inputs

Expected Outputs

Preferred Tools

Starter Pattern

from 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)

Workflow

1. Validate dataset access and structure

Confirm the EHR source is accessible and the required tables are present. Inspect patient counts, visit counts, and code distributions before building tasks.

2. Load data with `pyhealth.datasets`

Use 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.

3. Define the clinical task

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.

4. Split patients and build dataloaders

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.

5. Initialize and train the model

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.

6. Evaluate and report

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.

7. Calibrate and interpret where needed

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.

Output Artifacts

results/
├── model_checkpoint.pth
├── test_metrics.json
└── predictions.tsv
qc/
├── dataset_stats.tsv
└── split_summary.tsv
figures/
├── calibration_curve.pdf
└── feature_importance.pdf

Key Parameters

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

Quality Review

Anti-Patterns

Related Skills

Optional Supplements

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.