Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions docs/api/calib.rst
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,25 @@ New to calibration and uncertainty quantification? Check out this complete examp

This example shows the complete pipeline from model training to uncertainty-aware predictions with formal coverage guarantees.

.. note::

``CovariateLabel``'s finite-sample correction implements Corollary 1 of
Tibshirani, Barber, Candes, and Ramdas, "Conformal Prediction Under
Covariate Shift" (NeurIPS 2019, https://arxiv.org/abs/1904.06019): the
test point's reserved probability mass must be inserted as an actual
point in the weighted empirical distribution (at the conservative
extreme), not merely folded into the normalizing denominator -- doing
only the latter silently under-covers relative to the target coverage
level.

Corollary 1 also defines the threshold *per test point*, using that
point's own likelihood ratio w(x). Pass ``test_embeddings`` to
``CovariateLabel.forward()`` to get this exact per-point threshold;
omitting it falls back to a single threshold computed from the *mean*
calibration likelihood ratio, which is only an approximation of the
paper's guarantee (a ``UserWarning`` is raised when this fallback is
used).

Quick Links
-----------

Expand Down
37 changes: 35 additions & 2 deletions examples/conformal_eeg/tuev_covariate_shift_conformal.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@
Notes:
- CovariateLabel requires access to test embeddings to estimate density ratios.
- Test embeddings are recomputed each seed since the model changes.
- CovariateLabel's finite-sample correction implements Corollary 1 of
Tibshirani, Barber, Candes, and Ramdas (NeurIPS 2019, arXiv:1904.06019);
see docs/api/calib.rst for details.
"""

from __future__ import annotations
Expand Down Expand Up @@ -176,6 +179,36 @@ def set_seed(seed: int) -> None:
torch.cuda.manual_seed_all(seed)


def _inference_with_pointwise_threshold(cov_predictor, test_loader, test_embeddings):
"""Run CovariateLabel inference with each test point's own threshold.

Trainer.inference() calls model(**batch) with no way to also pass a
per-batch test_embeddings slice, so routing through it would silently
fall back to CovariateLabel's approximate mean-weight threshold for
every point (defeating the whole point of this example -- exercising
Corollary 1's exact per-test-point construction). This loop mirrors
Trainer.inference()'s logic directly, slicing test_embeddings in the
same fixed order test_loader yields batches in (shuffle=False).
"""
y_true_all, y_prob_all, y_predset_all = [], [], []
cov_predictor.eval()
offset = 0
with torch.no_grad():
for batch in test_loader:
batch_size = len(batch["patient_id"])
batch_embeddings = test_embeddings[offset : offset + batch_size]
offset += batch_size
output = cov_predictor(test_embeddings=batch_embeddings, **batch)
y_true_all.append(output["y_true"].cpu().numpy())
y_prob_all.append(output["y_prob"].cpu().numpy())
y_predset_all.append(output["y_predset"].cpu().numpy())
return (
np.concatenate(y_true_all, axis=0),
np.concatenate(y_prob_all, axis=0),
{"y_predset": np.concatenate(y_predset_all, axis=0)},
)


def _run_one_seed(
args,
sample_dataset,
Expand Down Expand Up @@ -246,8 +279,8 @@ def _run_one_seed(
test_embeddings=test_embeddings,
)

y_true, y_prob, _, extra = Trainer(model=cov_predictor).inference(
test_loader, additional_outputs=["y_predset"]
y_true, y_prob, extra = _inference_with_pointwise_threshold(
cov_predictor, test_loader, test_embeddings
)
conf_metrics = get_metrics_fn("multiclass")(
y_true, y_prob,
Expand Down
193 changes: 176 additions & 17 deletions pyhealth/calib/predictionset/covariate/covariate_label.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
https://arxiv.org/abs/2310.12033
"""

import warnings
from typing import Callable, Dict, Optional, Union

import numpy as np
Expand Down Expand Up @@ -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]
Expand All @@ -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")

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] 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).


# Handle edge cases
if idx >= len(sorted_scores):
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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(
Expand All @@ -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
Expand All @@ -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:

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] 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(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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

Expand Down Expand Up @@ -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"]
Expand Down
Loading
Loading