Skip to content

Add KEEP: Ontology-Informed Clinical Code Embeddings with MIMIC-IV Reproduction - #1666

Merged
solarsys merged 15 commits into
sunlabuiuc:masterfrom
DataMiner79:feature/keep-embeddings
Nov 29, 2026
Merged

solarsys merged 15 commits into
sunlabuiuc:masterfrom
DataMiner79:feature/keep-embeddings

Conversation

@DataMiner79

@DataMiner79 DataMiner79 commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Overview

This PR introduces KEEP, an ontology-informed clinical code embedding
method that combines medical ontology knowledge with empirical clinical
code co-occurrence statistics.

Implementation

  • Added KEEP, KEEPConfig, and fit_keep to the PyHealth public model API.
  • Implemented sparse GloVe-style embedding training with optional Node2Vec initialization.
  • Supported cosine and L2 ontology regularization.
  • Supported batch-level and full-vocabulary regularization.
  • Added random initialization for codes without matching ontology embeddings and excluded these codes from ontology regularization.
  • Used a dedicated local PyTorch random generator for deterministic initialization without modifying the global RNG state.
  • Added embedding export compatible with PyHealth downstream models.
  • Provided MIMIC-IV preprocessing, ontology extraction, embedding training, and downstream evaluation examples.
  • Used JSON-based ontology graph serialization that preserves both edges and isolated nodes.
  • Made Node2Vec and Gensim optional dependencies with informative error messages.
  • Provided configurable command-line arguments for data and output paths.
  • Supported CUDA, MPS, and CPU device selection for downstream evaluation.

KEEP intentionally inherits from torch.nn.Module rather than
BaseModel, as it performs unsupervised embedding pretraining rather
than downstream clinical prediction.

The sparsity preprocessing script intentionally reuses functions from
keep_mimic_preprocessing.py to ensure consistent diagnosis filtering
and co-occurrence construction across experiments.

Reproduction Results

Experimental results provenance: All reproduction, intrinsic evaluation,
and data-sparsity ablation results reported below were obtained using an
earlier version of the KEEP implementation, before the unmatched ontology
embedding initialization and RNG isolation fixes. The full MIMIC-IV
experiments have not been rerun with the current implementation.
These results therefore characterize the earlier experimental
implementation rather than the final revised code.

We evaluated four embedding initialization methods using a PyHealth
Transformer for 30-day readmission prediction on MIMIC-IV v3.1.

Results are reported as mean ± sample standard deviation across
three downstream random seeds.

Embedding Test AUROC Test AUPRC
Random 0.6646 ± 0.0016 0.5072 ± 0.0023
GloVe 0.6678 ± 0.0021 0.5128 ± 0.0027
Initialized GloVe 0.6681 ± 0.0016 0.5132 ± 0.0031
KEEP 0.6717 ± 0.0058 0.5172 ± 0.0053

In these experiments, KEEP achieved the highest mean performance on
both metrics, directionally reproducing the original paper's findings.
Statistical significance has not been established, and absolute
performance is not directly comparable to the original paper because
of differences in preprocessing, cohort construction, and downstream
experimental configuration.

Additional Experiments

We conducted two additional evaluations:

  • Intrinsic evaluation of embedding alignment with ontology structure
    and empirical co-occurrence statistics.
  • Data-sparsity ablation using 100%, 50%, 25%, 10%, and 5% of the
    empirical embedding pretraining cohort.

At 5% data availability, KEEP achieved a mean test AUPRC of 0.5157
compared with 0.5103 for GloVe. The downstream training cohort
remained fixed throughout the ablation.

The results suggest that KEEP retains its performance under reduced
empirical pretraining data. However, the relative advantage over
GloVe does not increase monotonically across all data fractions,
and statistical significance has not been established.

As noted above, these experiments were performed before the latest
implementation fixes.

Testing

All 33 KEEP unit tests passed locally, achieving 100% statement
coverage
of keep.py (119/119 statements).

The tests cover:

  • Embedding initialization, dimensions, and export.
  • Loss computation and gradient propagation.
  • Cosine and L2 ontology regularization.
  • Sparse embedding training.
  • Batch-level and full-vocabulary regularization.
  • Random initialization of unmatched ontology embeddings.
  • Exclusion of unmatched codes from ontology regularization.
  • Gradient propagation for unmatched codes.
  • Deterministic initialization.
  • Global PyTorch RNG isolation.
  • Rejection of nonfinite ontology references.
  • Invalid sparse input shapes.
  • Out-of-range vocabulary indices.
  • Empty, negative, and nonfinite co-occurrence counts.
  • Invalid vocabulary and embedding dimensions.
  • Incorrect initial embedding shapes.
  • Invalid regularization weights and configuration settings.
  • Invalid forward-pass inputs.

The synthetic example and public API imports were also verified.

Official GitHub CI Results

Metric Result
KEEP unit tests 33 passed locally
KEEP statement coverage 100%
Covered KEEP statements 119/119
Overall PyHealth statement coverage 87.69%

The official GitHub CI coverage report confirms 100% statement
coverage of the KEEP implementation, matching the local results
and exceeding the required 80% coverage threshold.

Run the KEEP unit tests and synthetic example from the repository root:

python -m pytest tests/core/test_keep.py -v
python examples/keep_synthetic.py

To measure KEEP statement coverage:

python -m coverage run --include="*/pyhealth/models/keep.py" -m pytest tests/core/test_keep.py -v
python -m coverage report -m --fail-under=80

Documentation and Reproducibility

The official documentation page at
docs/api/models/pyhealth.models.KEEP.rst contains implementation
details, API documentation, reproduction commands, experimental
configurations, historical results, and limitations.

KEEP is registered in the PyHealth model documentation index at
docs/api/models.rst.

The examples/ directory contains scripts for ontology extraction,
clinical co-occurrence preprocessing, embedding training, vector
export, intrinsic evaluation, downstream readmission prediction,
and data-sparsity experiments.

The historical experimental results are retained as numerical
tables in the documentation.

No MIMIC-IV source data, patient identifiers, pretrained embeddings,
trained model checkpoints, or generated experimental PNG and CSV
artifacts are included in the current contribution.

Relationship to PR #1661

This contribution focuses on KEEP's embedding-training model,
ontology regularization, and downstream evaluation. PR #1661
focuses on OMOP/SNOMED ontology construction and clinical
co-occurrence preprocessing.

The two contributions are complementary and provide a potential
foundation for integrating KEEP's data preprocessing and
embedding-training components within PyHealth.

Contributors

  • Stanislav Sheludko
  • Kalindu Madduma Hewage

This contribution was developed as part of Georgia Tech's CSE6250
Big Data Analytics for Healthcare course, Fall 2026.

@github-actions

github-actions Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 87.69% (53876 / 61441 lines)

Modified file Coverage Lines
pyhealth/datasets/__init__.py 100.00% 88 / 88
pyhealth/datasets/mitbih.py 97.35% 110 / 113
pyhealth/metrics/fairness_utils/__init__.py 100.00% 3 / 3
pyhealth/metrics/fairness_utils/capacity.py 100.00% 59 / 59
pyhealth/models/__init__.py 100.00% 109 / 109
pyhealth/models/concept_bottleneck.py 96.71% 294 / 304
pyhealth/models/keep.py 100.00% 119 / 119
pyhealth/tasks/__init__.py 98.43% 125 / 127
pyhealth/tasks/clinical_presence_mortality_mimic3.py 98.84% 256 / 259
pyhealth/tasks/mitbih.py 98.41% 62 / 63
pyhealth/tasks/vasopressor_onset_mimic3.py 94.98% 265 / 279
pyhealth/tasks/vasopressor_onset_mimic4.py 97.37% 37 / 38

Workflow run · 05d034b

@solarsys

Copy link
Copy Markdown
Collaborator

Thanks for KEEP. This PR doesn't have a review label yet, for these reasons:

  • KEEP_README.md and summarize.py sit at the repo root, outside the allowed folders.
  • The test is in tests/models/, which CI never runs. CI only runs tests/core and tests/nlp.
  • The draft KEEP Integration etc. #1661 also integrates KEEP. Please coordinate with its author.

To make it eligible for automatic review:

  • Move the README content into a docs page (docs/api/models/...) or an example's docstring, and move summarize.py into examples/ or drop it.
  • Move the test to tests/core/test_keep.py, and make sure it covers keep.py to at least 80%.
  • Register the model in docs/api/models.rst with a docs page.

Then we'll add status: automatic and request an AI review.

@solarsys solarsys mentioned this pull request Nov 28, 2026
@solarsys

Copy link
Copy Markdown
Collaborator

We compared this with the draft #1661. They're complementary: this PR trains the KEEP embeddings, and #1661 builds the OMOP/SNOMED data side. We'd like this PR to be the base for KEEP's model once it's ready:

  1. Move the test to tests/core/test_keep.py and cover keep.py to at least 80%. It's at 24% now, and tests/models/ doesn't run in CI.
  2. Delete the root KEEP_README.md and summarize.py. Put the README content in a docs/api/models page with a models.rst entry, and drop the committed PNGs and CSVs.
  3. Fix a likely bug: keep_prepare_embeddings.py zero-fills codes without a node2vec match. Zero target and context vectors get zero gradient, so those codes stay at zero. Initialize unmatched rows randomly, or guard against it in KEEP.
  4. Also:
    • replace the pickled graph with an edge list or JSON;
    • remove the global torch.manual_seed in __init__;
    • make node2vec/gensim optional, with a clear error;
    • remove the hard-coded paths.

Then it can get status: automatic.

@DataMiner79

Copy link
Copy Markdown
Contributor Author

We compared this with the draft #1661. They're complementary: this PR trains the KEEP embeddings, and #1661 builds the OMOP/SNOMED data side. We'd like this PR to be the base for KEEP's model once it's ready:

  1. Move the test to tests/core/test_keep.py and cover keep.py to at least 80%. It's at 24% now, and tests/models/ doesn't run in CI.

  2. Delete the root KEEP_README.md and summarize.py. Put the README content in a docs/api/models page with a models.rst entry, and drop the committed PNGs and CSVs.

  3. Fix a likely bug: keep_prepare_embeddings.py zero-fills codes without a node2vec match. Zero target and context vectors get zero gradient, so those codes stay at zero. Initialize unmatched rows randomly, or guard against it in KEEP.

  4. Also:

    • replace the pickled graph with an edge list or JSON;
    • remove the global torch.manual_seed in __init__;
    • make node2vec/gensim optional, with a clear error;
    • remove the hard-coded paths.

Then it can get status: automatic.

Thank you for comparing the two contributions and clarifying the intended direction for KEEP integration. We are glad that the two implementations are complementary and appreciate your recommendation to use #1666 as the base for the KEEP model.

We have already addressed the repository organization and documentation requirements and verified 91.15% local coverage of keep.py.

We will also address the additional feedback regarding unmatched embedding initialization, graph serialization, global RNG state, optional dependencies, configurable paths, and removal of committed experimental artifacts.

Thank you for the detailed technical review.

@solarsys solarsys added the status: automatic The PR will go through automatic review process. label Nov 28, 2026
@solarsys

Copy link
Copy Markdown
Collaborator

/review

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

Reviewed commit c2c29e6

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

AI Review

suggestion: need change
decision: need change

Thank you for contributing KEEP. It adds ontology-informed clinical code embedding pretraining to PyHealth, with a full MIMIC-IV reproduction pipeline, an intrinsic evaluation and a data-sparsity ablation. The implementation is self-contained and well tested. Coverage meets the bar: keep.py is at 91.6% and the whole repository is at 87.49%. The change is close, but a few things need fixing first.

To get this merged:

  1. The reported results are stale. The docs page says the tables come from runs made before the missing-reference and RNG fixes, and that they "have not been rerun with the revised code". The PR description presents the same numbers as the reproduction. Please rerun the pipeline with the final code and update the numbers in the description and docs. If you can't, say plainly in the description that the numbers come from an earlier code version.
  2. Fix the test references. The description cites tests/models/test_keep.py and says "seven" tests passed. The file is tests/core/test_keep.py, and it now has more tests. Please correct the path, the count and the pytest command.
  3. Clean up the docs page pyhealth.models.KEEP.rst. It contains internal review notes and process text: "added during review", "CI coverage ... must be confirmed", "Review the upstream PyHealth pull request", and the .gitignore advice. The page should describe the shipped code and no more. Please trim it so the statements match the final code and tests.

Optional suggestions:

  • Add tests for the index and shape validation in fit_keep.
  • Remove the commented-out debug prints in the example scripts.
  • keep_sparsity_preprocessing.py imports from keep_mimic_preprocessing.py. This is fine, but a one-line note in the description would make it clear it is intentional.
  • The description says "Fall 2026" for the course. Please check that date.

Reviewed commit c2c29e6

@DataMiner79

Copy link
Copy Markdown
Contributor Author

AI Review

suggestion: need change decision: need change

Thank you for contributing KEEP. It adds ontology-informed clinical code embedding pretraining to PyHealth, with a full MIMIC-IV reproduction pipeline, an intrinsic evaluation and a data-sparsity ablation. The implementation is self-contained and well tested. Coverage meets the bar: keep.py is at 91.6% and the whole repository is at 87.49%. The change is close, but a few things need fixing first.

To get this merged:

  1. The reported results are stale. The docs page says the tables come from runs made before the missing-reference and RNG fixes, and that they "have not been rerun with the revised code". The PR description presents the same numbers as the reproduction. Please rerun the pipeline with the final code and update the numbers in the description and docs. If you can't, say plainly in the description that the numbers come from an earlier code version.
  2. Fix the test references. The description cites tests/models/test_keep.py and says "seven" tests passed. The file is tests/core/test_keep.py, and it now has more tests. Please correct the path, the count and the pytest command.
  3. Clean up the docs page pyhealth.models.KEEP.rst. It contains internal review notes and process text: "added during review", "CI coverage ... must be confirmed", "Review the upstream PyHealth pull request", and the .gitignore advice. The page should describe the shipped code and no more. Please trim it so the statements match the final code and tests.

Optional suggestions:

  • Add tests for the index and shape validation in fit_keep.
  • Remove the commented-out debug prints in the example scripts.
  • keep_sparsity_preprocessing.py imports from keep_mimic_preprocessing.py. This is fine, but a one-line note in the description would make it clear it is intentional.
  • The description says "Fall 2026" for the course. Please check that date.

Reviewed commit c2c29e6

Thank you for the AI review. We have addressed all required changes
and optional suggestions:

  • Explicitly disclosed in the PR description that the reported
    experimental results were obtained using an earlier implementation.
  • Corrected the test path, test count, and pytest command.
  • Removed internal review notes and repository management advice
    from the RST documentation.
  • Added 20 validation test cases, including invalid input shapes
    and out-of-range vocabulary indices.
  • Removed commented-out debug prints from the example scripts.
  • Documented the intentional reuse of preprocessing functions.
  • Confirmed that Fall 2026 is the correct course date.

All 33 KEEP unit tests pass locally, achieving 100% statement
coverage
of keep.py (119/119 statements).

The updated PR is ready for another AI review.
Thank you!

@solarsys

Copy link
Copy Markdown
Collaborator

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed commit 05d034b

Comment thread pyhealth/models/keep.py
The GloVe term uses separate target/context vectors and biases. The
ontology penalty anchors the mean of the two tables to fixed Node2Vec
vectors. The cosine variant follows the released-code behavior described
in the project review; L2 is an alternative matching the paper's formula.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] Docstring cites an unexplained 'project review'

The KEEP class docstring says the cosine variant 'follows the released-code behavior described in the project review'. No such document is in the repository or the docs, so a reader cannot check the claim. Describe the behavior directly, for example 'cosine matches the released KEEP implementation; L2 matches the paper's formula', and link the source if one exists.

5% 0.6671 ± 0.0018 0.6711 ± 0.0063 0.5103 ± 0.0020 0.5157 ± 0.0051
======== =============== =============== =============== ===============

For test AUROC, the KEEP–GloVe mean gap changes from +0.0039 at 100% to +0.0041 at 5%; KEEP retains 99.92% of its full-data score. For test AUPRC, the KEEP–GloVe mean gap changes from +0.0044 at 100% to +0.0054 at 5%; KEEP retains 99.72% of its full-data score. Both methods retain substantial performance. The evidence for an increasing KEEP advantage is mixed rather than monotonic; the hypothesis is only partially supported. The downstream embeddings are fine-tuned using the full downstream cohort, so this is not a low-data downstream training experiment. Fixed vocabulary/ontology construction uses the full training cohort, pretraining and subset seeds are fixed, and smaller matrices result in fewer optimizer updates per epoch. Three downstream seeds do not establish significance or uncertainty across patient subsets.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] Gap and retention percentages do not match the table means

From the test table means, the 5% KEEP-GloVe AUROC gap is 0.6711 - 0.6671 = 0.0040, not +0.0041. Retention computed from the same means is 99.91% for AUROC (stated 99.92%) and 99.71% for AUPRC (stated 99.72%). Either recompute from unrounded values and say so, or use the rounded means as shown.

The training-only vocabulary contains 5,567 codes; the sparse co-occurrence matrix has 1,247,250 nonzero entries. Final embedding training losses were 0.005682 (GloVe), 0.006307 (initialized GloVe), and 0.011821 (KEEP). KEEP includes an additional penalty, so its total loss is not directly comparable to the reconstruction-only losses.

