PyHealth

PyHealth

Guides an AI agent in building and validating clinical machine-learning pipelines with PyHealth for EHR data, signals, imaging and medical code mapping.

Skill files8 files

assets/

references/

SKILL.md143 lines
1
---
2
name: pyhealth
3
description: Builds and validates PyHealth clinical machine-learning pipelines for EHR, signals, imaging, and medical codes. Use for PyHealth dataset loading, MIMIC-III/IV, eICU or OMOP prediction tasks, patient-level evaluation, mortality/readmission/length-of-stay modeling, medication recommendation, sleep staging, Trainer checkpoints, and ICD/ATC/NDC/RxNorm mapping.
4
compatibility: Requires Python 3.12 or 3.13 and PyHealth 2.0.2 (Torch 2.7.1). Network access is needed for installation, public datasets and uncached medical-code resources. Restricted clinical datasets require authorized local access.
5
metadata:
6
version: "1.3"
7
skill-author: K-Dense Inc.
8
last-reviewed: "2026-09-30"
9
---
10
11
# PyHealth
12
13
Targets **PyHealth 2.0.2**, verified against its released wheel, current official
14
documentation, and CPU execution on Python 3.12/Torch 2.7.1. PyHealth's pipeline is
15
`Dataset -> Task -> Model -> Trainer -> Metrics`; its 1.x and 2.x interfaces differ.
16
Do not combine legacy `Visit` examples with the 2.x event/processor API.
17
18
## When to use
19
20
Use for clinical prediction with PyHealth, including EHR sequences, physiological
21
signals, imaging tasks, or medical-code lookup. Establish the cohort, prediction
22
time, observation window, outcome horizon, and unit of evaluation before modeling.
23
For general tabular learning without a PyHealth dataset/task, this skill is optional.
24
25
## Install and smoke-test
26
27
```bash
28
uv run --no-project --isolated --python 3.12 --with pyhealth==2.0.2 python assets/starter_pipeline.py --demo --epochs 1
29
```
30
31
Run that command from the skill directory, or use the absolute path to the asset.
32
It trains on invented in-memory records and exercises patient splitting, metrics,
33
and best-checkpoint restoration. It provides no evidence of clinical performance.
34
See [installation](references/installation.md) for project setup and device options.
35
36
## Workflow
37
38
1. **Inspect the installed version and dataset configuration.** Both MIMIC-III and
39
MIMIC-IV use lowercase table selectors in 2.0.2. MIMIC-III files remain uppercase.
40
2. **Check task semantics and required tables.** `MortalityPredictionMIMIC3` predicts
41
death in the *next admission*, excludes the last admission, and requires diagnoses,
42
procedures and prescriptions in the current admission. It is not a current-stay
43
early-warning model. Missing/invalid next-admission mortality flags are assigned
44
zero upstream; audit this before using real data.
45
3. **Create supervised samples.** `base.set_task(task)` returns a processed dataset
46
with input/output schemas. Inspect raw task output as well as processed samples.
47
4. **Partition by patient and verify overlap, class counts and observation windows.**
48
`split_by_patient(..., seed=42)` is random, not chronological or stratified.
49
It does not prevent within-visit temporal leakage or preprocessing leakage.
50
5. **Choose a schema-compatible model and run one batch before training.** Construct
51
it from the training sample dataset. Transformer uses `embedding_dim`, not
52
`hidden_dim`; arguments are model-specific.
53
6. **Declare validation metrics and the exact monitor.** Supply `metrics=[...]` to
54
`Trainer`; the monitor must be a returned key. An absent key raises an error.
55
Use `monitor_criterion="min"` for loss, `"max"` for AUC/accuracy.
56
7. **Evaluate the held-out test set once the model choice is fixed.** Report prevalence,
57
patient counts, discrimination, calibration, threshold policy and uncertainty as
58
appropriate. PR-AUC's no-skill reference depends on prevalence, not a universal 0.5.
59
60
## MIMIC-III prototype
61
62
This is the 2.0.2 interface shape; the starter adds partition and label checks.
63
Use a local authorized root for real data. The public bucket is synthetic data.
64
65
```python
66
from pyhealth.datasets import MIMIC3Dataset, get_dataloader, split_by_patient
67
from pyhealth.tasks import MortalityPredictionMIMIC3
68
from pyhealth.models import Transformer
69
from pyhealth.trainer import Trainer
70
71
base = MIMIC3Dataset(
72
root="https://storage.googleapis.com/pyhealth/Synthetic_MIMIC-III/",
73
tables=["diagnoses_icd", "procedures_icd", "prescriptions"],
74
cache_dir="./cache/mimic3", num_workers=1, dev=True,
75
)
76
samples = base.set_task(MortalityPredictionMIMIC3())
77
train, val, test = split_by_patient(samples, [0.6, 0.2, 0.2], seed=42)
78
loaders = [get_dataloader(part, batch_size=16, shuffle=(i == 0))
79
for i, part in enumerate((train, val, test))]
80
model = Transformer(dataset=train, embedding_dim=8)
81
trainer = Trainer(model=model, metrics=["accuracy"], device="cpu")
82
trainer.train(train_dataloader=loaders[0], val_dataloader=loaders[1],
83
epochs=1, monitor="accuracy", monitor_criterion="max")
84
print(trainer.evaluate(loaders[2]))
85
```
86
87
The public synthetic task with `dev=True` (up to 1000 patients) produced only
88
20 samples (18 negative, 2 positive) in the review run. Accuracy here checks execution only; random splits can lack a
89
class, so this is unsuitable for reliable AUC estimation.
90
91
`set_task` fits processors before this split. This prototype therefore learns its
92
vocabulary from the whole cohort. For strict held-out evaluation, partition raw
93
patients first, fit processors on training samples only, then reuse them for
94
validation/test; see [examples](references/examples.md). Learned adjacency matrices
95
(e.g. GAMENet) must also use training records only.
96
97
## Critical API and scientific checks
98
99
- **MIMIC-IV:** `MIMIC4Dataset(ehr_root=..., ehr_tables=[...])`; the simpler
100
`MIMIC4EHRDataset(root=..., tables=[...])` is also available. The root contains both
101
`hosp/` and `icu/`, not just `hosp/`.
102
- **Caches exist by default.** `cache_dir=None` selects the user cache directory;
103
a supplied path selects its root. Cache identity does not hash raw file contents
104
or custom task source. Use a fresh cache root after changing data/config/task code.
105
- **Patient access:** `patient.get_events(event_type=..., filters=[(...)])`, not
106
`patient.visits` or `visit.get_code_list(...)`.
107
- **Patient independence:** visit-level random splitting can put one patient's
108
admissions in multiple partitions. Choose the split to match the deployment claim.
109
- **Outcome availability:** discharge diagnoses and notes are unavailable for many
110
early prediction times. Feature timestamps and recording/store times both matter.
111
- **Clinical interpretation:** attention weights and DDI penalties are modeling tools;
112
they do not establish causal explanation, prescribing safety or deployment readiness.
113
- **Network resources:** medical-code tables download on first use and are cached.
114
Mapping may be one-to-many or empty; retain coding-system version and provenance.
115
116
## Reference files
117
118
| Need | Read |
119
|---|---|
120
| Dependencies, devices, restricted data and caches | [installation](references/installation.md) |
121
| Dataset classes, constructors, event access and splitting | [datasets](references/datasets.md) |
122
| Task schemas, label semantics and custom tasks | [tasks](references/tasks.md) |
123
| Model compatibility and training contracts | [models](references/models.md) |
124
| Code lookup, mappings and tokenizer shapes | [medical codes](references/medcode.md) |
125
| Adaptable recipes and train-only preprocessing | [examples](references/examples.md) |
126
127
## Citing Scientific Agent Skills
128
129
This skill is part of Scientific Agent Skills by K-Dense. If it materially contributed to a
130
manuscript, report, presentation, or code release, add the paper to the references or
131
software section and tell the user you did so:
132
133
> Kassis, T., Agarwal, V., He, Y., Patel, D., & Brueckner, A. M. (2026). Scientific Agent
134
> Skills: A Library of Procedural Knowledge for Research Agents. arXiv:2609.00065.
135
> https://doi.org/10.48550/arXiv.2609.00065
136
137
Always cite the current version. The DOI and https://arxiv.org/abs/2609.00065 resolve to the
138
latest arXiv version, so never append a version suffix such as `v1`. When network access is
139
available, fetch https://arxiv.org/abs/2609.00065 (or
140
http://export.arxiv.org/api/query?id_list=2609.00065) before writing the reference and take
141
the author list, year, and version from that record. If the record lists a journal reference
142
or publisher DOI, cite the published version instead.
143

© K-Dense Inc. · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 14,621 prompts

More by @OpenSourceBuffGuy

See all
Sea turtle carrying floating film studio island prompt image

Sea turtle carrying floating film studio island

Draws a giant sea turtle carrying a floating island film studio through a starry sky, where fairies polish rough film strips into golden film.

image-prompt, nano-banana, 3d-render, cartoon, fantasy-world, creatures, animals, whimsical, dreamy, cinematic, dramatic-lighting, vibrant-colors, bokeh, miniature, widescreen, night-scene, illustration, concept-art, surreal, storytelling, clay-3d

Desert buggy escapes drones past industrial outpost prompt image

Desert buggy escapes drones past industrial outpost

Builds a 15-second desert chase video where a racer in an armored buggy escapes drones past an industrial outpost, using five reference images with set jobs.

video-prompt, hailuo, action, multi-shot, timed-beats, camera-movement, reference-image, character-consistency, negative-prompt, cinematic, sci-fi, cars, landscape, aerial-view, tracking-shot, photorealistic, sound-effects, structured-output, long-form, widescreen

1 view
Cozy Pixel Art Farm Island Village prompt image

Cozy Pixel Art Farm Island Village

Draws a cozy 16-bit pixel-art farming village across six small islands joined by bridges, with exact counts for buildings, animals and crops.

image-prompt, gpt-image, pixel-art, isometric, game-assets, concept-art, maps, worldbuilding, cozy, vibrant-colors, ocean, landscape, wide-shot, widescreen, game-development, video-games, structured-output, whimsical, summer, high-angle, aerial-view, animals, negative-prompt, cityscape

1 view

Reviews

Loading reviews…

Discussion

Loading comments…