Repository navigation
depth ablation: co-occurrence statistics and LogisticRegression - #9
Conversation
Varies only the SNOMED depth limit (3, 4, 5, 6) and reports, per depth, the KEEP co-occurrence matrix's size, roll-up, concentration and PMI statistics (plus a comparison with depth 5 on shared concepts), and next-admission mortality with PyHealth's LogisticRegression on diagnoses rolled up to that depth. Runs on synthetic data by default; outputs aggregates only. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01JrebVyPi1jFyjkAiLbLSC1
There was a problem hiding this comment.
The applied mortality example is useful. The two experiments answer different questions: the co-occurrence analysis measures how preprocessing changes relationships, while the mortality model uses rolled-up diagnosis histories directly. Please keep that distinction explicit; the matrix is not an input to the current predictor.
I have two correctness follow-ups and a non-blocking baseline FYI in the inline comments.
For the co-occurrence results, please make the reference configuration explicit and present a table with depth 3 / 4 / 5 (reference) / 6 columns, plus changes against the reference where appropriate:
| Measure | Current coverage | Suggested comparison |
|---|---|---|
| Vocabulary, coverage and sparsity | Retained/observed concepts, patient coverage, pairs and density | Keep these; also report concepts/pairs gained, lost or excluded from aligned comparisons |
| Counts and prevalence | Global summaries and median prevalence ratio | Add absolute count/prevalence changes on aligned concepts/pairs so normalization does not hide changes in magnitude |
| JSD | Mean count-profile JSD | Compare both count and PPMI partner profiles; report the number of valid rows and a distribution summary such as median/upper quantile |
| Cosine similarity | Not currently reported | Add count-profile and PPMI-profile cosine against the reference |
| Entropy | Global normalized entropy of nonzero pair counts | Report global raw entropy and normalized entropy, plus per-concept partner entropy; make the support/normalization denominator explicit |
| Association | PMI/PPMI/NPMI summaries and PPMI rank correlation | Retain these and add support-aware PPMI/NPMI changes on matched pairs, with undefined/new/lost associations accounted for |
| Conditional probability | Not currently compared | Summarize changes in P(B given A) and P(A given B), alongside the pair counts and marginal prevalence |
| Concentration | Gini, top-1% share and HHI | Keep these with an explicit denominator/universe so depths remain interpretable |
Use the same patients and align vectors by concept ID, with the diagonal excluded from partner profiles. State whether the comparison uses common retained axes or an explicitly mapped common vocabulary, and show what that choice excludes. Empty count/PPMI rows should be reported as undefined with coverage counts. Lower JSD means closer to the reference; higher entropy or cosine does not establish clinical quality.
Two definition details matter for comparison with our existing work: this PR normalizes entropy by the number of nonzero pairs, whereas the baseline/variants helper in #7 uses the number of possible pairs. Those normalized values are not directly interchangeable. Also retain base-2 JSD divergence consistently rather than mixing it with its square-root distance.
Non-blocking baseline FYI: the reproduction baseline in #7 was added after this work was prepared. It uses all_retained and direct traversal, whereas this example currently uses first_retained and closure. #8 investigates closure separately. As the branches come together, we can reconcile the introduction/defaults with the all_retained reproduction reference and add comparator statistics with one setting changed at a time. Depending on merge order, that can happen here or in a follow-up; it is not a requirement for this PR. The useful comparison is to make the reference configuration explicit and show which matrix changes come from depth versus another ablation parameter.
Non-blocking tooling suggestion: consolidate the overlapping association/distribution functions with the helpers from #7 after agreeing on axis, support and empty-row conventions. Keep the mortality task/model helpers separate from reusable matrix metrics.
Validation on the reviewed head: 14/14 tests passed and the full synthetic example reproduced the reported AUROC pattern. On our expanded synthetic fixture, all 28 aligned count-profile JSD comparisons agreed with the independent helper, and all eight nonzero-pair normalized-entropy checks matched an independent calculation. This validates those definitions, not the real-cohort findings; MIMIC/Athena results were not independently rerun.
Thanks Leo. Taking it in order: Matrix vs. predictor: agreed, and I'll say it explicitly in the docstring and PR. Part 2 never uses the co-occurrence matrix. It feeds rolled-up diagnosis tokens straight into Reference configuration: I'll put it at the top of the docstring and in the JSON: depth 5, Aligned comparisons: these use common retained axes, meaning the concepts every depth keeps (depth ≤ 3 when depth 3 is included), aligned by concept ID with the diagonal excluded from partner profiles. I'll report what this excludes: the number of concepts only deeper depths keep, and their share of pair mass. One consequence worth stating: under Your table, row by row:
I'll add an interpretation note: lower JSD means closer to the reference, and higher entropy or cosine doesn't mean clinically better. Consolidating with #7: agreed. Once #7 is merged, the aligned part can call its |
Move ConditionMortalityMIMIC4, ConceptFeaturizer and featurize_arms into examples/keep_depth_mortality_utils.py (tests to test_keep_depth_mortality.py) so keep_depth_ablation_utils.py holds only reusable co-occurrence measures. No behavior change: the synthetic run's output is identical. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01JrebVyPi1jFyjkAiLbLSC1
Previously each arm's SampleDataset was built from all samples, so the code vocabulary was fitted on validation and test patients too. Now patient folds are chosen once per seed with PatientSplit and shared by every arm; each arm fits its processors on that seed's training patients and reuses them for validation and test, so held-out-only codes map to <unk>. Reports the mean train vocabulary size. Adds tests from the review's 40-patient fixture. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01JrebVyPi1jFyjkAiLbLSC1
Before any training, check that each seed's shared patient folds give train, validation and test both labels; otherwise stop with the seed and per-part sample/positive counts (ROC-AUC/PR-AUC are undefined on one class and a one-class validation part cannot select an epoch). Scores are checked with math.isfinite before mean/std, so a NaN stops the run instead of being averaged or dropped. Reports per-seed scores and the fold counts in the printed tables and JSON. Adds tests using the review's one-positive fixture. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01JrebVyPi1jFyjkAiLbLSC1
Document the reference (depth 5, first_retained, closure, include_root False, on_unmapped empty, PRESENCE_THRESHOLD, same cohort and histories, Athena release) at the top of the example, record it as a "reference" block in the JSON, and mark the reference column in the printed table. State that the mortality model never uses the co-occurrence matrix, give the one-flag command for the #7 reproduction baseline (--policy all_retained --path-source direct), and note that synthetic checks establish our reproduction's behavior, not the original authors'. Results are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01JrebVyPi1jFyjkAiLbLSC1
Per depth: name every denominator (possible_pairs_observed for density, possible_pairs_axes as in #7), report raw pair entropy in bits plus pair_entropy_norm_nonzero_pairs and pair_entropy_norm_possible_pairs (not interchangeable), and median per-concept partner entropy. Against the reference depth, a new aligned_comparison replaces shared_concept_comparison on common retained axes (same patients, aligned by concept ID, diagonal excluded): concepts and pairs gained/lost/excluded and the excluded pair-mass share; absolute prevalence and count changes; base-2 JSD and cosine for both count and PPMI partner profiles with valid/undefined row counts and mean/median/p90 (p10 for cosine); matched- pair PPMI/NPMI changes with undefined counts; and |P(B|A)| changes in both directions. The example prints it as its own table and JSON block, and the docstring defines each measure. Tests check hand-computed values and an independent JSD/cosine implementation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01JrebVyPi1jFyjkAiLbLSC1
lee-leonardo
left a comment
There was a problem hiding this comment.
Approving the current head, 965e37e. The earlier correctness issues are addressed:
- Each seed's vocabulary is fitted on training patients only, and validation/test reuse the fitted processors. The original held-out-code probe now maps the held-out code to
<unk>. - Single-class folds fail clearly before training, and non-finite scores are rejected before aggregation.
- The expanded co-occurrence analysis includes count/PPMI JSD and cosine, explicit entropy denominators, conditional-probability changes, and excluded-support reporting.
- The reference configuration and the distinction between matrix analysis and diagnosis-token mortality prediction are explicit. Alignment with the later-added reproduction baseline remains a follow-up, as discussed.
Validation: all 24 focused tests passed, the complete synthetic example ran successfully, and 700 independent numerical comparisons passed across randomized synthetic matrices. Real MIMIC/Athena results were not independently rerun.
Optional follow-up: the default synthetic example currently has no valid aligned partner profiles, so its aligned JSD/cosine outputs are undefined. Adding more shared concepts would let the runnable example demonstrate those measures numerically; the calculations passed the separate checks.
This fixture improvement and further ablation refinements are non-blocking. We can adjust the ablations and shared tooling as the related PRs come together.
Summary
Reference configuration
Every arm differs from this in depth only:
max_depth=5,target_policy="first_retained",path_source="closure",include_root=False,on_unmapped="empty", presence ≥ 2 distinct diagnoses, same cohort and histories for every depth, Athena v5.0 29-AUG-26. The output JSON repeats it underreference. Our #7 reproduction baseline usesall_retained+direct;--policy all_retained --path-source directruns the ablation around it.Part 1, co-occurrence statistics (Leo)
builds KEEP matrix at each depth using our task and roll-up code, and reports the following:
Part 2, model performance (rubric's requirement)
Synthetic check:
I planted a rule that only depth 6 or deeper can see. The raw-ICD, depth-6 and no-limit arms score about 0.72 AUROC, and depths 3 to 5 score about 0.52–0.54, near chance. That confirms the pipeline works; it says nothing clinical. The 24 tests pass, each under a second.
Test
run on your machine, from PyHealth dir (change mimic
datapath):AI from here on out:
Changes / Additions
examples/mimic4_keep_depth_ablation_logistic_regression.py(new): runs both parts. Synthetic data by default; real MIMIC-IV + Athena with--mimic/--athena. Prints and saves aggregates only. The docstring documents the reference configuration, every metric and the expected effects.KeepConditionHistoryTaskhistories once, then per depth abuild_keep_omop_ancestor_rollup(max_depth=d)processor andtask.build_cooccurrence. Prints a per-depth table and a separate table aligned with depth 5 on common retained axes.PatientSplit, once per seed, shared by every arm; processors are fitted on training patients and reused for validation/test (held-out-only codes map to<unk>); every fold must contain both classes and every score must be finite.examples/keep_depth_ablation_utils.py(new): reusable co-occurrence measures only, includingmatrix_summary,aligned_comparisonand aRollupRecorderthat caches roll-ups per code.examples/keep_depth_mortality_utils.py(new): theConditionMortalityMIMIC4task, featurizer, fold and evaluation guards.tests/core/test_keep_depth_ablation.py,tests/core/test_keep_depth_mortality.py(new): 24 tests.Review fixes (one commit each)
Testing and validation
<unk>), single-class and NaN guards, task labels and exclusions, and an end-to-end two-depth check on the synthetic Athena bundle.--devsubset (1,000 patients), Athena v5.0 29-AUG-26:first_retaineda concept gains counts only as the nearest retained ancestor. The axes also exclude 85–90% of their pair mass, so their differences show in the per-depth table, not here.Notes
--dev).--policy all_retainedreruns with whole-tree roll-up, which should also move the depth-4 to 6 aligned comparison.all_retained+direct), and the shared measures can use Optimize KEEP ontology loading and add preprocessing ablations #7'scompare_matrices.