Repository navigation
Fix under-coverage in CovariateLabel's finite-sample correction #1223
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
2bc7f4e
6fb4181
a414d9a
f54f0fe
2676aa9
483f59c
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -22,6 +22,7 @@ | |
| https://arxiv.org/abs/2310.12033 | ||
| """ | ||
|
|
||
| import warnings | ||
| from typing import Callable, Dict, Optional, Union | ||
|
|
||
| import numpy as np | ||
|
|
@@ -196,10 +197,29 @@ def _query_weighted_quantile( | |
| direct callers of this helper). | ||
|
|
||
| Returns: | ||
| The weighted alpha-quantile of scores. Returns ``-inf`` if the | ||
| reserved test-point mass alone already meets or exceeds ``alpha``, | ||
| since there isn't enough calibration mass to justify a stricter, | ||
| finite threshold without risking under-coverage. | ||
| The largest calibration score ``t`` whose weighted mass strictly | ||
| below it, including the reserved test-point mass, is at most | ||
| ``alpha``. With equal weights this is the floor(alpha*(n+1))-th | ||
| smallest score, the same threshold as standard split conformal | ||
| prediction. Returns ``-inf`` if the reserved test-point mass alone | ||
| exceeds ``alpha``. | ||
|
|
||
| Note: | ||
| This implements Corollary 1 of Tibshirani, Barber, Candes, and | ||
| Ramdas, "Conformal Prediction Under Covariate Shift" (NeurIPS 2019, | ||
| https://arxiv.org/abs/1904.06019): the (1-alpha)-quantile of | ||
| sum_i p_i^w(x) * delta_{V_i} + p_{n+1}^w(x) * delta_infinity, where | ||
| p_i^w(x) = w(X_i) / (sum_j w(X_j) + w(x)) and p_{n+1}^w(x) is the | ||
| reserved test-point mass. The paper's V is a nonconformity score | ||
| (higher = worse) with the reserved mass placed at +infinity; this | ||
| codebase uses the opposite convention (conformity, higher = better), | ||
| so the reserved mass is placed at -infinity here instead. Crucially, | ||
| that reserved mass must be inserted as an actual point in the | ||
| weighted empirical distribution, not merely folded into the | ||
| normalizing denominator -- otherwise it dilutes every real | ||
| calibration weight without ever contributing to the cumulative sum | ||
| used to pick the threshold, which produces under-coverage instead of | ||
| the intended finite-sample guarantee. | ||
| """ | ||
| sorted_indices = np.argsort(scores) | ||
| sorted_scores = scores[sorted_indices] | ||
|
|
@@ -210,17 +230,22 @@ def _query_weighted_quantile( | |
| return -np.inf | ||
|
|
||
| p_test = test_weight / total_weight | ||
| if p_test >= alpha: | ||
| # Not enough calibration mass to reach the target coverage without | ||
| # dipping into the mass reserved for the test point itself: fall | ||
| # back to the maximally permissive (safe) threshold. | ||
| if p_test > alpha: | ||
| # The reserved test-point mass (at -inf) alone exceeds alpha, so no | ||
| # finite threshold is valid: include every class. | ||
| return -np.inf | ||
|
|
||
| # Compute cumulative weights over the reserved-mass-inclusive total. | ||
| cum_weights = np.cumsum(sorted_weights) / total_weight | ||
| # Cumulative weights over the reserved-mass-inclusive total, with the | ||
| # test point's reserved mass prepended as an actual point at -inf | ||
| # (equivalent to inserting it at the head of the sorted array before | ||
| # taking the cumulative sum). | ||
| cum_weights = (test_weight + np.cumsum(sorted_weights)) / total_weight | ||
|
|
||
| # Find the index where cumulative weight exceeds alpha | ||
| idx = np.searchsorted(cum_weights, alpha, side="left") | ||
| # First index whose cumulative weight strictly exceeds alpha. Using | ||
| # side="right" keeps a score whose mass below it equals alpha exactly | ||
| # (the paper's quantile); side="left" would be one rank too | ||
| # conservative whenever alpha*(n+1) is an integer. | ||
| idx = np.searchsorted(cum_weights, alpha, side="right") | ||
|
|
||
| # Handle edge cases | ||
| if idx >= len(sorted_scores): | ||
|
|
@@ -318,7 +343,13 @@ class CovariateLabel(SetPredictor): | |
| >>> cal_model.calibrate(cal_dataset=val_data, | ||
| ... cal_embeddings=cal_embs, test_embeddings=test_embs) | ||
| >>> | ||
| >>> # Evaluate | ||
| >>> # Evaluate. Trainer.inference() cannot pass test_embeddings, so | ||
| >>> # this uses one threshold from the mean calibration weight (an | ||
| >>> # approximation of Tibshirani et al.'s per-point threshold) and | ||
| >>> # warns once. For per-point thresholds, call | ||
| >>> # cal_model(test_embeddings=<this batch's rows of test_embs>, | ||
| >>> # **batch) batch by batch with shuffle=False; see | ||
| >>> # examples/conformal_eeg/tuev_covariate_shift_conformal.py. | ||
| >>> test_dl = get_dataloader(test_data, batch_size=32, | ||
| ... shuffle=False) | ||
| >>> from pyhealth.trainer import Trainer, get_metrics_fn | ||
|
|
@@ -400,6 +431,15 @@ def __init__( | |
| # Will be set during calibration | ||
| self.t = None | ||
| self._sum_cal_weights = None | ||
| # Calibration conformity scores/weights, kept so forward() can | ||
| # recompute a threshold per-test-point using that point's own | ||
| # likelihood ratio w(x), as Corollary 1 of Tibshirani et al. (2019) | ||
| # requires, when test_embeddings are provided. | ||
| self._cal_conformity_scores = None | ||
| self._cal_likelihood_ratios = None | ||
| self._cal_class_scores = None | ||
| self._cal_class_weights = None | ||
| self._warned_fixed_threshold = False | ||
|
|
||
| def calibrate( | ||
| self, | ||
|
|
@@ -516,7 +556,26 @@ def calibrate( | |
| y_prob, y_true, score_type=self.score_type, rng=self.rng | ||
| ) | ||
|
|
||
| # Compute weighted quantile thresholds | ||
| # Keep the raw calibration scores/weights so forward() can, when | ||
| # given test_embeddings, recompute a threshold per-test-point using | ||
| # that point's own likelihood ratio w(x) -- the construction | ||
| # Corollary 1 actually specifies -- rather than only the | ||
| # mean-weight approximation computed below. | ||
| self._cal_conformity_scores = conformity_scores | ||
| self._cal_likelihood_ratios = likelihood_ratios | ||
| if not isinstance(self.alpha, float): | ||
| self._cal_class_scores = [ | ||
| conformity_scores[y_true == k] for k in range(K) | ||
| ] | ||
| self._cal_class_weights = [ | ||
| likelihood_ratios[y_true == k] for k in range(K) | ||
| ] | ||
|
|
||
| # Compute weighted quantile thresholds using the mean calibration | ||
| # weight as a stand-in for a "typical" test point's weight. This is | ||
| # the fallback used when forward() isn't given test_embeddings (see | ||
| # forward()'s docstring for why that's only an approximation of | ||
| # Corollary 1, not an exact instance of it). | ||
| if isinstance(self.alpha, float): | ||
| test_weight = float(np.mean(likelihood_ratios)) | ||
| t = _query_weighted_quantile( | ||
|
|
@@ -541,9 +600,32 @@ def calibrate( | |
|
|
||
| self.t = torch.tensor(t, device=self.device) | ||
|
|
||
| def forward(self, **kwargs) -> Dict[str, torch.Tensor]: | ||
| def forward( | ||
| self, test_embeddings: np.ndarray | None = None, **kwargs | ||
| ) -> dict[str, torch.Tensor]: | ||
| """Forward propagation with prediction set construction. | ||
|
|
||
| Args: | ||
| test_embeddings: Optional embeddings for this batch's test | ||
| points, shape ``(batch_size, embedding_dim)``, aligned with | ||
| the batch order. When provided (and KDEs are available from | ||
| :meth:`calibrate`), the threshold is recomputed per test | ||
| point using that point's own likelihood ratio w(x) via | ||
| :func:`_query_weighted_quantile` -- exactly the construction | ||
| in Corollary 1 of Tibshirani, Barber, Candes, and Ramdas, | ||
| "Conformal Prediction Under Covariate Shift" (NeurIPS 2019, | ||
| https://arxiv.org/abs/1904.06019). | ||
|
|
||
| When omitted, falls back to the single threshold computed | ||
| during :meth:`calibrate` using the *mean* calibration | ||
| likelihood ratio as a stand-in for w(x). That fallback is | ||
| only an approximation of Corollary 1 -- the paper's formula | ||
| is defined per test point via that point's actual w(x), not | ||
| an aggregate over the calibration set -- so results from the | ||
| fallback do not carry the same finite-sample coverage | ||
| guarantee as the paper's construction. A warning is emitted | ||
| (once) the first time this fallback is used. | ||
|
|
||
| Returns: | ||
| Dictionary with all results from base model, plus: | ||
| - y_predset: Boolean tensor indicating which classes | ||
|
|
@@ -556,10 +638,84 @@ def forward(self, **kwargs) -> Dict[str, torch.Tensor]: | |
| conformity_scores = all_class_conformity_scores( | ||
| y_prob, score_type=self.score_type, rng=self.rng | ||
| ) | ||
| N, K = conformity_scores.shape | ||
|
|
||
| if test_embeddings is not None: | ||
| if self.kde_test is None or self.kde_cal is None: | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [medium] Pre-fitted KDEs combined with custom cal_weights silently produce wrong per-point thresholds calibrate(cal_weights=...) stores custom weights as the calibration likelihood ratios but leaves self.kde_test/self.kde_cal in place if they were passed to init. forward(test_embeddings=...) then scores test points with those KDEs and compares them against the custom calibration weights, which are on a different scale. The guard only checks for missing KDEs, and its message assumes that custom weights mean no KDEs, so this case is not caught. Fix: record in calibrate() whether the stored weights came from the KDEs (for example, a flag set in the KDE branch), and raise in forward() when the per-point path is requested without KDE-derived weights. Add a test for that combination. |
||
| raise ValueError( | ||
| "test_embeddings was provided but no KDEs are available " | ||
| "(calibrate() was called with custom cal_weights, which " | ||
| "has no way to score a new test point's likelihood " | ||
| "ratio). Per-test-point thresholding requires calibrate() " | ||
| "to have been called with cal_embeddings/test_embeddings " | ||
| "or pre-fitted kde_test/kde_cal." | ||
| ) | ||
| if self._cal_conformity_scores is None: | ||
| raise RuntimeError("Must call calibrate() before forward().") | ||
| if len(test_embeddings) != N: | ||
| raise ValueError( | ||
| f"test_embeddings has {len(test_embeddings)} rows but " | ||
| f"the batch has {N} examples; they must be aligned " | ||
| "one-to-one in the same order." | ||
| ) | ||
|
|
||
| test_weights = _compute_likelihood_ratio( | ||
| self.kde_test, self.kde_cal, test_embeddings | ||
| ) | ||
| thresholds = np.empty((N, K), dtype=np.float64) | ||
| if isinstance(self.alpha, float): | ||
| for i in range(N): | ||
| t_i = _query_weighted_quantile( | ||
| self._cal_conformity_scores, | ||
| self.alpha, | ||
| self._cal_likelihood_ratios, | ||
| float(test_weights[i]), | ||
| ) | ||
| thresholds[i, :] = t_i | ||
| else: | ||
| for i in range(N): | ||
| for k in range(K): | ||
| if len(self._cal_class_scores[k]) > 0: | ||
| thresholds[i, k] = _query_weighted_quantile( | ||
| self._cal_class_scores[k], | ||
| self.alpha[k], | ||
| self._cal_class_weights[k], | ||
| float(test_weights[i]), | ||
| ) | ||
| else: | ||
| thresholds[i, k] = -np.inf | ||
| threshold_tensor = torch.as_tensor( | ||
| thresholds, | ||
| device=pred["y_prob"].device, | ||
| dtype=pred["y_prob"].dtype, | ||
| ) | ||
| else: | ||
| if not self._warned_fixed_threshold: | ||
| warnings.warn( | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [low] Fallback warning gives advice that raises for custom-weight users The warning says to pass test_embeddings to get the paper's guarantee. When calibrate() was given only cal_weights, forward(test_embeddings=...) raises ValueError at line 645, and this warning fires for those users with no way to avoid it. Fix: when no KDEs are available, word the warning to say that the guarantee cannot be obtained with these weights, or skip the warning in that case. |
||
| "CovariateLabel.forward() was called without " | ||
| "test_embeddings: falling back to a single fixed " | ||
| "threshold computed from the mean calibration " | ||
| "likelihood ratio. This is only an approximation of " | ||
| "Corollary 1 of Tibshirani et al. (2019), which defines " | ||
| "the threshold per test point using that point's own " | ||
| "likelihood ratio w(x); pass test_embeddings to get the " | ||
| "paper's exact finite-sample coverage guarantee.", | ||
| UserWarning, | ||
| stacklevel=2, | ||
| ) | ||
| self._warned_fixed_threshold = True | ||
| threshold_tensor = self.t | ||
|
|
||
| conformity_scores = torch.as_tensor( | ||
| conformity_scores, device=pred["y_prob"].device, dtype=pred["y_prob"].dtype | ||
| ) | ||
| pred["y_predset"] = conformity_scores > self.t | ||
| # Corollary 1 (Tibshirani et al. 2019) includes a class whose score | ||
| # is *exactly* at the threshold: the weighted quantile is defined as | ||
| # the smallest score whose cumulative weight reaches alpha, so that | ||
| # score's own mass is part of what clears the target -- excluding it | ||
| # with a strict ">" would count it against coverage it was actually | ||
| # counted toward, under-covering whenever ties land on the threshold. | ||
| pred["y_predset"] = conformity_scores >= threshold_tensor | ||
|
|
||
| return pred | ||
|
|
||
|
|
@@ -622,7 +778,10 @@ def extract_embeddings(model, dataset): | |
| test_embeddings=test_embeddings | ||
| ) | ||
|
|
||
| # Evaluate | ||
| # Evaluate. Trainer.inference() cannot pass test_embeddings, so this | ||
| # uses the mean-weight fallback threshold and warns; see | ||
| # examples/conformal_eeg/tuev_covariate_shift_conformal.py for the | ||
| # per-test-point path. | ||
| test_dl = get_dataloader(test_data, batch_size=32, shuffle=False) | ||
| y_true, y_prob, _, extra = Trainer(model=cal_model_1).inference( | ||
| test_dl, additional_outputs=["y_predset"] | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[medium] Default threshold and set semantics change for all CovariateLabel users; PR description does not say so
The fix changes the default fixed-threshold path, which every existing CovariateLabel user gets. It adds the reserved test mass to the cumulative weights, switches searchsorted to side="right", and changes forward() from ">" to ">=". Together these shift thresholds and prediction-set sizes, so previously reported coverage and set sizes will not reproduce. The PR description only explains a flaky CI test and mentions none of this. Fix: describe the behavior change in the PR description and changelog, and add a regression test pinning the new default-path output for a fixed seed (for example, a small fixed-weight example whose y_predset differs between the old and new code).