Repository navigation
Add KEEP: Ontology-Informed Clinical Code Embeddings with MIMIC-IV Reproduction - #1666
Conversation
…vector-dir, summary script
Test CoverageTotal: 87.69% (53876 / 61441 lines)
|
|
Thanks for KEEP. This PR doesn't have a review label yet, for these reasons:
To make it eligible for automatic review:
Then we'll add |
|
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:
Then it can get |
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 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. |
|
/review |
There was a problem hiding this comment.
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:
- 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.
- Fix the test references. The description cites
tests/models/test_keep.pyand says "seven" tests passed. The file istests/core/test_keep.py, and it now has more tests. Please correct the path, the count and the pytest command. - 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.gitignoreadvice. 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.pyimports fromkeep_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
All 33 KEEP unit tests pass locally, achieving 100% statement The updated PR is ready for another AI review. |
|
/review |
| 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. |
There was a problem hiding this comment.
[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. |
There was a problem hiding this comment.
[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 | |
There was a problem hiding this comment.
[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 | |||
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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.pyhas 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 inpyhealth/models/__init__.pyand the docs index entry, and neither alters an existing export. - Sharing: the reuse of
keep_mimic_preprocessing.pyfunctions in the sparsity script is explained in the description.KEEPinheriting fromnn.Modulerather thanBaseModelis 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.pycould be removed. Theassertchecks inkeep_export_vectors.pycould 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
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.
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.
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
KEEP,KEEPConfig, andfit_keepto the PyHealth public model API.KEEP intentionally inherits from
torch.nn.Modulerather thanBaseModel, as it performs unsupervised embedding pretraining ratherthan downstream clinical prediction.
The sparsity preprocessing script intentionally reuses functions from
keep_mimic_preprocessing.pyto ensure consistent diagnosis filteringand 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.
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:
and empirical co-occurrence statistics.
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:
The synthetic example and public API imports were also verified.
Official GitHub CI Results
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:
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=80Documentation and Reproducibility
The official documentation page at
docs/api/models/pyhealth.models.KEEP.rstcontains implementationdetails, 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
This contribution was developed as part of Georgia Tech's CSE6250
Big Data Analytics for Healthcare course, Fall 2026.