"""
Neighborhood Conformal Prediction (NCP).
"""
import warnings
from typing import Dict, Optional, Union
import numpy as np
import torch
from sklearn.neighbors import NearestNeighbors
from torch.utils.data import IterableDataset
from pyhealth.calib.base_classes import SetPredictor
from pyhealth.calib.predictionset.base_conformal import _query_weighted_quantile
from pyhealth.calib.predictionset.scores import (
SUPPORTED_SCORE_TYPES,
all_class_conformity_scores,
true_class_conformity_scores,
)
from pyhealth.calib.utils import extract_embeddings, prepare_numpy_dataset
from pyhealth.models import BaseModel
__all__ = ["NeighborhoodLabel"]
[docs]class NeighborhoodLabel(SetPredictor):
"""Neighborhood Conformal Prediction (NCP) for multiclass classification.
Reference:
Ghosh, S., Belkhouja, T., Yan, Y., & Doppa, J. R. (2023).
Improving Uncertainty Quantification of Deep Classifiers via
Neighborhood Conformal Prediction. https://arxiv.org/abs/2303.10694
Note:
This implements the paper's NCP calibration with marginal coverage
only (the paper has no class-conditional variant). Two deviations
from a literal reading of the paper, both deliberate:
1. The paper does not say whether a calibration point is part of
its own neighbor set when searching for alpha_tilde. This
implementation excludes it (leave-one-out), matching test time,
where a test point's neighbors never include itself. Including
it inflates calibration coverage and causes under-coverage at
test time. With leave-one-out, the lowest-scoring calibration
point is never covered, so calibration coverage is at most
(N-1)/N for N calibration points, whatever ``k_neighbors`` is.
If the target 1 - alpha is unreachable, ``calibrate()`` warns:
above (N-1)/N it needs more calibration data or a larger alpha;
below it, a larger ``k_neighbors`` can also help.
2. If a prediction set would come out empty (no class's score
reaches the threshold), the model's top-1 predicted class is
force-included. This is not specified in the paper, but is
coverage-safe: adding a class to a set can only raise coverage,
never lower it.
Like standard split-conformal prediction, this assumes the
calibration and test data are exchangeable; it does not correct for
covariate shift (see
:class:`~pyhealth.calib.predictionset.CovariateLabel`).
Args:
model: A trained base model that supports embedding extraction
(must support `embed=True` in forward pass).
alpha: Target miscoverage rate; marginal coverage P(Y not in C(X)) <= alpha.
k_neighbors: Number of nearest calibration neighbors. Default 50.
lambda_L: Temperature for exponential weights; smaller => more localization.
Default 100.0.
score_type: Conformity score to use: "threshold" (default,
conformity score = p(true class), Sadinle, Lei, and Wasserman
2019) or "aps" (Adaptive Prediction Sets, Romano, Sesia, and
Candes 2020). See :mod:`pyhealth.calib.predictionset.scores`.
random_state: Optional int seed for the RNG used by
score_type="aps". Ignored for score_type="threshold".
debug: If True, process fewer samples for faster iteration.
Examples:
>>> from pyhealth.datasets import TUEVDataset, split_by_sample_conformal
>>> from pyhealth.datasets import get_dataloader
>>> from pyhealth.models import ContraWR
>>> from pyhealth.tasks import EEGEventsTUEV
>>> from pyhealth.calib.predictionset.cluster import NeighborhoodLabel
>>> from pyhealth.calib.utils import extract_embeddings
>>> from pyhealth.trainer import Trainer, get_metrics_fn
>>>
>>> dataset = TUEVDataset(root="path/to/tuev")
>>> sample_dataset = dataset.set_task(EEGEventsTUEV())
>>> train_ds, val_ds, cal_ds, test_ds = split_by_sample_conformal(
... sample_dataset, ratios=[0.6, 0.1, 0.15, 0.15], seed=42
... )
>>> model = ContraWR(dataset=sample_dataset)
>>> cal_embeddings = extract_embeddings(model, cal_ds, batch_size=32)
>>> ncp = NeighborhoodLabel(model=model, alpha=0.1, k_neighbors=50)
>>> ncp.calibrate(cal_dataset=cal_ds, cal_embeddings=cal_embeddings)
>>> test_loader = get_dataloader(test_ds, batch_size=32, shuffle=False)
>>> y_true, y_prob, _, extra = Trainer(model=ncp).inference(
... test_loader, additional_outputs=["y_predset"]
... )
>>> metrics = get_metrics_fn(ncp.mode)(
... y_true, y_prob, metrics=["accuracy", "miscoverage_ps"],
... y_predset=extra["y_predset"]
... )
>>>
>>> # Use APS instead of the default threshold score
>>> ncp_aps = NeighborhoodLabel(
... model=model, alpha=0.1, k_neighbors=50, score_type="aps")
>>> ncp_aps.calibrate(cal_dataset=cal_ds, cal_embeddings=cal_embeddings)
"""
[docs] def __init__(
self,
model: BaseModel,
alpha: float,
k_neighbors: int = 50,
lambda_L: float = 100.0,
score_type: str = "threshold",
random_state: int | None = None,
debug: bool = False,
**kwargs,
) -> None:
super().__init__(model, **kwargs)
if model.mode != "multiclass":
raise NotImplementedError(
"NeighborhoodLabel only supports multiclass classification"
)
if score_type not in SUPPORTED_SCORE_TYPES:
raise ValueError(
f"Unknown score_type: {score_type!r}. Supported: "
f"{SUPPORTED_SCORE_TYPES}."
)
self.mode = self.model.mode
for param in model.parameters():
param.requires_grad = False
self.model.eval()
self.device = model.device
self.debug = debug
self.score_type = score_type
self.rng = np.random.default_rng(random_state)
if not (0.0 < alpha < 1.0):
raise ValueError(f"alpha must be in (0, 1), got {alpha!r}")
self.alpha = float(alpha)
if not isinstance(k_neighbors, int) or k_neighbors <= 0:
raise ValueError(
f"k_neighbors must be a positive integer, got {k_neighbors!r}"
)
self.k_neighbors = k_neighbors
self.lambda_L = float(lambda_L)
self.cal_embeddings_ = None
self.cal_conformity_scores_ = None
self.alpha_tilde_ = None
self._nn = None
[docs] def calibrate(
self,
cal_dataset: IterableDataset,
cal_embeddings: Optional[np.ndarray] = None,
batch_size: int = 32,
) -> None:
"""Calibrate NCP steps:
Step 1: For each calibration point i, compute Q̃^NCP (weighted quantile)
over its k-NN in calibration using weights.
Step 2: Find ã^NCP(α) = largest ã such that empirical coverage on the
calibration set is >= 1-α; store as alpha_tilde_ for use at test time.
Args:
cal_dataset: Calibration dataset (for labels and predictions if
cal_embeddings not provided).
cal_embeddings: Optional precomputed calibration embeddings
(n_cal, embedding_dim). If None, extracted from cal_dataset.
batch_size: Batch size for embedding extraction when cal_embeddings
is not provided.
"""
cal_dict = prepare_numpy_dataset(
self.model,
cal_dataset,
["y_prob", "y_true"],
debug=self.debug,
)
y_prob = cal_dict["y_prob"]
y_true = cal_dict["y_true"]
N = y_prob.shape[0]
if cal_embeddings is None:
cal_embeddings = extract_embeddings(
self.model, cal_dataset, batch_size=batch_size, device=self.device
)
else:
cal_embeddings = np.asarray(cal_embeddings)
if cal_embeddings.shape[0] != N:
raise ValueError(
f"cal_embeddings length {cal_embeddings.shape[0]} must match "
f"cal_dataset size {N}"
)
conformity_scores = true_class_conformity_scores(
y_prob, y_true, score_type=self.score_type, rng=self.rng
)
k = min(self.k_neighbors, N)
self._nn = NearestNeighbors(n_neighbors=k, metric="euclidean").fit(
np.atleast_2d(cal_embeddings)
)
self.cal_embeddings_ = np.atleast_2d(cal_embeddings)
self.cal_conformity_scores_ = np.asarray(conformity_scores, dtype=np.float64)
# NCP calibration step. kneighbors(X) on the fitted set returns each
# point as its own nearest neighbor (distance 0), so request one
# extra neighbor and drop the self-match (leave-one-out). Otherwise a
# point's own score leaks into its own threshold, which a test point
# never gets, and the search under-covers at test time.
k_query = min(k + 1, N)
distances_all, indices_all = self._nn.kneighbors(
self.cal_embeddings_, n_neighbors=k_query
)
n_neighbors_loo = k_query - 1
distances_cal = np.zeros((N, n_neighbors_loo), dtype=distances_all.dtype)
indices_cal = np.zeros((N, n_neighbors_loo), dtype=indices_all.dtype)
for i in range(N):
mask = indices_all[i] != i
distances_cal[i] = distances_all[i][mask][:n_neighbors_loo]
indices_cal[i] = indices_all[i][mask][:n_neighbors_loo]
cal_weights = np.exp(-distances_cal / self.lambda_L)
cal_weights = cal_weights / cal_weights.sum(axis=1, keepdims=True)
def _empirical_coverage(alpha_tilde_cand: float) -> float:
t_all = np.zeros(N, dtype=np.float64)
for i in range(N):
t_all[i] = _query_weighted_quantile(
self.cal_conformity_scores_[indices_cal[i]],
alpha_tilde_cand,
cal_weights[i],
)
return float(np.mean(self.cal_conformity_scores_ >= t_all))
low, high = 0.0, 1.0
for _ in range(50):
mid = (low + high) / 2
if _empirical_coverage(mid) >= 1.0 - self.alpha:
low = mid
else:
high = mid
self.alpha_tilde_ = float(low)
# Coverage is largest at alpha_tilde = 0. If even that misses the
# target, the search above silently bottoms out at 0 and the
# prediction sets will under-cover. With leave-one-out the
# lowest-scoring point is never covered, so (N-1)/N is a ceiling
# that no k_neighbors can lift.
if self.alpha_tilde_ == 0.0:
best_coverage = _empirical_coverage(0.0)
target = 1.0 - self.alpha
if best_coverage < target:
ceiling = (N - 1) / N
if target > ceiling:
advice = (
f"With {N} calibration points coverage is at most "
f"{ceiling:.3f} for any k_neighbors; use a larger "
"calibration set or a larger alpha."
)
else:
advice = (
f"Increase k_neighbors (now {self.k_neighbors}), the "
"calibration set size, or alpha."
)
warnings.warn(
f"NeighborhoodLabel: target coverage {target:.3f} is not "
f"reachable on the calibration set (best achievable: "
f"{best_coverage:.3f}), so prediction sets will likely "
f"under-cover. {advice}",
UserWarning,
stacklevel=2,
)
[docs] def forward(self, **kwargs) -> Dict[str, torch.Tensor]:
"""Forward with NCP: per-sample weighted quantile threshold."""
if (
self.cal_embeddings_ is None
or self.cal_conformity_scores_ is None
or self.alpha_tilde_ is None
):
raise RuntimeError(
"NeighborhoodLabel must be calibrated before inference. "
"Call calibrate() first."
)
pred = self.model(**{**kwargs, "embed": True})
if "embed" not in pred:
raise ValueError(
f"Model {type(self.model).__name__} does not return "
"embeddings. Ensure it supports embed=True in forward()."
)
test_emb = pred["embed"].detach().cpu().numpy()
test_emb = np.atleast_2d(test_emb)
batch_size = test_emb.shape[0]
n_cal = self.cal_conformity_scores_.shape[0]
k = min(self.k_neighbors, n_cal)
distances, indices = self._nn.kneighbors(test_emb, n_neighbors=k)
thresholds = np.zeros(batch_size, dtype=np.float64)
for i in range(batch_size):
w = np.exp(-distances[i] / self.lambda_L)
w = w / np.sum(w)
scores_i = self.cal_conformity_scores_[indices[i]]
thresholds[i] = _query_weighted_quantile(
scores_i, self.alpha_tilde_, w
)
th = torch.as_tensor(
thresholds, device=self.device, dtype=pred["y_prob"].dtype
)
if pred["y_prob"].ndim > 1:
th = th.view(-1, *([1] * (pred["y_prob"].ndim - 1)))
y_prob_np = pred["y_prob"].detach().cpu().numpy()
conformity_scores = all_class_conformity_scores(
y_prob_np, score_type=self.score_type, rng=self.rng
)
conformity_scores = torch.as_tensor(
conformity_scores, device=pred["y_prob"].device, dtype=pred["y_prob"].dtype
)
y_predset = conformity_scores >= th
# if threshold is high, include at least argmax
empty = y_predset.sum(dim=1) == 0
if empty.any():
argmax_idx = pred["y_prob"].argmax(dim=1)
y_predset[empty, argmax_idx[empty]] = True
pred["y_predset"] = y_predset
pred.pop("embed", None)
return pred