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/_cqr.py ADDED
@@ -0,0 +1,440 @@
1
+ """Conformalized quantile regression (CQR).
2
+
3
+ Provides ``OOSConformalQuantileRegressor``, which fits out-of-sample
4
+ lower and upper quantile models on shared folds and conformalizes their
5
+ band with cross-conformal scores (Romano, Patterson & Candes, 2019).
6
+ Intervals adapt to local noise through the quantile models while keeping
7
+ the finite-sample marginal coverage guarantee of conformal prediction.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import warnings
13
+ from typing import Any
14
+
15
+ import numpy as np
16
+ import pandas as pd
17
+ from sklearn.base import BaseEstimator, MetaEstimatorMixin, RegressorMixin, clone
18
+ from sklearn.utils.validation import check_is_fitted
19
+
20
+ from ._estimators import OOSRegressor, _OOSBase
21
+ from ._intervals import cross_conformal_quantiles
22
+ from ._validation import extract_ids_and_features, reset_fitted_state, validate_target
23
+
24
+
25
+ def _quantile_params(estimator: Any, quantile: float, quantile_param: str | None) -> dict:
26
+ """Parameters that turn ``estimator`` into a ``quantile`` regressor.
27
+
28
+ Args:
29
+ estimator: A regressor (or an sklearn ``Pipeline`` ending in one).
30
+ quantile: Target quantile level in (0, 1).
31
+ quantile_param: Explicit parameter name to set, or ``None``/``"auto"``
32
+ to detect the estimator family.
33
+
34
+ Returns:
35
+ Keyword arguments for ``set_params``.
36
+
37
+ Raises:
38
+ ValueError: If the estimator family is not recognized.
39
+ """
40
+ if quantile_param not in (None, "auto"):
41
+ return {quantile_param: quantile}
42
+
43
+ prefix = ""
44
+ inner = estimator
45
+ steps = getattr(estimator, "steps", None)
46
+ if isinstance(steps, list) and steps:
47
+ # sklearn Pipeline: configure the final step
48
+ prefix = f"{steps[-1][0]}__"
49
+ inner = steps[-1][1]
50
+
51
+ name = type(inner).__name__
52
+ params: dict[str, Any]
53
+ if name == "GradientBoostingRegressor":
54
+ params = {"loss": "quantile", "alpha": quantile}
55
+ elif name == "HistGradientBoostingRegressor":
56
+ params = {"loss": "quantile", "quantile": quantile}
57
+ elif name == "QuantileRegressor":
58
+ params = {"quantile": quantile}
59
+ elif name == "LGBMRegressor":
60
+ params = {"objective": "quantile", "alpha": quantile}
61
+ elif name == "XGBRegressor":
62
+ params = {"objective": "reg:quantileerror", "quantile_alpha": quantile}
63
+ elif name == "CatBoostRegressor":
64
+ params = {"loss_function": f"Quantile:alpha={quantile}"}
65
+ else:
66
+ raise ValueError(
67
+ f"Cannot configure {name} for quantile regression automatically. Pass "
68
+ "quantile_param (the name of its quantile-level parameter, with the "
69
+ "quantile loss already selected) or explicit lower_estimator and "
70
+ "upper_estimator."
71
+ )
72
+ return {prefix + k: v for k, v in params.items()}
73
+
74
+
75
+ class OOSConformalQuantileRegressor(RegressorMixin, MetaEstimatorMixin, BaseEstimator):
76
+ """Conformalized quantile regression with out-of-sample quantile models.
77
+
78
+ Fits a lower (``alpha/2``) and an upper (``1 - alpha/2``) quantile
79
+ regressor as out-of-sample wrappers on identical folds. The OOS
80
+ nonconformity score of a training row is
81
+ ``E = max(q_lo(x) - y, y - q_hi(x))`` and the interval for a new row is
82
+ ``[q_lo(x) - Q, q_hi(x) + Q]``, where ``Q`` is the conformal quantile of
83
+ the scores. Widths follow the quantile models (wider where the data is
84
+ noisier), and coverage is guaranteed like any split/cross-conformal
85
+ method.
86
+
87
+ Routing follows the package's out-of-sample rule: training IDs use the
88
+ quantile models of the fold that held them out and a ``Q`` computed
89
+ from the other folds' scores (cross-conformal); unseen IDs use the
90
+ general quantile models and ``Q`` from all scores. As elsewhere, ``Q``
91
+ is infinite when a calibration set has fewer than ``1/alpha - 1``
92
+ scores.
93
+
94
+ Args:
95
+ estimator: A quantile-capable regressor, cloned for the lower and
96
+ upper quantile. Recognized automatically:
97
+ ``GradientBoostingRegressor``, ``HistGradientBoostingRegressor``,
98
+ ``QuantileRegressor``, LightGBM ``LGBMRegressor``, XGBoost
99
+ ``XGBRegressor`` and CatBoost ``CatBoostRegressor`` (also as the
100
+ last step of an sklearn ``Pipeline``). Ignored when both
101
+ ``lower_estimator`` and ``upper_estimator`` are given.
102
+ id_col: Column name or index for unique identifiers.
103
+ cv: Number of folds or a scikit-learn CV splitter.
104
+ random_state: Seed for fold splitting.
105
+ verbose: Verbosity level.
106
+ scoring: Metrics computed on the OOS folds of the quantile models.
107
+ alpha: Miscoverage rate. Default 0.1 gives 90% intervals; the
108
+ quantile models target ``alpha/2`` and ``1 - alpha/2``.
109
+ quantile_param: ``"auto"`` (default) detects how to set the quantile
110
+ level from the estimator class. Otherwise the name of the
111
+ parameter to set to the quantile level (the estimator must
112
+ already use a quantile loss).
113
+ lower_estimator: Explicit, already configured lower-quantile
114
+ regressor (overrides ``estimator`` together with
115
+ ``upper_estimator``).
116
+ upper_estimator: Explicit, already configured upper-quantile
117
+ regressor.
118
+ symmetric: If True (default), one score ``max(q_lo - y, y - q_hi)``
119
+ widens or shrinks both ends by the same ``Q``. If False, the two
120
+ one-sided scores are conformalized separately at ``alpha/2``
121
+ each (asymmetric CQR; slightly wider, but each tail is
122
+ controlled on its own).
123
+ group_col: Column for group-aware fold splitting.
124
+ strict: Raise instead of warn when the out-of-sample guarantee would
125
+ be silently broken (see ``OOSRegressor``).
126
+
127
+ Attributes:
128
+ lower_regressor_: Fitted OOS wrapper of the lower quantile model.
129
+ upper_regressor_: Fitted OOS wrapper of the upper quantile model.
130
+ conformal_scores_: OOS nonconformity scores (symmetric mode), or
131
+ ``None``.
132
+ quantiles_: Per-fold conformal margins (symmetric mode).
133
+ general_quantile_: Margin for unseen IDs (symmetric mode).
134
+ n_features_in_: Number of features.
135
+ feature_names_in_: Feature names (DataFrame input only).
136
+
137
+ Note:
138
+ ``predict_interval`` accepts any ``alpha`` at predict time: the
139
+ margin is recomputed from the stored scores, so the coverage
140
+ guarantee holds for that alpha. The quantile models themselves stay
141
+ at the fitted levels, so intervals for an alpha far from the fitted
142
+ one are valid but less efficient (refit for the best widths).
143
+
144
+ Examples:
145
+ >>> from outofsample import OOSConformalQuantileRegressor
146
+ >>> from sklearn.ensemble import HistGradientBoostingRegressor
147
+ >>> model = OOSConformalQuantileRegressor(
148
+ ... HistGradientBoostingRegressor(), id_col="id", cv=5, alpha=0.1
149
+ ... )
150
+ >>> model.fit(X, y)
151
+ >>> intervals = model.predict_interval(X) # (n, 2): [lower, upper]
152
+ """
153
+
154
+ def __init__(
155
+ self,
156
+ estimator: Any = None,
157
+ *,
158
+ id_col: str | int | None = "id",
159
+ cv: int | Any = 5,
160
+ random_state: int | None = None,
161
+ verbose: int = 0,
162
+ scoring: str | list[str] | dict[str, Any] | None = None,
163
+ alpha: float = 0.1,
164
+ quantile_param: str | None = "auto",
165
+ lower_estimator: Any = None,
166
+ upper_estimator: Any = None,
167
+ symmetric: bool = True,
168
+ group_col: str | None = None,
169
+ strict: bool = True,
170
+ ) -> None:
171
+ """Initialize the CQR wrapper. See the class docstring for arguments."""
172
+ self.estimator = estimator
173
+ self.id_col = id_col
174
+ self.cv = cv
175
+ self.random_state = random_state
176
+ self.verbose = verbose
177
+ self.scoring = scoring
178
+ self.alpha = alpha
179
+ self.quantile_param = quantile_param
180
+ self.lower_estimator = lower_estimator
181
+ self.upper_estimator = upper_estimator
182
+ self.symmetric = symmetric
183
+ self.group_col = group_col
184
+ self.strict = strict
185
+
186
+ def __sklearn_is_fitted__(self) -> bool:
187
+ return hasattr(self, "upper_regressor_") and self.upper_regressor_.__sklearn_is_fitted__()
188
+
189
+ @property
190
+ def cv_results_(self) -> dict[str, Any]:
191
+ """Fold metrics of the lower and upper quantile models."""
192
+ check_is_fitted(self)
193
+ return {
194
+ "lower": self.lower_regressor_.cv_results_,
195
+ "upper": self.upper_regressor_.cv_results_,
196
+ }
197
+
198
+ @property
199
+ def id_to_fold_(self) -> dict[Any, int]:
200
+ """ID-to-fold mapping shared by both quantile models."""
201
+ check_is_fitted(self)
202
+ return self.lower_regressor_.id_to_fold_
203
+
204
+ @property
205
+ def last_routing_(self) -> dict[str, Any]:
206
+ """Routing statistics of the most recent prediction call.
207
+
208
+ Both quantile models share folds and route identically, so this
209
+ delegates to the lower one (see ``OOSClassifier.last_routing_``).
210
+ """
211
+ check_is_fitted(self)
212
+ return self.lower_regressor_.last_routing_
213
+
214
+ def _quantile_estimators(self) -> tuple[Any, Any]:
215
+ """Resolve the (unfitted) lower and upper quantile estimators."""
216
+ if self.lower_estimator is not None or self.upper_estimator is not None:
217
+ if self.lower_estimator is None or self.upper_estimator is None:
218
+ raise ValueError("lower_estimator and upper_estimator must be given together")
219
+ return clone(self.lower_estimator), clone(self.upper_estimator)
220
+ if self.estimator is None:
221
+ raise ValueError("estimator is required unless lower/upper estimators are given")
222
+ lo, hi = self.alpha / 2, 1 - self.alpha / 2
223
+ lower = clone(self.estimator).set_params(
224
+ **_quantile_params(self.estimator, lo, self.quantile_param)
225
+ )
226
+ upper = clone(self.estimator).set_params(
227
+ **_quantile_params(self.estimator, hi, self.quantile_param)
228
+ )
229
+ return lower, upper
230
+
231
+ def refresh(self, X: Any, y: Any = None, **kwargs: Any) -> None:
232
+ """Not supported: call ``fit`` on the full updated data instead.
233
+
234
+ Raises:
235
+ NotImplementedError: Always.
236
+ """
237
+ from ._refresh import refresh_unsupported
238
+
239
+ refresh_unsupported(self)
240
+
241
+ def fit(
242
+ self, X: Any, y: Any, *, ids: Any | None = None, **fit_params: Any
243
+ ) -> OOSConformalQuantileRegressor:
244
+ """Fit both quantile models on shared folds and compute the margins.
245
+
246
+ Args:
247
+ X: Training data, optionally containing the ID column.
248
+ y: Target values.
249
+ ids: Explicit ID array when X does not contain an ID column.
250
+ **fit_params: Passed to both quantile models' ``fit``.
251
+
252
+ Returns:
253
+ self
254
+ """
255
+ if isinstance(self.alpha, bool) or not 0 < self.alpha < 1:
256
+ raise ValueError(f"alpha must be in (0, 1), got {self.alpha}")
257
+ reset_fitted_state(self)
258
+ lower_est, upper_est = self._quantile_estimators()
259
+
260
+ # Resolve the folds once so both quantile models share them exactly
261
+ from ._convenience import _FixedSplitter
262
+
263
+ X_features, id_array, _ = extract_ids_and_features(X, self.id_col, ids=ids)
264
+ y_arr = validate_target(y)
265
+ groups = None
266
+ if self.group_col is not None:
267
+ if not (isinstance(X_features, pd.DataFrame) and self.group_col in X_features):
268
+ raise ValueError(f"group_col '{self.group_col}' not found in X.")
269
+ groups = X_features[self.group_col].to_numpy()
270
+ temp = _OOSBase(
271
+ estimator=lower_est,
272
+ cv=self.cv,
273
+ random_state=self.random_state,
274
+ group_col=self.group_col,
275
+ strict=self.strict,
276
+ )
277
+ splitter, split_groups = temp._get_splitter(X_features, y_arr, id_array, groups)
278
+ if split_groups is not None:
279
+ splits = list(splitter.split(X_features, y_arr, groups=split_groups))
280
+ else:
281
+ splits = list(splitter.split(X_features, y_arr))
282
+ fixed_cv = _FixedSplitter(splits)
283
+
284
+ common: dict[str, Any] = {
285
+ "id_col": self.id_col,
286
+ "cv": fixed_cv,
287
+ "random_state": self.random_state,
288
+ "verbose": self.verbose,
289
+ "scoring": self.scoring,
290
+ "group_col": self.group_col,
291
+ "strict": self.strict,
292
+ }
293
+ self.lower_regressor_ = OOSRegressor(estimator=lower_est, **common)
294
+ self.lower_regressor_.fit(X, y, ids=ids, **fit_params)
295
+ self.upper_regressor_ = OOSRegressor(estimator=upper_est, **common)
296
+ self.upper_regressor_.fit(X, y, ids=ids, **fit_params)
297
+
298
+ self.n_features_in_ = self.lower_regressor_.n_features_in_
299
+ if hasattr(self.lower_regressor_, "feature_names_in_"):
300
+ self.feature_names_in_ = self.lower_regressor_.feature_names_in_
301
+
302
+ # OOS scores in fold-concatenated order (identical for both models)
303
+ oos_index = np.concatenate(self.lower_regressor_.oos_index_)
304
+ lo_oos = self.lower_regressor_.get_oos_predictions()
305
+ hi_oos = self.upper_regressor_.get_oos_predictions()
306
+ y_oos = np.asarray(y_arr[oos_index], dtype=float)
307
+ lower_scores = lo_oos["predictions"] - y_oos
308
+ upper_scores = y_oos - hi_oos["predictions"]
309
+ self._score_fold_indices_ = lo_oos["fold_indices"]
310
+ self.lower_scores_ = lower_scores
311
+ self.upper_scores_ = upper_scores
312
+ self.conformal_scores_ = np.maximum(lower_scores, upper_scores) if self.symmetric else None
313
+
314
+ margins = self._fold_margins(self.alpha)
315
+ if self.symmetric:
316
+ self.quantiles_, self.general_quantile_ = margins[0]
317
+ else:
318
+ (self.lower_quantiles_, self.general_lower_quantile_) = margins[0]
319
+ (self.upper_quantiles_, self.general_upper_quantile_) = margins[1]
320
+ finite = all(np.all(np.isfinite(q)) and np.isfinite(g) for q, g in margins)
321
+ if not finite:
322
+ warnings.warn(
323
+ "Some conformal calibration sets have too few scores for a finite "
324
+ f"margin at alpha={self.alpha}; the affected intervals are infinite. "
325
+ "Use a larger alpha or more data.",
326
+ UserWarning,
327
+ stacklevel=2,
328
+ )
329
+ return self
330
+
331
+ def _fold_margins(self, alpha: float) -> list[tuple[np.ndarray, float]]:
332
+ """Per-fold and general margins: one pair (symmetric) or lower/upper pairs."""
333
+ folds = self._score_fold_indices_
334
+ n_folds = len(self.lower_regressor_.models_)
335
+ if self.symmetric:
336
+ assert self.conformal_scores_ is not None
337
+ return [cross_conformal_quantiles(self.conformal_scores_, folds, n_folds, alpha)]
338
+ return [
339
+ cross_conformal_quantiles(self.lower_scores_, folds, n_folds, alpha / 2),
340
+ cross_conformal_quantiles(self.upper_scores_, folds, n_folds, alpha / 2),
341
+ ]
342
+
343
+ def predict_interval(
344
+ self, X: Any, *, ids: Any | None = None, alpha: float | None = None
345
+ ) -> np.ndarray:
346
+ """Predict conformalized quantile intervals.
347
+
348
+ Args:
349
+ X: Input data.
350
+ ids: Explicit ID array.
351
+ alpha: Override miscoverage rate for this call (see the class
352
+ note on efficiency). None uses the fitted alpha.
353
+
354
+ Returns:
355
+ Array of shape ``(n_samples, 2)`` with columns [lower, upper].
356
+ """
357
+ check_is_fitted(self)
358
+ if alpha is not None and (isinstance(alpha, bool) or not 0 < alpha < 1):
359
+ raise ValueError(f"alpha must be in (0, 1), got {alpha}")
360
+ q_lo = self.lower_regressor_.predict(X, ids=ids)
361
+ q_hi = self.upper_regressor_.predict(X, ids=ids)
362
+ _X, id_array, _ = extract_ids_and_features(X, self.id_col, ids=ids)
363
+
364
+ if alpha is None or alpha == self.alpha:
365
+ if self.symmetric:
366
+ margins = [(self.quantiles_, self.general_quantile_)]
367
+ else:
368
+ margins = [
369
+ (self.lower_quantiles_, self.general_lower_quantile_),
370
+ (self.upper_quantiles_, self.general_upper_quantile_),
371
+ ]
372
+ else:
373
+ margins = self._fold_margins(alpha)
374
+
375
+ id_to_fold = self.lower_regressor_.id_to_fold_
376
+ folds = np.array([id_to_fold.get(id_, -1) for id_ in id_array], dtype=int)
377
+
378
+ def _route(per_fold: np.ndarray, general: float) -> np.ndarray:
379
+ table = np.append(np.asarray(per_fold, dtype=float), general)
380
+ return table[folds] # fold -1 indexes the appended general margin
381
+
382
+ m_lo = _route(*margins[0])
383
+ m_hi = m_lo if self.symmetric else _route(*margins[1])
384
+ lower = q_lo - m_lo
385
+ upper = q_hi + m_hi
386
+ # Crossing quantile models with a negative margin can invert the band
387
+ crossed = lower > upper
388
+ if np.any(crossed):
389
+ mid = (lower[crossed] + upper[crossed]) / 2
390
+ lower[crossed] = mid
391
+ upper[crossed] = mid
392
+ return np.column_stack([lower, upper])
393
+
394
+ def predict(self, X: Any, *, ids: Any | None = None) -> np.ndarray:
395
+ """Midpoint of the conformalized interval (CQR has no point model).
396
+
397
+ Args:
398
+ X: Input data.
399
+ ids: Explicit ID array.
400
+
401
+ Returns:
402
+ Array of shape ``(n_samples,)``.
403
+ """
404
+ intervals = self.predict_interval(X, ids=ids)
405
+ with np.errstate(invalid="ignore"):
406
+ return intervals.mean(axis=1)
407
+
408
+ def coverage(
409
+ self, X: Any, y: Any, *, ids: Any | None = None, alpha: float | None = None
410
+ ) -> float:
411
+ """Fraction of samples whose target falls inside its interval.
412
+
413
+ Args:
414
+ X: Input data.
415
+ y: True targets.
416
+ ids: Explicit ID array.
417
+ alpha: Override miscoverage rate.
418
+
419
+ Returns:
420
+ Empirical coverage in [0, 1].
421
+ """
422
+ intervals = self.predict_interval(X, ids=ids, alpha=alpha)
423
+ y_arr = validate_target(y)
424
+ return float(np.mean((y_arr >= intervals[:, 0]) & (y_arr <= intervals[:, 1])))
425
+
426
+ def interval_width(
427
+ self, X: Any, *, ids: Any | None = None, alpha: float | None = None
428
+ ) -> np.ndarray:
429
+ """Width of each prediction interval.
430
+
431
+ Args:
432
+ X: Input data.
433
+ ids: Explicit ID array.
434
+ alpha: Override miscoverage rate.
435
+
436
+ Returns:
437
+ 1-D array of widths.
438
+ """
439
+ intervals = self.predict_interval(X, ids=ids, alpha=alpha)
440
+ return intervals[:, 1] - intervals[:, 0]