outofsample 1.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- outofsample/__init__.py +45 -0
- outofsample/_calibration.py +1011 -0
- outofsample/_compat.py +208 -0
- outofsample/_conformal_classifier.py +418 -0
- outofsample/_convenience.py +786 -0
- outofsample/_cqr.py +440 -0
- outofsample/_diagnostics.py +547 -0
- outofsample/_estimators.py +999 -0
- outofsample/_intervals.py +1147 -0
- outofsample/_metrics.py +239 -0
- outofsample/_persistence.py +1036 -0
- outofsample/_prediction.py +162 -0
- outofsample/_pu.py +951 -0
- outofsample/_refresh.py +395 -0
- outofsample/_stacking.py +598 -0
- outofsample/_transformer.py +362 -0
- outofsample/_validation.py +272 -0
- outofsample/py.typed +0 -0
- outofsample-1.1.0.dist-info/METADATA +522 -0
- outofsample-1.1.0.dist-info/RECORD +23 -0
- outofsample-1.1.0.dist-info/WHEEL +5 -0
- outofsample-1.1.0.dist-info/licenses/LICENSE +28 -0
- outofsample-1.1.0.dist-info/top_level.txt +1 -0
outofsample/_compat.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
"""Compatibility adapters for third-party libraries.
|
|
2
|
+
|
|
3
|
+
Provides ``SHAPWrapper`` for exposing OOS models to SHAP explainers
|
|
4
|
+
without adding SHAP as a dependency.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
from sklearn.utils.validation import check_is_fitted
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class SHAPWrapper:
|
|
16
|
+
"""Adapter exposing OOS models for SHAP explainability.
|
|
17
|
+
|
|
18
|
+
For IDs that were in the training data, SHAP values are computed using
|
|
19
|
+
the fold model that held that sample out (true out-of-sample explanation).
|
|
20
|
+
For unseen IDs, the general model is used.
|
|
21
|
+
|
|
22
|
+
This wrapper can also be used to explain a single model directly via
|
|
23
|
+
the ``model`` property or ``fold_model()`` method.
|
|
24
|
+
|
|
25
|
+
Args:
|
|
26
|
+
oos_model: A fitted OOSClassifier or OOSRegressor.
|
|
27
|
+
|
|
28
|
+
Examples:
|
|
29
|
+
>>> import shap
|
|
30
|
+
>>> sw = SHAPWrapper(fitted_oos_model)
|
|
31
|
+
|
|
32
|
+
Explain the general model:
|
|
33
|
+
|
|
34
|
+
>>> explainer = shap.TreeExplainer(sw.model)
|
|
35
|
+
>>> shap_values = explainer.shap_values(X)
|
|
36
|
+
|
|
37
|
+
Explain a specific fold:
|
|
38
|
+
|
|
39
|
+
>>> explainer = shap.TreeExplainer(sw.fold_model(0))
|
|
40
|
+
|
|
41
|
+
Fold-aware SHAP values (each row explained by its OOS fold model):
|
|
42
|
+
|
|
43
|
+
>>> shap_values = sw.shap_values(X, ids)
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
def __init__(self, oos_model: Any) -> None:
|
|
47
|
+
check_is_fitted(oos_model)
|
|
48
|
+
self._oos = oos_model
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def model(self) -> Any:
|
|
52
|
+
"""The general model (trained on all data)."""
|
|
53
|
+
return self._oos.general_model_
|
|
54
|
+
|
|
55
|
+
def fold_model(self, fold_idx: int) -> Any:
|
|
56
|
+
"""Return the trained model for a specific fold.
|
|
57
|
+
|
|
58
|
+
Args:
|
|
59
|
+
fold_idx: Zero-based fold index.
|
|
60
|
+
|
|
61
|
+
Returns:
|
|
62
|
+
The estimator trained on all data except fold ``fold_idx``.
|
|
63
|
+
"""
|
|
64
|
+
return self._oos.models_[fold_idx]
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def n_folds(self) -> int:
|
|
68
|
+
"""Number of fold models."""
|
|
69
|
+
return len(self._oos.models_)
|
|
70
|
+
|
|
71
|
+
@property
|
|
72
|
+
def feature_names(self) -> list[str] | None:
|
|
73
|
+
"""Feature names tracked during fit, or None."""
|
|
74
|
+
if hasattr(self._oos, "feature_names_in_"):
|
|
75
|
+
return list(self._oos.feature_names_in_)
|
|
76
|
+
return None
|
|
77
|
+
|
|
78
|
+
def predict(self, X: Any) -> np.ndarray:
|
|
79
|
+
"""Predict using the general model (for KernelExplainer).
|
|
80
|
+
|
|
81
|
+
Args:
|
|
82
|
+
X: Feature matrix (no ID column).
|
|
83
|
+
|
|
84
|
+
Returns:
|
|
85
|
+
Predictions from the general model.
|
|
86
|
+
"""
|
|
87
|
+
return self._oos.general_model_.predict(X)
|
|
88
|
+
|
|
89
|
+
def predict_proba(self, X: Any) -> np.ndarray:
|
|
90
|
+
"""Predict probabilities using the general model.
|
|
91
|
+
|
|
92
|
+
Args:
|
|
93
|
+
X: Feature matrix (no ID column).
|
|
94
|
+
|
|
95
|
+
Returns:
|
|
96
|
+
Probability estimates from the general model.
|
|
97
|
+
"""
|
|
98
|
+
return self._oos.general_model_.predict_proba(X)
|
|
99
|
+
|
|
100
|
+
def shap_values(
|
|
101
|
+
self,
|
|
102
|
+
X: Any,
|
|
103
|
+
ids: Any,
|
|
104
|
+
*,
|
|
105
|
+
explainer_type: str = "auto",
|
|
106
|
+
**explainer_kwargs: Any,
|
|
107
|
+
) -> np.ndarray:
|
|
108
|
+
"""Compute fold-aware SHAP values.
|
|
109
|
+
|
|
110
|
+
For each sample, selects the fold model that held it out during
|
|
111
|
+
training and computes SHAP values using that model. Unseen IDs
|
|
112
|
+
use the general model.
|
|
113
|
+
|
|
114
|
+
Requires the ``shap`` package to be installed.
|
|
115
|
+
|
|
116
|
+
Args:
|
|
117
|
+
X: Feature matrix (no ID column). Must be array-like with
|
|
118
|
+
shape ``(n_samples, n_features)``.
|
|
119
|
+
ids: 1-D array of identifiers, one per row of X. Used to
|
|
120
|
+
determine which fold model to use.
|
|
121
|
+
explainer_type: SHAP explainer to use. ``"auto"`` detects
|
|
122
|
+
tree-based models and uses ``TreeExplainer``; falls back
|
|
123
|
+
to ``KernelExplainer``. Also accepts ``"tree"`` or
|
|
124
|
+
``"kernel"`` explicitly.
|
|
125
|
+
**explainer_kwargs: Additional keyword arguments passed to
|
|
126
|
+
the SHAP explainer constructor.
|
|
127
|
+
|
|
128
|
+
Returns:
|
|
129
|
+
SHAP values array with the same shape as X (for regression or
|
|
130
|
+
binary classification) or a list of arrays (for multiclass).
|
|
131
|
+
|
|
132
|
+
Raises:
|
|
133
|
+
ImportError: If the ``shap`` package is not installed.
|
|
134
|
+
"""
|
|
135
|
+
try:
|
|
136
|
+
import shap
|
|
137
|
+
except ImportError as err:
|
|
138
|
+
raise ImportError(
|
|
139
|
+
"The shap package is required for shap_values(). Install it with: pip install shap"
|
|
140
|
+
) from err
|
|
141
|
+
|
|
142
|
+
X_arr = np.asarray(X)
|
|
143
|
+
ids_arr = np.asarray(ids)
|
|
144
|
+
if hasattr(self._oos, "_check_predict_ids"):
|
|
145
|
+
self._oos._check_predict_ids(ids_arr)
|
|
146
|
+
id_to_fold = self._oos.id_to_fold_
|
|
147
|
+
|
|
148
|
+
# Map each ID to its fold (-1 for unseen)
|
|
149
|
+
fold_indices = np.array([id_to_fold.get(id_, -1) for id_ in ids_arr])
|
|
150
|
+
unique_folds = np.unique(fold_indices)
|
|
151
|
+
|
|
152
|
+
# Cache explainers to avoid expensive re-creation
|
|
153
|
+
explainer_cache: dict[int, Any] = {}
|
|
154
|
+
|
|
155
|
+
def _get_explainer(model: Any, fold: int) -> Any:
|
|
156
|
+
if fold not in explainer_cache:
|
|
157
|
+
if explainer_type == "tree" or (explainer_type == "auto" and _is_tree_model(model)):
|
|
158
|
+
explainer_cache[fold] = shap.TreeExplainer(model, **explainer_kwargs)
|
|
159
|
+
else:
|
|
160
|
+
bg = X_arr[: min(50, len(X_arr))]
|
|
161
|
+
explainer_cache[fold] = shap.KernelExplainer(
|
|
162
|
+
model.predict, bg, **explainer_kwargs
|
|
163
|
+
)
|
|
164
|
+
return explainer_cache[fold]
|
|
165
|
+
|
|
166
|
+
# Compute SHAP values per fold
|
|
167
|
+
# Result is an ndarray, or a list of ndarrays for multiclass
|
|
168
|
+
result: Any = None
|
|
169
|
+
for fold in unique_folds:
|
|
170
|
+
mask = fold_indices == fold
|
|
171
|
+
model = self._oos.general_model_ if fold == -1 else self._oos.models_[fold]
|
|
172
|
+
explainer = _get_explainer(model, fold)
|
|
173
|
+
sv = explainer.shap_values(X_arr[mask])
|
|
174
|
+
|
|
175
|
+
if isinstance(sv, list):
|
|
176
|
+
# Multiclass: list of arrays, each (n_masked, n_features)
|
|
177
|
+
if result is None:
|
|
178
|
+
result = [np.empty_like(X_arr, dtype=float) for _ in sv]
|
|
179
|
+
for cls_idx, cls_sv in enumerate(sv):
|
|
180
|
+
result[cls_idx][mask] = cls_sv
|
|
181
|
+
else:
|
|
182
|
+
sv = np.asarray(sv)
|
|
183
|
+
if result is None:
|
|
184
|
+
result = np.empty((len(X_arr), *sv.shape[1:]), dtype=float)
|
|
185
|
+
result[mask] = sv
|
|
186
|
+
|
|
187
|
+
return result
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _is_tree_model(model: Any) -> bool:
|
|
191
|
+
"""Check if a model is tree-based (supports TreeExplainer).
|
|
192
|
+
|
|
193
|
+
Uses feature detection rather than class name matching for robustness
|
|
194
|
+
across library versions.
|
|
195
|
+
|
|
196
|
+
Args:
|
|
197
|
+
model: An sklearn-compatible estimator.
|
|
198
|
+
|
|
199
|
+
Returns:
|
|
200
|
+
True if the model appears to be tree-based.
|
|
201
|
+
"""
|
|
202
|
+
# Feature detection: attributes that tree-based models expose
|
|
203
|
+
tree_attrs = ("tree_", "estimators_", "get_booster", "get_dump")
|
|
204
|
+
if any(hasattr(model, attr) for attr in tree_attrs):
|
|
205
|
+
return True
|
|
206
|
+
# Fallback: class name matching for models that don't expose tree attributes
|
|
207
|
+
tree_names = ("CatBoost", "LGBM", "LightGBM")
|
|
208
|
+
return any(t in type(model).__name__ for t in tree_names)
|
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
"""Conformal prediction sets for classification.
|
|
2
|
+
|
|
3
|
+
Provides ``OOSConformalClassifier``, which turns the out-of-sample class
|
|
4
|
+
probabilities of an ``OOSClassifier`` into prediction sets with a
|
|
5
|
+
finite-sample coverage guarantee: the set contains the true label with
|
|
6
|
+
probability at least ``1 - alpha``. Supports the LAC, APS (Romano, Sesia &
|
|
7
|
+
Candes, 2020) and RAPS (Angelopoulos et al., 2021) scores, randomized or
|
|
8
|
+
not, and class-conditional (Mondrian) coverage.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import warnings
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
import numpy as np
|
|
17
|
+
from sklearn.base import BaseEstimator, ClassifierMixin, MetaEstimatorMixin
|
|
18
|
+
from sklearn.utils.validation import check_is_fitted
|
|
19
|
+
|
|
20
|
+
from ._estimators import OOSClassifier
|
|
21
|
+
from ._intervals import cross_conformal_quantiles
|
|
22
|
+
from ._validation import extract_ids_and_features, reset_fitted_state, validate_target
|
|
23
|
+
|
|
24
|
+
_METHODS = ("lac", "aps", "raps")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def class_scores(
|
|
28
|
+
probs: np.ndarray,
|
|
29
|
+
method: str,
|
|
30
|
+
u: np.ndarray | None = None,
|
|
31
|
+
*,
|
|
32
|
+
lam: float = 0.0,
|
|
33
|
+
k_reg: int = 1,
|
|
34
|
+
) -> np.ndarray:
|
|
35
|
+
"""Nonconformity score of every candidate label.
|
|
36
|
+
|
|
37
|
+
Args:
|
|
38
|
+
probs: Probability matrix of shape ``(n, n_classes)``.
|
|
39
|
+
method: ``"lac"`` (``1 - p_y``), ``"aps"`` (probability mass of the
|
|
40
|
+
labels ranked above ``y`` plus ``u * p_y``) or ``"raps"`` (APS
|
|
41
|
+
plus ``lam * max(0, rank(y) - k_reg)``).
|
|
42
|
+
u: Per-row uniform draws for the randomized scores, or None for the
|
|
43
|
+
non-randomized versions (``u = 1``).
|
|
44
|
+
lam: RAPS penalty weight.
|
|
45
|
+
k_reg: RAPS rank from which the penalty applies (1-based).
|
|
46
|
+
|
|
47
|
+
Returns:
|
|
48
|
+
Score matrix of shape ``(n, n_classes)`` (lower = more conforming).
|
|
49
|
+
"""
|
|
50
|
+
probs = np.asarray(probs, dtype=float)
|
|
51
|
+
if method == "lac":
|
|
52
|
+
return 1.0 - probs
|
|
53
|
+
n, n_classes = probs.shape
|
|
54
|
+
# Stable descending order: ties are broken by column index, identically
|
|
55
|
+
# for calibration and prediction
|
|
56
|
+
order = np.argsort(-probs, axis=1, kind="stable")
|
|
57
|
+
sorted_p = np.take_along_axis(probs, order, axis=1)
|
|
58
|
+
above = np.cumsum(sorted_p, axis=1) - sorted_p # mass strictly ranked above
|
|
59
|
+
weight = np.ones((n, 1)) if u is None else np.asarray(u, dtype=float).reshape(-1, 1)
|
|
60
|
+
sorted_scores = above + weight * sorted_p
|
|
61
|
+
if method == "raps":
|
|
62
|
+
ranks = np.arange(1, n_classes + 1)
|
|
63
|
+
sorted_scores = sorted_scores + lam * np.maximum(0, ranks - k_reg)[None, :]
|
|
64
|
+
scores = np.empty_like(sorted_scores)
|
|
65
|
+
np.put_along_axis(scores, order, sorted_scores, axis=1)
|
|
66
|
+
return scores
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class OOSConformalClassifier(ClassifierMixin, MetaEstimatorMixin, BaseEstimator):
|
|
70
|
+
"""Cross-conformal prediction sets from out-of-sample probabilities.
|
|
71
|
+
|
|
72
|
+
Wraps an ``OOSClassifier``. The OOS probability of each training row's
|
|
73
|
+
true label gives its nonconformity score; a label enters a row's
|
|
74
|
+
prediction set when its score is at most the conformal quantile of the
|
|
75
|
+
calibration scores. Training IDs use the fold model that held them out
|
|
76
|
+
and a quantile from the other folds' scores (cross-conformal); unseen
|
|
77
|
+
IDs use the general model and the quantile of all scores. Quantiles are
|
|
78
|
+
infinite (every label included) when a calibration set has fewer than
|
|
79
|
+
``1/alpha - 1`` scores.
|
|
80
|
+
|
|
81
|
+
Args:
|
|
82
|
+
estimator: A scikit-learn-compatible classifier with
|
|
83
|
+
``predict_proba``.
|
|
84
|
+
id_col: Column name or index for unique identifiers.
|
|
85
|
+
cv: Number of folds or a scikit-learn CV splitter.
|
|
86
|
+
random_state: Seed for fold splitting and the randomized scores.
|
|
87
|
+
stratified: Stratified folds (see ``OOSClassifier``).
|
|
88
|
+
verbose: Verbosity level.
|
|
89
|
+
scoring: Metrics computed on the OOS folds.
|
|
90
|
+
alpha: Miscoverage rate. Default 0.1: sets contain the true label
|
|
91
|
+
for at least 90% of rows.
|
|
92
|
+
method: ``"aps"`` (default, adaptive sets), ``"raps"`` (APS with a
|
|
93
|
+
rank penalty that discourages large sets) or ``"lac"`` (least
|
|
94
|
+
ambiguous set-valued classifier, ``1 - p_y``; smallest sets on
|
|
95
|
+
average, least adaptive).
|
|
96
|
+
lam: RAPS penalty per rank beyond ``k_reg``.
|
|
97
|
+
k_reg: RAPS: number of top-ranked labels that are not penalized.
|
|
98
|
+
randomized: Randomize APS/RAPS scores (``u ~ U(0, 1)`` per row) for
|
|
99
|
+
exact rather than conservative coverage. Draws are seeded by
|
|
100
|
+
``random_state``.
|
|
101
|
+
allow_empty: If False (default), an empty set is replaced by the
|
|
102
|
+
most probable label (only increases coverage).
|
|
103
|
+
mondrian: ``None`` for marginal coverage, or ``"class"`` for
|
|
104
|
+
class-conditional coverage: each label uses a quantile computed
|
|
105
|
+
from the calibration rows of that class, so coverage holds
|
|
106
|
+
within every true class.
|
|
107
|
+
group_col: Column for group-aware fold splitting.
|
|
108
|
+
strict: Raise instead of warn when the out-of-sample guarantee would
|
|
109
|
+
be silently broken (see ``OOSClassifier``).
|
|
110
|
+
|
|
111
|
+
Attributes:
|
|
112
|
+
oos_classifier_: The fitted inner ``OOSClassifier``.
|
|
113
|
+
classes_: Class labels; columns of ``predict_set`` follow this order.
|
|
114
|
+
conformal_scores_: OOS score of each training row's true label.
|
|
115
|
+
quantiles_: Per-fold thresholds; shape ``(n_folds,)``, or
|
|
116
|
+
``(n_folds, n_classes)`` with ``mondrian="class"``.
|
|
117
|
+
general_quantile_: Threshold for unseen IDs (per class with
|
|
118
|
+
``mondrian="class"``).
|
|
119
|
+
n_features_in_: Number of features.
|
|
120
|
+
feature_names_in_: Feature names (DataFrame input only).
|
|
121
|
+
|
|
122
|
+
Examples:
|
|
123
|
+
>>> from outofsample import OOSConformalClassifier
|
|
124
|
+
>>> from sklearn.ensemble import RandomForestClassifier
|
|
125
|
+
>>> model = OOSConformalClassifier(RandomForestClassifier(), alpha=0.1)
|
|
126
|
+
>>> model.fit(X, y)
|
|
127
|
+
>>> sets = model.predict_set(X) # (n, n_classes) booleans
|
|
128
|
+
>>> labels = model.predict_set(X, return_labels=True)
|
|
129
|
+
"""
|
|
130
|
+
|
|
131
|
+
def __init__(
|
|
132
|
+
self,
|
|
133
|
+
estimator: Any = None,
|
|
134
|
+
*,
|
|
135
|
+
id_col: str | int | None = "id",
|
|
136
|
+
cv: int | Any = 5,
|
|
137
|
+
random_state: int | None = None,
|
|
138
|
+
stratified: bool = True,
|
|
139
|
+
verbose: int = 0,
|
|
140
|
+
scoring: str | list[str] | dict[str, Any] | None = None,
|
|
141
|
+
alpha: float = 0.1,
|
|
142
|
+
method: str = "aps",
|
|
143
|
+
lam: float = 0.01,
|
|
144
|
+
k_reg: int = 1,
|
|
145
|
+
randomized: bool = False,
|
|
146
|
+
allow_empty: bool = False,
|
|
147
|
+
mondrian: str | None = None,
|
|
148
|
+
group_col: str | None = None,
|
|
149
|
+
strict: bool = True,
|
|
150
|
+
) -> None:
|
|
151
|
+
"""Initialize the conformal classifier. See the class docstring."""
|
|
152
|
+
self.estimator = estimator
|
|
153
|
+
self.id_col = id_col
|
|
154
|
+
self.cv = cv
|
|
155
|
+
self.random_state = random_state
|
|
156
|
+
self.stratified = stratified
|
|
157
|
+
self.verbose = verbose
|
|
158
|
+
self.scoring = scoring
|
|
159
|
+
self.alpha = alpha
|
|
160
|
+
self.method = method
|
|
161
|
+
self.lam = lam
|
|
162
|
+
self.k_reg = k_reg
|
|
163
|
+
self.randomized = randomized
|
|
164
|
+
self.allow_empty = allow_empty
|
|
165
|
+
self.mondrian = mondrian
|
|
166
|
+
self.group_col = group_col
|
|
167
|
+
self.strict = strict
|
|
168
|
+
|
|
169
|
+
def __sklearn_is_fitted__(self) -> bool:
|
|
170
|
+
return hasattr(self, "oos_classifier_") and self.oos_classifier_.__sklearn_is_fitted__()
|
|
171
|
+
|
|
172
|
+
@property
|
|
173
|
+
def cv_results_(self) -> dict[str, Any]:
|
|
174
|
+
"""Overall and per-fold metrics from the inner OOS classifier."""
|
|
175
|
+
check_is_fitted(self)
|
|
176
|
+
return self.oos_classifier_.cv_results_
|
|
177
|
+
|
|
178
|
+
@property
|
|
179
|
+
def id_to_fold_(self) -> dict[Any, int]:
|
|
180
|
+
"""ID-to-fold mapping from the inner OOS classifier."""
|
|
181
|
+
check_is_fitted(self)
|
|
182
|
+
return self.oos_classifier_.id_to_fold_
|
|
183
|
+
|
|
184
|
+
@property
|
|
185
|
+
def last_routing_(self) -> dict[str, Any]:
|
|
186
|
+
"""Routing statistics of the most recent prediction call.
|
|
187
|
+
|
|
188
|
+
Delegates to the inner OOS classifier (see ``OOSClassifier.last_routing_``).
|
|
189
|
+
"""
|
|
190
|
+
check_is_fitted(self)
|
|
191
|
+
return self.oos_classifier_.last_routing_
|
|
192
|
+
|
|
193
|
+
def _validate_params(self) -> None:
|
|
194
|
+
if self.method not in _METHODS:
|
|
195
|
+
raise ValueError(f"method must be one of {_METHODS}, got {self.method!r}")
|
|
196
|
+
if isinstance(self.alpha, bool) or not 0 < self.alpha < 1:
|
|
197
|
+
raise ValueError(f"alpha must be in (0, 1), got {self.alpha}")
|
|
198
|
+
if self.mondrian not in (None, "class"):
|
|
199
|
+
raise ValueError(f"mondrian must be None or 'class', got {self.mondrian!r}")
|
|
200
|
+
if self.lam < 0:
|
|
201
|
+
raise ValueError(f"lam must be >= 0, got {self.lam}")
|
|
202
|
+
if isinstance(self.k_reg, bool) or not isinstance(self.k_reg, (int, np.integer)):
|
|
203
|
+
raise ValueError(f"k_reg must be an int, got {self.k_reg!r}")
|
|
204
|
+
if self.randomized and self.method == "lac":
|
|
205
|
+
raise ValueError("randomized applies to method='aps' or 'raps' only")
|
|
206
|
+
|
|
207
|
+
def _uniforms(self, n: int, stream: int) -> np.ndarray | None:
|
|
208
|
+
"""Seeded per-row uniform draws (None when not randomized)."""
|
|
209
|
+
if not self.randomized:
|
|
210
|
+
return None
|
|
211
|
+
return np.random.default_rng([stream, self.random_state or 0]).uniform(size=n)
|
|
212
|
+
|
|
213
|
+
def _scores(self, probs: np.ndarray, u: np.ndarray | None) -> np.ndarray:
|
|
214
|
+
return class_scores(probs, self.method, u, lam=self.lam, k_reg=int(self.k_reg))
|
|
215
|
+
|
|
216
|
+
def refresh(self, X: Any, y: Any = None, **kwargs: Any) -> None:
|
|
217
|
+
"""Not supported: call ``fit`` on the full updated data instead.
|
|
218
|
+
|
|
219
|
+
Raises:
|
|
220
|
+
NotImplementedError: Always.
|
|
221
|
+
"""
|
|
222
|
+
from ._refresh import refresh_unsupported
|
|
223
|
+
|
|
224
|
+
refresh_unsupported(self)
|
|
225
|
+
|
|
226
|
+
def fit(self, X: Any, y: Any, *, ids: Any | None = None, **fit_params: Any):
|
|
227
|
+
"""Fit the OOS classifier and compute the conformal thresholds.
|
|
228
|
+
|
|
229
|
+
Args:
|
|
230
|
+
X: Training data, optionally containing the ID column.
|
|
231
|
+
y: Class labels.
|
|
232
|
+
ids: Explicit ID array when X does not contain an ID column.
|
|
233
|
+
**fit_params: Passed to the underlying estimator's ``fit``.
|
|
234
|
+
|
|
235
|
+
Returns:
|
|
236
|
+
self
|
|
237
|
+
"""
|
|
238
|
+
self._validate_params()
|
|
239
|
+
reset_fitted_state(self)
|
|
240
|
+
self.oos_classifier_ = OOSClassifier(
|
|
241
|
+
estimator=self.estimator,
|
|
242
|
+
id_col=self.id_col,
|
|
243
|
+
cv=self.cv,
|
|
244
|
+
random_state=self.random_state,
|
|
245
|
+
stratified=self.stratified,
|
|
246
|
+
verbose=self.verbose,
|
|
247
|
+
scoring=self.scoring,
|
|
248
|
+
group_col=self.group_col,
|
|
249
|
+
strict=self.strict,
|
|
250
|
+
)
|
|
251
|
+
self.oos_classifier_.fit(X, y, ids=ids, **fit_params)
|
|
252
|
+
if not hasattr(self.oos_classifier_.general_model_, "predict_proba"):
|
|
253
|
+
raise ValueError(
|
|
254
|
+
f"{type(self.estimator).__name__} does not implement predict_proba, "
|
|
255
|
+
"which conformal prediction sets require"
|
|
256
|
+
)
|
|
257
|
+
y_arr = validate_target(y)
|
|
258
|
+
if y_arr.ndim != 1:
|
|
259
|
+
raise ValueError("OOSConformalClassifier supports single-output targets only")
|
|
260
|
+
|
|
261
|
+
self.classes_ = self.oos_classifier_.classes_
|
|
262
|
+
self.n_features_in_ = self.oos_classifier_.n_features_in_
|
|
263
|
+
if hasattr(self.oos_classifier_, "feature_names_in_"):
|
|
264
|
+
self.feature_names_in_ = self.oos_classifier_.feature_names_in_
|
|
265
|
+
|
|
266
|
+
oos = self.oos_classifier_.get_oos_predictions()
|
|
267
|
+
oos_index = np.concatenate(self.oos_classifier_.oos_index_)
|
|
268
|
+
label_idx = np.searchsorted(self.classes_, y_arr[oos_index])
|
|
269
|
+
probs = oos["probabilities"]
|
|
270
|
+
all_scores = self._scores(probs, self._uniforms(len(probs), stream=0))
|
|
271
|
+
self.conformal_scores_ = all_scores[np.arange(len(probs)), label_idx]
|
|
272
|
+
self._score_labels_ = label_idx
|
|
273
|
+
self._score_fold_indices_ = oos["fold_indices"]
|
|
274
|
+
|
|
275
|
+
self.quantiles_, self.general_quantile_ = self._thresholds(self.alpha)
|
|
276
|
+
if not (
|
|
277
|
+
np.all(np.isfinite(self.quantiles_)) and np.all(np.isfinite(self.general_quantile_))
|
|
278
|
+
):
|
|
279
|
+
warnings.warn(
|
|
280
|
+
"Some conformal calibration sets have fewer than 1/alpha - 1 = "
|
|
281
|
+
f"{1 / self.alpha - 1:.0f} scores (per class with mondrian='class'); "
|
|
282
|
+
"the affected labels are always included in the prediction sets.",
|
|
283
|
+
UserWarning,
|
|
284
|
+
stacklevel=2,
|
|
285
|
+
)
|
|
286
|
+
return self
|
|
287
|
+
|
|
288
|
+
def _thresholds(self, alpha: float) -> tuple[np.ndarray, Any]:
|
|
289
|
+
"""Per-fold and general thresholds at ``alpha`` (per class for Mondrian)."""
|
|
290
|
+
scores = self.conformal_scores_
|
|
291
|
+
folds = self._score_fold_indices_
|
|
292
|
+
n_folds = len(self.oos_classifier_.models_)
|
|
293
|
+
if self.mondrian is None:
|
|
294
|
+
return cross_conformal_quantiles(scores, folds, n_folds, alpha)
|
|
295
|
+
n_classes = len(self.classes_)
|
|
296
|
+
per_fold = np.empty((n_folds, n_classes))
|
|
297
|
+
general = np.empty(n_classes)
|
|
298
|
+
for c in range(n_classes):
|
|
299
|
+
in_class = self._score_labels_ == c
|
|
300
|
+
per_fold[:, c], general[c] = cross_conformal_quantiles(
|
|
301
|
+
scores[in_class], folds[in_class], n_folds, alpha
|
|
302
|
+
)
|
|
303
|
+
return per_fold, general
|
|
304
|
+
|
|
305
|
+
def predict_set(
|
|
306
|
+
self,
|
|
307
|
+
X: Any,
|
|
308
|
+
*,
|
|
309
|
+
ids: Any | None = None,
|
|
310
|
+
alpha: float | None = None,
|
|
311
|
+
return_labels: bool = False,
|
|
312
|
+
) -> Any:
|
|
313
|
+
"""Conformal prediction sets.
|
|
314
|
+
|
|
315
|
+
Args:
|
|
316
|
+
X: Input data.
|
|
317
|
+
ids: Explicit ID array.
|
|
318
|
+
alpha: Override miscoverage rate for this call; thresholds are
|
|
319
|
+
recomputed from the stored scores (no refit). None uses the
|
|
320
|
+
fitted alpha.
|
|
321
|
+
return_labels: If True, return a list with the array of labels
|
|
322
|
+
in each row's set instead of the membership matrix.
|
|
323
|
+
|
|
324
|
+
Returns:
|
|
325
|
+
Boolean array of shape ``(n_samples, n_classes)`` whose column
|
|
326
|
+
``j`` says whether ``classes_[j]`` is in the row's set, or a list
|
|
327
|
+
of label arrays when ``return_labels=True``.
|
|
328
|
+
"""
|
|
329
|
+
check_is_fitted(self)
|
|
330
|
+
if alpha is not None and (isinstance(alpha, bool) or not 0 < alpha < 1):
|
|
331
|
+
raise ValueError(f"alpha must be in (0, 1), got {alpha}")
|
|
332
|
+
probs = self.oos_classifier_.predict_proba(X, ids=ids)
|
|
333
|
+
_X, id_array, _ = extract_ids_and_features(X, self.id_col, ids=ids)
|
|
334
|
+
scores = self._scores(probs, self._uniforms(len(probs), stream=1))
|
|
335
|
+
|
|
336
|
+
if alpha is None or alpha == self.alpha:
|
|
337
|
+
per_fold, general = self.quantiles_, self.general_quantile_
|
|
338
|
+
else:
|
|
339
|
+
per_fold, general = self._thresholds(alpha)
|
|
340
|
+
id_to_fold = self.oos_classifier_.id_to_fold_
|
|
341
|
+
folds = np.array([id_to_fold.get(id_, -1) for id_ in id_array], dtype=int)
|
|
342
|
+
# The last entry of the table is the general threshold (fold -1)
|
|
343
|
+
if self.mondrian is None:
|
|
344
|
+
thresholds = np.append(np.asarray(per_fold, dtype=float), general)[folds][:, None]
|
|
345
|
+
else:
|
|
346
|
+
table = np.vstack([per_fold, np.asarray(general, dtype=float)[None, :]])
|
|
347
|
+
thresholds = table[folds]
|
|
348
|
+
sets = scores <= thresholds
|
|
349
|
+
|
|
350
|
+
if not self.allow_empty:
|
|
351
|
+
empty = ~sets.any(axis=1)
|
|
352
|
+
sets[empty, np.argmax(probs[empty], axis=1)] = True
|
|
353
|
+
if return_labels:
|
|
354
|
+
return [self.classes_[row] for row in sets]
|
|
355
|
+
return sets
|
|
356
|
+
|
|
357
|
+
def predict(self, X: Any, *, ids: Any | None = None) -> np.ndarray:
|
|
358
|
+
"""Most probable class from the fold-routed OOS model.
|
|
359
|
+
|
|
360
|
+
Args:
|
|
361
|
+
X: Input data.
|
|
362
|
+
ids: Explicit ID array.
|
|
363
|
+
|
|
364
|
+
Returns:
|
|
365
|
+
Array of shape ``(n_samples,)``.
|
|
366
|
+
"""
|
|
367
|
+
check_is_fitted(self)
|
|
368
|
+
return self.oos_classifier_.predict(X, ids=ids)
|
|
369
|
+
|
|
370
|
+
def predict_proba(self, X: Any, *, ids: Any | None = None) -> np.ndarray:
|
|
371
|
+
"""Fold-routed OOS class probabilities.
|
|
372
|
+
|
|
373
|
+
Args:
|
|
374
|
+
X: Input data.
|
|
375
|
+
ids: Explicit ID array.
|
|
376
|
+
|
|
377
|
+
Returns:
|
|
378
|
+
Array of shape ``(n_samples, n_classes)``.
|
|
379
|
+
"""
|
|
380
|
+
check_is_fitted(self)
|
|
381
|
+
return self.oos_classifier_.predict_proba(X, ids=ids)
|
|
382
|
+
|
|
383
|
+
def coverage(
|
|
384
|
+
self, X: Any, y: Any, *, ids: Any | None = None, alpha: float | None = None
|
|
385
|
+
) -> float:
|
|
386
|
+
"""Fraction of rows whose true label is in the prediction set.
|
|
387
|
+
|
|
388
|
+
Args:
|
|
389
|
+
X: Input data.
|
|
390
|
+
y: True labels.
|
|
391
|
+
ids: Explicit ID array.
|
|
392
|
+
alpha: Override miscoverage rate.
|
|
393
|
+
|
|
394
|
+
Returns:
|
|
395
|
+
Empirical coverage in [0, 1].
|
|
396
|
+
"""
|
|
397
|
+
sets = self.predict_set(X, ids=ids, alpha=alpha)
|
|
398
|
+
y_arr = validate_target(y)
|
|
399
|
+
idx = np.searchsorted(self.classes_, y_arr)
|
|
400
|
+
known = (idx < len(self.classes_)) & (
|
|
401
|
+
self.classes_[np.minimum(idx, len(self.classes_) - 1)] == y_arr
|
|
402
|
+
)
|
|
403
|
+
covered = np.zeros(len(y_arr), dtype=bool)
|
|
404
|
+
covered[known] = sets[np.flatnonzero(known), idx[known]]
|
|
405
|
+
return float(covered.mean())
|
|
406
|
+
|
|
407
|
+
def set_size(self, X: Any, *, ids: Any | None = None, alpha: float | None = None) -> np.ndarray:
|
|
408
|
+
"""Number of labels in each row's prediction set.
|
|
409
|
+
|
|
410
|
+
Args:
|
|
411
|
+
X: Input data.
|
|
412
|
+
ids: Explicit ID array.
|
|
413
|
+
alpha: Override miscoverage rate.
|
|
414
|
+
|
|
415
|
+
Returns:
|
|
416
|
+
Integer array of shape ``(n_samples,)``.
|
|
417
|
+
"""
|
|
418
|
+
return self.predict_set(X, ids=ids, alpha=alpha).sum(axis=1)
|