Repository navigation
Add generic co-occurrence matrix builder (split from KEEP #1661 [CS 598 - DL4H]) - #1707
Conversation
Add explicit diagonal selection, retaining prevalence by default. Preserve the merged example’s zero-diagonal float32 CSR output and observed vocabulary by delegating only pair counting. Add independent old-builder regression and counter edge-case tests; retain admission and ICD filtering.
Test CoverageTotal: 89.32% (65267 / 73067 lines)
|
|
/review |
There was a problem hiding this comment.
Previous review
AI Review
suggestion: need change
decision: need change
Thank you for splitting this out of the KEEP work. build_cooccurrence is a clean, well-tested counter, and it replaces the example's local pair counting without changing the example's output. Tests cover axis order, validation, empty cohorts, diagonal choice, device placement and transform behavior. The example is also checked against an independent copy of the old algorithm. Coverage is 100% for pyhealth/graph/cooccurrence.py, above the 80% per-file bar. Whole-repo coverage is 88.2%, above the 60% bar.
To get this merged:
pyhealth/models/evicare.pyappears to already contain patient-level co-occurrence counting inCooccurrenceGraph.fit, and the description doesn't mention it. Please say in the description how the new builder relates to it. For example, you could note that it is deliberately separate because it is sparse, uses a caller-defined axis order, and has a diagonal option and a transform. If the two do the same job, please say why a second implementation is needed. Either way, keep the components self-contained unless you intend to share code, and if you do share code, state the reason.
Optional suggestions:
- The builder expects sets. If someone passes a list with a repeated concept, it overcounts. With
include_diagonal=False, it can also put a nonzero value on the diagonal. You could convert each input withset(concepts)or state the requirement more prominently in the docstring. - The docs page could be shorter. The cosine-similarity and ETL-batching paragraphs could be cut or trimmed.
- The example now imports
pyhealthwhen it loads. This is fine, but it may be worth a short note in the example's docs.
Reviewed commit 8019c7f
|
/review |
| import torch | ||
|
|
||
|
|
||
| def build_cooccurrence( |
There was a problem hiding this comment.
[low] Overlaps with existing EviCare CooccurrenceGraph.fit; description does not mention it
pyhealth/models/evicare.py:248-312 (CooccurrenceGraph.fit) already counts patient-level code co-occurrences by summing np.ix_ blocks over per-patient code sets, including diagonal prevalence. The new build_cooccurrence performs the same counting. It differs in output (sparse torch COO rather than dense numpy), include_diagonal, the transform hook and device placement, so it is not a near-copy and is not flagged as redundant. Please add a sentence to the description explaining why a separate generic counter is needed rather than reusing CooccurrenceGraph.
| patient_count = 0 | ||
| for patient_count, concepts in enumerate(patient_concepts, start=1): | ||
| try: | ||
| positions = sorted(axis_index[code] for code in concepts) |
There was a problem hiding this comment.
[low] List inputs with repeated codes silently overcount
positions = sorted(axis_index[code] for code in concepts) keeps duplicates. If a caller passes a list such as ["A", "A"] (the form the example's patient_codes naturally has), the diagonal is counted more than once with include_diagonal=True and the pair with include_diagonal=False is miscounted. The docstring warns about this, but deduplicating here with set(concepts) before sorting would remove the silent wrong result at negligible cost.
There was a problem hiding this comment.
AI Review
suggestion: approve
decision: approve
Thank you for this contribution, and for splitting it out of the KEEP work as the maintainer asked. pyhealth.graph.cooccurrence.build_cooccurrence is a clear, self-contained counter. It keeps the caller's concept order and returns a coalesced sparse COO integer matrix. It has a diagonal switch, output device placement and an optional transform. The KEEP preprocessing example now uses it, and a regression test checks that against the original algorithm.
It looks ready to merge.
- Correctness: I found no problems in the diff. Empty cohorts, empty patients, absent concepts and the validation paths are all handled.
- Docs: The API page matches the code, including the CPU-only counting note and the diagonal behavior.
- Tests:
pyhealth/graph/cooccurrence.pyis at 100% coverage, above the 80% bar. Total repository coverage is 89.32%, above the 60% bar. - Links between components: The only new link is the example importing the new utility. The description explains it.
Optional suggestions:
pyhealth/models/evicare.py(CooccurrenceGraph.fit) already computes patient-level co-occurrence counts as dense numpy. Your counter returns a different output type and has different options, so I don't see it as a duplicate. You could add one sentence to the description saying how the two differ.- The counter does not deduplicate list inputs, so repeated codes overcount. The docstring warns about this. If you want it to be safer, you could deduplicate inside the function. That is entirely your choice.
Reviewed commit 265e910
Overview
Extract the reusable patient-level co-occurrence counter from KEEP integration PR #1661, following the maintainer’s request to split co-occurrence construction into a separate contribution.
The counter accepts caller-selected concept sets and builds a symmetric sparse matrix. This contribution also replaces the local pair-counting implementation in
examples/keep_mimic_preprocessing.py, introduced by KEEP embedding trainer PR #1666.The original KEEP contribution includes work by Rishab Shah (
rishabs4), Leo Lee (ll37), and Murali Rachakonda (muralir2). Existing source attribution is preserved.Implementation
pyhealth.graph.cooccurrence.build_cooccurrence, independent of medical vocabularies, OMOP, and ancestor roll-up.include_diagonal=Falseto count only distinct-concept pairs.Pair counting runs on CPU and requires no CUDA. The default output is also on CPU. The optional
deviceargument controls where the resulting sparse tensor is constructed; it does not move pair counting to CUDA.Clinical presence rules remain the caller’s responsibility. The counter counts the supplied patient sets without choosing occurrence thresholds or ontology policies.
Validation
Supporting preprocessing studies
The accompanying research notebooks in keep-validation examine how upstream preprocessing choices change the sets supplied to co-occurrence counting.
Two relevant synthetic findings are:
These studies motivate separating counting arithmetic from presence selection. They use the earlier KEEP development revision and establish synthetic preprocessing sensitivity; they do not validate improved embeddings or predictive performance for this extracted branch. The notebooks and research helpers remain in the external repository. Execution provenance and verification.