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.
@@ -0,0 +1,1147 @@
1
+ """Conformal prediction intervals for regression.
2
+
3
+ Provides ``OOSConformalRegressor`` which wraps an ``OOSRegressor`` and
4
+ computes distribution-free prediction intervals using cross-conformal
5
+ (CV+) nonconformity scores. Guarantees finite-sample marginal coverage.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import warnings
11
+ from typing import Any
12
+
13
+ import numpy as np
14
+ import pandas as pd
15
+ from sklearn.base import BaseEstimator, MetaEstimatorMixin, RegressorMixin
16
+ from sklearn.model_selection import KFold
17
+ from sklearn.utils.validation import check_is_fitted
18
+
19
+ from ._diagnostics import conditional_coverage as _conditional_coverage
20
+ from ._diagnostics import coverage_curve as _coverage_curve
21
+ from ._estimators import OOSRegressor
22
+ from ._validation import extract_ids_and_features, reset_fitted_state, validate_target
23
+
24
+ # Minimum scores per (fold, bin) cell before Mondrian falls back to the
25
+ # corresponding non-Mondrian quantile
26
+ _MIN_MONDRIAN_BIN = 30
27
+
28
+
29
+ def conformal_quantile(scores: np.ndarray, alpha: float) -> float:
30
+ """Conformal quantile of nonconformity scores with finite-sample correction.
31
+
32
+ Shared by every conformal wrapper in the package so the quantile rule
33
+ is defined in one place. Returns the exact conformal order statistic:
34
+ the k-th smallest score with ``k = ceil((n+1)(1-alpha))``, which
35
+ guarantees marginal coverage ``>= 1-alpha``. When ``k > n`` (fewer than
36
+ ``1/alpha - 1`` scores) no finite quantile carries the guarantee and the
37
+ result is ``inf``. NaN scores are ignored.
38
+
39
+ Args:
40
+ scores: Nonconformity scores (may be signed).
41
+ alpha: Miscoverage rate in (0, 1).
42
+
43
+ Returns:
44
+ The k-th smallest score, or ``inf`` when ``k > n``.
45
+ """
46
+ scores = np.asarray(scores, dtype=float)
47
+ scores = scores[~np.isnan(scores)]
48
+ n = len(scores)
49
+ if n == 0:
50
+ return np.inf
51
+ k = int(np.ceil((n + 1) * (1 - alpha)))
52
+ if k > n:
53
+ # Capping at the largest score would silently break the
54
+ # finite-sample coverage guarantee
55
+ return np.inf
56
+ # Exact order statistic; linear interpolation at level k/n would land
57
+ # between the k-th and (k+1)-th scores (valid but wider)
58
+ return float(np.partition(scores, k - 1)[k - 1])
59
+
60
+
61
+ def cross_conformal_quantiles(
62
+ scores: np.ndarray, fold_indices: np.ndarray, n_folds: int, alpha: float
63
+ ) -> tuple[np.ndarray, float]:
64
+ """Cross-conformal quantiles: fold ``i`` uses the scores of all other folds.
65
+
66
+ Args:
67
+ scores: Nonconformity scores, one per OOS row.
68
+ fold_indices: Fold that held out each row.
69
+ n_folds: Number of folds.
70
+ alpha: Miscoverage rate in (0, 1).
71
+
72
+ Returns:
73
+ ``(per_fold, general)``: an array with one quantile per fold (for
74
+ training IDs routed to that fold) and the quantile over all scores
75
+ (for unseen IDs).
76
+ """
77
+ per_fold = np.array(
78
+ [conformal_quantile(scores[fold_indices != i], alpha) for i in range(n_folds)]
79
+ )
80
+ return per_fold, conformal_quantile(scores, alpha)
81
+
82
+
83
+ class OOSConformalRegressor(RegressorMixin, MetaEstimatorMixin, BaseEstimator):
84
+ """Cross-conformal prediction intervals for regression.
85
+
86
+ Wraps an ``OOSRegressor`` and computes distribution-free prediction
87
+ intervals using the OOS residuals as nonconformity scores. Provides
88
+ finite-sample marginal coverage guarantees without assumptions on
89
+ the data distribution or the base estimator.
90
+
91
+ Args:
92
+ estimator: A scikit-learn-compatible regressor.
93
+ id_col: Column name or index for unique identifiers.
94
+ cv: Number of folds or a scikit-learn CV splitter.
95
+ random_state: Seed for fold splitting.
96
+ verbose: Verbosity level.
97
+ scoring: Metrics to compute on OOS folds.
98
+ alpha: Miscoverage rate. Default 0.1 gives 90% prediction intervals.
99
+ conformal_cv: Calibration strategy for residual quantiles:
100
+ - ``"cross"`` (default) — quantile for fold i trained on
101
+ residuals from all folds except i (fully OOS).
102
+ - An integer ``C >= 2`` — sub-fold quantiles within each fold,
103
+ analogous to ``calibration_cv`` in ``OOSCalibratedClassifier``.
104
+
105
+ Attributes:
106
+ oos_regressor_: The fitted inner OOSRegressor.
107
+ quantiles_: Per-fold residual quantiles (for cross mode) or
108
+ per-fold sub-fold quantile data (for cv mode).
109
+ general_quantile_: Quantile for unseen IDs.
110
+ n_features_in_: Number of features.
111
+ feature_names_in_: Feature names (only for string column names).
112
+
113
+ Examples:
114
+ >>> from outofsample import OOSConformalRegressor
115
+ >>> from sklearn.ensemble import GradientBoostingRegressor
116
+ >>> model = OOSConformalRegressor(
117
+ ... GradientBoostingRegressor(n_estimators=100),
118
+ ... id_col="id", cv=5, alpha=0.1,
119
+ ... )
120
+ >>> model.fit(X, y)
121
+ >>> intervals = model.predict_interval(X) # (n, 2): [lower, upper]
122
+ >>> point = model.predict(X)
123
+ """
124
+
125
+ def __init__(
126
+ self,
127
+ estimator: Any = None,
128
+ *,
129
+ id_col: str | int | None = "id",
130
+ cv: int | Any = 5,
131
+ random_state: int | None = None,
132
+ verbose: int = 0,
133
+ scoring: str | list[str] | dict[str, Any] | None = None,
134
+ alpha: float = 0.1,
135
+ conformal_cv: str | int = "cross",
136
+ hybrid_cv_weight: float = 2.0,
137
+ normalize: bool = False,
138
+ normalize_estimator: Any = None,
139
+ symmetric: bool = True,
140
+ group_col: str | None = None,
141
+ interval_method: str = "quantile",
142
+ mondrian: str | None = None,
143
+ mondrian_bins: int = 10,
144
+ strict: bool = True,
145
+ ) -> None:
146
+ """Initialize the conformal regressor.
147
+
148
+ Args:
149
+ estimator: Any sklearn-compatible regressor.
150
+ id_col: Column name, index, or None for row indices.
151
+ cv: Number of OOS folds or sklearn CV splitter.
152
+ random_state: Seed for splitting.
153
+ verbose: 0 = silent, 1 = progress bar.
154
+ scoring: Metrics for OOS folds.
155
+ alpha: Miscoverage rate (0.1 = 90% intervals).
156
+ conformal_cv: ``"cross"``, ``"hybrid"``, or int >= 2 for
157
+ sub-fold quantiles. ``"hybrid"`` pools cross-model
158
+ residuals with model-specific CV residuals, weighting
159
+ CV residuals by ``hybrid_cv_weight``.
160
+ hybrid_cv_weight: Weight given to each CV residual relative
161
+ to each cross residual when ``conformal_cv="hybrid"``.
162
+ Default 2.0 (CV residuals count double). Ignored for
163
+ other modes.
164
+ normalize: If True, train a secondary model to predict residual
165
+ magnitude from features, then normalize nonconformity scores
166
+ by predicted difficulty. Produces adaptive-width intervals
167
+ (wider in noisy regions, tighter in clean regions) while
168
+ preserving the coverage guarantee.
169
+ normalize_estimator: Estimator for the residual predictor when
170
+ ``normalize=True``. Any sklearn regressor. Defaults to
171
+ ``ExtraTreesRegressor(n_estimators=50)`` with max_depth
172
+ scaled by log2(n_samples), clamped to [4, 12].
173
+ symmetric: If True (default), intervals are symmetric around the
174
+ point prediction. If False and ``normalize=True``, trains
175
+ separate upper/lower residual predictors for asymmetric
176
+ intervals that adapt independently above and below the
177
+ prediction. Useful for skewed error distributions.
178
+ interval_method: ``"quantile"`` (default) — fold-routed point
179
+ prediction ± a conformal residual quantile. ``"cv_plus"`` —
180
+ the CV+ construction of Barber et al. (2019): interval
181
+ endpoints are order statistics of ``{yhat_k(i)(x) ± R_i}``
182
+ over all training residuals, using every fold model. CV+
183
+ carries a finite-sample >= 1-2*alpha guarantee (typically
184
+ ~1-alpha in practice), ignores ID routing at predict time
185
+ (every row is treated as new), and is unaffected by
186
+ ``normalize``. True jackknife+ is CV+ with ``cv="loo"``
187
+ (guarded above n=2000 — pass ``cv=n`` to override).
188
+ mondrian: Bin-conditional (Mondrian) conformal. ``None``
189
+ (default) disables. ``"difficulty"`` bins samples by
190
+ predicted residual magnitude (the residual predictor is
191
+ fitted for binning even when ``normalize=False``). A column
192
+ name bins by that feature — categorical/string columns bin
193
+ by category (and are dropped from the features passed to
194
+ the estimator); numeric columns get ``mondrian_bins``
195
+ quantile bins (and stay in the feature matrix). Coverage
196
+ then holds *within each bin*, not just on average.
197
+ Requires ``conformal_cv="cross"`` and
198
+ ``interval_method="quantile"``.
199
+ mondrian_bins: Number of quantile bins for numeric/difficulty
200
+ Mondrian binning. Ignored for categorical columns.
201
+ strict: If True (default), conditions that would silently produce
202
+ in-sample predictions or drop requested metrics raise a
203
+ ``ValueError``: a CV splitter that never holds some rows out
204
+ or splits duplicate IDs across folds, prediction IDs whose
205
+ type differs from the training IDs, unknown metric names,
206
+ and supervised transformer steps in ``OOSPipeline``. If
207
+ False, these conditions only emit a ``UserWarning``.
208
+ """
209
+ self.estimator = estimator
210
+ self.id_col = id_col
211
+ self.cv = cv
212
+ self.random_state = random_state
213
+ self.verbose = verbose
214
+ self.scoring = scoring
215
+ self.alpha = alpha
216
+ self.conformal_cv = conformal_cv
217
+ self.hybrid_cv_weight = hybrid_cv_weight
218
+ self.normalize = normalize
219
+ self.normalize_estimator = normalize_estimator
220
+ self.symmetric = symmetric
221
+ self.group_col = group_col
222
+ self.interval_method = interval_method
223
+ self.mondrian = mondrian
224
+ self.mondrian_bins = mondrian_bins
225
+ self.strict = strict
226
+
227
+ def __sklearn_is_fitted__(self) -> bool:
228
+ return hasattr(self, "oos_regressor_") and self.oos_regressor_.__sklearn_is_fitted__()
229
+
230
+ @property
231
+ def cv_results_(self) -> dict[str, Any]:
232
+ """Overall and per-fold metrics from the inner OOS regressor."""
233
+ check_is_fitted(self)
234
+ return self.oos_regressor_.cv_results_
235
+
236
+ @property
237
+ def id_to_fold_(self) -> dict[Any, int]:
238
+ """ID-to-fold mapping from the inner OOS regressor."""
239
+ check_is_fitted(self)
240
+ return self.oos_regressor_.id_to_fold_
241
+
242
+ @property
243
+ def last_routing_(self) -> dict[str, Any]:
244
+ """Routing statistics of the most recent prediction call.
245
+
246
+ Delegates to the inner OOS regressor (see ``OOSClassifier.last_routing_``).
247
+ """
248
+ check_is_fitted(self)
249
+ return self.oos_regressor_.last_routing_
250
+
251
+ def refresh(self, X: Any, y: Any = None, **kwargs: Any) -> None:
252
+ """Not supported: call ``fit`` on the full updated data instead.
253
+
254
+ Raises:
255
+ NotImplementedError: Always.
256
+ """
257
+ from ._refresh import refresh_unsupported
258
+
259
+ refresh_unsupported(self)
260
+
261
+ def fit(
262
+ self, X: Any, y: Any, *, ids: Any | None = None, **fit_params: Any
263
+ ) -> OOSConformalRegressor:
264
+ """Fit the OOS regressor and compute conformal quantiles.
265
+
266
+ Args:
267
+ X: Training data, optionally containing the ID column.
268
+ y: Target values.
269
+ ids: Explicit ID array when X does not contain an ID column.
270
+ **fit_params: Passed to the underlying estimator's ``fit``.
271
+
272
+ Returns:
273
+ self
274
+ """
275
+ conf_cv = self.conformal_cv
276
+ is_int = isinstance(conf_cv, int) and not isinstance(conf_cv, bool)
277
+ if not (is_int or conf_cv in ("cross", "hybrid")):
278
+ raise ValueError(
279
+ f"conformal_cv must be 'cross', 'hybrid', or an int >= 2, got {conf_cv!r}"
280
+ )
281
+ if is_int and int(conf_cv) < 2:
282
+ raise ValueError(f"conformal_cv int must be >= 2, got {conf_cv}")
283
+ if not 0 < self.alpha < 1:
284
+ raise ValueError(f"alpha must be in (0, 1), got {self.alpha}")
285
+ if self.interval_method not in ("quantile", "cv_plus"):
286
+ raise ValueError(
287
+ f"interval_method must be 'quantile' or 'cv_plus', got {self.interval_method!r}"
288
+ )
289
+ if self.mondrian is not None:
290
+ if self.conformal_cv != "cross":
291
+ raise ValueError("mondrian requires conformal_cv='cross'")
292
+ if self.interval_method == "cv_plus":
293
+ raise ValueError("mondrian cannot be combined with interval_method='cv_plus'")
294
+ reset_fitted_state(self)
295
+ cv_param = self.cv
296
+ if isinstance(cv_param, str) and cv_param == "loo":
297
+ n_rows = len(X)
298
+ if n_rows > 2000:
299
+ raise ValueError(
300
+ f"cv='loo' with n={n_rows} would fit {n_rows} models. "
301
+ "Pass cv=<n> explicitly to override the guard."
302
+ )
303
+ if n_rows > 500:
304
+ warnings.warn(
305
+ f"cv='loo' fits {n_rows} models — this may be slow.",
306
+ UserWarning,
307
+ stacklevel=2,
308
+ )
309
+ cv_param = n_rows
310
+ if self.interval_method == "cv_plus" and self.conformal_cv != "cross":
311
+ warnings.warn(
312
+ "conformal_cv is ignored when interval_method='cv_plus'",
313
+ UserWarning,
314
+ stacklevel=2,
315
+ )
316
+
317
+ # Non-numeric Mondrian columns are used for binning only and are
318
+ # dropped from the features passed to the estimator
319
+ X_inner = self._strip_mondrian_col(X)
320
+
321
+ # 1. Fit inner OOS regressor
322
+ self.oos_regressor_ = OOSRegressor(
323
+ estimator=self.estimator,
324
+ id_col=self.id_col,
325
+ cv=cv_param,
326
+ random_state=self.random_state,
327
+ verbose=self.verbose,
328
+ scoring=self.scoring,
329
+ group_col=self.group_col,
330
+ strict=self.strict,
331
+ )
332
+ self.oos_regressor_.fit(X_inner, y, ids=ids, **fit_params)
333
+
334
+ # Copy sklearn attributes
335
+ self.n_features_in_ = self.oos_regressor_.n_features_in_
336
+ if hasattr(self.oos_regressor_, "feature_names_in_"):
337
+ self.feature_names_in_ = self.oos_regressor_.feature_names_in_
338
+
339
+ # 2. Get OOS predictions and compute residuals
340
+ oos_data = self.oos_regressor_.get_oos_predictions()
341
+ y_arr = validate_target(y)
342
+ all_oos_indices = np.concatenate(self.oos_regressor_.oos_index_)
343
+ y_true_oos = y_arr[all_oos_indices]
344
+ y_pred_oos = oos_data["predictions"]
345
+ fold_indices = oos_data["fold_indices"]
346
+ signed_residuals = y_true_oos - y_pred_oos
347
+ abs_residuals = np.abs(signed_residuals)
348
+ # Raw (un-normalized) residuals, kept for the CV+ construction
349
+ self.raw_abs_residuals_ = abs_residuals.copy()
350
+
351
+ n_folds = len(self.oos_regressor_.models_)
352
+
353
+ # 2b. Optionally normalize residuals by predicted difficulty
354
+ self._asymmetric_ = self.normalize and not self.symmetric
355
+ if self.normalize:
356
+ if self._asymmetric_:
357
+ # Train separate upper (positive residual) and lower (negative) predictors
358
+ upper_residuals = np.maximum(signed_residuals, 0)
359
+ lower_residuals = np.maximum(-signed_residuals, 0)
360
+ self._fit_residual_predictor(
361
+ X_inner,
362
+ upper_residuals,
363
+ all_oos_indices,
364
+ ids,
365
+ attr_name="residual_predictor_upper_",
366
+ )
367
+ self._fit_residual_predictor(
368
+ X_inner,
369
+ lower_residuals,
370
+ all_oos_indices,
371
+ ids,
372
+ attr_name="residual_predictor_lower_",
373
+ )
374
+ # Normalize upper and lower separately
375
+ sigma_upper = np.maximum(
376
+ self.residual_predictor_upper_.predict(X_inner, ids=ids)[all_oos_indices], 1e-6
377
+ )
378
+ sigma_lower = np.maximum(
379
+ self.residual_predictor_lower_.predict(X_inner, ids=ids)[all_oos_indices], 1e-6
380
+ )
381
+ # Normalize: positive residuals by upper sigma, negative by lower sigma
382
+ norm_upper = upper_residuals / sigma_upper
383
+ norm_lower = lower_residuals / sigma_lower
384
+ # Use max of both as the symmetric-ish nonconformity score for quantile computation
385
+ abs_residuals = np.maximum(norm_upper, norm_lower)
386
+ else:
387
+ self._fit_residual_predictor(X_inner, abs_residuals, all_oos_indices, ids)
388
+ sigma = self.residual_predictor_.predict(X_inner, ids=ids)
389
+ sigma_oos = np.maximum(sigma[all_oos_indices], 1e-6)
390
+ abs_residuals = abs_residuals / sigma_oos
391
+
392
+ # Store nonconformity scores so intervals at any alpha can be
393
+ # recomputed at predict time without refitting
394
+ self.conformal_scores_ = abs_residuals
395
+ self._score_fold_indices_ = fold_indices
396
+
397
+ # 3. Compute quantiles based on strategy
398
+ if self.conformal_cv == "cross":
399
+ self._fit_cross_quantiles(abs_residuals, fold_indices, n_folds)
400
+ elif self.conformal_cv == "hybrid":
401
+ self._fit_hybrid_quantiles(abs_residuals, fold_indices, n_folds)
402
+ elif isinstance(self.conformal_cv, int):
403
+ self._fit_cv_quantiles(abs_residuals, fold_indices, n_folds)
404
+ else:
405
+ raise ValueError(f"Invalid conformal_cv: {self.conformal_cv!r}")
406
+
407
+ # 4. General quantile from all residuals (for unseen IDs)
408
+ self.general_quantile_ = self._conformal_quantile(abs_residuals)
409
+
410
+ self._warn_if_unbounded()
411
+
412
+ # 5. Mondrian: per-(fold, bin) quantile tables
413
+ if self.mondrian is not None:
414
+ if self.mondrian == "difficulty" and not hasattr(self, "residual_predictor_"):
415
+ # Fit the residual predictor solely for binning
416
+ self._fit_residual_predictor(X_inner, self.raw_abs_residuals_, all_oos_indices, ids)
417
+ bin_var = self._mondrian_variable(X, ids)
418
+ self._fit_mondrian_bins(bin_var[all_oos_indices], abs_residuals, fold_indices, n_folds)
419
+
420
+ return self
421
+
422
+ def _warn_if_unbounded(self) -> None:
423
+ """Warn when some calibration set is too small for a finite margin."""
424
+ values = [self.general_quantile_]
425
+ if self._conformal_mode_ in ("cross", "hybrid"):
426
+ values.extend(self.quantiles_)
427
+ else:
428
+ values.extend(q for fold in self._fold_quantile_data_ for q, _pos in fold)
429
+ if not np.all(np.isfinite(values)):
430
+ warnings.warn(
431
+ f"Some conformal calibration sets have fewer than 1/alpha - 1 = "
432
+ f"{1 / self.alpha - 1:.0f} residuals; the affected intervals are "
433
+ "infinite (the finite-sample guarantee admits no finite margin). "
434
+ "Use a larger alpha, fewer sub-folds or more data.",
435
+ UserWarning,
436
+ stacklevel=3,
437
+ )
438
+
439
+ def _fit_hybrid_quantiles(
440
+ self, abs_residuals: np.ndarray, fold_indices: np.ndarray, n_folds: int
441
+ ) -> None:
442
+ """Hybrid: pool cross residuals + CV residuals with configurable weighting.
443
+
444
+ For fold i, computes a single quantile from:
445
+ - Cross residuals: absolute residuals from folds != i (weight 1.0 each)
446
+ - CV residuals: absolute residuals from fold i's own sub-fold holdout
447
+ (weight ``hybrid_cv_weight`` each)
448
+
449
+ The weighted pool is built by repeating CV residuals proportionally,
450
+ then computing the quantile from the combined pool.
451
+
452
+ Args:
453
+ abs_residuals: Absolute OOS residuals.
454
+ fold_indices: Fold assignment per residual.
455
+ n_folds: Number of folds.
456
+ """
457
+ w = self.hybrid_cv_weight
458
+ rng = np.random.RandomState(self.random_state)
459
+ # Use 2 sub-folds for the CV component
460
+ cv_cal = 2
461
+
462
+ self.quantiles_ = []
463
+ # CV-train positions per fold/sub-fold, kept for any-alpha recomputation
464
+ self._hybrid_train_pos_: list[list[np.ndarray]] = []
465
+
466
+ for fold_i in range(n_folds):
467
+ fold_mask = fold_indices == fold_i
468
+ fold_positions = np.where(fold_mask)[0]
469
+ cross_mask = fold_indices != fold_i
470
+ cross_residuals = abs_residuals[cross_mask]
471
+
472
+ n_fold = len(fold_positions)
473
+ if n_fold < cv_cal:
474
+ # Not enough for sub-folding; use cross residuals only
475
+ q = self._conformal_quantile(cross_residuals)
476
+ self.quantiles_.append(q)
477
+ self._hybrid_train_pos_.append([])
478
+ continue
479
+
480
+ # Split fold i into sub-folds for CV residuals
481
+ sub_splitter = KFold(n_splits=cv_cal, shuffle=True, random_state=rng)
482
+ fold_quantiles_per_subfold: list[float] = []
483
+ fold_train_pos: list[np.ndarray] = []
484
+
485
+ for sub_train_idx, _sub_test_idx in sub_splitter.split(fold_positions):
486
+ cv_train_pos = fold_positions[sub_train_idx]
487
+ cv_residuals = abs_residuals[cv_train_pos]
488
+ fold_train_pos.append(cv_train_pos)
489
+
490
+ # Build weighted pool: repeat CV residuals to achieve weighting
491
+ # If w=2.0 and we have 100 cross + 50 cv, effective pool is
492
+ # 100 cross + 100 cv (each cv residual counted twice)
493
+ n_cv_repeats = max(1, round(w))
494
+ cv_repeated = np.repeat(cv_residuals, n_cv_repeats)
495
+ pooled = np.concatenate([cross_residuals, cv_repeated])
496
+
497
+ q = self._conformal_quantile(pooled)
498
+ fold_quantiles_per_subfold.append(q)
499
+
500
+ # Average quantiles across sub-folds for this fold
501
+ self.quantiles_.append(float(np.mean(fold_quantiles_per_subfold)))
502
+ self._hybrid_train_pos_.append(fold_train_pos)
503
+
504
+ self._conformal_mode_ = "hybrid"
505
+
506
+ def _fit_cross_quantiles(
507
+ self, abs_residuals: np.ndarray, fold_indices: np.ndarray, n_folds: int
508
+ ) -> None:
509
+ """Cross-conformal: quantile i from residuals of all folds except i.
510
+
511
+ Args:
512
+ abs_residuals: Absolute OOS residuals.
513
+ fold_indices: Fold assignment per residual.
514
+ n_folds: Number of folds.
515
+ """
516
+ self.quantiles_ = []
517
+ for fold_i in range(n_folds):
518
+ mask = fold_indices != fold_i
519
+ q = self._conformal_quantile(abs_residuals[mask])
520
+ self.quantiles_.append(q)
521
+ self._conformal_mode_ = "cross"
522
+
523
+ def _fit_cv_quantiles(
524
+ self, abs_residuals: np.ndarray, fold_indices: np.ndarray, n_folds: int
525
+ ) -> None:
526
+ """CV sub-fold quantiles within each fold.
527
+
528
+ Args:
529
+ abs_residuals: Absolute OOS residuals.
530
+ fold_indices: Fold assignment per residual.
531
+ n_folds: Number of folds.
532
+ """
533
+ cv_cal = self.conformal_cv
534
+ assert isinstance(cv_cal, int) # guaranteed by the fit() dispatch
535
+ rng = np.random.RandomState(self.random_state)
536
+
537
+ self._fold_quantile_data_: list[list[tuple[float, np.ndarray]]] = []
538
+ self._oos_to_subfold_: dict[int, tuple[int, int]] = {}
539
+ # Quantile-source positions per fold/sub-fold, kept for any-alpha
540
+ # recomputation at predict time
541
+ self._subfold_train_pos_: list[list[np.ndarray]] = []
542
+
543
+ for fold_i in range(n_folds):
544
+ fold_mask = fold_indices == fold_i
545
+ fold_positions = np.where(fold_mask)[0]
546
+ n_fold = len(fold_positions)
547
+
548
+ if n_fold < cv_cal:
549
+ # Too few samples for sub-folding — fall back to cross-conformal
550
+ # (quantile from OTHER folds' residuals to stay OOS)
551
+ cross_mask = fold_indices != fold_i
552
+ q = self._conformal_quantile(abs_residuals[cross_mask])
553
+ self._fold_quantile_data_.append([(q, fold_positions)])
554
+ self._subfold_train_pos_.append([np.flatnonzero(cross_mask)])
555
+ for pos in fold_positions:
556
+ self._oos_to_subfold_[pos] = (fold_i, 0)
557
+ continue
558
+
559
+ sub_splitter = KFold(n_splits=cv_cal, shuffle=True, random_state=rng)
560
+ sub_data: list[tuple[float, np.ndarray]] = []
561
+ fold_train_pos: list[np.ndarray] = []
562
+
563
+ for sub_j, (sub_train_idx, sub_test_idx) in enumerate(
564
+ sub_splitter.split(fold_positions)
565
+ ):
566
+ train_pos = fold_positions[sub_train_idx]
567
+ test_pos = fold_positions[sub_test_idx]
568
+ q = self._conformal_quantile(abs_residuals[train_pos])
569
+ sub_data.append((q, test_pos))
570
+ fold_train_pos.append(train_pos)
571
+ for pos in test_pos:
572
+ self._oos_to_subfold_[pos] = (fold_i, sub_j)
573
+
574
+ self._fold_quantile_data_.append(sub_data)
575
+ self._subfold_train_pos_.append(fold_train_pos)
576
+
577
+ # Build ID → (fold, subfold) mapping
578
+ oos_ids = self.oos_regressor_.get_oos_predictions()["ids"]
579
+ self._id_to_subfold_: dict[Any, tuple[int, int]] = {}
580
+ for pos, (fold_i, sub_j) in self._oos_to_subfold_.items():
581
+ self._id_to_subfold_[oos_ids[pos]] = (fold_i, sub_j)
582
+
583
+ self._conformal_mode_ = "cv_calibrate"
584
+
585
+ def _fit_residual_predictor(
586
+ self,
587
+ X: Any,
588
+ abs_residuals: np.ndarray,
589
+ all_oos_indices: np.ndarray,
590
+ ids: Any | None,
591
+ attr_name: str = "residual_predictor_",
592
+ ) -> None:
593
+ """Train an OOS model to predict residual magnitude from features.
594
+
595
+ The residual predictor is itself an OOSRegressor to avoid leakage —
596
+ each fold's difficulty estimate comes from a model that never saw
597
+ that fold's residuals.
598
+
599
+ Args:
600
+ X: Original training features (with ID column).
601
+ abs_residuals: Residual magnitudes (or signed components) in fold order.
602
+ all_oos_indices: Original row indices for each OOS residual.
603
+ ids: Explicit ID array (if used).
604
+ attr_name: Name of the attribute to store the fitted predictor on self.
605
+ """
606
+ # Build target: absolute residuals mapped back to original row order
607
+ X_features, _id_array, _ = extract_ids_and_features(X, self.id_col, ids=ids)
608
+ residual_target = np.zeros(len(X_features))
609
+ residual_target[all_oos_indices] = abs_residuals
610
+
611
+ # Resolve the residual predictor estimator
612
+ if self.normalize_estimator is not None:
613
+ norm_est = self.normalize_estimator
614
+ else:
615
+ from sklearn.ensemble import ExtraTreesRegressor
616
+
617
+ # Scale depth with dataset size: log2(n) clamped to [4, 12]
618
+ n_samples = len(X_features)
619
+ depth = min(max(int(np.log2(max(n_samples, 16))), 4), 12)
620
+ norm_est = ExtraTreesRegressor(
621
+ n_estimators=50, max_depth=depth, random_state=self.random_state
622
+ )
623
+
624
+ # Train OOS residual predictor using the same fold structure: the
625
+ # resolved cv of the point model (cv="loo" is expanded to n there)
626
+ # and the same group column, so groups never straddle folds and the
627
+ # group column is not used as a feature
628
+ predictor = OOSRegressor(
629
+ estimator=norm_est,
630
+ id_col=self.id_col,
631
+ cv=self.oos_regressor_.cv,
632
+ random_state=self.random_state,
633
+ group_col=self.group_col,
634
+ strict=self.strict,
635
+ )
636
+ predictor.fit(X, residual_target, ids=ids)
637
+ setattr(self, attr_name, predictor)
638
+
639
+ def _conformal_quantile(self, residuals: np.ndarray, alpha: float | None = None) -> float:
640
+ """Compute the conformal quantile with finite-sample correction.
641
+
642
+ Returns the exact conformal order statistic: the k-th smallest
643
+ residual with ``k = ceil((n+1)(1-alpha))``, which guarantees
644
+ marginal coverage >= 1-alpha. When ``k > n`` (fewer than
645
+ ``1/alpha - 1`` residuals) no finite quantile carries the guarantee
646
+ and the margin is infinite.
647
+
648
+ Args:
649
+ residuals: Absolute residuals.
650
+ alpha: Miscoverage rate. Defaults to the fitted ``self.alpha``.
651
+
652
+ Returns:
653
+ The k-th smallest residual, or ``inf`` when ``k > n``.
654
+ """
655
+ return conformal_quantile(residuals, self.alpha if alpha is None else alpha)
656
+
657
+ # ------------------------------------------------------------------
658
+ # Mondrian binning
659
+ # ------------------------------------------------------------------
660
+
661
+ def _strip_mondrian_col(self, X: Any) -> Any:
662
+ """Drop a non-numeric Mondrian column from the estimator's features."""
663
+ if (
664
+ self.mondrian is not None
665
+ and self.mondrian != "difficulty"
666
+ and isinstance(X, pd.DataFrame)
667
+ and self.mondrian in X.columns
668
+ and not np.issubdtype(np.asarray(X[self.mondrian]).dtype, np.number)
669
+ ):
670
+ return X.drop(columns=[self.mondrian])
671
+ return X
672
+
673
+ def _mondrian_variable(self, X: Any, ids: Any | None) -> np.ndarray:
674
+ """Binning variable per row of X (difficulty predictions or a column)."""
675
+ if self.mondrian == "difficulty":
676
+ return np.asarray(self.residual_predictor_.predict(X, ids=ids))
677
+ X_features, _, _ = extract_ids_and_features(X, self.id_col, ids=ids)
678
+ if self.mondrian not in X_features.columns:
679
+ raise ValueError(f"mondrian column '{self.mondrian}' not found in X")
680
+ return X_features[self.mondrian].to_numpy()
681
+
682
+ def _assign_bins(self, values: np.ndarray) -> np.ndarray:
683
+ """Map binning-variable values to bin indices (-1 = unknown category)."""
684
+ if self.mondrian_categories_ is not None:
685
+ values = np.asarray(values).astype(str)
686
+ idx = np.searchsorted(self.mondrian_categories_, values)
687
+ idx = np.clip(idx, 0, len(self.mondrian_categories_) - 1)
688
+ known = self.mondrian_categories_[idx] == values
689
+ return np.where(known, idx, -1)
690
+ assert self.mondrian_bin_edges_ is not None # numeric binning
691
+ inner_edges = self.mondrian_bin_edges_[1:-1]
692
+ return np.clip(
693
+ np.digitize(np.asarray(values, dtype=float), inner_edges),
694
+ 0,
695
+ len(self.mondrian_bin_edges_) - 2,
696
+ )
697
+
698
+ def _fit_mondrian_bins(
699
+ self,
700
+ bin_var: np.ndarray,
701
+ scores: np.ndarray,
702
+ fold_indices: np.ndarray,
703
+ n_folds: int,
704
+ ) -> None:
705
+ """Learn bin edges/categories and per-(fold, bin) conformal quantiles.
706
+
707
+ Args:
708
+ bin_var: Binning-variable values in score (fold-concatenated) order.
709
+ scores: Nonconformity scores in the same order.
710
+ fold_indices: Fold assignment per score.
711
+ n_folds: Number of folds.
712
+ """
713
+ is_categorical = bin_var.dtype.kind in ("O", "U", "S") or isinstance(
714
+ bin_var.dtype, pd.CategoricalDtype
715
+ )
716
+ self.mondrian_categories_: np.ndarray | None = None
717
+ self.mondrian_bin_edges_: np.ndarray | None = None
718
+ if is_categorical:
719
+ self.mondrian_categories_ = np.unique(np.asarray(bin_var).astype(str))
720
+ n_bins = len(self.mondrian_categories_)
721
+ else:
722
+ edges = np.quantile(
723
+ np.asarray(bin_var, dtype=float),
724
+ np.linspace(0, 1, self.mondrian_bins + 1),
725
+ )
726
+ self.mondrian_bin_edges_ = np.unique(edges)
727
+ n_bins = len(self.mondrian_bin_edges_) - 1
728
+ self._row_bins_ = self._assign_bins(bin_var)
729
+ self.mondrian_quantiles_, self.mondrian_general_quantiles_ = self._mondrian_tables(
730
+ scores, fold_indices, n_folds, n_bins, self.alpha
731
+ )
732
+
733
+ def _mondrian_tables(
734
+ self,
735
+ scores: np.ndarray,
736
+ fold_indices: np.ndarray,
737
+ n_folds: int,
738
+ n_bins: int,
739
+ alpha: float,
740
+ ) -> tuple[list[np.ndarray], np.ndarray]:
741
+ """Quantile tables at a given alpha.
742
+
743
+ Cells with fewer than ``_MIN_MONDRIAN_BIN`` scores fall back to the
744
+ corresponding non-Mondrian quantile (one warning listing the bins).
745
+ """
746
+ starved: set[int] = set()
747
+ general = np.empty(n_bins)
748
+ for b in range(n_bins):
749
+ in_bin = self._row_bins_ == b
750
+ if in_bin.sum() < _MIN_MONDRIAN_BIN:
751
+ general[b] = self._conformal_quantile(scores, alpha)
752
+ starved.add(b)
753
+ else:
754
+ general[b] = self._conformal_quantile(scores[in_bin], alpha)
755
+ per_fold = []
756
+ for f in range(n_folds):
757
+ row = np.empty(n_bins)
758
+ not_fold = fold_indices != f
759
+ for b in range(n_bins):
760
+ cell = scores[not_fold & (self._row_bins_ == b)]
761
+ if len(cell) < _MIN_MONDRIAN_BIN:
762
+ row[b] = self._conformal_quantile(scores[not_fold], alpha)
763
+ starved.add(b)
764
+ else:
765
+ row[b] = self._conformal_quantile(cell, alpha)
766
+ per_fold.append(row)
767
+ if starved:
768
+ warnings.warn(
769
+ f"Mondrian bins {sorted(starved)} have fewer than "
770
+ f"{_MIN_MONDRIAN_BIN} scores in at least one cell; those "
771
+ "cells fall back to non-Mondrian quantiles.",
772
+ UserWarning,
773
+ stacklevel=3,
774
+ )
775
+ return per_fold, general
776
+
777
+ # ------------------------------------------------------------------
778
+ # Predict
779
+ # ------------------------------------------------------------------
780
+
781
+ def predict(self, X: Any, *, ids: Any | None = None) -> np.ndarray:
782
+ """Predict target values using fold-routed OOS predictions.
783
+
784
+ Args:
785
+ X: Input data.
786
+ ids: Explicit ID array.
787
+
788
+ Returns:
789
+ Point predictions of shape ``(n_samples,)``.
790
+ """
791
+ check_is_fitted(self)
792
+ return self.oos_regressor_.predict(self._strip_mondrian_col(X), ids=ids)
793
+
794
+ def predict_interval(
795
+ self, X: Any, *, ids: Any | None = None, alpha: float | None = None
796
+ ) -> np.ndarray:
797
+ """Predict intervals [lower, upper] with coverage guarantee.
798
+
799
+ Args:
800
+ X: Input data.
801
+ ids: Explicit ID array.
802
+ alpha: Override miscoverage rate for this call. If None, uses
803
+ the fitted alpha. Any value in (0, 1) is supported without
804
+ refitting — quantiles are recomputed from the stored
805
+ nonconformity scores.
806
+
807
+ Returns:
808
+ Array of shape ``(n_samples, 2)`` with columns [lower, upper].
809
+ """
810
+ check_is_fitted(self)
811
+ X_inner = self._strip_mondrian_col(X)
812
+ point_preds = self.oos_regressor_.predict(X_inner, ids=ids)
813
+
814
+ if alpha is not None and not 0 < alpha < 1:
815
+ raise ValueError(f"alpha must be in (0, 1), got {alpha}")
816
+
817
+ if self.interval_method == "cv_plus":
818
+ return self._predict_interval_cv_plus(X, ids, self.alpha if alpha is None else alpha)
819
+
820
+ _X_features, id_array, _ = extract_ids_and_features(X_inner, self.id_col, ids=ids)
821
+
822
+ row_bins = None
823
+ if self.mondrian is not None:
824
+ row_bins = self._assign_bins(self._mondrian_variable(X, ids))
825
+
826
+ if alpha is None or alpha == self.alpha:
827
+ margins = self._get_margins(id_array, row_bins=row_bins)
828
+ else:
829
+ margins = self._margins_for_alpha(id_array, alpha, row_bins=row_bins)
830
+
831
+ # Scale margins by predicted difficulty if normalized
832
+ if self.normalize:
833
+ if self._asymmetric_:
834
+ sigma_upper = np.maximum(
835
+ self.residual_predictor_upper_.predict(X_inner, ids=ids), 1e-6
836
+ )
837
+ sigma_lower = np.maximum(
838
+ self.residual_predictor_lower_.predict(X_inner, ids=ids), 1e-6
839
+ )
840
+ return np.column_stack(
841
+ [
842
+ point_preds - margins * sigma_lower,
843
+ point_preds + margins * sigma_upper,
844
+ ]
845
+ )
846
+ else:
847
+ sigma = np.maximum(self.residual_predictor_.predict(X_inner, ids=ids), 1e-6)
848
+ margins = margins * sigma
849
+
850
+ return np.column_stack([point_preds - margins, point_preds + margins])
851
+
852
+ def _get_margins(self, id_array: np.ndarray, row_bins: np.ndarray | None = None) -> np.ndarray:
853
+ """Get the interval half-width for each sample.
854
+
855
+ When ``normalize=True``, these are the *normalized* quantiles
856
+ (before scaling by difficulty). The caller multiplies by sigma.
857
+
858
+ Args:
859
+ id_array: Sample IDs.
860
+ row_bins: Mondrian bin per sample (-1 = unknown category), or
861
+ None when Mondrian is not fitted.
862
+
863
+ Returns:
864
+ 1-D array of margin values.
865
+ """
866
+ if row_bins is not None:
867
+ return self._mondrian_margins(
868
+ id_array,
869
+ row_bins,
870
+ self.mondrian_quantiles_,
871
+ self.mondrian_general_quantiles_,
872
+ self.general_quantile_,
873
+ )
874
+ if self._conformal_mode_ in ("cross", "hybrid"):
875
+ id_to_fold = self.oos_regressor_.id_to_fold_
876
+ margins = np.array(
877
+ [
878
+ self.quantiles_[id_to_fold[id_]]
879
+ if id_ in id_to_fold
880
+ else self.general_quantile_
881
+ for id_ in id_array
882
+ ]
883
+ )
884
+ elif self._conformal_mode_ == "cv_calibrate":
885
+ margins = np.full(len(id_array), self.general_quantile_)
886
+ for i, id_val in enumerate(id_array):
887
+ if id_val in self._id_to_subfold_:
888
+ fold_i, sub_j = self._id_to_subfold_[id_val]
889
+ q, _ = self._fold_quantile_data_[fold_i][sub_j]
890
+ margins[i] = q
891
+ else:
892
+ margins = np.full(len(id_array), self.general_quantile_)
893
+
894
+ return margins
895
+
896
+ def _mondrian_margins(
897
+ self,
898
+ id_array: np.ndarray,
899
+ row_bins: np.ndarray,
900
+ quantile_table: list[np.ndarray],
901
+ general_table: np.ndarray,
902
+ global_q: float,
903
+ ) -> np.ndarray:
904
+ """Route each sample to its (fold, bin) Mondrian quantile.
905
+
906
+ Unknown categories (bin -1) use the global quantile; unseen IDs use
907
+ the per-bin general quantile.
908
+ """
909
+ id_to_fold = self.oos_regressor_.id_to_fold_
910
+ margins = np.empty(len(id_array))
911
+ for i, (id_, b) in enumerate(zip(id_array, row_bins, strict=True)):
912
+ if b < 0:
913
+ margins[i] = global_q
914
+ elif id_ in id_to_fold:
915
+ margins[i] = quantile_table[id_to_fold[id_]][b]
916
+ else:
917
+ margins[i] = general_table[b]
918
+ return margins
919
+
920
+ def _margins_for_alpha(
921
+ self, id_array: np.ndarray, alpha: float, row_bins: np.ndarray | None = None
922
+ ) -> np.ndarray:
923
+ """Recompute per-sample margins for an arbitrary alpha.
924
+
925
+ Uses the nonconformity scores stored at fit time and the exact same
926
+ fold/sub-fold (and Mondrian bin) routing as the fitted alpha, so any
927
+ miscoverage rate is available at predict time without refitting.
928
+
929
+ Args:
930
+ id_array: Sample IDs.
931
+ alpha: Miscoverage rate in (0, 1).
932
+ row_bins: Mondrian bin per sample, or None when Mondrian is not
933
+ fitted.
934
+
935
+ Returns:
936
+ 1-D array of margin values.
937
+ """
938
+ scores = self.conformal_scores_
939
+ fold_indices = self._score_fold_indices_
940
+ n_folds = len(self.oos_regressor_.models_)
941
+ general_q = self._conformal_quantile(scores, alpha)
942
+
943
+ if row_bins is not None:
944
+ n_bins = len(self.mondrian_general_quantiles_)
945
+ with warnings.catch_warnings():
946
+ # The starved-cell warning already fired at fit time
947
+ warnings.simplefilter("ignore", UserWarning)
948
+ table, general_table = self._mondrian_tables(
949
+ scores, fold_indices, n_folds, n_bins, alpha
950
+ )
951
+ return self._mondrian_margins(id_array, row_bins, table, general_table, general_q)
952
+
953
+ if self._conformal_mode_ == "cross":
954
+ quantiles = [
955
+ self._conformal_quantile(scores[fold_indices != i], alpha) for i in range(n_folds)
956
+ ]
957
+ elif self._conformal_mode_ == "hybrid":
958
+ n_cv_repeats = max(1, round(self.hybrid_cv_weight))
959
+ quantiles = []
960
+ for fold_i in range(n_folds):
961
+ cross_scores = scores[fold_indices != fold_i]
962
+ train_pos_list = self._hybrid_train_pos_[fold_i]
963
+ if not train_pos_list:
964
+ # This fold fell back to cross-only at fit time
965
+ quantiles.append(self._conformal_quantile(cross_scores, alpha))
966
+ continue
967
+ sub_qs = [
968
+ self._conformal_quantile(
969
+ np.concatenate([cross_scores, np.repeat(scores[train_pos], n_cv_repeats)]),
970
+ alpha,
971
+ )
972
+ for train_pos in train_pos_list
973
+ ]
974
+ quantiles.append(float(np.mean(sub_qs)))
975
+ else:
976
+ # cv_calibrate mode: quantile per (fold, sub-fold)
977
+ margins = np.full(len(id_array), general_q)
978
+ quantile_cache: dict[tuple[int, int], float] = {}
979
+ for i, id_val in enumerate(id_array):
980
+ if id_val in self._id_to_subfold_:
981
+ key = self._id_to_subfold_[id_val]
982
+ if key not in quantile_cache:
983
+ fold_i, sub_j = key
984
+ train_pos = self._subfold_train_pos_[fold_i][sub_j]
985
+ quantile_cache[key] = self._conformal_quantile(scores[train_pos], alpha)
986
+ margins[i] = quantile_cache[key]
987
+ return margins
988
+
989
+ id_to_fold = self.oos_regressor_.id_to_fold_
990
+ return np.array(
991
+ [quantiles[id_to_fold[id_]] if id_ in id_to_fold else general_q for id_ in id_array]
992
+ )
993
+
994
+ def _predict_interval_cv_plus(self, X: Any, ids: Any | None, alpha: float) -> np.ndarray:
995
+ """CV+ intervals (Barber et al. 2019).
996
+
997
+ Endpoints are order statistics of ``{yhat_k(i)(x) - R_i}`` and
998
+ ``{yhat_k(i)(x) + R_i}`` over all training residuals, where k(i) is
999
+ the fold that held row i out and R_i its raw absolute OOS residual.
1000
+ Every prediction row is treated as new (no ID routing).
1001
+
1002
+ Args:
1003
+ X: Input data.
1004
+ ids: Explicit ID array (used only for feature extraction).
1005
+ alpha: Miscoverage rate in (0, 1).
1006
+
1007
+ Returns:
1008
+ Array of shape ``(n_samples, 2)`` with columns [lower, upper].
1009
+ """
1010
+ X_features, _ = self.oos_regressor_._extract_predict_features(X, ids)
1011
+ fold_preds = np.column_stack(
1012
+ [m.predict(X_features) for m in self.oos_regressor_.models_]
1013
+ ) # (m, K)
1014
+ scores = self.raw_abs_residuals_
1015
+ k_i = self._score_fold_indices_
1016
+ n = len(scores)
1017
+ # 1-based order statistics; out of range means too few residuals
1018
+ # for this alpha, and the guarantee requires an unbounded endpoint
1019
+ lo_k = int(np.floor(alpha * (n + 1)))
1020
+ hi_k = int(np.ceil((1 - alpha) * (n + 1)))
1021
+ lo_idx = min(max(lo_k - 1, 0), n - 1)
1022
+ hi_idx = min(max(hi_k - 1, 0), n - 1)
1023
+
1024
+ m = fold_preds.shape[0]
1025
+ # Chunk rows so the (rows x n) work matrices stay bounded in memory
1026
+ # (~80 MB each)
1027
+ chunk = max(1, int(1e7 // max(n, 1)))
1028
+ lower = np.empty(m)
1029
+ upper = np.empty(m)
1030
+ for start in range(0, m, chunk):
1031
+ stop = min(start + chunk, m)
1032
+ yhat = fold_preds[start:stop][:, k_i] # (chunk, n)
1033
+ # Only one order statistic per row is needed: an in-place
1034
+ # partition selects it exactly in O(n) instead of a full sort
1035
+ work = yhat - scores[None, :]
1036
+ work.partition(lo_idx, axis=1)
1037
+ lower[start:stop] = work[:, lo_idx]
1038
+ np.add(yhat, scores[None, :], out=work)
1039
+ work.partition(hi_idx, axis=1)
1040
+ upper[start:stop] = work[:, hi_idx]
1041
+ if lo_k < 1:
1042
+ lower[:] = -np.inf
1043
+ if hi_k > n:
1044
+ upper[:] = np.inf
1045
+ return np.column_stack([lower, upper])
1046
+
1047
+ def score(self, X: Any, y: Any, *, ids: Any | None = None, sample_weight: Any = None) -> float:
1048
+ """Return R^2 score using point predictions.
1049
+
1050
+ Args:
1051
+ X: Input data.
1052
+ y: True targets.
1053
+ ids: Explicit ID array.
1054
+ sample_weight: Sample weights.
1055
+
1056
+ Returns:
1057
+ R^2 score.
1058
+ """
1059
+ from sklearn.metrics import r2_score
1060
+
1061
+ preds = self.predict(X, ids=ids)
1062
+ return r2_score(y, preds, sample_weight=sample_weight)
1063
+
1064
+ def coverage(
1065
+ self, X: Any, y: Any, *, ids: Any | None = None, alpha: float | None = None
1066
+ ) -> float:
1067
+ """Compute empirical coverage on given data.
1068
+
1069
+ Args:
1070
+ X: Input data.
1071
+ y: True targets.
1072
+ ids: Explicit ID array.
1073
+ alpha: Override miscoverage rate. None uses the fitted alpha.
1074
+
1075
+ Returns:
1076
+ Fraction of samples where y falls within the predicted interval.
1077
+ """
1078
+ check_is_fitted(self)
1079
+ intervals = self.predict_interval(X, ids=ids, alpha=alpha)
1080
+ y_arr = validate_target(y)
1081
+ in_interval = (y_arr >= intervals[:, 0]) & (y_arr <= intervals[:, 1])
1082
+ return float(np.mean(in_interval))
1083
+
1084
+ def interval_width(
1085
+ self, X: Any, *, ids: Any | None = None, alpha: float | None = None
1086
+ ) -> np.ndarray:
1087
+ """Return the width of each prediction interval.
1088
+
1089
+ Args:
1090
+ X: Input data.
1091
+ ids: Explicit ID array.
1092
+ alpha: Override miscoverage rate. None uses the fitted alpha.
1093
+
1094
+ Returns:
1095
+ 1-D array of interval widths.
1096
+ """
1097
+ check_is_fitted(self)
1098
+ intervals = self.predict_interval(X, ids=ids, alpha=alpha)
1099
+ return intervals[:, 1] - intervals[:, 0]
1100
+
1101
+ def coverage_curve(
1102
+ self, X: Any, y: Any, *, ids: Any | None = None, alphas: Any | None = None
1103
+ ) -> pd.DataFrame:
1104
+ """Empirical coverage and mean width across a grid of alphas.
1105
+
1106
+ See :func:`outofsample._diagnostics.coverage_curve`.
1107
+
1108
+ Args:
1109
+ X: Input data.
1110
+ y: True targets.
1111
+ ids: Explicit ID array.
1112
+ alphas: Iterable of miscoverage rates (default six-point grid).
1113
+
1114
+ Returns:
1115
+ DataFrame with one row per alpha.
1116
+ """
1117
+ check_is_fitted(self)
1118
+ return _coverage_curve(self, X, y, ids=ids, alphas=alphas)
1119
+
1120
+ def conditional_coverage(
1121
+ self,
1122
+ X: Any,
1123
+ y: Any,
1124
+ *,
1125
+ ids: Any | None = None,
1126
+ by: str | None = None,
1127
+ bins: int = 10,
1128
+ alpha: float | None = None,
1129
+ ) -> pd.DataFrame:
1130
+ """Coverage and mean width per bin of a conditioning variable.
1131
+
1132
+ See :func:`outofsample._diagnostics.conditional_coverage`.
1133
+
1134
+ Args:
1135
+ X: Input data.
1136
+ y: True targets.
1137
+ ids: Explicit ID array.
1138
+ by: ``None`` (Mondrian variable when fitted, else prediction),
1139
+ ``"prediction"``, ``"difficulty"``, or a column name.
1140
+ bins: Quantile bins for numeric conditioning variables.
1141
+ alpha: Override miscoverage rate. None uses the fitted alpha.
1142
+
1143
+ Returns:
1144
+ DataFrame with one row per bin.
1145
+ """
1146
+ check_is_fitted(self)
1147
+ return _conditional_coverage(self, X, y, ids=ids, by=by, bins=bins, alpha=alpha)