pyhealth

davila7/claude-code-templates · updated Apr 8, 2026

MDX-style export adds YAML metadata + attribution linking explainx.ai and this canonical listing URL.

$npx skills add https://github.com/davila7/claude-code-templates --skill pyhealth
0 commentsdiscussion
summary

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.

skill.md

PyHealth: Healthcare AI Toolkit

Overview

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.

When to Use This Skill

Invoke this skill when:

  • Working with healthcare datasets: MIMIC-III, MIMIC-IV, eICU, OMOP, sleep EEG data, medical images
  • Clinical prediction tasks: Mortality prediction, hospital readmission, length of stay, drug recommendation
  • Medical coding: Translating between ICD-9/10, NDC, RxNorm, ATC coding systems
  • Processing clinical data: Sequential events, physiological signals, clinical text, medical images
  • Implementing healthcare models: RETAIN, SafeDrug, GAMENet, StageNet, Transformer for EHR
  • Evaluating clinical models: Fairness metrics, calibration, interpretability, uncertainty quantification

Core Capabilities

PyHealth operates through a modular 5-stage pipeline optimized for healthcare AI:

  1. Data Loading: Access 10+ healthcare datasets with standardized interfaces
  2. Task Definition: Apply 20+ predefined clinical prediction tasks or create custom tasks
  3. Model Selection: Choose from 33+ models (baselines, deep learning, healthcare-specific)
  4. Training: Train with automatic checkpointing, monitoring, and evaluation
  5. Deployment: Calibrate, interpret, and validate for clinical use

Performance: 3x faster than pandas for healthcare data processing

Quick Start Workflow

from pyhealth.datasets import MIMIC4Dataset
from pyhealth.tasks import mortality_prediction_mimic4_fn
from pyhealth.datasets import split_by_patient, get_dataloader
from pyhealth.models import Transformer
from pyhealth.trainer import Trainer

# 1. Load dataset and set task
dataset = MIMIC4Dataset(root="/path/to/data")
sample_dataset = dataset.set_task(mortality_prediction_mimic4_fn)

# 2. Split data
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 model
model = Transformer(
    dataset=sample_dataset,
    feature_keys=["diagnoses", "medications"],
    mode="binary",
    embedding_dim=128
)

trainer = Trainer(model=model, device="cuda")
trainer.train(
    train_dataloader=train_loader,
    val_dataloader=val_loader,
    epochs=50,
    monitor="pr_auc_score"
)

# 5. Evaluate
results = trainer.evaluate(test_loader)

Detailed Documentation

This skill includes comprehensive reference documentation organized by functionality. Read specific reference files as needed:

1. Datasets and Data Structures

File: references/datasets.md

Read when:

  • Loading healthcare datasets (MIMIC, eICU, OMOP, sleep EEG, etc.)
  • Understanding Event, Patient, Visit data structures
  • Processing different data types (EHR, signals, images, text)
  • Splitting data for training/validation/testing
  • Working with SampleDataset for task-specific formatting

Key Topics:

  • Core data structures (Event, Patient, Visit)
  • 10+ available datasets (EHR, physiological signals, imaging, text)
  • Data loading and iteration
  • Train/val/test splitting strategies
  • Performance optimization for large datasets

2. Medical Coding Translation

File: references/medical_coding.md

Read when:

  • Translating between medical coding systems
  • Working with diagnosis codes (ICD-9-CM, ICD-10-CM, CCS)
  • Processing medication codes (NDC, RxNorm, ATC)
  • Standardizing procedure codes (ICD-9-PROC, ICD-10-PROC)
  • Grouping codes into clinical categories
  • Handling hierarchical drug classifications

Key Topics:

  • InnerMap for within-system lookups
  • CrossMap for cross-system translation
  • Supported coding systems (ICD, NDC, ATC, CCS, RxNorm)
  • Code standardization and hierarchy traversal
  • Medication classification by therapeutic class
  • Integration with datasets

3. Clinical Prediction Tasks

File: references/tasks.md

Read when:

  • Defining clinical prediction objectives
  • Using predefined tasks (mortality, readmission, drug recommendation)
  • Working with EHR, signal, imaging, or text-based tasks
  • Creating custom prediction tasks
  • Setting up input/output schemas for models
  • Applying task-specific filtering logic

Key Topics:

  • 20+ predefined clinical tasks
  • EHR tasks (mortality, readmission, length of stay, drug recommendation)
  • Signal tasks (sleep staging, EEG analysis, seizure detection)
  • Imaging tasks (COVID-19 chest X-ray classification)
  • Text tasks (medical coding, specialty classification)
  • Custom task creation patterns

4. Models and Architectures

File: references/models.md

Read when:

  • Selecting models for clinical prediction
  • Understanding model architectures and capabilities
  • Choosing between general-purpose and healthcare-specific models
  • Implementing interpretable models (RETAIN, AdaCare)
  • Working with medication recommendation (SafeDrug, GAMENet)
  • Using graph neural networks for healthcare
  • Configuring model hyperparameters

Key Topics:

  • 33+ available models
  • General-purpose: Logistic Regression, MLP, CNN, RNN, Transformer, GNN
  • Healthcare-specific: RETAIN, SafeDrug, GAMENet, StageNet, AdaCare
  • Model selection by task type and data type
  • Interpretability considerations
  • Computational requirements
  • Hyperparameter tuning guidelines

5. Data Preprocessing

File: references/preprocessing.md

Read when:

  • Preprocessing clinical data for models
  • Handling sequential events and time-series data
  • Processing physiological signals (EEG, ECG)
  • Normalizing lab values and vital signs
  • Preparing labels for different task types
  • Building feature vocabularies
  • Managing missing data and outliers

Key Topics:

  • 15+ processor types
  • Sequence processing (padding, truncation)
  • Signal processing (filtering, segmentation)
  • Feature extraction and encoding
  • Label processors (binary, multi-class, multi-label, regression)
  • Text and image preprocessing
  • Common preprocessing workflows

6. Training and Evaluation

File: references/training_evaluation.md

Read when:

  • Training models with the Trainer class
  • Evaluating model performance
  • Computing clinical metrics
  • Assessing model fairness across demographics
  • Calibrating predictions for reliability
  • Quantifying prediction uncertainty
  • Interpreting model predictions
  • Preparing models for clinical deployment

Key Topics:

  • Trainer class (train, evaluate, inference)
  • Metrics for binary, multi-class, multi-label, regression tasks
  • Fairness metrics for bias assessment
  • Calibration methods (Platt scaling, temperature scaling)
  • Uncertainty quantification (conformal prediction, MC dropout)
  • Interpretability tools (attention visualization, SHAP, ChEFER)
  • Complete training pipeline example

Installation

uv pip install pyhealth

Requirements:

  • Python ≥ 3.7
  • PyTorch ≥ 1.8
  • NumPy, pandas, scikit-learn

Common Use Cases

Use Case 1: ICU Mortality Prediction

Objective: Predict patient mortality in intensive care unit

Approach:

  1. Load MIMIC-IV dataset → Read references/datasets.md
  2. Apply mortality prediction task → Read references/tasks.md
  3. Select interpretable model (RETAIN) → Read references/models.md
  4. Train and evaluate → Read references/training_evaluation.md
  5. Interpret predictions for clinical use → Read references/training_evaluation.md

Use Case 2: Safe Medication Recommendation

Objective: Recommend medications while avoiding drug-drug interactions

Approach:

  1. Load EHR dataset (MIMIC-IV or OMOP) → Read references/datasets.md
  2. Apply drug recommendation task → Read references/tasks.md
  3. Use SafeDrug model with DDI constraints → Read references/models.md
  4. Preprocess medication codes → Read references/medical_coding.md
  5. Evaluate with multi-label metrics → Read references/training_evaluation.md

Use Case 3: Hospital Readmission Prediction

Objective: Identify patients at risk of 30-day readmission

Approach:

  1. Load multi-site EHR data (eICU or OMOP) → Read references/datasets.md
  2. Apply readmission prediction task → Read references/tasks.md
  3. Handle class imbalance in preprocessing → Read references/preprocessing.md
  4. Train Transformer model → Read references/models.md
  5. Calibrate predictions and assess fairness → Read references/training_evaluation.md

Use Case 4: Sleep Disorder Diagnosis

Objective: Classify sleep stages from EEG signals

Approach:

  1. Load sleep EEG dataset (SleepEDF, SHHS) → Read references/datasets.md
  2. Apply sleep staging task → Read references/tasks.md
  3. Preprocess EEG signals (filtering, segmentation) → Read references/preprocessing.md
  4. Train CNN or RNN model → Read references/models.md
  5. Evaluate per-stage performance → Read references/training_evaluation.md

Use Case 5: Medical Code Translation

Objective: Standardize diagnoses across different coding systems

Approach:

  1. Read references/medical_coding.md for comprehensive guidance
  2. Use CrossMap to translate between ICD-9, ICD-10, CCS
  3. Group codes into clinically meaningful categories
  4. Integrate with dataset processing

Use Case 6: Clinical Text to ICD Coding

Objective: Automatically assign ICD codes from clinical notes

Approach:

  1. Load MIMIC-III with clinical text → Read references/datasets.md
  2. Apply ICD coding task → Read references/tasks.md
  3. Preprocess clinical text → Read references/preprocessing.md
  4. Use TransformersModel (ClinicalBERT) → Read references/models.md
  5. Evaluate with multi-label metrics → Read references/training_evaluation.md

Best Practices

Data Handling

  1. Always split by patient: Prevent data leakage by ensuring no patient appears in multiple splits

    from pyhealth.datasets import split_by_patient
    train, val, test = split_by_patient(dataset, [0.7, 0.1, 0.2])
    
  2. Check dataset statistics: Understand your data before modeling

    print(dataset.stats())  # Patients, visits, events, code distributions
    
  3. Use appropriate preprocessing: Match processors to data types (see references/preprocessing.md)

Model Development

  1. Start with baselines: Establish baseline performance with simple models

    • Logistic Regression for binary/multi-class tasks
    • MLP for initial deep learning baseline
  2. Choose task-appropriate models:

    • Interpretability needed → RETAIN, AdaCare
    • Drug recommendation → SafeDrug, GAMENet
    • Long sequences → Transformer
    • Graph relationships → GNN
  3. Monitor validation metrics: Use appropriate metrics for task and handle class imbalance

    • Binary classification: AUROC, AUPRC (especially for rare events)
    • Multi-class: macro-F1 (for imbalanced), weighted-F1
    • Multi-label: Jaccard, example-F1
    • Regression: MAE, RMSE

Clinical Deployment

  1. Calibrate predictions: Ensure probabilities are reliable (see references/training_evaluation.md)

  2. Assess fairness: Evaluate across demographic groups to detect bias

  3. Quantify uncertainty: Provide confidence estimates for predictions

  4. Interpret predictions: Use attention weights, SHAP, or ChEFER for clinical trust

  5. Validate thoroughly: Use held-out test sets from different time periods or sites

Limitations and Considerations

Data Requirements

  • Large datasets: Deep learning models require sufficient data (thousands of patients)
  • Data quality: Missing data and coding errors impact performance
  • Temporal consistency: Ensure train/test split respects temporal ordering when needed

Clinical Validation

  • External validation: Test on data from different hospitals/systems
  • Prospective evaluation: Validate in real clinical settings before deployment
  • Clinical review: Have clinicians review predictions and interpretations
  • Ethical considerations: Address privacy (HIPAA/GDPR), fairness, and safety

Computational Resources

  • GPU recommended: For training deep learning models efficiently
  • Memory requirements: Large datasets may require 16GB+ RAM
  • Storage: Healthcare datasets can be 10s-100s of GB

Troubleshooting

Common Issues

ImportError for dataset:

  • Ensure dataset files are downloaded and path is correct
  • Check PyHealth version compatibility

Out of memory:

  • Reduce batch size
  • Reduce sequence length (max_seq_length)
  • Use gradient accumulation
  • Process data in chunks

Poor performance:

  • Check class imbalance and use appropriate metrics (AUPRC vs AUROC)
  • Verify preprocessing (normalization, missing data handling)
  • Increase model capacity or training epochs
  • Check for data leakage in train/test split

Slow training:

  • Use GPU (device="cuda")
  • Increase batch size (if memory allows)
  • Reduce sequence length
  • Use more efficient model (CNN vs Transformer)

Getting Help

Example: Complete Workflow

# Complete mortality prediction pipeline
from pyhealth.datasets import MIMIC4Dataset
from pyhealth.tasks import morta
how to use pyhealth

How to use pyhealth on Cursor

AI-first code editor with Composer

1

Prerequisites

Before installing skills in Cursor, ensure your development environment meets these requirements:

  • Cursor installed and configured on your development machine
  • Node.js version 16.0+ with npm package manager (verify with node --version)
  • Active project directory or workspace where you want to add pyhealth
2

Execute installation command

Execute the skills CLI command in your project's root directory to begin installation:

$npx skills add https://github.com/davila7/claude-code-templates --skill pyhealth

The skills CLI fetches pyhealth from GitHub repository davila7/claude-code-templates and configures it for Cursor.

3

Select Cursor when prompted

The CLI will show a list of available agents. Use arrow keys to navigate and space to select Cursor:

◆ Which agents do you want to install to?
│ ── Universal (.agents/skills) ── always included ────
│ • Amp
│ • Antigravity
│ • Cline
│ • Codex
│ ●Cursor(selected)
│ • Cursor
│ • Windsurf
4

Verify installation

Confirm successful installation by checking the skill directory location:

.cursor/skills/pyhealth

Reload or restart Cursor to activate pyhealth. Access the skill through slash commands (e.g., /pyhealth) or your agent's skill management interface.

Security & Verification Notice

We perform automated surface-level scans (Gen AI Scanner, Socket, Snyk) during installation. These checks detect common vulnerabilities but do not guarantee complete security. Always review skill source code and verify the publisher's reputation before production use.

Skills execute code in your development environment. Always verify the publisher's identity, review recent commits, and test in isolated environments before production deployment.

List & Monetize Your Skill

Submit your Claude Code skill and start earning

GET_STARTED →

Use Cases

User Story & Requirements Generation

Create detailed user stories, acceptance criteria, and feature specs

Example

Generate user stories for 'password reset feature' with acceptance criteria, edge cases, and test scenarios

Reduce spec writing time by 50%, ensure comprehensive coverage

Competitive Analysis

Research competitors, compare features, identify gaps

Example

Analyze 5 competitor products, create feature comparison matrix, suggest differentiation opportunities

Complete competitive research in 2 hours instead of 2 days

Roadmap Prioritization

Evaluate features using frameworks (RICE, ICE, Kano) and create prioritized backlogs

Example

Score 20 feature ideas using RICE framework, generate prioritized roadmap with rationale

Make data-driven prioritization decisions faster

Stakeholder Communication

Draft PRDs, status updates, and stakeholder presentations

Example

Create executive summary of Q3 roadmap, monthly progress report, feature launch announcement

Save 3-5 hours/week on communication overhead

Implementation Guide

Prerequisites

  • Claude Desktop or compatible AI client
  • Access to product documentation and roadmap tools (Jira, Notion, etc.)
  • Understanding of product management frameworks (RICE, Jobs-to-be-Done, etc.)
  • Stakeholder contact information and communication channels

Time Estimate

30-60 minutes to see productivity improvements

Installation Steps

  1. 1.Install product management skill
  2. 2.Start with user story generation for known feature
  3. 3.Progress to competitive analysis: research 2-3 competitors
  4. 4.Use for roadmap prioritization: apply RICE/ICE scoring
  5. 5.Draft stakeholder communications and refine based on feedback
  6. 6.Build template library for recurring PM tasks
  7. 7.Share effective prompts with product team

Common Pitfalls

  • Not validating competitive research—verify facts before sharing
  • Accepting user stories without involving engineering team
  • Over-relying on frameworks without qualitative judgment
  • Not customizing outputs to company culture and communication style
  • Skipping stakeholder validation of generated requirements

Best Practices

✓ Do

  • +Validate research and competitive analysis with real data
  • +Collaborate with engineering when generating technical requirements
  • +Customize frameworks and templates to your company context
  • +Use skill for first drafts, refine with stakeholder input
  • +Document successful prompt patterns for PM tasks
  • +Combine AI efficiency with human judgment and intuition

✗ Don't

  • Don't publish competitive analysis without fact-checking
  • Don't finalize user stories without engineering review
  • Don't make prioritization decisions solely on AI scoring
  • Don't skip customer validation of generated requirements
  • Don't ignore company-specific context and culture

💡 Pro Tips

  • Provide context: company goals, constraints, customer feedback
  • Ask for alternatives: 'Show 3 ways to prioritize this roadmap'
  • Request stakeholder-specific formatting: 'Executive summary vs. engineering spec'
  • Use skill for 70% generation + 30% customization to company needs

When to Use This

✓ Use When

Use for user story writing, competitive research, roadmap prioritization, stakeholder communication, and PRD drafting. Best for reducing repetitive documentation and research work.

✗ Avoid When

Avoid for strategic product vision (requires deep customer empathy), pricing decisions (needs market and financial expertise), or when face-to-face customer discovery is more valuable than speed.

Learning Path

  1. 1Basic: user stories, feature specs, status updates
  2. 2Intermediate: competitive analysis, prioritization frameworks, PRDs
  3. 3Advanced: product strategy, go-to-market planning, OKR setting
  4. 4Expert: product vision, market positioning, business model innovation

Discussion

Product Hunt–style comments (not star reviews)
  • No comments yet — start the thread.
general reviews

Ratings

4.573 reviews
  • Zara Thomas· Dec 20, 2024

    pyhealth has been reliable in day-to-day use. Documentation quality is above average for community skills.

  • Jin Garcia· Dec 20, 2024

    Registry listing for pyhealth matched our evaluation — installs cleanly and behaves as described in the markdown.

  • Li Jain· Dec 12, 2024

    pyhealth reduced setup friction for our internal harness; good balance of opinion and flexibility.

  • Arjun Ghosh· Dec 8, 2024

    pyhealth is among the better-maintained entries we tried; worth keeping pinned for repeat workflows.

  • Dev Desai· Dec 4, 2024

    pyhealth fits our agent workflows well — practical, well scoped, and easy to wire into existing repos.

  • Benjamin Chawla· Dec 4, 2024

    pyhealth reduced setup friction for our internal harness; good balance of opinion and flexibility.

  • Lucas Khan· Nov 27, 2024

    Solid pick for teams standardizing on skills: pyhealth is focused, and the summary matches what you get after install.

  • Zara Brown· Nov 23, 2024

    I recommend pyhealth for anyone iterating fast on agent tooling; clear intent and a small, reviewable surface area.

  • Lucas Li· Nov 15, 2024

    We added pyhealth from the explainx registry; install was straightforward and the SKILL.md answered most questions upfront.

  • Arya Anderson· Nov 11, 2024

    We added pyhealth from the explainx registry; install was straightforward and the SKILL.md answered most questions upfront.

showing 1-10 of 73

1 / 8