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,786 @@
|
|
|
1
|
+
"""Convenience functions for out-of-sample workflows.
|
|
2
|
+
|
|
3
|
+
Provides ``predict_oos`` for one-shot OOS predictions and ``oos_pipeline``
|
|
4
|
+
for chaining OOS transformers with an OOS estimator while sharing fold
|
|
5
|
+
configuration.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import inspect
|
|
11
|
+
import warnings
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
import pandas as pd
|
|
16
|
+
from sklearn.base import clone
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def predict_oos(
|
|
20
|
+
estimator: Any,
|
|
21
|
+
X: Any,
|
|
22
|
+
y: Any,
|
|
23
|
+
*,
|
|
24
|
+
id_col: str | int | None = "id",
|
|
25
|
+
ids: Any | None = None,
|
|
26
|
+
cv: int | Any = 5,
|
|
27
|
+
random_state: int | None = None,
|
|
28
|
+
stratified: bool = True,
|
|
29
|
+
scoring: str | list[str] | dict[str, Any] | None = None,
|
|
30
|
+
verbose: int = 0,
|
|
31
|
+
group_col: str | None = None,
|
|
32
|
+
strict: bool = True,
|
|
33
|
+
) -> dict[str, Any]:
|
|
34
|
+
"""Fit and return out-of-sample predictions in one call.
|
|
35
|
+
|
|
36
|
+
Constructs a temporary OOS wrapper, fits it, extracts results in
|
|
37
|
+
original row order, and discards the model. Use this when you only
|
|
38
|
+
need the OOS predictions and don't need the fitted model.
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
estimator: Any scikit-learn-compatible estimator.
|
|
42
|
+
X: Training data, optionally containing the ID column.
|
|
43
|
+
y: Target values.
|
|
44
|
+
id_col: Column name or index for unique identifiers, or None.
|
|
45
|
+
ids: Explicit ID array when X does not contain an ID column.
|
|
46
|
+
cv: Number of folds or a scikit-learn CV splitter.
|
|
47
|
+
random_state: Seed for fold splitting.
|
|
48
|
+
stratified: Use StratifiedKFold for binary classification.
|
|
49
|
+
scoring: Metrics to compute. Same format as ``OOSClassifier.scoring``.
|
|
50
|
+
verbose: Verbosity level. 0 = silent, 1 = progress bar.
|
|
51
|
+
group_col: Column name for group-aware fold splitting.
|
|
52
|
+
strict: Raise instead of warn when the CV splitter breaks the
|
|
53
|
+
out-of-sample guarantee or a metric name is unknown.
|
|
54
|
+
|
|
55
|
+
Returns:
|
|
56
|
+
Dict with the following keys, all in **original row order**
|
|
57
|
+
(``result[i]`` corresponds to ``X[i]``) as long as the splitter holds
|
|
58
|
+
every row out exactly once (always true for integer ``cv``; a custom
|
|
59
|
+
splitter such as ``TimeSeriesSplit`` that never holds some rows out
|
|
60
|
+
yields only the held-out rows, sorted by row position — use
|
|
61
|
+
``"ids"`` to align them):
|
|
62
|
+
|
|
63
|
+
- ``"predictions"`` — OOS predictions (ndarray)
|
|
64
|
+
- ``"probabilities"`` — OOS probabilities, classifiers only (ndarray or None)
|
|
65
|
+
- ``"ids"`` — sample IDs (ndarray)
|
|
66
|
+
- ``"fold_indices"`` — which fold model made each prediction (ndarray)
|
|
67
|
+
- ``"cv_results"`` — overall and per-fold metrics (dict)
|
|
68
|
+
|
|
69
|
+
Examples:
|
|
70
|
+
>>> from outofsample import predict_oos
|
|
71
|
+
>>> from sklearn.ensemble import RandomForestClassifier
|
|
72
|
+
>>> result = predict_oos(RandomForestClassifier(), X, y, id_col="id", cv=5)
|
|
73
|
+
>>> result["predictions"] # OOS predictions in original row order
|
|
74
|
+
"""
|
|
75
|
+
from ._estimators import OOSModel
|
|
76
|
+
|
|
77
|
+
wrapper = OOSModel(
|
|
78
|
+
estimator,
|
|
79
|
+
id_col=id_col,
|
|
80
|
+
cv=cv,
|
|
81
|
+
random_state=random_state,
|
|
82
|
+
stratified=stratified,
|
|
83
|
+
scoring=scoring,
|
|
84
|
+
verbose=verbose,
|
|
85
|
+
group_col=group_col,
|
|
86
|
+
strict=strict,
|
|
87
|
+
)
|
|
88
|
+
wrapper.fit(X, y, ids=ids)
|
|
89
|
+
|
|
90
|
+
oos = wrapper.get_oos_predictions()
|
|
91
|
+
|
|
92
|
+
# Reorder from fold order to original row order
|
|
93
|
+
# oos_index_ contains the original row indices for each fold
|
|
94
|
+
all_orig_indices = np.concatenate(wrapper.oos_index_)
|
|
95
|
+
sort_order = np.argsort(all_orig_indices)
|
|
96
|
+
|
|
97
|
+
result: dict[str, Any] = {
|
|
98
|
+
"predictions": oos["predictions"][sort_order],
|
|
99
|
+
"ids": oos["ids"][sort_order],
|
|
100
|
+
"fold_indices": oos["fold_indices"][sort_order],
|
|
101
|
+
"cv_results": wrapper.cv_results_,
|
|
102
|
+
"probabilities": None,
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
if "probabilities" in oos:
|
|
106
|
+
result["probabilities"] = oos["probabilities"][sort_order]
|
|
107
|
+
|
|
108
|
+
return result
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class OOSPipeline:
|
|
112
|
+
"""Chain OOS transformers with a final OOS estimator.
|
|
113
|
+
|
|
114
|
+
Shares ``id_col``, ``group_col``, ``cv``, and ``random_state`` across
|
|
115
|
+
all steps so fold assignments are consistent. Transformer steps use
|
|
116
|
+
``OOSTransformer``; the final step uses ``OOSClassifier``,
|
|
117
|
+
``OOSRegressor``, or any OOS wrapper.
|
|
118
|
+
|
|
119
|
+
Each transformer step calls ``fit_transform`` during ``fit()``,
|
|
120
|
+
passing the OOS-transformed features to the next step. The final
|
|
121
|
+
step calls ``fit``. At predict time, each transformer calls
|
|
122
|
+
``transform`` and the final step calls ``predict``.
|
|
123
|
+
|
|
124
|
+
**Target-dependent steps (nested cross-fitting).** A fold transformer
|
|
125
|
+
is fitted on the other folds, so with plain chaining the features the
|
|
126
|
+
final fold model ``k`` trains on were produced by transformers that saw
|
|
127
|
+
fold ``k``'s targets. For a target-dependent step (e.g. ``TargetEncoder``)
|
|
128
|
+
that is second-order leakage. With ``nested="auto"`` (default) such
|
|
129
|
+
steps are cross-fitted in a nested way: for every outer fold ``k`` the
|
|
130
|
+
chain from the first target-dependent step onwards is refitted on the
|
|
131
|
+
rows outside fold ``k``, with inner cross-fitting over the remaining
|
|
132
|
+
outer folds producing the training features of downstream steps and of
|
|
133
|
+
final fold model ``k``. A training row of fold ``k`` is then predicted
|
|
134
|
+
through that per-fold chain and final fold model ``k``, so no model on
|
|
135
|
+
its prediction path has seen fold ``k``'s targets, directly or through
|
|
136
|
+
features. Unseen IDs keep the regular path (fold-OOS chaining over all
|
|
137
|
+
rows, then the general models). Steps before the first target-dependent
|
|
138
|
+
step are not nested (they never see the target).
|
|
139
|
+
|
|
140
|
+
Cost: each nested step is fitted ``K * K`` extra times (``K - 1`` inner
|
|
141
|
+
fits plus one refit on the outer training rows, per outer fold) on
|
|
142
|
+
about ``(K - 1) / K`` of the rows, in addition to the regular ``K + 1``
|
|
143
|
+
fits. Pipelines without target-dependent steps are unaffected.
|
|
144
|
+
|
|
145
|
+
Target dependence is detected from the scikit-learn ``target_tags``
|
|
146
|
+
tag or a required ``y`` in ``fit``. Transformers that accept ``y=None``
|
|
147
|
+
but use ``y`` when given (e.g. ``SelectKBest``) are not detected; pass
|
|
148
|
+
``nested=True`` to nest every step. Nesting requires the final step to
|
|
149
|
+
be a plain estimator, ``OOSClassifier`` or ``OOSRegressor`` and a CV
|
|
150
|
+
splitter that holds every row out exactly once (any integer ``cv``);
|
|
151
|
+
otherwise, and with ``nested=False``, target-dependent steps raise
|
|
152
|
+
under ``strict=True`` (warn with ``strict=False``). The step objects
|
|
153
|
+
passed in ``steps`` are never modified; fitted copies live in
|
|
154
|
+
``transformers_``, ``fold_chains_`` and ``final_estimator_``.
|
|
155
|
+
|
|
156
|
+
Args:
|
|
157
|
+
steps: List of ``(name, estimator)`` tuples. All steps except
|
|
158
|
+
the last must be sklearn transformers (wrapped in
|
|
159
|
+
``OOSTransformer`` automatically). The last step must be
|
|
160
|
+
an sklearn estimator (wrapped in ``OOSClassifier`` or
|
|
161
|
+
``OOSRegressor`` automatically).
|
|
162
|
+
id_col: Shared ID column for all steps.
|
|
163
|
+
cv: Shared number of folds for all steps.
|
|
164
|
+
random_state: Shared seed for all steps.
|
|
165
|
+
group_col: Shared group column for all steps.
|
|
166
|
+
stratified: Use stratified folds for classifiers.
|
|
167
|
+
scoring: Metrics for the final estimator.
|
|
168
|
+
strict: Shared ``strict`` flag for all steps (see ``OOSClassifier``).
|
|
169
|
+
nested: ``"auto"`` (default) nests from the first target-dependent
|
|
170
|
+
step, ``True`` nests every transformer step, ``False`` never
|
|
171
|
+
nests (target-dependent steps then raise under ``strict``).
|
|
172
|
+
|
|
173
|
+
Attributes:
|
|
174
|
+
transformers_: ``(name, OOSTransformer)`` pairs of the regular chain.
|
|
175
|
+
final_estimator_: The fitted final OOS wrapper.
|
|
176
|
+
nested_from_: Index of the first nested step, or None.
|
|
177
|
+
fold_chains_: Per outer fold, the transformers of the nested steps
|
|
178
|
+
refitted on the rows outside that fold (empty when not nested).
|
|
179
|
+
|
|
180
|
+
Examples:
|
|
181
|
+
>>> from outofsample import OOSPipeline
|
|
182
|
+
>>> from sklearn.preprocessing import StandardScaler, TargetEncoder
|
|
183
|
+
>>> from sklearn.ensemble import GradientBoostingClassifier
|
|
184
|
+
>>>
|
|
185
|
+
>>> pipe = OOSPipeline(
|
|
186
|
+
... steps=[
|
|
187
|
+
... ("encoder", TargetEncoder()), # nested cross-fitting
|
|
188
|
+
... ("clf", GradientBoostingClassifier()),
|
|
189
|
+
... ],
|
|
190
|
+
... id_col="id", cv=5,
|
|
191
|
+
... )
|
|
192
|
+
>>> pipe.fit(X, y)
|
|
193
|
+
>>> predictions = pipe.predict(X)
|
|
194
|
+
"""
|
|
195
|
+
|
|
196
|
+
def __init__(
|
|
197
|
+
self,
|
|
198
|
+
steps: list[tuple[str, Any]],
|
|
199
|
+
*,
|
|
200
|
+
id_col: str | int | None = "id",
|
|
201
|
+
cv: int | Any = 5,
|
|
202
|
+
random_state: int | None = None,
|
|
203
|
+
group_col: str | None = None,
|
|
204
|
+
stratified: bool = True,
|
|
205
|
+
scoring: str | list[str] | dict[str, Any] | None = None,
|
|
206
|
+
strict: bool = True,
|
|
207
|
+
nested: bool | str = "auto",
|
|
208
|
+
) -> None:
|
|
209
|
+
"""Initialize the OOS pipeline.
|
|
210
|
+
|
|
211
|
+
Args:
|
|
212
|
+
steps: List of ``(name, estimator)`` tuples.
|
|
213
|
+
id_col: Shared ID column.
|
|
214
|
+
cv: Shared fold count.
|
|
215
|
+
random_state: Shared seed.
|
|
216
|
+
group_col: Shared group column.
|
|
217
|
+
stratified: Stratify folds for classifiers.
|
|
218
|
+
scoring: Metrics for the final step.
|
|
219
|
+
strict: Shared ``strict`` flag for all steps.
|
|
220
|
+
nested: Nested cross-fitting mode: ``"auto"``, ``True`` or ``False``.
|
|
221
|
+
"""
|
|
222
|
+
if len(steps) < 1:
|
|
223
|
+
raise ValueError("Pipeline must have at least one step")
|
|
224
|
+
self.steps = steps
|
|
225
|
+
self.id_col = id_col
|
|
226
|
+
self.cv = cv
|
|
227
|
+
self.random_state = random_state
|
|
228
|
+
self.group_col = group_col
|
|
229
|
+
self.stratified = stratified
|
|
230
|
+
self.scoring = scoring
|
|
231
|
+
self.strict = strict
|
|
232
|
+
self.nested = nested
|
|
233
|
+
|
|
234
|
+
def fit(self, X: Any, y: Any, *, ids: Any | None = None, **fit_params: Any):
|
|
235
|
+
"""Fit all steps sequentially.
|
|
236
|
+
|
|
237
|
+
Transformer steps use ``fit_transform`` to produce OOS features.
|
|
238
|
+
The final step uses ``fit``. Target-dependent steps are nested
|
|
239
|
+
(see the class docstring).
|
|
240
|
+
|
|
241
|
+
Args:
|
|
242
|
+
X: Training data with ID (and optionally group) columns.
|
|
243
|
+
y: Target values.
|
|
244
|
+
ids: Explicit ID array.
|
|
245
|
+
**fit_params: Passed to the final estimator's fit.
|
|
246
|
+
|
|
247
|
+
Returns:
|
|
248
|
+
self
|
|
249
|
+
"""
|
|
250
|
+
from ._calibration import OOSCalibratedClassifier
|
|
251
|
+
from ._estimators import OOSModel, _OOSBase
|
|
252
|
+
from ._intervals import OOSConformalRegressor
|
|
253
|
+
from ._transformer import OOSTransformer
|
|
254
|
+
from ._validation import extract_ids_and_features, validate_target
|
|
255
|
+
|
|
256
|
+
if self.nested not in ("auto", True, False):
|
|
257
|
+
raise ValueError(f"nested must be 'auto', True or False, got {self.nested!r}")
|
|
258
|
+
|
|
259
|
+
# Pre-compute fold assignments once so all steps use identical splits
|
|
260
|
+
X_features, id_array, _ = extract_ids_and_features(X, self.id_col, ids=ids)
|
|
261
|
+
y_arr = validate_target(y)
|
|
262
|
+
|
|
263
|
+
groups = None
|
|
264
|
+
if (
|
|
265
|
+
self.group_col is not None
|
|
266
|
+
and isinstance(X_features, pd.DataFrame)
|
|
267
|
+
and self.group_col in X_features.columns
|
|
268
|
+
):
|
|
269
|
+
groups = X_features[self.group_col].to_numpy()
|
|
270
|
+
|
|
271
|
+
# Use a temporary _OOSBase to resolve the splitter
|
|
272
|
+
_final_name, final_est = self.steps[-1]
|
|
273
|
+
temp = _OOSBase(
|
|
274
|
+
estimator=final_est,
|
|
275
|
+
cv=self.cv,
|
|
276
|
+
random_state=self.random_state,
|
|
277
|
+
stratified=self.stratified,
|
|
278
|
+
group_col=self.group_col,
|
|
279
|
+
strict=self.strict,
|
|
280
|
+
)
|
|
281
|
+
splitter, split_groups = temp._get_splitter(X_features, y_arr, id_array, groups)
|
|
282
|
+
if split_groups is not None:
|
|
283
|
+
splits = list(splitter.split(X_features, y_arr, groups=split_groups))
|
|
284
|
+
else:
|
|
285
|
+
splits = list(splitter.split(X_features, y_arr))
|
|
286
|
+
|
|
287
|
+
# Create a fixed splitter that yields these exact splits
|
|
288
|
+
fixed_cv = _FixedSplitter(splits)
|
|
289
|
+
|
|
290
|
+
nested_from = self._resolve_nesting(final_est, splits, len(X_features))
|
|
291
|
+
|
|
292
|
+
self.transformers_ = []
|
|
293
|
+
self.nested_from_ = nested_from
|
|
294
|
+
self.fold_chains_: list[list[Any]] = []
|
|
295
|
+
X_current = X
|
|
296
|
+
# Pure (ID/group-free) OOS output of every transformer step
|
|
297
|
+
step_outputs: list[np.ndarray] = []
|
|
298
|
+
|
|
299
|
+
# Fit transformer steps (all except last)
|
|
300
|
+
for name, est in self.steps[:-1]:
|
|
301
|
+
oos_t = OOSTransformer(
|
|
302
|
+
estimator=est,
|
|
303
|
+
id_col=self.id_col,
|
|
304
|
+
cv=fixed_cv,
|
|
305
|
+
random_state=self.random_state,
|
|
306
|
+
group_col=self.group_col,
|
|
307
|
+
strict=self.strict,
|
|
308
|
+
)
|
|
309
|
+
X_transformed = oos_t.fit_transform(X_current, y, ids=ids)
|
|
310
|
+
step_outputs.append(X_transformed)
|
|
311
|
+
|
|
312
|
+
# Rebuild DataFrame with ID/group columns for next step
|
|
313
|
+
if isinstance(X_current, pd.DataFrame):
|
|
314
|
+
X_next = pd.DataFrame(
|
|
315
|
+
X_transformed,
|
|
316
|
+
columns=[f"{name}_{i}" for i in range(X_transformed.shape[1])],
|
|
317
|
+
)
|
|
318
|
+
if self.id_col is not None and self.id_col in X_current.columns:
|
|
319
|
+
X_next[self.id_col] = X_current[self.id_col].values
|
|
320
|
+
if self.group_col is not None and self.group_col in X_current.columns:
|
|
321
|
+
X_next[self.group_col] = X_current[self.group_col].values
|
|
322
|
+
X_current = X_next
|
|
323
|
+
else:
|
|
324
|
+
X_current = X_transformed
|
|
325
|
+
|
|
326
|
+
self.transformers_.append((name, oos_t))
|
|
327
|
+
|
|
328
|
+
fold_features = None
|
|
329
|
+
if nested_from is not None:
|
|
330
|
+
if nested_from == 0:
|
|
331
|
+
start = self._drop_group(X_features)
|
|
332
|
+
else:
|
|
333
|
+
start = self._stage_frame(step_outputs[nested_from - 1], nested_from)
|
|
334
|
+
fold_features = self._fit_fold_chains(start, y_arr, id_array, splits, nested_from)
|
|
335
|
+
|
|
336
|
+
# Fit final estimator — detect already-OOS wrappers to avoid double-folding
|
|
337
|
+
from ._conformal_classifier import OOSConformalClassifier
|
|
338
|
+
from ._cqr import OOSConformalQuantileRegressor
|
|
339
|
+
|
|
340
|
+
oos_wrappers = (
|
|
341
|
+
OOSCalibratedClassifier,
|
|
342
|
+
OOSConformalRegressor,
|
|
343
|
+
OOSConformalQuantileRegressor,
|
|
344
|
+
OOSConformalClassifier,
|
|
345
|
+
_OOSBase,
|
|
346
|
+
)
|
|
347
|
+
if isinstance(final_est, oos_wrappers):
|
|
348
|
+
# Configure a clone with the shared fold setup; the step object
|
|
349
|
+
# passed by the caller is left untouched
|
|
350
|
+
self.final_estimator_ = clone(final_est).set_params(
|
|
351
|
+
cv=fixed_cv,
|
|
352
|
+
id_col=self.id_col,
|
|
353
|
+
group_col=self.group_col,
|
|
354
|
+
random_state=self.random_state,
|
|
355
|
+
strict=self.strict,
|
|
356
|
+
)
|
|
357
|
+
else:
|
|
358
|
+
# Raw sklearn estimator — wrap in OOSModel
|
|
359
|
+
self.final_estimator_ = OOSModel(
|
|
360
|
+
final_est,
|
|
361
|
+
stratified=self.stratified,
|
|
362
|
+
scoring=self.scoring,
|
|
363
|
+
id_col=self.id_col,
|
|
364
|
+
cv=fixed_cv,
|
|
365
|
+
random_state=self.random_state,
|
|
366
|
+
group_col=self.group_col,
|
|
367
|
+
strict=self.strict,
|
|
368
|
+
)
|
|
369
|
+
if fold_features is not None:
|
|
370
|
+
self.final_estimator_._fit_impl(
|
|
371
|
+
X_current, y, ids=ids, _fold_features=fold_features, **fit_params
|
|
372
|
+
)
|
|
373
|
+
else:
|
|
374
|
+
self.final_estimator_.fit(X_current, y, ids=ids, **fit_params)
|
|
375
|
+
|
|
376
|
+
return self
|
|
377
|
+
|
|
378
|
+
def refresh(self, X: Any, y: Any = None, **kwargs: Any) -> None:
|
|
379
|
+
"""Not supported: call ``fit`` on the full updated data instead.
|
|
380
|
+
|
|
381
|
+
Raises:
|
|
382
|
+
NotImplementedError: Always.
|
|
383
|
+
"""
|
|
384
|
+
from ._refresh import refresh_unsupported
|
|
385
|
+
|
|
386
|
+
refresh_unsupported(self)
|
|
387
|
+
|
|
388
|
+
# ------------------------------------------------------------------
|
|
389
|
+
# Nested cross-fitting
|
|
390
|
+
# ------------------------------------------------------------------
|
|
391
|
+
|
|
392
|
+
def _resolve_nesting(self, final_est: Any, splits: list, n_samples: int) -> int | None:
|
|
393
|
+
"""Index of the first step to nest, or None (raising/warning if unsafe)."""
|
|
394
|
+
from ._estimators import OOSClassifier, OOSRegressor, _OOSBase
|
|
395
|
+
|
|
396
|
+
transformer_steps = self.steps[:-1]
|
|
397
|
+
target_steps = [i for i, (_n, est) in enumerate(transformer_steps) if _requires_target(est)]
|
|
398
|
+
if self.nested is True:
|
|
399
|
+
nested_from: int | None = 0 if transformer_steps else None
|
|
400
|
+
elif self.nested == "auto":
|
|
401
|
+
nested_from = target_steps[0] if target_steps else None
|
|
402
|
+
else:
|
|
403
|
+
nested_from = None
|
|
404
|
+
if nested_from is None:
|
|
405
|
+
self._check_supervised_steps(target_steps, "nested=False")
|
|
406
|
+
return None
|
|
407
|
+
|
|
408
|
+
reason = None
|
|
409
|
+
nestable_final = isinstance(final_est, (OOSClassifier, OOSRegressor)) or not (
|
|
410
|
+
isinstance(final_est, _OOSBase) or _is_oos_composite(final_est)
|
|
411
|
+
)
|
|
412
|
+
if not nestable_final:
|
|
413
|
+
reason = f"a {type(final_est).__name__} final step"
|
|
414
|
+
else:
|
|
415
|
+
held_out = np.concatenate([oos for _train, oos in splits]) if splits else np.array([])
|
|
416
|
+
if len(held_out) != n_samples or len(np.unique(held_out)) != n_samples:
|
|
417
|
+
reason = "a CV splitter that does not hold every row out exactly once"
|
|
418
|
+
if reason is None:
|
|
419
|
+
return nested_from
|
|
420
|
+
if self.nested is True:
|
|
421
|
+
raise ValueError(f"nested=True is not supported with {reason}.")
|
|
422
|
+
self._check_supervised_steps(target_steps, f"nesting is not supported with {reason}")
|
|
423
|
+
return None
|
|
424
|
+
|
|
425
|
+
def _fit_fold_chains(
|
|
426
|
+
self,
|
|
427
|
+
start: pd.DataFrame,
|
|
428
|
+
y_arr: np.ndarray,
|
|
429
|
+
id_array: np.ndarray,
|
|
430
|
+
splits: list[tuple[np.ndarray, np.ndarray]],
|
|
431
|
+
nested_from: int,
|
|
432
|
+
) -> list[tuple[np.ndarray, np.ndarray]]:
|
|
433
|
+
"""Refit the nested steps per outer fold; return final-model features.
|
|
434
|
+
|
|
435
|
+
For outer fold ``k`` the nested steps are fitted on the rows outside
|
|
436
|
+
fold ``k`` with inner cross-fitting over the remaining outer folds,
|
|
437
|
+
so the inner OOS features (the training features of downstream steps
|
|
438
|
+
and of final fold model ``k``) never depend on fold ``k``'s targets.
|
|
439
|
+
The refitted step transformers form ``fold_chains_[k]`` and produce
|
|
440
|
+
fold ``k``'s own features.
|
|
441
|
+
|
|
442
|
+
Args:
|
|
443
|
+
start: Pure feature frame entering the first nested step (all rows).
|
|
444
|
+
y_arr: Target array.
|
|
445
|
+
id_array: Training IDs.
|
|
446
|
+
splits: Outer ``(train_idx, oos_idx)`` splits.
|
|
447
|
+
nested_from: Index of the first nested step.
|
|
448
|
+
|
|
449
|
+
Returns:
|
|
450
|
+
One ``(X_train, X_oos)`` feature pair per outer fold.
|
|
451
|
+
"""
|
|
452
|
+
from ._transformer import OOSTransformer
|
|
453
|
+
|
|
454
|
+
n_samples = len(start)
|
|
455
|
+
fold_features = []
|
|
456
|
+
for k, (train_idx, oos_idx) in enumerate(splits):
|
|
457
|
+
# Inner folds: the other outer folds, re-indexed into train_idx
|
|
458
|
+
position = np.full(n_samples, -1)
|
|
459
|
+
position[train_idx] = np.arange(len(train_idx))
|
|
460
|
+
inner_splits = []
|
|
461
|
+
for j, (_train_j, oos_j) in enumerate(splits):
|
|
462
|
+
if j == k:
|
|
463
|
+
continue
|
|
464
|
+
inner_oos = position[oos_j]
|
|
465
|
+
in_oos = np.zeros(len(train_idx), dtype=bool)
|
|
466
|
+
in_oos[inner_oos] = True
|
|
467
|
+
inner_splits.append((np.flatnonzero(~in_oos), inner_oos))
|
|
468
|
+
inner_cv = _FixedSplitter(inner_splits)
|
|
469
|
+
|
|
470
|
+
X_train = start.iloc[train_idx].reset_index(drop=True)
|
|
471
|
+
X_oos = start.iloc[oos_idx].reset_index(drop=True)
|
|
472
|
+
chain = []
|
|
473
|
+
for step in range(nested_from, len(self.steps) - 1):
|
|
474
|
+
inner = OOSTransformer(
|
|
475
|
+
estimator=self.steps[step][1], id_col=None, cv=inner_cv, strict=self.strict
|
|
476
|
+
)
|
|
477
|
+
train_out = inner.fit_transform(X_train, y_arr[train_idx], ids=id_array[train_idx])
|
|
478
|
+
fitted = inner.general_model_
|
|
479
|
+
chain.append(fitted)
|
|
480
|
+
X_train = self._stage_frame(train_out, step + 1)
|
|
481
|
+
X_oos = self._stage_frame(_dense(fitted.transform(X_oos)), step + 1)
|
|
482
|
+
self.fold_chains_.append(chain)
|
|
483
|
+
fold_features.append((X_train.to_numpy(), X_oos.to_numpy()))
|
|
484
|
+
return fold_features
|
|
485
|
+
|
|
486
|
+
def _stage_frame(self, arr: np.ndarray, stage: int) -> pd.DataFrame:
|
|
487
|
+
"""Frame entering step ``stage`` (columns named after the previous step)."""
|
|
488
|
+
name = self.steps[stage - 1][0]
|
|
489
|
+
arr = np.asarray(arr)
|
|
490
|
+
if arr.ndim == 1:
|
|
491
|
+
arr = arr.reshape(-1, 1)
|
|
492
|
+
return pd.DataFrame(arr, columns=[f"{name}_{i}" for i in range(arr.shape[1])])
|
|
493
|
+
|
|
494
|
+
def _drop_group(self, X_features: pd.DataFrame) -> pd.DataFrame:
|
|
495
|
+
if self.group_col is not None and self.group_col in X_features.columns:
|
|
496
|
+
return X_features.drop(columns=[self.group_col])
|
|
497
|
+
return X_features
|
|
498
|
+
|
|
499
|
+
def _final_input(self, X: Any, ids: Any | None) -> tuple[Any, Any]:
|
|
500
|
+
"""Features and IDs to pass to the final estimator for prediction."""
|
|
501
|
+
if not getattr(self, "fold_chains_", None):
|
|
502
|
+
return self._transform_steps(X, ids=ids), ids
|
|
503
|
+
from ._prediction import dispatch_predict
|
|
504
|
+
from ._validation import extract_ids_and_features
|
|
505
|
+
|
|
506
|
+
nested_from = self.nested_from_
|
|
507
|
+
assert nested_from is not None # set whenever fold_chains_ is non-empty
|
|
508
|
+
X_features, id_array, _ = extract_ids_and_features(X, self.id_col, ids=ids)
|
|
509
|
+
current: pd.DataFrame = self._drop_group(X_features)
|
|
510
|
+
# Regular (non-nested) prefix steps, routed by ID as usual
|
|
511
|
+
for stage in range(nested_from):
|
|
512
|
+
_name, oos_t = self.transformers_[stage]
|
|
513
|
+
out = dispatch_predict(
|
|
514
|
+
oos_t.models_,
|
|
515
|
+
oos_t.general_model_,
|
|
516
|
+
_as_fitted_frame(current, oos_t),
|
|
517
|
+
oos_t.id_to_fold_,
|
|
518
|
+
id_array,
|
|
519
|
+
"transform",
|
|
520
|
+
)
|
|
521
|
+
current = self._stage_frame(out, stage + 1)
|
|
522
|
+
|
|
523
|
+
id_to_fold = self.final_estimator_.id_to_fold_
|
|
524
|
+
fold_of = np.array([id_to_fold.get(id_, -1) for id_ in id_array])
|
|
525
|
+
pieces: dict[int, np.ndarray] = {}
|
|
526
|
+
for fold in np.unique(fold_of):
|
|
527
|
+
rows = np.flatnonzero(fold_of == fold)
|
|
528
|
+
part = current.iloc[rows].reset_index(drop=True)
|
|
529
|
+
for offset, stage in enumerate(range(nested_from, len(self.steps) - 1)):
|
|
530
|
+
if fold == -1:
|
|
531
|
+
oos_t = self.transformers_[stage][1]
|
|
532
|
+
out = _dense(oos_t.general_model_.transform(_as_fitted_frame(part, oos_t)))
|
|
533
|
+
else:
|
|
534
|
+
out = _dense(self.fold_chains_[fold][offset].transform(part))
|
|
535
|
+
part = self._stage_frame(out, stage + 1)
|
|
536
|
+
pieces[int(fold)] = part.to_numpy()
|
|
537
|
+
width = next(iter(pieces.values())).shape[1]
|
|
538
|
+
final_features = np.empty((len(id_array), width))
|
|
539
|
+
for fold, values in pieces.items():
|
|
540
|
+
final_features[fold_of == fold] = values
|
|
541
|
+
final = self.final_estimator_
|
|
542
|
+
names = getattr(final, "feature_names_in_", None)
|
|
543
|
+
if names is not None and all(isinstance(c, str) for c in names):
|
|
544
|
+
return pd.DataFrame(final_features, columns=[str(c) for c in names]), id_array
|
|
545
|
+
return pd.DataFrame(final_features), id_array
|
|
546
|
+
|
|
547
|
+
# ------------------------------------------------------------------
|
|
548
|
+
# Prediction
|
|
549
|
+
# ------------------------------------------------------------------
|
|
550
|
+
|
|
551
|
+
def predict(self, X: Any, *, ids: Any | None = None) -> np.ndarray:
|
|
552
|
+
"""Transform X through all steps and predict.
|
|
553
|
+
|
|
554
|
+
Args:
|
|
555
|
+
X: Input data with ID/group columns.
|
|
556
|
+
ids: Explicit ID array.
|
|
557
|
+
|
|
558
|
+
Returns:
|
|
559
|
+
Predictions from the final estimator.
|
|
560
|
+
"""
|
|
561
|
+
X_current, ids_current = self._final_input(X, ids)
|
|
562
|
+
return self.final_estimator_.predict(X_current, ids=ids_current)
|
|
563
|
+
|
|
564
|
+
def predict_proba(self, X: Any, *, ids: Any | None = None) -> np.ndarray:
|
|
565
|
+
"""Transform X through all steps and predict probabilities.
|
|
566
|
+
|
|
567
|
+
Args:
|
|
568
|
+
X: Input data.
|
|
569
|
+
ids: Explicit ID array.
|
|
570
|
+
|
|
571
|
+
Returns:
|
|
572
|
+
Probability estimates from the final estimator.
|
|
573
|
+
"""
|
|
574
|
+
X_current, ids_current = self._final_input(X, ids)
|
|
575
|
+
return self.final_estimator_.predict_proba(X_current, ids=ids_current)
|
|
576
|
+
|
|
577
|
+
def score(self, X: Any, y: Any, *, ids: Any | None = None) -> float:
|
|
578
|
+
"""Transform and score.
|
|
579
|
+
|
|
580
|
+
Args:
|
|
581
|
+
X: Input data.
|
|
582
|
+
y: True targets/labels.
|
|
583
|
+
ids: Explicit ID array.
|
|
584
|
+
|
|
585
|
+
Returns:
|
|
586
|
+
Score from the final estimator.
|
|
587
|
+
"""
|
|
588
|
+
X_current, ids_current = self._final_input(X, ids)
|
|
589
|
+
return self.final_estimator_.score(X_current, y, ids=ids_current)
|
|
590
|
+
|
|
591
|
+
def predict_interval(self, X: Any, *, ids: Any | None = None, **kwargs: Any) -> np.ndarray:
|
|
592
|
+
"""Transform X and predict intervals (OOSConformalRegressor final step).
|
|
593
|
+
|
|
594
|
+
Args:
|
|
595
|
+
X: Input data.
|
|
596
|
+
ids: Explicit ID array.
|
|
597
|
+
**kwargs: Passed to predict_interval.
|
|
598
|
+
|
|
599
|
+
Returns:
|
|
600
|
+
Array of shape ``(n_samples, 2)`` with [lower, upper].
|
|
601
|
+
"""
|
|
602
|
+
X_current, ids_current = self._final_input(X, ids)
|
|
603
|
+
return self.final_estimator_.predict_interval(X_current, ids=ids_current, **kwargs)
|
|
604
|
+
|
|
605
|
+
def coverage(self, X: Any, y: Any, *, ids: Any | None = None, **kwargs: Any) -> float:
|
|
606
|
+
"""Transform X and compute coverage (conformal final step)."""
|
|
607
|
+
X_current, ids_current = self._final_input(X, ids)
|
|
608
|
+
return self.final_estimator_.coverage(X_current, y, ids=ids_current, **kwargs)
|
|
609
|
+
|
|
610
|
+
def interval_width(self, X: Any, *, ids: Any | None = None) -> np.ndarray:
|
|
611
|
+
"""Transform X and compute interval widths (OOSConformalRegressor final step)."""
|
|
612
|
+
X_current, ids_current = self._final_input(X, ids)
|
|
613
|
+
return self.final_estimator_.interval_width(X_current, ids=ids_current)
|
|
614
|
+
|
|
615
|
+
def predict_set(self, X: Any, *, ids: Any | None = None, **kwargs: Any) -> Any:
|
|
616
|
+
"""Transform X and predict conformal sets (OOSConformalClassifier final step).
|
|
617
|
+
|
|
618
|
+
Args:
|
|
619
|
+
X: Input data.
|
|
620
|
+
ids: Explicit ID array.
|
|
621
|
+
**kwargs: Passed to predict_set.
|
|
622
|
+
|
|
623
|
+
Returns:
|
|
624
|
+
Prediction-set membership matrix (or label lists).
|
|
625
|
+
"""
|
|
626
|
+
X_current, ids_current = self._final_input(X, ids)
|
|
627
|
+
return self.final_estimator_.predict_set(X_current, ids=ids_current, **kwargs)
|
|
628
|
+
|
|
629
|
+
def set_size(self, X: Any, *, ids: Any | None = None, **kwargs: Any) -> np.ndarray:
|
|
630
|
+
"""Transform X and return prediction-set sizes (OOSConformalClassifier final step)."""
|
|
631
|
+
X_current, ids_current = self._final_input(X, ids)
|
|
632
|
+
return self.final_estimator_.set_size(X_current, ids=ids_current, **kwargs)
|
|
633
|
+
|
|
634
|
+
def _transform_steps(self, X: Any, *, ids: Any | None = None) -> Any:
|
|
635
|
+
"""Run X through all transformer steps of the regular chain.
|
|
636
|
+
|
|
637
|
+
Args:
|
|
638
|
+
X: Input data.
|
|
639
|
+
ids: Explicit ID array.
|
|
640
|
+
|
|
641
|
+
Returns:
|
|
642
|
+
Transformed features with ID/group columns preserved.
|
|
643
|
+
"""
|
|
644
|
+
X_current = X
|
|
645
|
+
for name, oos_t in self.transformers_:
|
|
646
|
+
X_transformed = oos_t.transform(X_current, ids=ids)
|
|
647
|
+
if isinstance(X_current, pd.DataFrame):
|
|
648
|
+
X_next = pd.DataFrame(
|
|
649
|
+
X_transformed,
|
|
650
|
+
columns=[f"{name}_{i}" for i in range(X_transformed.shape[1])],
|
|
651
|
+
)
|
|
652
|
+
if self.id_col is not None and self.id_col in X_current.columns:
|
|
653
|
+
X_next[self.id_col] = X_current[self.id_col].values
|
|
654
|
+
if self.group_col is not None and self.group_col in X_current.columns:
|
|
655
|
+
X_next[self.group_col] = X_current[self.group_col].values
|
|
656
|
+
X_current = X_next
|
|
657
|
+
else:
|
|
658
|
+
X_current = X_transformed
|
|
659
|
+
return X_current
|
|
660
|
+
|
|
661
|
+
def _check_supervised_steps(self, target_steps: list[int], why: str) -> None:
|
|
662
|
+
"""Refuse target-dependent transformer steps that are not nested.
|
|
663
|
+
|
|
664
|
+
Without nesting, a transformer step produces each row's features with
|
|
665
|
+
the fold transformer that held the row out, but that transformer was
|
|
666
|
+
fitted on the other folds — including the rows the final estimator
|
|
667
|
+
later holds out. For target-dependent transformers (e.g.
|
|
668
|
+
``TargetEncoder``) the features of fold k's training rows therefore
|
|
669
|
+
encode fold k's targets, and fold k's OOS scores are optimistic
|
|
670
|
+
(second-order leakage). Unsupervised transformers are unaffected.
|
|
671
|
+
|
|
672
|
+
Args:
|
|
673
|
+
target_steps: Indices of the target-dependent transformer steps.
|
|
674
|
+
why: Why the steps are not nested (for the message).
|
|
675
|
+
"""
|
|
676
|
+
for index in target_steps:
|
|
677
|
+
name, est = self.steps[index]
|
|
678
|
+
message = (
|
|
679
|
+
f"Transformer step {name!r} ({type(est).__name__}) is fitted on the "
|
|
680
|
+
f"target but is not cross-fitted in a nested way ({why}). Its OOS "
|
|
681
|
+
"features for one fold's training rows come from transformers that saw "
|
|
682
|
+
"the held-out fold's targets, so the final model's OOS predictions leak "
|
|
683
|
+
"(second-order leakage). Use nested='auto' with a plain, OOSClassifier "
|
|
684
|
+
"or OOSRegressor final step, or put target-dependent preprocessing "
|
|
685
|
+
"inside the final estimator (e.g. an sklearn Pipeline as the last step)."
|
|
686
|
+
)
|
|
687
|
+
if self.strict:
|
|
688
|
+
raise ValueError(message + " Pass strict=False to only warn.")
|
|
689
|
+
warnings.warn(message, UserWarning, stacklevel=4)
|
|
690
|
+
|
|
691
|
+
@property
|
|
692
|
+
def cv_results_(self) -> dict:
|
|
693
|
+
"""Metrics from the final estimator."""
|
|
694
|
+
return self.final_estimator_.cv_results_
|
|
695
|
+
|
|
696
|
+
@property
|
|
697
|
+
def last_routing_(self) -> dict[str, Any]:
|
|
698
|
+
"""Routing statistics of the final estimator's most recent prediction call.
|
|
699
|
+
|
|
700
|
+
Each fitted transformer step in ``transformers_`` records its own
|
|
701
|
+
``last_routing_`` as well (see ``OOSClassifier.last_routing_``).
|
|
702
|
+
"""
|
|
703
|
+
return self.final_estimator_.last_routing_
|
|
704
|
+
|
|
705
|
+
|
|
706
|
+
def _is_oos_composite(estimator: Any) -> bool:
|
|
707
|
+
"""True for OOS wrappers that cannot take nested per-fold features."""
|
|
708
|
+
from ._calibration import OOSCalibratedClassifier
|
|
709
|
+
from ._conformal_classifier import OOSConformalClassifier
|
|
710
|
+
from ._cqr import OOSConformalQuantileRegressor
|
|
711
|
+
from ._intervals import OOSConformalRegressor
|
|
712
|
+
|
|
713
|
+
composites = (
|
|
714
|
+
OOSCalibratedClassifier,
|
|
715
|
+
OOSConformalRegressor,
|
|
716
|
+
OOSConformalQuantileRegressor,
|
|
717
|
+
OOSConformalClassifier,
|
|
718
|
+
)
|
|
719
|
+
return isinstance(estimator, composites)
|
|
720
|
+
|
|
721
|
+
|
|
722
|
+
def _dense(out: Any) -> np.ndarray:
|
|
723
|
+
"""Dense 2-D array from a transformer output."""
|
|
724
|
+
from scipy import sparse
|
|
725
|
+
|
|
726
|
+
if sparse.issparse(out):
|
|
727
|
+
out = out.toarray()
|
|
728
|
+
out = np.asarray(out)
|
|
729
|
+
return out.reshape(-1, 1) if out.ndim == 1 else out
|
|
730
|
+
|
|
731
|
+
|
|
732
|
+
def _as_fitted_frame(frame: pd.DataFrame, oos_t: Any) -> pd.DataFrame:
|
|
733
|
+
"""Label a pure feature frame the way an OOSTransformer's models were fitted."""
|
|
734
|
+
names = getattr(oos_t, "feature_names_in_", None)
|
|
735
|
+
if names is not None and len(names) == frame.shape[1]:
|
|
736
|
+
return frame.set_axis([c if not isinstance(c, str) else str(c) for c in names], axis=1)
|
|
737
|
+
return frame.set_axis(range(frame.shape[1]), axis=1)
|
|
738
|
+
|
|
739
|
+
|
|
740
|
+
def _requires_target(estimator: Any) -> bool:
|
|
741
|
+
"""True if a transformer needs ``y`` to fit (target-dependent).
|
|
742
|
+
|
|
743
|
+
Uses the scikit-learn ``target_tags.required`` tag, falling back to a
|
|
744
|
+
``fit`` signature whose ``y`` parameter has no default. Transformers
|
|
745
|
+
that accept ``y=None`` but use it when given (e.g. ``SelectKBest``)
|
|
746
|
+
cannot be detected this way.
|
|
747
|
+
"""
|
|
748
|
+
try:
|
|
749
|
+
if estimator.__sklearn_tags__().target_tags.required:
|
|
750
|
+
return True
|
|
751
|
+
except (AttributeError, TypeError):
|
|
752
|
+
pass
|
|
753
|
+
try:
|
|
754
|
+
params = inspect.signature(estimator.fit).parameters
|
|
755
|
+
except (TypeError, ValueError):
|
|
756
|
+
return False
|
|
757
|
+
y_param = params.get("y")
|
|
758
|
+
return y_param is not None and y_param.default is inspect.Parameter.empty
|
|
759
|
+
|
|
760
|
+
|
|
761
|
+
class _FixedSplitter:
|
|
762
|
+
"""CV splitter that yields pre-computed (train, test) index arrays.
|
|
763
|
+
|
|
764
|
+
Used by OOSPipeline to ensure all steps use identical fold assignments.
|
|
765
|
+
"""
|
|
766
|
+
|
|
767
|
+
def __init__(self, splits: list[tuple[np.ndarray, np.ndarray]]) -> None:
|
|
768
|
+
self.splits = splits
|
|
769
|
+
# Store expected row count for validation
|
|
770
|
+
if splits:
|
|
771
|
+
all_indices = np.concatenate([np.concatenate(s) for s in splits])
|
|
772
|
+
self._n_samples = int(all_indices.max()) + 1
|
|
773
|
+
else:
|
|
774
|
+
self._n_samples = 0
|
|
775
|
+
|
|
776
|
+
def split(self, X: Any = None, y: Any = None, groups: Any = None):
|
|
777
|
+
"""Yield pre-computed splits, validating row count if X is provided."""
|
|
778
|
+
if X is not None and hasattr(X, "__len__") and len(X) != self._n_samples:
|
|
779
|
+
raise ValueError(
|
|
780
|
+
f"FixedSplitter expected {self._n_samples} samples but got {len(X)}. "
|
|
781
|
+
"A pipeline step may have changed the number of rows."
|
|
782
|
+
)
|
|
783
|
+
yield from self.splits
|
|
784
|
+
|
|
785
|
+
def get_n_splits(self, X: Any = None, y: Any = None, groups: Any = None) -> int:
|
|
786
|
+
return len(self.splits)
|