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
|
@@ -0,0 +1,1011 @@
|
|
|
1
|
+
"""Calibrated out-of-sample classifier.
|
|
2
|
+
|
|
3
|
+
Provides ``OOSCalibratedClassifier`` which wraps an ``OOSClassifier`` and
|
|
4
|
+
fits probability calibrators on OOS predictions. Two calibration strategies
|
|
5
|
+
are supported:
|
|
6
|
+
|
|
7
|
+
- **Cross-calibration** (``calibration_cv="cross"``): calibrator i is trained
|
|
8
|
+
on OOS predictions from all folds except fold i. Fast, abundant data per
|
|
9
|
+
calibrator, but assumes all fold models share similar miscalibration.
|
|
10
|
+
|
|
11
|
+
- **CV-calibrate** (``calibration_cv=<int>``): each fold's OOS data is
|
|
12
|
+
further split into sub-folds, and calibrators are fit in a leave-one-out
|
|
13
|
+
fashion within each fold. Each calibrator is trained on its own fold
|
|
14
|
+
model's predictions — model-specific, no cross-model assumption.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
import numpy as np
|
|
22
|
+
from scipy.optimize import minimize_scalar
|
|
23
|
+
from sklearn.base import BaseEstimator, ClassifierMixin, MetaEstimatorMixin
|
|
24
|
+
from sklearn.isotonic import IsotonicRegression
|
|
25
|
+
from sklearn.linear_model import LogisticRegression
|
|
26
|
+
from sklearn.model_selection import KFold
|
|
27
|
+
from sklearn.utils.validation import check_is_fitted
|
|
28
|
+
|
|
29
|
+
from ._estimators import OOSClassifier
|
|
30
|
+
from ._validation import extract_ids_and_features, reset_fitted_state, validate_target
|
|
31
|
+
|
|
32
|
+
_PLATT_ALIASES = frozenset({"sigmoid", "platt"})
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class OOSCalibratedClassifier(ClassifierMixin, MetaEstimatorMixin, BaseEstimator):
|
|
36
|
+
"""Calibrated out-of-sample classifier.
|
|
37
|
+
|
|
38
|
+
Wraps an ``OOSClassifier`` and fits probability calibrators on the
|
|
39
|
+
OOS predictions generated during fit.
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
estimator: A scikit-learn-compatible classifier.
|
|
43
|
+
id_col: Column name or index for unique identifiers.
|
|
44
|
+
cv: Number of folds or a scikit-learn CV splitter for the base OOS model.
|
|
45
|
+
random_state: Seed for fold splitting.
|
|
46
|
+
stratified: Use StratifiedKFold for binary classification.
|
|
47
|
+
verbose: Verbosity level.
|
|
48
|
+
scoring: Metrics to compute on OOS folds.
|
|
49
|
+
calibration_method: Calibration algorithm. One of:
|
|
50
|
+
- ``"beta"`` — Beta calibration via LogisticRegression
|
|
51
|
+
on ``[log(s), log(1-s)]``. 3 parameters.
|
|
52
|
+
- ``"sigmoid"`` or ``"platt"`` (default) — Platt scaling via
|
|
53
|
+
LogisticRegression. 2 parameters.
|
|
54
|
+
- ``"isotonic"`` — Isotonic regression. Non-parametric.
|
|
55
|
+
calibration_cv: Calibration strategy. One of:
|
|
56
|
+
- ``"cross"`` (default) — Cross-calibration: calibrator i trained
|
|
57
|
+
on OOS predictions from all folds except fold i.
|
|
58
|
+
- An integer ``C >= 2`` — CV-calibrate: each OOS fold is split
|
|
59
|
+
into C sub-folds, and C calibrators are fit per fold model in
|
|
60
|
+
a leave-one-sub-fold-out fashion. Higher C means more data per
|
|
61
|
+
calibrator. Each calibrator is model-specific.
|
|
62
|
+
- ``"hybrid"`` — Average of cross-calibrated and CV-calibrated
|
|
63
|
+
probabilities. Blends cross-model and model-specific calibration.
|
|
64
|
+
Use ``hybrid_cv_cal`` to set the number of sub-folds for the
|
|
65
|
+
CV-calibrate component (default 2).
|
|
66
|
+
hybrid_cv_cal: Number of sub-folds for the CV-calibrate component
|
|
67
|
+
when ``calibration_cv="hybrid"``. Default 2. Ignored for other
|
|
68
|
+
calibration_cv values.
|
|
69
|
+
|
|
70
|
+
Attributes:
|
|
71
|
+
oos_classifier_: The fitted inner OOSClassifier.
|
|
72
|
+
calibrators_: Calibrator data (structure depends on calibration_cv).
|
|
73
|
+
general_calibrator_: Calibrator for unseen IDs (general model).
|
|
74
|
+
classes_: Unique class labels.
|
|
75
|
+
n_features_in_: Number of features.
|
|
76
|
+
feature_names_in_: Feature names (only for string column names).
|
|
77
|
+
|
|
78
|
+
Examples:
|
|
79
|
+
Cross-calibration (default):
|
|
80
|
+
|
|
81
|
+
>>> model = OOSCalibratedClassifier(estimator, id_col="id", cv=5)
|
|
82
|
+
>>> model.fit(X, y)
|
|
83
|
+
|
|
84
|
+
CV-calibrate with 5 sub-folds per OOS fold:
|
|
85
|
+
|
|
86
|
+
>>> model = OOSCalibratedClassifier(
|
|
87
|
+
... estimator, id_col="id", cv=5, calibration_cv=5,
|
|
88
|
+
... )
|
|
89
|
+
>>> model.fit(X, y)
|
|
90
|
+
"""
|
|
91
|
+
|
|
92
|
+
def __init__(
|
|
93
|
+
self,
|
|
94
|
+
estimator: Any = None,
|
|
95
|
+
*,
|
|
96
|
+
id_col: str | int | None = "id",
|
|
97
|
+
cv: int | Any = 5,
|
|
98
|
+
random_state: int | None = None,
|
|
99
|
+
stratified: bool = True,
|
|
100
|
+
verbose: int = 0,
|
|
101
|
+
scoring: str | list[str] | dict[str, Any] | None = None,
|
|
102
|
+
calibration_method: str = "platt",
|
|
103
|
+
calibration_cv: str | int = "cross",
|
|
104
|
+
hybrid_cv_cal: int = 2,
|
|
105
|
+
group_col: str | None = None,
|
|
106
|
+
strict: bool = True,
|
|
107
|
+
) -> None:
|
|
108
|
+
"""Initialize the calibrated OOS classifier.
|
|
109
|
+
|
|
110
|
+
Args:
|
|
111
|
+
estimator: Any sklearn-compatible classifier with predict_proba.
|
|
112
|
+
id_col: Column name, index, or None for row indices.
|
|
113
|
+
cv: Number of base OOS folds or an sklearn CV splitter.
|
|
114
|
+
random_state: Seed for all splitting (base folds + calibration sub-folds).
|
|
115
|
+
stratified: Use StratifiedKFold for binary targets.
|
|
116
|
+
verbose: 0 = silent, 1 = progress bar.
|
|
117
|
+
scoring: Metrics to compute. String, list, dict, or None.
|
|
118
|
+
calibration_method: ``"beta"``, ``"sigmoid"``/``"platt"``, or ``"isotonic"``.
|
|
119
|
+
calibration_cv: ``"cross"``, ``"hybrid"``, or an int >= 2.
|
|
120
|
+
hybrid_cv_cal: Sub-fold count for hybrid's CV-calibrate component.
|
|
121
|
+
group_col: Column name for group-aware fold splitting.
|
|
122
|
+
strict: If True (default), conditions that would silently produce
|
|
123
|
+
in-sample predictions or drop requested metrics raise a
|
|
124
|
+
``ValueError``: a CV splitter that never holds some rows out
|
|
125
|
+
or splits duplicate IDs across folds, prediction IDs whose
|
|
126
|
+
type differs from the training IDs, unknown metric names,
|
|
127
|
+
and supervised transformer steps in ``OOSPipeline``. If
|
|
128
|
+
False, these conditions only emit a ``UserWarning``.
|
|
129
|
+
"""
|
|
130
|
+
self.estimator = estimator
|
|
131
|
+
self.id_col = id_col
|
|
132
|
+
self.cv = cv
|
|
133
|
+
self.random_state = random_state
|
|
134
|
+
self.stratified = stratified
|
|
135
|
+
self.verbose = verbose
|
|
136
|
+
self.scoring = scoring
|
|
137
|
+
self.calibration_method = calibration_method
|
|
138
|
+
self.calibration_cv = calibration_cv
|
|
139
|
+
self.hybrid_cv_cal = hybrid_cv_cal
|
|
140
|
+
self.group_col = group_col
|
|
141
|
+
self.strict = strict
|
|
142
|
+
|
|
143
|
+
def __sklearn_is_fitted__(self) -> bool:
|
|
144
|
+
return hasattr(self, "oos_classifier_") and self.oos_classifier_.__sklearn_is_fitted__()
|
|
145
|
+
|
|
146
|
+
@property
|
|
147
|
+
def cv_results_(self) -> dict[str, Any]:
|
|
148
|
+
"""Overall and per-fold metrics from the inner OOS classifier."""
|
|
149
|
+
check_is_fitted(self)
|
|
150
|
+
return self.oos_classifier_.cv_results_
|
|
151
|
+
|
|
152
|
+
@property
|
|
153
|
+
def id_to_fold_(self) -> dict[Any, int]:
|
|
154
|
+
"""ID-to-fold mapping from the inner OOS classifier."""
|
|
155
|
+
check_is_fitted(self)
|
|
156
|
+
return self.oos_classifier_.id_to_fold_
|
|
157
|
+
|
|
158
|
+
@property
|
|
159
|
+
def last_routing_(self) -> dict[str, Any]:
|
|
160
|
+
"""Routing statistics of the most recent prediction call.
|
|
161
|
+
|
|
162
|
+
Delegates to the inner OOS classifier (see ``OOSClassifier.last_routing_``).
|
|
163
|
+
"""
|
|
164
|
+
check_is_fitted(self)
|
|
165
|
+
return self.oos_classifier_.last_routing_
|
|
166
|
+
|
|
167
|
+
def refresh(self, X: Any, y: Any = None, **kwargs: Any) -> None:
|
|
168
|
+
"""Not supported: call ``fit`` on the full updated data instead.
|
|
169
|
+
|
|
170
|
+
Raises:
|
|
171
|
+
NotImplementedError: Always.
|
|
172
|
+
"""
|
|
173
|
+
from ._refresh import refresh_unsupported
|
|
174
|
+
|
|
175
|
+
refresh_unsupported(self)
|
|
176
|
+
|
|
177
|
+
def fit(
|
|
178
|
+
self, X: Any, y: Any, *, ids: Any | None = None, **fit_params: Any
|
|
179
|
+
) -> OOSCalibratedClassifier:
|
|
180
|
+
"""Fit the OOS classifier and calibrate probabilities.
|
|
181
|
+
|
|
182
|
+
Args:
|
|
183
|
+
X: Training data, optionally containing the ID column.
|
|
184
|
+
y: Target values.
|
|
185
|
+
ids: Explicit ID array when X does not contain an ID column.
|
|
186
|
+
**fit_params: Passed to the underlying estimator's ``fit``.
|
|
187
|
+
|
|
188
|
+
Returns:
|
|
189
|
+
self
|
|
190
|
+
"""
|
|
191
|
+
self._validate_params()
|
|
192
|
+
reset_fitted_state(self)
|
|
193
|
+
# 1. Fit inner OOS classifier
|
|
194
|
+
self.oos_classifier_ = OOSClassifier(
|
|
195
|
+
estimator=self.estimator,
|
|
196
|
+
id_col=self.id_col,
|
|
197
|
+
cv=self.cv,
|
|
198
|
+
random_state=self.random_state,
|
|
199
|
+
stratified=self.stratified,
|
|
200
|
+
verbose=self.verbose,
|
|
201
|
+
scoring=self.scoring,
|
|
202
|
+
group_col=self.group_col,
|
|
203
|
+
strict=self.strict,
|
|
204
|
+
)
|
|
205
|
+
self.oos_classifier_.fit(X, y, ids=ids, **fit_params)
|
|
206
|
+
|
|
207
|
+
# Copy sklearn attributes
|
|
208
|
+
self.classes_ = self.oos_classifier_.classes_
|
|
209
|
+
self.n_features_in_ = self.oos_classifier_.n_features_in_
|
|
210
|
+
if hasattr(self.oos_classifier_, "feature_names_in_"):
|
|
211
|
+
self.feature_names_in_ = self.oos_classifier_.feature_names_in_
|
|
212
|
+
|
|
213
|
+
# 2. Get OOS predictions with probabilities
|
|
214
|
+
oos_data = self.oos_classifier_.get_oos_predictions()
|
|
215
|
+
if "probabilities" not in oos_data:
|
|
216
|
+
raise ValueError(
|
|
217
|
+
"The underlying estimator does not support predict_proba. "
|
|
218
|
+
"Calibration requires probability estimates."
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
oos_probs = oos_data["probabilities"]
|
|
222
|
+
oos_fold_indices = oos_data["fold_indices"]
|
|
223
|
+
|
|
224
|
+
# Recover true labels in fold order
|
|
225
|
+
y_arr = validate_target(y)
|
|
226
|
+
all_oos_indices = np.concatenate(self.oos_classifier_.oos_index_)
|
|
227
|
+
oos_y = y_arr[all_oos_indices]
|
|
228
|
+
|
|
229
|
+
n_folds = len(self.oos_classifier_.models_)
|
|
230
|
+
is_binary = len(self.classes_) == 2
|
|
231
|
+
|
|
232
|
+
# 3. Dispatch to calibration strategy
|
|
233
|
+
if isinstance(self.calibration_cv, int):
|
|
234
|
+
self._fit_cv_calibrate(oos_probs, oos_y, oos_fold_indices, n_folds, is_binary)
|
|
235
|
+
elif self.calibration_cv == "cross":
|
|
236
|
+
self._fit_cross_calibrate(oos_probs, oos_y, oos_fold_indices, n_folds, is_binary)
|
|
237
|
+
elif self.calibration_cv == "hybrid":
|
|
238
|
+
self._fit_cross_calibrate(oos_probs, oos_y, oos_fold_indices, n_folds, is_binary)
|
|
239
|
+
self._fit_cv_calibrate(
|
|
240
|
+
oos_probs,
|
|
241
|
+
oos_y,
|
|
242
|
+
oos_fold_indices,
|
|
243
|
+
n_folds,
|
|
244
|
+
is_binary,
|
|
245
|
+
cv_cal=self.hybrid_cv_cal,
|
|
246
|
+
)
|
|
247
|
+
self._calibration_mode_ = "hybrid"
|
|
248
|
+
else:
|
|
249
|
+
raise ValueError(
|
|
250
|
+
f"calibration_cv must be 'cross', 'hybrid', or an int >= 2, "
|
|
251
|
+
f"got {self.calibration_cv!r}"
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
# 4. General model calibrator — trained on raw OOS probs
|
|
255
|
+
# (not fold-calibrated probs, to avoid indirect leakage through fold calibrators)
|
|
256
|
+
self.general_calibrator_ = self._fit_calibrator(oos_probs, oos_y, is_binary)
|
|
257
|
+
|
|
258
|
+
return self
|
|
259
|
+
|
|
260
|
+
def _validate_params(self) -> None:
|
|
261
|
+
"""Validate constructor parameters (at fit time, per sklearn convention)."""
|
|
262
|
+
cal_cv = self.calibration_cv
|
|
263
|
+
is_int = isinstance(cal_cv, int) and not isinstance(cal_cv, bool)
|
|
264
|
+
if not (is_int or cal_cv in ("cross", "hybrid")):
|
|
265
|
+
raise ValueError(
|
|
266
|
+
f"calibration_cv must be 'cross', 'hybrid', or an int >= 2, got {cal_cv!r}"
|
|
267
|
+
)
|
|
268
|
+
if is_int and int(cal_cv) < 2:
|
|
269
|
+
raise ValueError(f"calibration_cv int must be >= 2, got {cal_cv}")
|
|
270
|
+
hyb = self.hybrid_cv_cal
|
|
271
|
+
if isinstance(hyb, bool) or not isinstance(hyb, int) or hyb < 2:
|
|
272
|
+
raise ValueError(f"hybrid_cv_cal must be an int >= 2, got {hyb!r}")
|
|
273
|
+
|
|
274
|
+
# ------------------------------------------------------------------
|
|
275
|
+
# Calibration strategies
|
|
276
|
+
# ------------------------------------------------------------------
|
|
277
|
+
|
|
278
|
+
def _fit_cross_calibrate(
|
|
279
|
+
self,
|
|
280
|
+
oos_probs: np.ndarray,
|
|
281
|
+
oos_y: np.ndarray,
|
|
282
|
+
oos_fold_indices: np.ndarray,
|
|
283
|
+
n_folds: int,
|
|
284
|
+
is_binary: bool,
|
|
285
|
+
) -> None:
|
|
286
|
+
"""Cross-calibration: calibrator i trained on all folds except i.
|
|
287
|
+
|
|
288
|
+
Args:
|
|
289
|
+
oos_probs: OOS probability predictions in fold order.
|
|
290
|
+
oos_y: True labels in fold order.
|
|
291
|
+
oos_fold_indices: Fold index for each OOS prediction.
|
|
292
|
+
n_folds: Number of folds.
|
|
293
|
+
is_binary: Whether this is binary classification.
|
|
294
|
+
"""
|
|
295
|
+
self.calibrators_ = []
|
|
296
|
+
for fold_i in range(n_folds):
|
|
297
|
+
mask = oos_fold_indices != fold_i
|
|
298
|
+
calibrator = self._fit_calibrator(oos_probs[mask], oos_y[mask], is_binary)
|
|
299
|
+
self.calibrators_.append(calibrator)
|
|
300
|
+
self._calibration_mode_ = "cross"
|
|
301
|
+
|
|
302
|
+
def _fit_cv_calibrate(
|
|
303
|
+
self,
|
|
304
|
+
oos_probs: np.ndarray,
|
|
305
|
+
oos_y: np.ndarray,
|
|
306
|
+
oos_fold_indices: np.ndarray,
|
|
307
|
+
n_folds: int,
|
|
308
|
+
is_binary: bool,
|
|
309
|
+
cv_cal: int | None = None,
|
|
310
|
+
) -> None:
|
|
311
|
+
"""CV-calibrate: sub-fold calibration within each OOS fold.
|
|
312
|
+
|
|
313
|
+
For each fold model i, its OOS predictions are split into C sub-folds.
|
|
314
|
+
Calibrator (i, j) is trained on all sub-folds except j and applied
|
|
315
|
+
to sub-fold j. This gives model-specific calibrators with no
|
|
316
|
+
cross-model assumptions.
|
|
317
|
+
|
|
318
|
+
Args:
|
|
319
|
+
oos_probs: OOS probability predictions in fold order.
|
|
320
|
+
oos_y: True labels in fold order.
|
|
321
|
+
oos_fold_indices: Fold index for each OOS prediction.
|
|
322
|
+
n_folds: Number of folds.
|
|
323
|
+
is_binary: Whether this is binary classification.
|
|
324
|
+
cv_cal: Number of sub-folds. If None, uses ``self.calibration_cv``.
|
|
325
|
+
"""
|
|
326
|
+
if cv_cal is None:
|
|
327
|
+
cv_cal = self.calibration_cv if isinstance(self.calibration_cv, int) else None
|
|
328
|
+
if not isinstance(cv_cal, int) or cv_cal < 2:
|
|
329
|
+
raise ValueError(f"calibration_cv must be >= 2, got {cv_cal}")
|
|
330
|
+
|
|
331
|
+
# For each fold, build sub-fold calibrators
|
|
332
|
+
# Store: per fold, a list of (calibrator, sub_fold_mask) pairs
|
|
333
|
+
self._fold_cal_data_: list[list[tuple[Any, np.ndarray]]] = []
|
|
334
|
+
# Map each OOS sample (by its position in the oos arrays) to its sub-fold calibrator
|
|
335
|
+
self._oos_to_cal_: np.ndarray = np.empty(len(oos_probs), dtype=int)
|
|
336
|
+
|
|
337
|
+
rng = np.random.RandomState(self.random_state)
|
|
338
|
+
|
|
339
|
+
for fold_i in range(n_folds):
|
|
340
|
+
fold_mask = oos_fold_indices == fold_i
|
|
341
|
+
fold_indices = np.where(fold_mask)[0]
|
|
342
|
+
n_fold = len(fold_indices)
|
|
343
|
+
|
|
344
|
+
if n_fold < cv_cal:
|
|
345
|
+
# Too few samples for sub-folding: fall back to cross-calibration
|
|
346
|
+
# (other folds' OOS data) so the calibrator never sees the rows
|
|
347
|
+
# it is applied to
|
|
348
|
+
other = oos_fold_indices != fold_i
|
|
349
|
+
cal = self._fit_calibrator(oos_probs[other], oos_y[other], is_binary)
|
|
350
|
+
self._fold_cal_data_.append([(cal, fold_indices)])
|
|
351
|
+
self._oos_to_cal_[fold_indices] = 0
|
|
352
|
+
continue
|
|
353
|
+
|
|
354
|
+
# Split this fold's OOS samples into cv_cal sub-folds
|
|
355
|
+
sub_splitter = KFold(n_splits=cv_cal, shuffle=True, random_state=rng)
|
|
356
|
+
sub_fold_cals: list[tuple[Any, np.ndarray]] = []
|
|
357
|
+
|
|
358
|
+
for sub_j, (sub_train_idx, sub_test_idx) in enumerate(sub_splitter.split(fold_indices)):
|
|
359
|
+
# sub_train_idx/sub_test_idx are indices INTO fold_indices
|
|
360
|
+
cal_train_pos = fold_indices[sub_train_idx]
|
|
361
|
+
cal_test_pos = fold_indices[sub_test_idx]
|
|
362
|
+
|
|
363
|
+
calibrator = self._fit_calibrator(
|
|
364
|
+
oos_probs[cal_train_pos], oos_y[cal_train_pos], is_binary
|
|
365
|
+
)
|
|
366
|
+
sub_fold_cals.append((calibrator, cal_test_pos))
|
|
367
|
+
self._oos_to_cal_[cal_test_pos] = sub_j
|
|
368
|
+
|
|
369
|
+
self._fold_cal_data_.append(sub_fold_cals)
|
|
370
|
+
|
|
371
|
+
self._calibration_mode_ = "cv_calibrate"
|
|
372
|
+
|
|
373
|
+
# Build ID-to-(fold, sub_fold) mapping for predict-time routing
|
|
374
|
+
oos_ids = self.oos_classifier_.get_oos_predictions()["ids"]
|
|
375
|
+
self._id_to_subfold_: dict[Any, tuple[int, int]] = {}
|
|
376
|
+
for fold_i in range(n_folds):
|
|
377
|
+
fold_mask = oos_fold_indices == fold_i
|
|
378
|
+
fold_positions = np.where(fold_mask)[0]
|
|
379
|
+
for pos in fold_positions:
|
|
380
|
+
id_val = oos_ids[pos]
|
|
381
|
+
sub_j = int(self._oos_to_cal_[pos])
|
|
382
|
+
self._id_to_subfold_[id_val] = (fold_i, sub_j)
|
|
383
|
+
|
|
384
|
+
# ------------------------------------------------------------------
|
|
385
|
+
# Predict
|
|
386
|
+
# ------------------------------------------------------------------
|
|
387
|
+
|
|
388
|
+
def predict_proba(self, X: Any, *, ids: Any | None = None) -> np.ndarray:
|
|
389
|
+
"""Predict calibrated class probabilities.
|
|
390
|
+
|
|
391
|
+
Routes each sample to its fold model, gets raw probabilities,
|
|
392
|
+
then applies the appropriate calibrator based on the calibration
|
|
393
|
+
strategy.
|
|
394
|
+
|
|
395
|
+
Args:
|
|
396
|
+
X: Input data.
|
|
397
|
+
ids: Explicit ID array.
|
|
398
|
+
|
|
399
|
+
Returns:
|
|
400
|
+
Calibrated probability estimates of shape ``(n_samples, n_classes)``.
|
|
401
|
+
"""
|
|
402
|
+
check_is_fitted(self)
|
|
403
|
+
raw_probs = self.oos_classifier_.predict_proba(X, ids=ids)
|
|
404
|
+
|
|
405
|
+
_X_features, id_array, _ = extract_ids_and_features(X, self.id_col, ids=ids)
|
|
406
|
+
is_binary = len(self.classes_) == 2
|
|
407
|
+
|
|
408
|
+
if self._calibration_mode_ == "cross":
|
|
409
|
+
calibrated = self._predict_cross(raw_probs, id_array, is_binary)
|
|
410
|
+
elif self._calibration_mode_ == "cv_calibrate":
|
|
411
|
+
calibrated = self._predict_cv_calibrate(raw_probs, id_array, is_binary)
|
|
412
|
+
elif self._calibration_mode_ == "hybrid":
|
|
413
|
+
cross_probs = self._predict_cross(raw_probs, id_array, is_binary)
|
|
414
|
+
cv_probs = self._predict_cv_calibrate(raw_probs, id_array, is_binary)
|
|
415
|
+
calibrated = 0.5 * cross_probs + 0.5 * cv_probs
|
|
416
|
+
else:
|
|
417
|
+
raise ValueError(f"Unknown calibration mode: {self._calibration_mode_!r}")
|
|
418
|
+
|
|
419
|
+
return calibrated
|
|
420
|
+
|
|
421
|
+
def _predict_cross(
|
|
422
|
+
self, raw_probs: np.ndarray, id_array: np.ndarray, is_binary: bool
|
|
423
|
+
) -> np.ndarray:
|
|
424
|
+
"""Apply cross-calibration at predict time.
|
|
425
|
+
|
|
426
|
+
Args:
|
|
427
|
+
raw_probs: Raw probabilities from OOS fold dispatch.
|
|
428
|
+
id_array: Sample IDs.
|
|
429
|
+
is_binary: Whether binary classification.
|
|
430
|
+
|
|
431
|
+
Returns:
|
|
432
|
+
Calibrated probabilities.
|
|
433
|
+
"""
|
|
434
|
+
id_to_fold = self.oos_classifier_.id_to_fold_
|
|
435
|
+
fold_indices = np.array([id_to_fold.get(id_, -1) for id_ in id_array])
|
|
436
|
+
calibrated = np.empty_like(raw_probs)
|
|
437
|
+
|
|
438
|
+
for fold in np.unique(fold_indices):
|
|
439
|
+
mask = fold_indices == fold
|
|
440
|
+
if fold == -1 or fold >= len(self.calibrators_):
|
|
441
|
+
cal = self.general_calibrator_
|
|
442
|
+
else:
|
|
443
|
+
cal = self.calibrators_[fold]
|
|
444
|
+
calibrated[mask] = self._apply_calibrator(cal, raw_probs[mask], is_binary)
|
|
445
|
+
|
|
446
|
+
return calibrated
|
|
447
|
+
|
|
448
|
+
def _predict_cv_calibrate(
|
|
449
|
+
self, raw_probs: np.ndarray, id_array: np.ndarray, is_binary: bool
|
|
450
|
+
) -> np.ndarray:
|
|
451
|
+
"""Apply cv-calibrate at predict time.
|
|
452
|
+
|
|
453
|
+
For known IDs: use the sub-fold calibrator that didn't see this sample.
|
|
454
|
+
For unseen IDs: use the general calibrator.
|
|
455
|
+
|
|
456
|
+
Args:
|
|
457
|
+
raw_probs: Raw probabilities from OOS fold dispatch.
|
|
458
|
+
id_array: Sample IDs.
|
|
459
|
+
is_binary: Whether binary classification.
|
|
460
|
+
|
|
461
|
+
Returns:
|
|
462
|
+
Calibrated probabilities.
|
|
463
|
+
"""
|
|
464
|
+
calibrated = np.empty_like(raw_probs)
|
|
465
|
+
|
|
466
|
+
# Build (fold, subfold) arrays for vectorized routing
|
|
467
|
+
fold_arr = np.full(len(id_array), -1, dtype=int)
|
|
468
|
+
sub_arr = np.full(len(id_array), -1, dtype=int)
|
|
469
|
+
for i, id_val in enumerate(id_array):
|
|
470
|
+
if id_val in self._id_to_subfold_:
|
|
471
|
+
fold_arr[i], sub_arr[i] = self._id_to_subfold_[id_val]
|
|
472
|
+
|
|
473
|
+
# Apply calibrators per (fold, subfold) group
|
|
474
|
+
for fold_i, sub_fold_cals in enumerate(self._fold_cal_data_):
|
|
475
|
+
for sub_j, (cal, _positions) in enumerate(sub_fold_cals):
|
|
476
|
+
mask = (fold_arr == fold_i) & (sub_arr == sub_j)
|
|
477
|
+
if mask.any():
|
|
478
|
+
calibrated[mask] = self._apply_calibrator(cal, raw_probs[mask], is_binary)
|
|
479
|
+
|
|
480
|
+
# Unseen IDs → general calibrator
|
|
481
|
+
unseen_mask = fold_arr == -1
|
|
482
|
+
if unseen_mask.any():
|
|
483
|
+
calibrated[unseen_mask] = self._apply_calibrator(
|
|
484
|
+
self.general_calibrator_, raw_probs[unseen_mask], is_binary
|
|
485
|
+
)
|
|
486
|
+
|
|
487
|
+
return calibrated
|
|
488
|
+
|
|
489
|
+
def predict(self, X: Any, *, ids: Any | None = None) -> np.ndarray:
|
|
490
|
+
"""Predict class labels using calibrated probabilities.
|
|
491
|
+
|
|
492
|
+
Args:
|
|
493
|
+
X: Input data.
|
|
494
|
+
ids: Explicit ID array.
|
|
495
|
+
|
|
496
|
+
Returns:
|
|
497
|
+
Class labels of shape ``(n_samples,)``.
|
|
498
|
+
"""
|
|
499
|
+
probs = self.predict_proba(X, ids=ids)
|
|
500
|
+
return self.classes_[np.argmax(probs, axis=1)]
|
|
501
|
+
|
|
502
|
+
def predict_proba_interval(self, X: Any, *, ids: Any | None = None) -> np.ndarray:
|
|
503
|
+
"""Venn-ABERS probability intervals [p0, p1] for the positive class.
|
|
504
|
+
|
|
505
|
+
Each sample's raw fold-routed probability is calibrated twice —
|
|
506
|
+
with the test point forced to label 0 (p0) and to label 1 (p1) —
|
|
507
|
+
yielding an interval that brackets the calibrated probability
|
|
508
|
+
without any symmetry assumption. The point estimate from
|
|
509
|
+
``predict_proba`` always lies within it.
|
|
510
|
+
|
|
511
|
+
Requires ``calibration_method="venn-abers"`` and
|
|
512
|
+
``calibration_cv="cross"`` (the default).
|
|
513
|
+
|
|
514
|
+
Args:
|
|
515
|
+
X: Input data.
|
|
516
|
+
ids: Explicit ID array.
|
|
517
|
+
|
|
518
|
+
Returns:
|
|
519
|
+
Array of shape ``(n_samples, 2)`` with columns [p0, p1].
|
|
520
|
+
|
|
521
|
+
Raises:
|
|
522
|
+
ValueError: If the calibration method is not venn-abers or the
|
|
523
|
+
calibration strategy is not cross-calibration.
|
|
524
|
+
"""
|
|
525
|
+
check_is_fitted(self)
|
|
526
|
+
if self.calibration_method != "venn-abers":
|
|
527
|
+
raise ValueError(
|
|
528
|
+
"predict_proba_interval requires calibration_method='venn-abers', "
|
|
529
|
+
f"got {self.calibration_method!r}"
|
|
530
|
+
)
|
|
531
|
+
if self._calibration_mode_ != "cross":
|
|
532
|
+
raise ValueError(
|
|
533
|
+
"predict_proba_interval requires calibration_cv='cross', "
|
|
534
|
+
f"got {self.calibration_cv!r}"
|
|
535
|
+
)
|
|
536
|
+
|
|
537
|
+
raw_probs = self.oos_classifier_.predict_proba(X, ids=ids)[:, 1]
|
|
538
|
+
_X_features, id_array, _ = extract_ids_and_features(X, self.id_col, ids=ids)
|
|
539
|
+
|
|
540
|
+
id_to_fold = self.oos_classifier_.id_to_fold_
|
|
541
|
+
fold_indices = np.array([id_to_fold.get(id_, -1) for id_ in id_array])
|
|
542
|
+
lower = np.empty(len(raw_probs))
|
|
543
|
+
upper = np.empty(len(raw_probs))
|
|
544
|
+
for fold in np.unique(fold_indices):
|
|
545
|
+
mask = fold_indices == fold
|
|
546
|
+
if fold == -1 or fold >= len(self.calibrators_):
|
|
547
|
+
cal = self.general_calibrator_
|
|
548
|
+
else:
|
|
549
|
+
cal = self.calibrators_[fold]
|
|
550
|
+
p0, p1 = venn_abers_interval(cal, raw_probs[mask])
|
|
551
|
+
lower[mask] = p0
|
|
552
|
+
upper[mask] = p1
|
|
553
|
+
return np.column_stack([lower, upper])
|
|
554
|
+
|
|
555
|
+
def score(self, X: Any, y: Any, *, ids: Any | None = None, sample_weight: Any = None) -> float:
|
|
556
|
+
"""Return mean accuracy using calibrated predictions.
|
|
557
|
+
|
|
558
|
+
Args:
|
|
559
|
+
X: Input data.
|
|
560
|
+
y: True labels.
|
|
561
|
+
ids: Explicit ID array.
|
|
562
|
+
sample_weight: Sample weights.
|
|
563
|
+
|
|
564
|
+
Returns:
|
|
565
|
+
Accuracy score.
|
|
566
|
+
"""
|
|
567
|
+
from sklearn.metrics import accuracy_score
|
|
568
|
+
|
|
569
|
+
preds = self.predict(X, ids=ids)
|
|
570
|
+
return accuracy_score(y, preds, sample_weight=sample_weight)
|
|
571
|
+
|
|
572
|
+
# ------------------------------------------------------------------
|
|
573
|
+
# Calibrator fitting and application
|
|
574
|
+
# ------------------------------------------------------------------
|
|
575
|
+
|
|
576
|
+
def _fit_calibrator(self, probs: np.ndarray, y: np.ndarray, is_binary: bool) -> Any:
|
|
577
|
+
"""Fit a calibrator on probability estimates.
|
|
578
|
+
|
|
579
|
+
Args:
|
|
580
|
+
probs: Raw probability estimates of shape ``(n, n_classes)``.
|
|
581
|
+
y: True labels.
|
|
582
|
+
is_binary: Whether this is binary classification.
|
|
583
|
+
|
|
584
|
+
Returns:
|
|
585
|
+
Fitted calibrator (tuple for binary, list of tuples for multiclass).
|
|
586
|
+
"""
|
|
587
|
+
method = self.calibration_method
|
|
588
|
+
|
|
589
|
+
if is_binary:
|
|
590
|
+
p = probs[:, 1] if probs.ndim == 2 else probs
|
|
591
|
+
return self._fit_single_calibrator(p, y, method)
|
|
592
|
+
else:
|
|
593
|
+
if method == "venn-abers":
|
|
594
|
+
raise ValueError(
|
|
595
|
+
"calibration_method='venn-abers' supports binary classification only"
|
|
596
|
+
)
|
|
597
|
+
calibrators = []
|
|
598
|
+
for cls_idx in range(probs.shape[1]):
|
|
599
|
+
p = probs[:, cls_idx]
|
|
600
|
+
y_binary = (y == self.classes_[cls_idx]).astype(int)
|
|
601
|
+
calibrators.append(self._fit_single_calibrator(p, y_binary, method))
|
|
602
|
+
return calibrators
|
|
603
|
+
|
|
604
|
+
def _fit_single_calibrator(self, p: np.ndarray, y: np.ndarray, method: str) -> tuple[str, Any]:
|
|
605
|
+
"""Fit a single calibrator on 1D probabilities vs binary labels.
|
|
606
|
+
|
|
607
|
+
Args:
|
|
608
|
+
p: 1D array of predicted probabilities.
|
|
609
|
+
y: 1D array of binary labels.
|
|
610
|
+
method: Calibration method name.
|
|
611
|
+
|
|
612
|
+
Returns:
|
|
613
|
+
Tuple of ``(method_name, fitted_model)``.
|
|
614
|
+
"""
|
|
615
|
+
if method == "auto":
|
|
616
|
+
return self._fit_auto_calibrator(p, y)
|
|
617
|
+
return fit_single_calibrator(p, y, method)
|
|
618
|
+
|
|
619
|
+
def _fit_auto_calibrator(self, p: np.ndarray, y: np.ndarray) -> tuple[str, Any]:
|
|
620
|
+
"""Pick the calibration method with the best cross-validated Brier score.
|
|
621
|
+
|
|
622
|
+
Selection uses a small stratified K-fold CV over the calibration data.
|
|
623
|
+
In-sample selection would nearly always favor isotonic (the most
|
|
624
|
+
flexible method) even when a 1-3 parameter method generalizes better.
|
|
625
|
+
The winning method is refit on all data. Falls back to in-sample
|
|
626
|
+
selection when the data is too small to split.
|
|
627
|
+
|
|
628
|
+
Args:
|
|
629
|
+
p: 1D array of predicted probabilities.
|
|
630
|
+
y: 1D array of binary labels.
|
|
631
|
+
|
|
632
|
+
Returns:
|
|
633
|
+
Tuple of ``(method_name, fitted_model)`` for the best method.
|
|
634
|
+
"""
|
|
635
|
+
from sklearn.metrics import brier_score_loss
|
|
636
|
+
from sklearn.model_selection import StratifiedKFold
|
|
637
|
+
|
|
638
|
+
candidates = ["platt", "beta", "isotonic", "temperature"]
|
|
639
|
+
|
|
640
|
+
n_pos = int(np.sum(y == 1))
|
|
641
|
+
n_neg = len(y) - n_pos
|
|
642
|
+
n_splits = min(3, n_pos, n_neg)
|
|
643
|
+
|
|
644
|
+
best_brier = np.inf
|
|
645
|
+
best_method = None
|
|
646
|
+
|
|
647
|
+
if n_splits >= 2:
|
|
648
|
+
splitter = StratifiedKFold(
|
|
649
|
+
n_splits=n_splits, shuffle=True, random_state=self.random_state
|
|
650
|
+
)
|
|
651
|
+
splits = list(splitter.split(p.reshape(-1, 1), y))
|
|
652
|
+
for candidate in candidates:
|
|
653
|
+
try:
|
|
654
|
+
briers = []
|
|
655
|
+
for train_idx, test_idx in splits:
|
|
656
|
+
cal = self._fit_single_calibrator(p[train_idx], y[train_idx], candidate)
|
|
657
|
+
cal_probs = self._apply_single_calibrator(cal, p[test_idx])
|
|
658
|
+
briers.append(brier_score_loss(y[test_idx], cal_probs))
|
|
659
|
+
brier = float(np.mean(briers))
|
|
660
|
+
except Exception:
|
|
661
|
+
continue
|
|
662
|
+
if brier < best_brier:
|
|
663
|
+
best_brier = brier
|
|
664
|
+
best_method = candidate
|
|
665
|
+
else:
|
|
666
|
+
# Too few samples per class to cross-validate — in-sample fallback
|
|
667
|
+
for candidate in candidates:
|
|
668
|
+
try:
|
|
669
|
+
cal = self._fit_single_calibrator(p, y, candidate)
|
|
670
|
+
brier = brier_score_loss(y, self._apply_single_calibrator(cal, p))
|
|
671
|
+
except Exception:
|
|
672
|
+
continue
|
|
673
|
+
if brier < best_brier:
|
|
674
|
+
best_brier = brier
|
|
675
|
+
best_method = candidate
|
|
676
|
+
|
|
677
|
+
if best_method is None:
|
|
678
|
+
best_method = "platt"
|
|
679
|
+
|
|
680
|
+
if not hasattr(self, "best_calibration_method_"):
|
|
681
|
+
self.best_calibration_method_ = best_method
|
|
682
|
+
|
|
683
|
+
# Refit the winning method on all calibration data
|
|
684
|
+
return self._fit_single_calibrator(p, y, best_method)
|
|
685
|
+
|
|
686
|
+
def _apply_calibrator(self, calibrator: Any, probs: np.ndarray, is_binary: bool) -> np.ndarray:
|
|
687
|
+
"""Apply a fitted calibrator to raw probabilities.
|
|
688
|
+
|
|
689
|
+
Args:
|
|
690
|
+
calibrator: Fitted calibrator from ``_fit_calibrator``.
|
|
691
|
+
probs: Raw probability estimates.
|
|
692
|
+
is_binary: Whether this is binary classification.
|
|
693
|
+
|
|
694
|
+
Returns:
|
|
695
|
+
Calibrated probabilities of shape ``(n, n_classes)``.
|
|
696
|
+
"""
|
|
697
|
+
if is_binary:
|
|
698
|
+
p = probs[:, 1] if probs.ndim == 2 else probs
|
|
699
|
+
cal_p = self._apply_single_calibrator(calibrator, p)
|
|
700
|
+
return np.column_stack([1 - cal_p, cal_p])
|
|
701
|
+
else:
|
|
702
|
+
cal_probs = np.empty_like(probs)
|
|
703
|
+
for cls_idx, cal in enumerate(calibrator):
|
|
704
|
+
cal_probs[:, cls_idx] = self._apply_single_calibrator(cal, probs[:, cls_idx])
|
|
705
|
+
row_sums = cal_probs.sum(axis=1, keepdims=True)
|
|
706
|
+
row_sums = np.maximum(row_sums, 1e-10)
|
|
707
|
+
return cal_probs / row_sums
|
|
708
|
+
|
|
709
|
+
def _apply_single_calibrator(self, calibrator: tuple[str, Any], p: np.ndarray) -> np.ndarray:
|
|
710
|
+
"""Apply a single calibrator to 1D probabilities.
|
|
711
|
+
|
|
712
|
+
Args:
|
|
713
|
+
calibrator: Tuple of ``(method_name, fitted_model)``.
|
|
714
|
+
p: 1D array of probabilities.
|
|
715
|
+
|
|
716
|
+
Returns:
|
|
717
|
+
1D array of calibrated probabilities.
|
|
718
|
+
"""
|
|
719
|
+
return apply_single_calibrator(calibrator, p)
|
|
720
|
+
|
|
721
|
+
|
|
722
|
+
# ----------------------------------------------------------------------
|
|
723
|
+
# Module-level calibrator primitives (shared with e.g. the PU module)
|
|
724
|
+
# ----------------------------------------------------------------------
|
|
725
|
+
|
|
726
|
+
|
|
727
|
+
def fit_single_calibrator(p: np.ndarray, y: np.ndarray, method: str) -> tuple[str, Any]:
|
|
728
|
+
"""Fit a single calibrator on 1D probabilities vs binary labels.
|
|
729
|
+
|
|
730
|
+
Args:
|
|
731
|
+
p: 1D array of predicted probabilities.
|
|
732
|
+
y: 1D array of binary labels.
|
|
733
|
+
method: One of ``"beta"``, ``"sigmoid"``/``"platt"``, ``"isotonic"``,
|
|
734
|
+
or ``"temperature"`` (``"auto"`` is handled at the estimator level).
|
|
735
|
+
|
|
736
|
+
Returns:
|
|
737
|
+
Tuple of ``(method_name, fitted_model)``.
|
|
738
|
+
"""
|
|
739
|
+
if method == "beta":
|
|
740
|
+
p_clipped = np.clip(p, 1e-10, 1 - 1e-10)
|
|
741
|
+
features = np.column_stack([np.log(p_clipped), np.log(1 - p_clipped)])
|
|
742
|
+
cal = LogisticRegression(max_iter=1000, solver="lbfgs")
|
|
743
|
+
cal.fit(features, y)
|
|
744
|
+
return ("beta", cal)
|
|
745
|
+
|
|
746
|
+
if method in _PLATT_ALIASES:
|
|
747
|
+
cal = LogisticRegression(max_iter=1000, solver="lbfgs")
|
|
748
|
+
cal.fit(p.reshape(-1, 1), y)
|
|
749
|
+
return ("platt", cal)
|
|
750
|
+
|
|
751
|
+
if method == "isotonic":
|
|
752
|
+
cal = IsotonicRegression(out_of_bounds="clip", y_min=0, y_max=1)
|
|
753
|
+
cal.fit(p, y)
|
|
754
|
+
return ("isotonic", cal)
|
|
755
|
+
|
|
756
|
+
if method == "temperature":
|
|
757
|
+
p_clipped = np.clip(p, 1e-10, 1 - 1e-10)
|
|
758
|
+
logits = np.log(p_clipped / (1 - p_clipped))
|
|
759
|
+
|
|
760
|
+
def neg_log_likelihood(T):
|
|
761
|
+
scaled = logits / T
|
|
762
|
+
probs = 1 / (1 + np.exp(-scaled))
|
|
763
|
+
probs = np.clip(probs, 1e-10, 1 - 1e-10)
|
|
764
|
+
return -np.mean(y * np.log(probs) + (1 - y) * np.log(1 - probs))
|
|
765
|
+
|
|
766
|
+
result = minimize_scalar(neg_log_likelihood, bounds=(0.01, 10.0), method="bounded")
|
|
767
|
+
return ("temperature", result.x)
|
|
768
|
+
|
|
769
|
+
if method == "venn-abers":
|
|
770
|
+
# The calibrator is the calibration data itself, sorted by score;
|
|
771
|
+
# prediction refits isotonic with the test point forced to 0 and 1
|
|
772
|
+
order = np.argsort(p, kind="stable")
|
|
773
|
+
return (
|
|
774
|
+
"venn-abers",
|
|
775
|
+
(np.asarray(p, dtype=float)[order], np.asarray(y, dtype=float)[order]),
|
|
776
|
+
)
|
|
777
|
+
|
|
778
|
+
raise ValueError(
|
|
779
|
+
f"Unknown calibration_method '{method}'. "
|
|
780
|
+
"Supported: 'auto', 'beta', 'sigmoid', 'platt', 'isotonic', 'temperature', "
|
|
781
|
+
"'venn-abers'."
|
|
782
|
+
)
|
|
783
|
+
|
|
784
|
+
|
|
785
|
+
def apply_single_calibrator(calibrator: tuple[str, Any], p: np.ndarray) -> np.ndarray:
|
|
786
|
+
"""Apply a fitted single calibrator to 1D probabilities.
|
|
787
|
+
|
|
788
|
+
Args:
|
|
789
|
+
calibrator: Tuple of ``(method_name, fitted_model)``.
|
|
790
|
+
p: 1D array of probabilities.
|
|
791
|
+
|
|
792
|
+
Returns:
|
|
793
|
+
1D array of calibrated probabilities.
|
|
794
|
+
"""
|
|
795
|
+
method, cal = calibrator
|
|
796
|
+
|
|
797
|
+
if method == "beta":
|
|
798
|
+
p_clipped = np.clip(p, 1e-10, 1 - 1e-10)
|
|
799
|
+
features = np.column_stack([np.log(p_clipped), np.log(1 - p_clipped)])
|
|
800
|
+
return cal.predict_proba(features)[:, 1]
|
|
801
|
+
|
|
802
|
+
if method == "platt":
|
|
803
|
+
return cal.predict_proba(p.reshape(-1, 1))[:, 1]
|
|
804
|
+
|
|
805
|
+
if method == "isotonic":
|
|
806
|
+
return cal.predict(p)
|
|
807
|
+
|
|
808
|
+
if method == "temperature":
|
|
809
|
+
T = cal # cal is the temperature scalar
|
|
810
|
+
p_clipped = np.clip(p, 1e-10, 1 - 1e-10)
|
|
811
|
+
logits = np.log(p_clipped / (1 - p_clipped))
|
|
812
|
+
scaled = logits / T
|
|
813
|
+
return 1 / (1 + np.exp(-scaled))
|
|
814
|
+
|
|
815
|
+
if method == "venn-abers":
|
|
816
|
+
p0, p1 = venn_abers_interval(calibrator, p)
|
|
817
|
+
# Log-loss-optimal point combination; always within [p0, p1]
|
|
818
|
+
return p1 / np.clip(1 - p0 + p1, 1e-12, None)
|
|
819
|
+
|
|
820
|
+
raise ValueError(f"Unknown calibrator method: {method}")
|
|
821
|
+
|
|
822
|
+
|
|
823
|
+
def venn_abers_interval(
|
|
824
|
+
calibrator: tuple[str, Any], p: np.ndarray
|
|
825
|
+
) -> tuple[np.ndarray, np.ndarray]:
|
|
826
|
+
"""Venn-ABERS probability interval [p0, p1] for each test score.
|
|
827
|
+
|
|
828
|
+
For a test score t, ``p0`` (``p1``) is the value at t of the isotonic
|
|
829
|
+
regression fitted on the calibration pairs plus (t, 0) (plus (t, 1)).
|
|
830
|
+
The pair brackets the calibrated probability without a symmetry
|
|
831
|
+
assumption.
|
|
832
|
+
|
|
833
|
+
Instead of refitting an isotonic regression per test score, the values
|
|
834
|
+
are read off the cumulative sum diagram (CSD) of the calibration data
|
|
835
|
+
(Vovk, Petej & Fedorova, 2015): the isotonic value at the added point
|
|
836
|
+
is the slope of the bridge between the lower convex hull of the CSD
|
|
837
|
+
prefix left of t and the hull of the suffix right of t shifted by the
|
|
838
|
+
added point, ``max_p min_q slope(p, q + (1, label))``. Both hull
|
|
839
|
+
families are built once in O(n); each test score is then answered with
|
|
840
|
+
nested binary-lifting searches over the hulls, vectorized across test
|
|
841
|
+
scores — O(n log n + U log^2 n) overall versus O(U * n log n) for
|
|
842
|
+
refitting. Calibration ties are pooled like ``IsotonicRegression``
|
|
843
|
+
(a test score within its tie tolerance of a calibration score joins
|
|
844
|
+
that score's block), so the result matches the refitting definition
|
|
845
|
+
up to floating-point rounding.
|
|
846
|
+
|
|
847
|
+
Args:
|
|
848
|
+
calibrator: ``("venn-abers", (sorted_scores, sorted_labels))``.
|
|
849
|
+
p: 1D array of raw probabilities to calibrate.
|
|
850
|
+
|
|
851
|
+
Returns:
|
|
852
|
+
Tuple ``(p0, p1)`` of arrays aligned with ``p``.
|
|
853
|
+
"""
|
|
854
|
+
_method, (cal_scores, cal_labels) = calibrator
|
|
855
|
+
cal_scores = np.asarray(cal_scores, dtype=float)
|
|
856
|
+
cal_labels = np.asarray(cal_labels, dtype=float)
|
|
857
|
+
p = np.asarray(p, dtype=float)
|
|
858
|
+
|
|
859
|
+
# Pool calibration ties into blocks exactly like IsotonicRegression's
|
|
860
|
+
# _make_unique: a new block starts once a score is >= eps above the
|
|
861
|
+
# current block's first score
|
|
862
|
+
xs, weights, sums = _pool_ties(cal_scores, cal_labels)
|
|
863
|
+
# Cumulative sum diagram C_0..C_m: (cumulative weight, cumulative label sum)
|
|
864
|
+
cum_w = np.concatenate([[0.0], np.cumsum(weights)])
|
|
865
|
+
cum_y = np.concatenate([[0.0], np.cumsum(sums)])
|
|
866
|
+
prv_jumps = _jump_table(_hull_links(cum_w, cum_y, reverse=False))
|
|
867
|
+
nxt_jumps = _jump_table(_hull_links(cum_w, cum_y, reverse=True))
|
|
868
|
+
|
|
869
|
+
# Position of each test score: CSD prefix C_0..C_left lies left of it,
|
|
870
|
+
# the suffix C_right..C_m right of it (a tie merges with its block)
|
|
871
|
+
pos = np.searchsorted(xs, p, side="left")
|
|
872
|
+
tie_prev = np.zeros(len(p), dtype=bool)
|
|
873
|
+
has_prev = pos > 0
|
|
874
|
+
tie_prev[has_prev] = (p[has_prev] - xs[pos[has_prev] - 1]) < _VA_TIE_EPS
|
|
875
|
+
tie_next = np.zeros(len(p), dtype=bool)
|
|
876
|
+
has_next = pos < len(xs)
|
|
877
|
+
tie_next[has_next] = (xs[pos[has_next]] - p[has_next]) < _VA_TIE_EPS
|
|
878
|
+
left = np.where(tie_prev, pos - 1, pos)
|
|
879
|
+
right = np.where(tie_prev | tie_next, left + 1, left)
|
|
880
|
+
|
|
881
|
+
p0 = _va_bridge_slope(cum_w, cum_y, left, right, 0.0, prv_jumps, nxt_jumps)
|
|
882
|
+
p1 = _va_bridge_slope(cum_w, cum_y, left, right, 1.0, prv_jumps, nxt_jumps)
|
|
883
|
+
# Numerical safety: theory gives p0 <= p1
|
|
884
|
+
return np.minimum(p0, p1), np.maximum(p0, p1)
|
|
885
|
+
|
|
886
|
+
|
|
887
|
+
# IsotonicRegression treats X values closer than this as ties
|
|
888
|
+
_VA_TIE_EPS = float(np.finfo(np.float64).resolution)
|
|
889
|
+
|
|
890
|
+
|
|
891
|
+
def _pool_ties(scores: np.ndarray, labels: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
|
892
|
+
"""Pool sorted scores into tie blocks: (block score, weight, label sum)."""
|
|
893
|
+
n = len(scores)
|
|
894
|
+
if n == 0:
|
|
895
|
+
return np.empty(0), np.empty(0), np.empty(0)
|
|
896
|
+
# Run starts depend on the first score of the current run, so this is a
|
|
897
|
+
# sequential scan; with exact ties only it reduces to np.unique
|
|
898
|
+
starts = [0]
|
|
899
|
+
current = scores[0]
|
|
900
|
+
for j, x in enumerate(scores.tolist()):
|
|
901
|
+
if x - current >= _VA_TIE_EPS:
|
|
902
|
+
starts.append(j)
|
|
903
|
+
current = x
|
|
904
|
+
start_idx = np.asarray(starts, dtype=np.intp)
|
|
905
|
+
weights = np.diff(np.append(start_idx, n)).astype(float)
|
|
906
|
+
return scores[start_idx], weights, np.add.reduceat(labels, start_idx)
|
|
907
|
+
|
|
908
|
+
|
|
909
|
+
def _hull_links(cum_w: np.ndarray, cum_y: np.ndarray, *, reverse: bool) -> np.ndarray:
|
|
910
|
+
"""Lower convex hull links of every CSD prefix (or suffix).
|
|
911
|
+
|
|
912
|
+
Built with one monotone-chain pass. Forward (``reverse=False``), the
|
|
913
|
+
hull of the prefix ending at ``i`` is ``i, link[i], link[link[i]], ...``
|
|
914
|
+
down to 0; reversed, the hull of the suffix starting at ``i`` is
|
|
915
|
+
``i, link[i], ...`` up to the last point. End points link to themselves.
|
|
916
|
+
"""
|
|
917
|
+
n_points = len(cum_w)
|
|
918
|
+
link = np.empty(n_points, dtype=np.intp)
|
|
919
|
+
w, y = cum_w.tolist(), cum_y.tolist()
|
|
920
|
+
stack: list[int] = []
|
|
921
|
+
for i in range(n_points - 1, -1, -1) if reverse else range(n_points):
|
|
922
|
+
while len(stack) >= 2:
|
|
923
|
+
b, c = stack[-1], stack[-2]
|
|
924
|
+
# x order is (lo, b, hi); drop b unless strictly below lo -> hi
|
|
925
|
+
lo, hi = (i, c) if reverse else (c, i)
|
|
926
|
+
if (w[b] - w[lo]) * (y[hi] - y[lo]) - (y[b] - y[lo]) * (w[hi] - w[lo]) <= 0:
|
|
927
|
+
stack.pop()
|
|
928
|
+
else:
|
|
929
|
+
break
|
|
930
|
+
link[i] = stack[-1] if stack else i
|
|
931
|
+
stack.append(i)
|
|
932
|
+
return link
|
|
933
|
+
|
|
934
|
+
|
|
935
|
+
def _jump_table(link: np.ndarray) -> list[np.ndarray]:
|
|
936
|
+
"""Binary-lifting table: ``table[k][i]`` follows ``link`` 2**k times from i."""
|
|
937
|
+
table = [link]
|
|
938
|
+
while (1 << len(table)) < len(link):
|
|
939
|
+
table.append(table[-1][table[-1]])
|
|
940
|
+
return table
|
|
941
|
+
|
|
942
|
+
|
|
943
|
+
def _va_tangent(
|
|
944
|
+
cum_w: np.ndarray,
|
|
945
|
+
cum_y: np.ndarray,
|
|
946
|
+
p: np.ndarray,
|
|
947
|
+
right: np.ndarray,
|
|
948
|
+
label: float,
|
|
949
|
+
nxt_jumps: list[np.ndarray],
|
|
950
|
+
) -> np.ndarray:
|
|
951
|
+
"""Smallest slope from C_p to the suffix hull from ``right`` shifted by (1, label).
|
|
952
|
+
|
|
953
|
+
Along a convex chain the slope from an outside point to the chain's
|
|
954
|
+
vertices first decreases, then increases, so the minimizing vertex is
|
|
955
|
+
found by binary lifting on "the next vertex still lowers the slope".
|
|
956
|
+
"""
|
|
957
|
+
nxt = nxt_jumps[0]
|
|
958
|
+
px, py = cum_w[p], cum_y[p]
|
|
959
|
+
|
|
960
|
+
def slope(q: np.ndarray) -> np.ndarray:
|
|
961
|
+
return (cum_y[q] + label - py) / (cum_w[q] + 1.0 - px)
|
|
962
|
+
|
|
963
|
+
def improves(q: np.ndarray) -> np.ndarray:
|
|
964
|
+
return slope(nxt[q]) < slope(q)
|
|
965
|
+
|
|
966
|
+
q = right.copy()
|
|
967
|
+
move = improves(q)
|
|
968
|
+
for jump in reversed(nxt_jumps):
|
|
969
|
+
candidate = jump[q]
|
|
970
|
+
q = np.where(move & improves(candidate), candidate, q)
|
|
971
|
+
q = np.where(move, nxt[q], q)
|
|
972
|
+
return slope(q)
|
|
973
|
+
|
|
974
|
+
|
|
975
|
+
def _va_bridge_slope(
|
|
976
|
+
cum_w: np.ndarray,
|
|
977
|
+
cum_y: np.ndarray,
|
|
978
|
+
left: np.ndarray,
|
|
979
|
+
right: np.ndarray,
|
|
980
|
+
label: float,
|
|
981
|
+
prv_jumps: list[np.ndarray],
|
|
982
|
+
nxt_jumps: list[np.ndarray],
|
|
983
|
+
) -> np.ndarray:
|
|
984
|
+
"""Isotonic value at an added (t, label): ``max_p min_q slope(C_p, C_q + (1, label))``.
|
|
985
|
+
|
|
986
|
+
``p`` ranges over the prefix hull ending at ``left`` and ``q`` over the
|
|
987
|
+
suffix hull starting at ``right``. The maximizing ``p`` is the left end
|
|
988
|
+
of the bridge between the two hulls: walking the prefix hull leftwards
|
|
989
|
+
from ``left``, it is the first vertex whose incoming hull edge is no
|
|
990
|
+
steeper than its own tangent slope to the suffix hull (all vertices
|
|
991
|
+
further left satisfy this too), found by binary lifting.
|
|
992
|
+
"""
|
|
993
|
+
prv = prv_jumps[0]
|
|
994
|
+
|
|
995
|
+
def bridge_reached(p: np.ndarray, rgt: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
|
996
|
+
tangent = _va_tangent(cum_w, cum_y, p, rgt, label, nxt_jumps)
|
|
997
|
+
prev = prv[p]
|
|
998
|
+
first = prev == p
|
|
999
|
+
run = np.where(first, 1.0, cum_w[p] - cum_w[prev])
|
|
1000
|
+
edge = np.where(first, -np.inf, (cum_y[p] - cum_y[prev]) / run)
|
|
1001
|
+
return edge <= tangent, tangent
|
|
1002
|
+
|
|
1003
|
+
reached, value = bridge_reached(left, right)
|
|
1004
|
+
if not reached.all():
|
|
1005
|
+
idx = np.flatnonzero(~reached)
|
|
1006
|
+
p, rgt = left[idx], right[idx]
|
|
1007
|
+
for jump in reversed(prv_jumps):
|
|
1008
|
+
candidate = jump[p]
|
|
1009
|
+
p = np.where(~bridge_reached(candidate, rgt)[0], candidate, p)
|
|
1010
|
+
value[idx] = _va_tangent(cum_w, cum_y, prv[p], rgt, label, nxt_jumps)
|
|
1011
|
+
return value
|