+--------------------------------------------------------------+----------------------+-----------------------+
| Metric | Earlier 10-epoch run | Revised 300-epoch run |

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] Results column labelled 'Revised' contradicts the provenance note

Line 82 says all reported tables predate the missing-reference and RNG fixes. This table labels the 300-epoch run 'Revised', which implies it was produced with the current code. Relabel it as the pre-fix 300-epoch run so the provenance is consistent throughout.

@@ -0,0 +1,484 @@
KEEP: Ontology-Informed Clinical Code Embeddings in PyHealth

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] Docs page is long and mostly run logs and history

The page is about 480 lines and includes shell loops, historical result tables, sparsity-ablation tables, output-layout notes and version-control advice. Compare with other pages under docs/api/models/, which document the API and a short usage example. Keep the public API, a short description of the method, the data requirements, a brief results summary and the limitations; move the full reproduction workflow and the per-seed logs to the examples directory or a separate note.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI Review

suggestion: approve
decision: approve

Thank you for contributing KEEP. It adds an ontology-informed GloVe-style embedding pretrainer to PyHealth, with unit tests, a docs page, a synthetic example, and MIMIC-IV reproduction scripts. It looks ready to merge.

  • Code and tests: keep.py has 100% coverage (119/119 statements), above the 80% bar. Total repository coverage is 87.69%, above the 60% bar. The 33 tests cover the main paths and the input validation.
  • Scope: KEEP is a self-contained nn.Module. The only shared-file changes are the new export line in pyhealth/models/__init__.py and the docs index entry, and neither alters an existing export.
  • Sharing: the reuse of keep_mimic_preprocessing.py functions in the sparsity script is explained in the description. KEEP inheriting from nn.Module rather than BaseModel is also explained.
  • Results: the description states clearly that the reported results come from the earlier implementation.

Optional suggestions:

  • Docs and results: the docs page labels some tables "Revised 300-epoch run" and says the 12 revised test evaluations are complete. The description and the page's own caveats say those results predate the final fixes. One sentence near each results table, saying which implementation version produced it, would remove the ambiguity. I also noticed a few small rounding inconsistencies in the tables.
  • Docs length: the "Implementation and scripts" table could be shortened to one line per script.
  • Code style: the commented-out block in keep_readmission.py could be removed. The assert checks in keep_export_vectors.py could become explicit errors.
  • Reproducibility: a split-only command would avoid the step that retrains a legacy checkpoint just to produce train_patient_ids.txt.

Reviewed commit 05d034b

@solarsys
solarsys merged commit 9758860 into sunlabuiuc:master Nov 29, 2026
3 checks passed
lee-leonardo added a commit to lee-leonardo/PyHealth that referenced this pull request Dec 2, 2026
Extend the existing sunlabuiuc#1666 synthetic example with a raw-result adapter and use it from the synthetic MIMIC history examples. Derive positive off-diagonal CPU NumPy triplets without mutating raw counts, retain count-one pairs and complete axes, align synthetic reference vectors by concept ID, and export every retained concept in matrix order. Skip fit_keep when no training pairs exist. Use the depth-five clinical baseline while preserving the separate ICD/two-admission preprocessing example. Validation: 254 tests passed, two CUDA-only cases skipped, and 27 subtests passed across the assembled workflow; processor/task coverage is 96%/93%; 14 public doctests passed. Both clinical examples and the original synthetic trainer example execute successfully; contribution rules pass with the CI Ruff version.
lee-leonardo added a commit to lee-leonardo/PyHealth that referenced this pull request Dec 3, 2026
Extend the existing sunlabuiuc#1666 synthetic example with a raw-result adapter and use it from the synthetic MIMIC history examples. Derive positive off-diagonal CPU NumPy triplets without mutating raw counts, retain count-one pairs and complete axes, align synthetic reference vectors by concept ID, and export every retained concept in matrix order. Skip fit_keep when no training pairs exist. Use the depth-five clinical baseline while preserving the separate ICD/two-admission preprocessing example. Validation: 254 tests passed, two CUDA-only cases skipped, and 27 subtests passed across the assembled workflow; processor/task coverage is 96%/93%; 14 public doctests passed. Both clinical examples and the original synthetic trainer example execute successfully; contribution rules pass with the CI Ruff version.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status: automatic The PR will go through automatic review process.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants