Skip to content

ClusterLabel audit + tests - #1221

Open
lehendo wants to merge 3 commits into
sunlabuiuc:masterfrom
lehendo:clusterlabelaudit
Open

lehendo wants to merge 3 commits into
sunlabuiuc:masterfrom
lehendo:clusterlabelaudit

Conversation

@lehendo

@lehendo lehendo commented Aug 30, 2026

Copy link
Copy Markdown
Collaborator

Title is self explanatory.

…fied K-means design choice, add coverage tests

ClusterLabel had no paper citation at all, despite being a legitimate,
correctly-implemented instance of Mondrian conformal prediction (Vovk,
Lindsay, Nouretdinov, and Gammerman, 'Mondrian confidence machine,' 2003)
using K-means clusters as the category function. Added that citation plus
Vovk/Gammerman/Shafer 2005, and documented the actual guarantee this
class provides: per-cluster coverage (P(Y not in C(X) | cluster=c) <=
alpha for every cluster), which is strictly stronger than plain marginal
coverage -- the previous docstring didn't call this out.

Investigated a theoretical concern by analogy to the NeighborhoodLabel
self-inclusion bug fixed earlier this session: calibrate() fits KMeans on
train+cal embeddings combined, so calibration points influence the very
cluster centroids used to assign their own threshold, unlike a strict
split-conformal setup where the category function would be fit on data
disjoint from calibration. Verified via Monte Carlo simulation (including
a calibration-set-dominated stress test, 10 train vs 300 cal points) that
this does NOT introduce measurable coverage bias, unlike k-NN's self-
inclusion (a hard, always-occurring artifact) -- a single point's leverage
on a K-means centroid, an average over many points, is negligible.
Documented this as a deliberate, verified design choice rather than
leaving it unexamined, and added regression tests locking in both the
per-cluster coverage guarantee and the train+cal-vs-train-only equivalence
finding.
@fbonc

fbonc commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

The documentation promises coverage for each cluster separately, but the clusters are built using the same calibration patients that are later used to set each cluster's threshold. That means the calibration data helps define the groups and choose their thresholds, so the usual finite-sample guarantee does not apply.

Fit K-means on training embeddings only, then assign calibration patients with predict(). The test should also measure coverage inside each cluster, rather than only across the whole test set.

calibrate() fit K-means on concatenate([train_embeddings, cal_embeddings])
and read calibration points' cluster assignments off kmeans_model.labels_
-- i.e. in-sample. Each calibration point's own presence in the fit could
shift the cluster boundary used to assign its own threshold, breaking the
Mondrian conformal guarantee's requirement (Vovk, Lindsay, Nouretdinov,
and Gammerman 2003) that the category function be independent of the
calibration data it's evaluated against.

A prior commit on this branch (b1964a3) investigated this exact concern
via Monte Carlo simulation and found no measurable coverage bias, given
K-means centroids are a smooth average over many points (unlike
NeighborhoodLabel's k-NN self-match, which is an exact, always-occurring
distance-0 hit). That's a reasonable empirical argument, but the
textbook-correct fix -- fit K-means on train_embeddings only, assign
calibration/test points via out-of-sample .predict() -- is simpler code
(no concatenation bookkeeping) and needs no ongoing empirical
justification, so there's no reason to keep the weaker guarantee.

Replaced the "combined vs. train-only fit" Monte Carlo comparison test
(whose premise no longer applies, since only train-only fitting remains)
with a regression test spying on KMeans.fit/.predict to directly verify
calibrate() fits on train_embeddings only and assigns calibration points
out-of-sample.
@lehendo

lehendo commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

@fbonc , fixed. pls review.

@DarylOkeke

Copy link
Copy Markdown
Contributor

The new coverage test still averages all test patients together, so one well-covered cluster can hide another that under-covers. Please calculate and check coverage separately for each cluster.

@github-actions

Copy link
Copy Markdown

Test Coverage

Total: 67.87% (16689 / 24590 lines)

Modified file Coverage Lines
pyhealth/calib/predictionset/cluster/cluster_label.py 77.31% 92 / 119

Workflow run · 668228a

@solarsys solarsys added the status: automatic The PR will go through automatic review process. label Oct 25, 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.

AI review: findings

The PR changes ClusterLabel.calibrate() to fit K-means on training embeddings only and assign calibration points out-of-sample via predict(), instead of fitting on train plus calibration embeddings. It also adds Mondrian-conformal docstrings and notes, and adds two tests. The core fix is sound and forward() already assigns test points with predict(), so the behavior is consistent. The change is self-contained: no base class or other component changes, and nothing else in the library uses ClusterLabel internals. Blocking problems: (1) the new class docstring says NeighborhoodLabel avoids self-inclusion "via leave-one-out", but NeighborhoodLabel.calibrate() queries the calibration set against an index built on itself with no exclusion, so the justification cites a mechanism that does not exist; (2) TestClusterLabelCoverage never calls ClusterLabel, it re-implements the logic, so reverting calibrate() would still pass; (3) that same test is named per-cluster coverage but measures pooled marginal coverage; (4) the PR is described as "audit + tests", yet it silently changes the cluster assignments and thresholds that existing ClusterLabel users and the TUEV example get, and it adds a new failure when n_clusters exceeds the training-set size. The mock-based regression test TestClusterLabelKMeansFitIsOutOfSample does fail on the old code, so the fit change is covered. Redundancy: none found; NeighborhoodLabel and CovariateLabel use different category functions, so ClusterLabel is not a duplicate. Risk is moderate: the code change is small and correct, but the docs and tests overstate what is verified and the behavior change is not disclosed.

Reviewed commit 668228a

threshold. Fitting on calibration data too (even combined with
training data) would let a calibration point influence the cluster
boundary used to assign its own threshold -- the same kind of
self-inclusion leak that :class:`~pyhealth.calib.predictionset.NeighborhoodLabel`

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[medium] Docstring claims NeighborhoodLabel uses leave-one-out, which it does not

The class Note says NeighborhoodLabel avoids the self-inclusion leak 'via leave-one-out for its k-nearest-neighbor category function'. In pyhealth/calib/predictionset/cluster/neighborhood_label.py, calibrate() fits NearestNeighbors on cal_embeddings and then calls kneighbors(self.cal_embeddings_) on the same set, with no exclusion of self. Each calibration point is therefore its own nearest neighbour, so the stated mechanism does not exist. The same self-inclusion arguably applies to NeighborhoodLabel, which the audit did not catch. Fix: remove or correct the NeighborhoodLabel comparison in this docstring, and optionally flag the NeighborhoodLabel self-inclusion separately.

"""Monte Carlo verification of ClusterLabel's core statistical claim:
per-cluster (Mondrian) coverage, at scale a full trained-model pipeline
can't practically reach. Exercises the same calibration logic
ClusterLabel.calibrate()/forward() use (KMeans + _query_quantile),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[medium] Coverage test re-implements the calibration logic and never calls ClusterLabel

TestClusterLabelCoverage._run_trial rebuilds KMeans fit, predict, and per-cluster _query_quantile by hand. Its docstring says it 'exercises the same calibration logic ClusterLabel.calibrate()/forward() use', but it never imports or instantiates ClusterLabel. If calibrate() were reverted to fit on train plus calibration embeddings, this test would still pass, so it gives no regression protection for the change it is meant to verify. Fix: drive ClusterLabel.calibrate() and forward() with embeddings from a synthetic dataset, or delete the test and rely on the mock-based regression test.

_query_quantile(cal_scores[mask], alpha) if mask.sum() > 0 else np.inf
)
t_test = np.array([thresholds[c] for c in test_cluster])
return (test_scores <= t_test).mean()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[medium] Test named per-cluster coverage measures pooled marginal coverage

test_per_cluster_coverage_matches_target and its docstring claim to check per-cluster (Mondrian) coverage. _run_trial returns (test_scores <= t_test).mean() over all test points, which is pooled marginal coverage. Per-cluster coverage, P(covered | cluster=c) >= 1-alpha for each c, is never checked. Fix: compute coverage per predicted cluster and assert the minimum over clusters, or rename the test and docstring to marginal coverage.

n_init=10,
)
self.kmeans_model.fit(all_embeddings)
self.kmeans_model.fit(train_embeddings)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[medium] Undisclosed behavior change to ClusterLabel results and failure mode

Calibration now fits K-means on train_embeddings only, where it previously fit on train plus calibration embeddings. This changes cluster membership, thresholds and y_predset for identical inputs, including the TUEV example's reported results. It also makes calibrate() raise from sklearn when n_clusters exceeds the number of training embeddings, which the old combined fit did not. The PR description ('ClusterLabel audit + tests') does not mention either change. Fix: state the behavior change and its impact on published numbers in the PR description, and document or validate the n_clusters <= n_train requirement.

@github-actions github-actions Bot added status: manual Pending maintainer's review and removed status: automatic The PR will go through automatic review process. labels Oct 25, 2026

@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: human review
decision: not available

Haiku found that this change needs a human review: The change alters what the public ClusterLabel.calibrate() and forward() produce for identical inputs, because K-means cluster membership and per-cluster thresholds now come from training embeddings only. It also adds a new exception path when n_clusters exceeds the training-set size. No base class is modified and nothing else in the library depends on ClusterLabel, so it is largely self-contained, but the public results change. Under the rule to answer yes when unsure, a human should review it.

Reviewed commit 668228a

@solarsys solarsys 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.

Thanks @lehendo. Fitting K-means on the training embeddings only is the right fix, and the mock test pins it down well. A few items before merge:

  1. @DarylOkeke's point is still open. test_per_cluster_coverage_matches_target still pools coverage over all test points (_run_trial returns (test_scores <= t_test).mean()). Could you compute coverage within each predicted cluster and assert on the minimum?
  2. That test re-implements KMeans and _query_quantile by hand. Ideally it would go through ClusterLabel.calibrate() and forward() instead.
  3. Please drop the sentence in the docstring saying NeighborhoodLabel avoids self-inclusion "via leave-one-out". It doesn't: it fits on the calibration set and queries that same set.
  4. calibrate() now raises when n_clusters is larger than the number of training embeddings. Please document that. Also add a line to the PR description saying that cluster assignments and thresholds change.

This branch has not been deployed

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

Labels

status: manual Pending maintainer's review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants