Skip to content

depth ablation: co-occurrence statistics and LogisticRegression - #9

Merged
rishabshah merged 6 commits into
keepfrom
rishab/depth-ablation
Nov 28, 2026
Merged

rishabshah merged 6 commits into
keepfrom
rishab/depth-ablation

Conversation

@rishabshah

@rishabshah rishabshah commented Nov 26, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Depth ablation for our KEEP reproduction - changes only SNOMED depth limit (3, 4, 5 = KEEP default, 6) and measures effect on (1) the KEEP co-occurrence matrix and (2) an existing PyHealth model
  • covering rubric sec. 4 for a dataset/task contribution: varies a task configuration and shows its effect on model performance
  • The two parts answer different questions: Part 1 measures how depth changes the relationships in the co-occurrence matrix; Part 2 feeds rolled-up diagnosis tokens straight to the model. The predictor never uses the co-occurrence matrix.

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 under reference. Our #7 reproduction baseline uses all_retained + direct; --policy all_retained --path-source direct runs 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:

  • Size: concepts, patients with conditions, nonzero pairs, density, and how often codes had to be rolled up.
  • Concentration: Gini, entropy, top-1% share and HHI. This is where the "cough becomes useless" effect would show up. Entropy is reported raw (bits) and normalized two ways, with the denominator in the name (nonzero pairs, or possible pairs as in Optimize KEEP ontology loading and add preprocessing ablations #7).
  • Association: PMI, PPMI and NPMI.
  • Comparison with depth 5: each depth has its own vocabulary, so this is done on common retained axes (the concepts every depth keeps, same patients, aligned by concept ID): coverage and what the axes exclude, absolute count/prevalence changes, JSD and cosine on count and PPMI partner profiles (with undefined rows counted), matched-pair PPMI/NPMI changes, and P(B|A) changes.

Part 2, model performance (rubric's requirement)

  • Task: predict death in the next admission from a patient's diagnosis history. It's PyHealth's MortalityPredictionMIMIC4 setup, but diagnoses only, since you didn't download procedures or prescriptions.
  • Model: PyHealth's LogisticRegression, scored by test ROC-AUC and PR-AUC over 3 seeds (mean, std and per-seed).
  • Arms: raw ICD codes; codes rolled up to depth 3, 4, 5 and 6; and no depth limit. All arms use the same patients, labels and patient folds; each arm's vocabulary is fitted on the training patients only, and a seed whose folds would have a single class stops the run.

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 data path):

pytest tests/core/test_keep_depth_ablation.py tests/core/test_keep_depth_mortality.py -q
python -m examples.mimic4_keep_depth_ablation_logistic_regression          # synthetic, ~20s
python -m examples.mimic4_keep_depth_ablation_logistic_regression \
  --mimic ~/data/mimiciv/3.1 \
  --athena "$HOME/Desktop/vocabulary_download_v5_{5eac9ffa-9264-4e61-a8c0-77a902a87a07}_1794439651133" \
  --cache ~/.cache/pyhealth/keep_depth --out keep_depth_ablation.json --dev

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.
    • Part 1: builds KeepConditionHistoryTask histories once, then per depth a build_keep_omop_ancestor_rollup(max_depth=d) processor and task.build_cooccurrence. Prints a per-depth table and a separate table aligned with depth 5 on common retained axes.
    • Part 2: next-admission mortality from diagnosis history. Patient folds come from 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, including matrix_summary, aligned_comparison and a RollupRecorder that caches roll-ups per code.
  • examples/keep_depth_mortality_utils.py (new): the ConditionMortalityMIMIC4 task, 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)

  1. Separate the mortality helpers from the matrix measures (no behavior change).
  2. Fit the vocabulary on each seed's training patients (P2).
  3. Guard single-class folds and non-finite scores; report per-seed scores and fold counts (P2).
  4. Make the reference configuration explicit; state that the predictor doesn't use the matrix.
  5. Expand the co-occurrence comparisons per the review table.

Testing and validation

  • 24 tests pass, each under 1s: statistics against hand-computed values, JSD/cosine against an independent implementation, entropy denominators, caching, train-only vocabulary fitting (a test-only code maps to <unk>), single-class and NaN guards, task labels and exclusions, and an end-to-end two-depth check on the synthetic Athena bundle.
  • Synthetic run (~20s) with a planted rule only depth 6 can see: raw ICD, depth 6 and no-limit reach ~0.72 AUROC vs ~0.52–0.54 for depths 3–5. Checks the pipeline, not a clinical effect.
  • MIMIC-IV 3.1, --dev subset (1,000 patients), Athena v5.0 29-AUG-26:
Co-occurrence (each depth's own axes) depth 3 depth 4 depth 5 (ref) depth 6
Retained concepts 20,764 44,816 69,445 84,172
Concepts observed 965 1,141 1,206 1,209
Patients with conditions 822 752 686 677
Nonzero pairs 57,940 57,727 52,056 46,932
Density 0.125 0.089 0.072 0.064
Mean prevalence 12.9 8.8 7.1 6.3
Pair Gini 0.585 0.493 0.439 0.403
Pair top-1% share 0.208 0.159 0.146 0.133
Pair entropy (bits) 14.50 14.87 14.86 14.82
÷ log2 nonzero pairs / ÷ log2 possible pairs 0.916 / 0.524 0.940 / 0.497 0.949 / 0.477 0.955 / 0.467
Mean NPMI 0.317 0.362 0.392 0.414
Concepts rolled up 63.7% 29.6% 13.4% 2.4%
  • Shallower depths pile mass onto broad concepts: higher prevalence and density, more concentrated pair counts and lower NPMI, the expected effect of common ancestors co-occurring with almost everything.
Aligned with depth 5 (20,764 common retained axes) depth 3 depths 4 and 6
Concepts observed in both / only here 452 / 513 452 / 0
Concepts excluded by the axes (share of pair mass) 0 (0%) 689 (90%) / 757 (85%)
Pairs matched / gained / lost 7,721 / 50,219 / 0 7,721 / 0 / 0
Σ|Δ prevalence| / Σ|Δ count| 9,693 / 166,161 0 / 0
Count profile JSD mean / median / p90 0.53 / 0.50 / 0.71 0
PPMI profile JSD mean 0.46 0
Count / PPMI profile cosine mean 0.47 / 0.60 1 / 1
Profile rows valid / undefined 439 / 526 439 / 13
PPMI Spearman 0.17 1
Matched pairs: mean |ΔNPMI| / mean |ΔP(B|A)| 0.049 / 0.045 0 / 0
  • Depth 3 reshapes the shared concepts' partner profiles (JSD ~0.5) mostly by adding pairs: 50k new pairs, none lost, and the 7.7k matched pairs barely move (median changes 0).
  • Depths 4 and 6 are identical to depth 5 on these axes by construction: under first_retained a 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.
Next-admission mortality ICD depth 3 depth 4 depth 5 (ref) depth 6 no limit
Test ROC-AUC (± std) 0.55 ± 0.05 0.63 ± 0.08 0.57 ± 0.01 0.46 ± 0.09 0.58 ± 0.17 0.56 ± 0.03
ROC-AUC per seed .59/.56/.50 .68/.53/.67 .56/.58/.59 .53/.36/.50 .69/.38/.66 .54/.54/.60
Test PR-AUC 0.018 0.022 0.020 0.014 0.021 0.019
Train vocabulary (mean) 4,152 1,476 1,876 2,075 2,151 2,147
  • Not conclusive: 3,541 samples with a 1.4% positive rate, so each test fold holds only 8–11 deaths and per-seed scores swing by up to 0.3. No arm is reliably better yet; the full MIMIC-IV run will replace these numbers.

Notes

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
@rishabshah rishabshah changed the title Add KEEP depth ablation: co-occurrence statistics and LogisticRegression depth ablation: co-occurrence statistics and LogisticRegression Nov 26, 2026

@lee-leonardo lee-leonardo left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

@rishabshah

rishabshah commented Nov 26, 2026 •

Copy link
Copy Markdown
Owner Author

Leo PR note

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 LogisticRegression, so it measures how depth changes the information in the features, not the KEEP embedding.

Reference configuration: I'll put it at the top of the docstring and in the JSON: depth 5, first_retained, closure, include_root=False, presence ≥ 2 distinct diagnoses, the same cohort and histories for every depth, and the Athena release. The co-occurrence table will have depth 3 / 4 / 5 (reference) / 6 columns, with changes against the reference.

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 first_retained, a depth-≤3 concept only gains counts when it is the nearest retained ancestor, so depths 4–6 are identical on these axes by construction. A mapped common vocabulary doesn't help either, because rolling every depth's targets up to depth 3 under first_retained reproduces the depth-3 matrix. So differences among depths 4–6 show up in the per-depth statistics, not in the aligned ones.

Your table, row by row:

  • Vocabulary/coverage: keep, and add shared/observed-in-both counts, gained/lost concepts and pairs, and the excluded concepts with their pair-mass share.
  • Counts/prevalence: add absolute and median Δprevalence on aligned concepts, and Σ|Δcount| plus the number of changed pairs on aligned pairs.
  • JSD: base-2 divergence (already, not the square-root distance) on both count and PPMI partner profiles, with valid/undefined row counts and mean, median and p90.
  • Cosine: count and PPMI profiles, same summaries.
  • Entropy: raw entropy in bits, normalized two ways with the denominator in the name (_norm_nonzero_pairs, as now, and _norm_possible_pairs, as in Optimize KEEP ontology loading and add preprocessing ablations #7), plus the median per-concept partner entropy.
  • Association: keep the current summaries, and add ΔPPMI/ΔNPMI on matched pairs, with new/lost/undefined counts.
  • Conditional probability: median |ΔP(B|A)| and |ΔP(A|B)| on matched pairs.
  • Concentration: keep it, and name the universe explicitly (nonzero pairs on that depth's own axes, with possible pairs alongside).

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 compare_matrices directly, since restricting each depth to the common axes gives exactly the same-universe, same-cohort input it requires. The per-depth statistics stay separate. I'll also move the mortality task and featurizer out of keep_depth_ablation_utils.py, so that module holds only reusable matrix metrics.

rishabshah and others added 5 commits November 26, 2026 17:44
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 lee-leonardo left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants