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,999 @@
|
|
|
1
|
+
"""Core out-of-sample estimator classes.
|
|
2
|
+
|
|
3
|
+
Provides ``OOSClassifier``, ``OOSRegressor``, and the ``OOSModel``
|
|
4
|
+
factory function for building K-fold OOS wrappers around any
|
|
5
|
+
scikit-learn-compatible estimator.
|
|
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 (
|
|
17
|
+
BaseEstimator,
|
|
18
|
+
ClassifierMixin,
|
|
19
|
+
MetaEstimatorMixin,
|
|
20
|
+
RegressorMixin,
|
|
21
|
+
clone,
|
|
22
|
+
is_classifier,
|
|
23
|
+
)
|
|
24
|
+
from sklearn.model_selection import GroupKFold, KFold, StratifiedGroupKFold, StratifiedKFold
|
|
25
|
+
from sklearn.utils.validation import check_is_fitted
|
|
26
|
+
|
|
27
|
+
from ._metrics import compute_fold_metrics, resolve_scoring
|
|
28
|
+
from ._prediction import align_proba, dispatch_predict
|
|
29
|
+
from ._refresh import record_refresh_state, refresh_impl, row_fingerprints
|
|
30
|
+
from ._validation import (
|
|
31
|
+
check_id_kind,
|
|
32
|
+
extract_ids_and_features,
|
|
33
|
+
id_kind,
|
|
34
|
+
reset_fitted_state,
|
|
35
|
+
slice_fit_params,
|
|
36
|
+
string_feature_names,
|
|
37
|
+
validate_target,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _group_kfold(n_splits: int, random_state: int | None) -> GroupKFold:
|
|
42
|
+
"""Build a GroupKFold, shuffling when supported (sklearn >= 1.6)."""
|
|
43
|
+
if "shuffle" in inspect.signature(GroupKFold.__init__).parameters:
|
|
44
|
+
return GroupKFold(n_splits=n_splits, shuffle=True, random_state=random_state)
|
|
45
|
+
return GroupKFold(n_splits=n_splits)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class _OOSBase(BaseEstimator):
|
|
49
|
+
"""Private base implementing the K-fold out-of-sample pattern.
|
|
50
|
+
|
|
51
|
+
Trains ``cv`` clones of the base estimator, tracks which fold scored
|
|
52
|
+
each record, and ensures every record is predicted by a model that
|
|
53
|
+
never saw it during training. A general model trained on all data
|
|
54
|
+
handles unseen IDs.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
def __init__(
|
|
58
|
+
self,
|
|
59
|
+
estimator: Any = None,
|
|
60
|
+
*,
|
|
61
|
+
id_col: str | int | None = "id",
|
|
62
|
+
cv: int | Any = 5,
|
|
63
|
+
random_state: int | None = None,
|
|
64
|
+
stratified: bool = True,
|
|
65
|
+
verbose: int = 0,
|
|
66
|
+
scoring: str | list[str] | dict[str, Any] | None = None,
|
|
67
|
+
group_col: str | None = None,
|
|
68
|
+
strict: bool = True,
|
|
69
|
+
) -> None:
|
|
70
|
+
"""Initialize the OOS base estimator.
|
|
71
|
+
|
|
72
|
+
Args:
|
|
73
|
+
estimator: Any sklearn-compatible estimator with fit/predict.
|
|
74
|
+
id_col: Column name, positional index, or None for row indices.
|
|
75
|
+
Used for prediction routing (mapping each sample to its
|
|
76
|
+
fold model at predict time).
|
|
77
|
+
cv: Number of folds or an sklearn CV splitter instance.
|
|
78
|
+
random_state: Seed for the internal fold splitter.
|
|
79
|
+
stratified: Use StratifiedKFold for classification targets
|
|
80
|
+
(or StratifiedGroupKFold when group_col is set).
|
|
81
|
+
verbose: 0 = silent, 1 = progress bar (requires tqdm).
|
|
82
|
+
scoring: Metrics to compute: a metric name, a list of names, a dict
|
|
83
|
+
mapping display names to names or to metric functions
|
|
84
|
+
``f(y_true, y_pred) -> float``, or None for defaults. sklearn
|
|
85
|
+
scorer objects (``(estimator, X, y)`` signature) are rejected.
|
|
86
|
+
group_col: Column name for group-aware fold splitting. When set,
|
|
87
|
+
all rows sharing a ``group_col`` value are placed in the same
|
|
88
|
+
fold, preventing information leakage between correlated
|
|
89
|
+
observations (e.g., multiple rows per customer, repeated
|
|
90
|
+
measurements over time, or data from the same session/build).
|
|
91
|
+
Uses GroupKFold or StratifiedGroupKFold depending on
|
|
92
|
+
``stratified``. If None, grouping is auto-detected from
|
|
93
|
+
duplicate values in ``id_col``.
|
|
94
|
+
strict: If True (default), conditions that would silently produce
|
|
95
|
+
in-sample predictions or drop requested metrics raise a
|
|
96
|
+
``ValueError``: a CV splitter that never holds some rows out
|
|
97
|
+
or splits duplicate IDs across folds, prediction IDs whose
|
|
98
|
+
type differs from the training IDs, unknown metric names,
|
|
99
|
+
and supervised transformer steps in ``OOSPipeline``. If
|
|
100
|
+
False, these conditions only emit a ``UserWarning``.
|
|
101
|
+
"""
|
|
102
|
+
self.estimator = estimator
|
|
103
|
+
self.id_col = id_col
|
|
104
|
+
self.cv = cv
|
|
105
|
+
self.random_state = random_state
|
|
106
|
+
self.stratified = stratified
|
|
107
|
+
self.verbose = verbose
|
|
108
|
+
self.scoring = scoring
|
|
109
|
+
self.group_col = group_col
|
|
110
|
+
self.strict = strict
|
|
111
|
+
|
|
112
|
+
def __sklearn_is_fitted__(self) -> bool:
|
|
113
|
+
return hasattr(self, "general_model_")
|
|
114
|
+
|
|
115
|
+
def _integrity_issue(self, message: str) -> None:
|
|
116
|
+
"""Raise (strict) or warn about a broken out-of-sample guarantee."""
|
|
117
|
+
if self.strict:
|
|
118
|
+
raise ValueError(message + " Pass strict=False to downgrade this to a warning.")
|
|
119
|
+
warnings.warn(message, UserWarning, stacklevel=4)
|
|
120
|
+
|
|
121
|
+
def _get_splitter(
|
|
122
|
+
self,
|
|
123
|
+
X: pd.DataFrame,
|
|
124
|
+
y: np.ndarray,
|
|
125
|
+
ids: np.ndarray,
|
|
126
|
+
groups: np.ndarray | None,
|
|
127
|
+
) -> tuple[Any, np.ndarray | None]:
|
|
128
|
+
"""Determine the CV splitter strategy.
|
|
129
|
+
|
|
130
|
+
Priority:
|
|
131
|
+
1. Explicit ``group_col`` → GroupKFold or StratifiedGroupKFold
|
|
132
|
+
2. Duplicate IDs auto-detected → GroupKFold (with warning)
|
|
133
|
+
3. Classification + stratified → StratifiedKFold
|
|
134
|
+
4. Default → KFold
|
|
135
|
+
|
|
136
|
+
Args:
|
|
137
|
+
X: Feature matrix.
|
|
138
|
+
y: Target array.
|
|
139
|
+
ids: 1-D array of sample identifiers.
|
|
140
|
+
groups: 1-D array of group labels (from group_col), or None.
|
|
141
|
+
|
|
142
|
+
Returns:
|
|
143
|
+
A tuple of ``(splitter, groups_array)`` where groups_array is
|
|
144
|
+
the array to pass to ``splitter.split(..., groups=)``, or None.
|
|
145
|
+
"""
|
|
146
|
+
if not isinstance(self.cv, int):
|
|
147
|
+
# Custom splitter — use as-is, pass groups if available
|
|
148
|
+
return self.cv, groups
|
|
149
|
+
|
|
150
|
+
use_groups = groups is not None
|
|
151
|
+
n_splits = self.cv
|
|
152
|
+
|
|
153
|
+
def _stratifiable() -> bool:
|
|
154
|
+
# Stratify only for classifiers with a modest number of 1-D labels
|
|
155
|
+
if not (self.stratified and is_classifier(self.estimator)) or y.ndim > 1:
|
|
156
|
+
return False
|
|
157
|
+
return 2 <= len(np.unique(y)) <= 100
|
|
158
|
+
|
|
159
|
+
# Explicit group_col → use group-aware splitter
|
|
160
|
+
if use_groups:
|
|
161
|
+
if _stratifiable():
|
|
162
|
+
return StratifiedGroupKFold(
|
|
163
|
+
n_splits=n_splits, shuffle=True, random_state=self.random_state
|
|
164
|
+
), groups
|
|
165
|
+
return _group_kfold(n_splits, self.random_state), groups
|
|
166
|
+
|
|
167
|
+
# Auto-detect duplicate IDs → GroupKFold
|
|
168
|
+
if len(ids) != len(np.unique(ids)):
|
|
169
|
+
warnings.warn(
|
|
170
|
+
"Duplicate IDs detected. Using GroupKFold to keep duplicates "
|
|
171
|
+
"in the same fold. Set group_col explicitly to suppress this "
|
|
172
|
+
"warning and enable StratifiedGroupKFold.",
|
|
173
|
+
UserWarning,
|
|
174
|
+
stacklevel=3,
|
|
175
|
+
)
|
|
176
|
+
return _group_kfold(n_splits, self.random_state), ids
|
|
177
|
+
|
|
178
|
+
# No groups — standard splitting
|
|
179
|
+
if _stratifiable():
|
|
180
|
+
return StratifiedKFold(
|
|
181
|
+
n_splits=n_splits, shuffle=True, random_state=self.random_state
|
|
182
|
+
), None
|
|
183
|
+
return KFold(n_splits=n_splits, shuffle=True, random_state=self.random_state), None
|
|
184
|
+
|
|
185
|
+
def _fit_impl(
|
|
186
|
+
self,
|
|
187
|
+
X: Any,
|
|
188
|
+
y: Any,
|
|
189
|
+
*,
|
|
190
|
+
ids: Any | None = None,
|
|
191
|
+
_fold_features: list[tuple[Any, Any]] | None = None,
|
|
192
|
+
**fit_params: Any,
|
|
193
|
+
):
|
|
194
|
+
"""Shared fit implementation for classifier and regressor.
|
|
195
|
+
|
|
196
|
+
Args:
|
|
197
|
+
X: Training data, optionally containing the ID column.
|
|
198
|
+
y: Target values.
|
|
199
|
+
ids: Explicit ID array when X does not contain an ID column.
|
|
200
|
+
_fold_features: Private hook for nested cross-fitting
|
|
201
|
+
(``OOSPipeline``): one ``(X_train, X_oos)`` pair of feature
|
|
202
|
+
frames per fold, in the row order of the fold's
|
|
203
|
+
``train_idx`` / ``oos_idx``. Fold model ``k`` is trained on
|
|
204
|
+
and scores these instead of slices of ``X``; the general
|
|
205
|
+
model is still trained on ``X``.
|
|
206
|
+
**fit_params: Passed through to the underlying estimator's fit.
|
|
207
|
+
|
|
208
|
+
Returns:
|
|
209
|
+
self
|
|
210
|
+
"""
|
|
211
|
+
reset_fitted_state(self)
|
|
212
|
+
# Validate and extract IDs
|
|
213
|
+
X_features, id_array, _ = extract_ids_and_features(X, self.id_col, ids=ids)
|
|
214
|
+
y_arr = validate_target(y)
|
|
215
|
+
|
|
216
|
+
if len(X_features) != len(y_arr):
|
|
217
|
+
raise ValueError(
|
|
218
|
+
f"X and y must have the same length, got {len(X_features)} and {len(y_arr)}"
|
|
219
|
+
)
|
|
220
|
+
self._id_kind_ = self._validated_id_kind(id_array)
|
|
221
|
+
|
|
222
|
+
# Extract group column if specified
|
|
223
|
+
groups = None
|
|
224
|
+
if self.group_col is not None:
|
|
225
|
+
if isinstance(X_features, pd.DataFrame) and self.group_col in X_features.columns:
|
|
226
|
+
groups = X_features[self.group_col].to_numpy()
|
|
227
|
+
X_features = X_features.drop(columns=[self.group_col])
|
|
228
|
+
elif isinstance(X, pd.DataFrame) and self.group_col in X.columns:
|
|
229
|
+
groups = X[self.group_col].to_numpy()
|
|
230
|
+
else:
|
|
231
|
+
raise ValueError(
|
|
232
|
+
f"group_col '{self.group_col}' not found in X. "
|
|
233
|
+
"group_col must be a column name in the input DataFrame."
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
# Store feature metadata
|
|
237
|
+
self.n_features_in_ = X_features.shape[1]
|
|
238
|
+
feature_names = string_feature_names(X_features)
|
|
239
|
+
if feature_names is not None:
|
|
240
|
+
self.feature_names_in_ = feature_names
|
|
241
|
+
|
|
242
|
+
# Determine splitter
|
|
243
|
+
splitter, split_groups = self._get_splitter(X_features, y_arr, id_array, groups)
|
|
244
|
+
self.cv_strategy_ = splitter
|
|
245
|
+
|
|
246
|
+
# Determine task type
|
|
247
|
+
is_clf = is_classifier(self.estimator)
|
|
248
|
+
|
|
249
|
+
# Set classes_ for classifiers
|
|
250
|
+
if is_clf:
|
|
251
|
+
self.classes_ = np.unique(y_arr)
|
|
252
|
+
|
|
253
|
+
# Resolve scoring once for all folds
|
|
254
|
+
resolved_scoring = resolve_scoring(self.scoring, is_clf, strict=self.strict)
|
|
255
|
+
# Full label set for fold metrics (single-output classification only)
|
|
256
|
+
metric_classes = self.classes_ if is_clf and y_arr.ndim == 1 else None
|
|
257
|
+
|
|
258
|
+
# X_features is always a DataFrame (extract_ids_and_features converts);
|
|
259
|
+
# slicing it directly preserves feature names and avoids a full copy
|
|
260
|
+
n_samples = len(X_features)
|
|
261
|
+
|
|
262
|
+
# Prepare iteration
|
|
263
|
+
if split_groups is not None:
|
|
264
|
+
iterator = splitter.split(X_features, y_arr, groups=split_groups)
|
|
265
|
+
else:
|
|
266
|
+
iterator = splitter.split(X_features, y_arr)
|
|
267
|
+
|
|
268
|
+
if self.verbose >= 1:
|
|
269
|
+
try:
|
|
270
|
+
from tqdm import tqdm
|
|
271
|
+
|
|
272
|
+
total = splitter.get_n_splits(X_features, y_arr)
|
|
273
|
+
iterator = tqdm(iterator, total=total, desc="Training folds")
|
|
274
|
+
except ImportError:
|
|
275
|
+
pass
|
|
276
|
+
|
|
277
|
+
# Train fold models
|
|
278
|
+
self.models_ = []
|
|
279
|
+
self.id_to_fold_ = {}
|
|
280
|
+
self.oos_ids_ = []
|
|
281
|
+
self.oos_index_ = []
|
|
282
|
+
self.train_ids_ = []
|
|
283
|
+
|
|
284
|
+
per_fold_metrics: list[dict[str, Any]] = []
|
|
285
|
+
all_true: list[np.ndarray] = []
|
|
286
|
+
all_pred: list[np.ndarray] = []
|
|
287
|
+
all_prob: list[np.ndarray] = []
|
|
288
|
+
train_indices: list[np.ndarray] = []
|
|
289
|
+
|
|
290
|
+
for fold, (train_idx, oos_idx) in enumerate(iterator):
|
|
291
|
+
train_indices.append(np.asarray(train_idx))
|
|
292
|
+
model = clone(self.estimator)
|
|
293
|
+
if _fold_features is not None:
|
|
294
|
+
# Nested cross-fitting: fold-specific features, labelled like X
|
|
295
|
+
X_train, X_oos = (
|
|
296
|
+
pd.DataFrame(np.asarray(f), columns=X_features.columns)
|
|
297
|
+
for f in _fold_features[fold]
|
|
298
|
+
)
|
|
299
|
+
else:
|
|
300
|
+
# Use DataFrame slicing to preserve feature names for estimators that care
|
|
301
|
+
X_train = X_features.iloc[train_idx]
|
|
302
|
+
X_oos = X_features.iloc[oos_idx]
|
|
303
|
+
# Per-sample fit params (e.g. sample_weight) are sliced to the fold
|
|
304
|
+
fold_fit_params = slice_fit_params(fit_params, n_samples, train_idx)
|
|
305
|
+
model.fit(X_train, y_arr[train_idx], **fold_fit_params)
|
|
306
|
+
self.models_.append(model)
|
|
307
|
+
|
|
308
|
+
fold_train_ids = id_array[train_idx]
|
|
309
|
+
fold_oos_ids = id_array[oos_idx]
|
|
310
|
+
self.train_ids_.append(fold_train_ids)
|
|
311
|
+
self.oos_ids_.append(fold_oos_ids)
|
|
312
|
+
self.oos_index_.append(oos_idx)
|
|
313
|
+
|
|
314
|
+
self.id_to_fold_.update(dict.fromkeys(fold_oos_ids.tolist(), fold))
|
|
315
|
+
|
|
316
|
+
# OOS predictions for metrics (use same format model was trained on)
|
|
317
|
+
oos_y = y_arr[oos_idx]
|
|
318
|
+
preds = model.predict(X_oos)
|
|
319
|
+
|
|
320
|
+
prob_preds = None
|
|
321
|
+
if is_clf and hasattr(model, "predict_proba"):
|
|
322
|
+
prob_preds = model.predict_proba(X_oos)
|
|
323
|
+
# Fold models trained on splits missing a rare class output
|
|
324
|
+
# fewer columns — align to the full class set
|
|
325
|
+
if not isinstance(prob_preds, list) and hasattr(model, "classes_"):
|
|
326
|
+
prob_preds = align_proba(prob_preds, model.classes_, self.classes_)
|
|
327
|
+
|
|
328
|
+
per_fold_metrics.append(
|
|
329
|
+
compute_fold_metrics(
|
|
330
|
+
oos_y, preds, prob_preds, is_clf, resolved_scoring, classes=metric_classes
|
|
331
|
+
)
|
|
332
|
+
)
|
|
333
|
+
all_true.append(oos_y)
|
|
334
|
+
all_pred.append(preds)
|
|
335
|
+
if prob_preds is not None:
|
|
336
|
+
all_prob.append(prob_preds)
|
|
337
|
+
|
|
338
|
+
oos_complete = self._check_oos_integrity(n_samples)
|
|
339
|
+
record_refresh_state(
|
|
340
|
+
self,
|
|
341
|
+
row_fingerprints(X_features, id_array, groups, y_arr, fit_params),
|
|
342
|
+
train_indices,
|
|
343
|
+
n_samples,
|
|
344
|
+
groups,
|
|
345
|
+
oos_complete,
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
# Warn about small folds (affects calibration/interval reliability)
|
|
349
|
+
_MIN_FOLD_SIZE = 20
|
|
350
|
+
fold_sizes = [len(oos) for oos in self.oos_ids_]
|
|
351
|
+
small_folds = [i for i, s in enumerate(fold_sizes) if s < _MIN_FOLD_SIZE]
|
|
352
|
+
if small_folds:
|
|
353
|
+
warnings.warn(
|
|
354
|
+
f"Folds {small_folds} have fewer than {_MIN_FOLD_SIZE} OOS samples "
|
|
355
|
+
f"(sizes: {[fold_sizes[i] for i in small_folds]}). "
|
|
356
|
+
"Calibration and conformal intervals may be unreliable for these folds. "
|
|
357
|
+
"Consider using fewer folds (lower cv) or cross-calibration mode.",
|
|
358
|
+
UserWarning,
|
|
359
|
+
stacklevel=2,
|
|
360
|
+
)
|
|
361
|
+
|
|
362
|
+
# Train general model on all data
|
|
363
|
+
self.general_model_ = clone(self.estimator)
|
|
364
|
+
self.general_model_.fit(X_features, y_arr, **fit_params)
|
|
365
|
+
|
|
366
|
+
# Compute overall metrics
|
|
367
|
+
overall_metrics: dict[str, float] = {}
|
|
368
|
+
if all_true:
|
|
369
|
+
y_true_all = np.concatenate(all_true)
|
|
370
|
+
y_pred_all = np.concatenate(all_pred)
|
|
371
|
+
y_prob_all = np.vstack(all_prob) if all_prob else None
|
|
372
|
+
overall_metrics = compute_fold_metrics(
|
|
373
|
+
y_true_all, y_pred_all, y_prob_all, is_clf, resolved_scoring, classes=metric_classes
|
|
374
|
+
)
|
|
375
|
+
|
|
376
|
+
self.cv_results_ = {
|
|
377
|
+
"overall": overall_metrics,
|
|
378
|
+
"folds": per_fold_metrics,
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
# Store raw fold results for lazy OOS prediction retrieval
|
|
382
|
+
self._oos_raw_preds_ = all_pred
|
|
383
|
+
self._oos_raw_probs_ = all_prob if all_prob else None
|
|
384
|
+
|
|
385
|
+
return self
|
|
386
|
+
|
|
387
|
+
def _check_oos_integrity(self, n_samples: int) -> bool:
|
|
388
|
+
"""Warn when the fold structure cannot guarantee out-of-sample routing.
|
|
389
|
+
|
|
390
|
+
The built-in integer-``cv`` splitters always hold every row out
|
|
391
|
+
exactly once and keep duplicate IDs together, so the check only runs
|
|
392
|
+
when a custom splitter is used or some IDs are duplicated or never
|
|
393
|
+
held out. Two failure modes are detected:
|
|
394
|
+
|
|
395
|
+
- Rows never held out (e.g. ``TimeSeriesSplit``): their IDs are
|
|
396
|
+
unknown to ``id_to_fold_``, so ``predict`` routes them to the
|
|
397
|
+
general model, which was trained on them.
|
|
398
|
+
- IDs routed to a fold model that trained on a row with the same ID
|
|
399
|
+
(duplicate IDs split across folds by a splitter that ignores
|
|
400
|
+
them): their predictions are in-sample.
|
|
401
|
+
|
|
402
|
+
Args:
|
|
403
|
+
n_samples: Number of training rows.
|
|
404
|
+
|
|
405
|
+
Returns:
|
|
406
|
+
True if no issue was found (always the case under ``strict=True``,
|
|
407
|
+
which raises instead).
|
|
408
|
+
"""
|
|
409
|
+
if isinstance(self.cv, int) and len(self.id_to_fold_) == n_samples:
|
|
410
|
+
return True
|
|
411
|
+
clean = True
|
|
412
|
+
|
|
413
|
+
n_held_out = len(np.unique(np.concatenate(self.oos_index_))) if self.oos_index_ else 0
|
|
414
|
+
if n_held_out < n_samples:
|
|
415
|
+
clean = False
|
|
416
|
+
self._integrity_issue(
|
|
417
|
+
f"{n_samples - n_held_out} of {n_samples} training rows are never held "
|
|
418
|
+
"out by the CV splitter. predict() routes their IDs to the general "
|
|
419
|
+
"model, which was trained on them, so those predictions are in-sample."
|
|
420
|
+
)
|
|
421
|
+
|
|
422
|
+
ids_by_fold: dict[int, list[Any]] = {}
|
|
423
|
+
for id_, fold in self.id_to_fold_.items():
|
|
424
|
+
ids_by_fold.setdefault(fold, []).append(id_)
|
|
425
|
+
n_leaky = 0
|
|
426
|
+
for fold, routed_ids in ids_by_fold.items():
|
|
427
|
+
train_set = set(self.train_ids_[fold].tolist())
|
|
428
|
+
n_leaky += sum(id_ in train_set for id_ in routed_ids)
|
|
429
|
+
if n_leaky:
|
|
430
|
+
clean = False
|
|
431
|
+
self._integrity_issue(
|
|
432
|
+
f"{n_leaky} IDs are routed to a fold model that was trained on a row "
|
|
433
|
+
"with the same ID: the CV splitter placed duplicate IDs in different "
|
|
434
|
+
"folds. Their predictions are not out-of-sample. Use group_col, an "
|
|
435
|
+
"integer cv (duplicate IDs are then grouped automatically), or a "
|
|
436
|
+
"group-aware splitter."
|
|
437
|
+
)
|
|
438
|
+
return clean
|
|
439
|
+
|
|
440
|
+
def _refresh_outputs(
|
|
441
|
+
self, X_features: pd.DataFrame, y_arr: np.ndarray | None, fold_rows: list[np.ndarray]
|
|
442
|
+
) -> None:
|
|
443
|
+
"""Recompute ``cv_results_`` and the stored OOS predictions after ``refresh``.
|
|
444
|
+
|
|
445
|
+
Every row is scored by its routed fold model (inference only).
|
|
446
|
+
"""
|
|
447
|
+
assert y_arr is not None
|
|
448
|
+
is_clf = is_classifier(self.estimator)
|
|
449
|
+
resolved_scoring = resolve_scoring(self.scoring, is_clf, strict=self.strict)
|
|
450
|
+
metric_classes = self.classes_ if is_clf and y_arr.ndim == 1 else None
|
|
451
|
+
per_fold: list[dict[str, Any]] = []
|
|
452
|
+
all_true, all_pred, all_prob = [], [], []
|
|
453
|
+
for model, rows in zip(self.models_, fold_rows, strict=True):
|
|
454
|
+
if len(rows) == 0:
|
|
455
|
+
per_fold.append({})
|
|
456
|
+
all_pred.append(np.empty((0, *y_arr.shape[1:]), dtype=y_arr.dtype))
|
|
457
|
+
continue
|
|
458
|
+
X_oos = X_features.iloc[rows]
|
|
459
|
+
preds = model.predict(X_oos)
|
|
460
|
+
prob = None
|
|
461
|
+
if is_clf and hasattr(model, "predict_proba"):
|
|
462
|
+
prob = model.predict_proba(X_oos)
|
|
463
|
+
if not isinstance(prob, list) and hasattr(model, "classes_"):
|
|
464
|
+
prob = align_proba(prob, model.classes_, self.classes_)
|
|
465
|
+
per_fold.append(
|
|
466
|
+
compute_fold_metrics(
|
|
467
|
+
y_arr[rows], preds, prob, is_clf, resolved_scoring, classes=metric_classes
|
|
468
|
+
)
|
|
469
|
+
)
|
|
470
|
+
all_true.append(y_arr[rows])
|
|
471
|
+
all_pred.append(preds)
|
|
472
|
+
if prob is not None:
|
|
473
|
+
all_prob.append(prob)
|
|
474
|
+
overall: dict[str, float] = {}
|
|
475
|
+
if all_true:
|
|
476
|
+
overall = compute_fold_metrics(
|
|
477
|
+
np.concatenate(all_true),
|
|
478
|
+
np.concatenate([p for p in all_pred if len(p)]),
|
|
479
|
+
np.vstack(all_prob) if all_prob else None,
|
|
480
|
+
is_clf,
|
|
481
|
+
resolved_scoring,
|
|
482
|
+
classes=metric_classes,
|
|
483
|
+
)
|
|
484
|
+
self.cv_results_ = {"overall": overall, "folds": per_fold}
|
|
485
|
+
self._oos_raw_preds_ = all_pred
|
|
486
|
+
if all_prob and any(len(r) == 0 for r in fold_rows):
|
|
487
|
+
# Keep one block per fold so blocks line up with the fold indices
|
|
488
|
+
n_cls = all_prob[0].shape[1]
|
|
489
|
+
it = iter(all_prob)
|
|
490
|
+
all_prob = [np.empty((0, n_cls)) if len(rows) == 0 else next(it) for rows in fold_rows]
|
|
491
|
+
self._oos_raw_probs_ = all_prob if all_prob else None
|
|
492
|
+
|
|
493
|
+
def refresh(
|
|
494
|
+
self,
|
|
495
|
+
X: Any,
|
|
496
|
+
y: Any,
|
|
497
|
+
*,
|
|
498
|
+
ids: Any | None = None,
|
|
499
|
+
strategy: str = "append",
|
|
500
|
+
**fit_params: Any,
|
|
501
|
+
):
|
|
502
|
+
"""Add new rows and IDs without retraining every fold model.
|
|
503
|
+
|
|
504
|
+
``X``/``y`` must be the **full updated training set** (previous rows
|
|
505
|
+
plus new ones): the package does not cache training data, and the
|
|
506
|
+
models that are retrained need all of their training rows. IDs (or
|
|
507
|
+
groups, with ``group_col``) seen before keep their fold, so the
|
|
508
|
+
out-of-sample guarantee is preserved: no row is ever routed to a
|
|
509
|
+
model that trained on its ID or group.
|
|
510
|
+
|
|
511
|
+
Strategies:
|
|
512
|
+
|
|
513
|
+
- ``"append"`` (default, cheapest): new IDs form one new fold whose
|
|
514
|
+
model is the previous general model, which never saw them; only the
|
|
515
|
+
general model is retrained (once, on all rows). Existing fold
|
|
516
|
+
models are not updated with the new data.
|
|
517
|
+
- ``"assign"``: new IDs are placed in existing folds by a stable hash
|
|
518
|
+
of the ID (or group), identical in every process and independent of
|
|
519
|
+
``random_state``. Every fold model whose training rows changed is
|
|
520
|
+
retrained, plus the general model. Fold models whose training rows
|
|
521
|
+
are unchanged (detected via row fingerprints stored at ``fit``)
|
|
522
|
+
are kept.
|
|
523
|
+
|
|
524
|
+
A refresh with unchanged data is a no-op. ``cv_results_`` and
|
|
525
|
+
``get_oos_predictions()`` are recomputed on the refreshed data by
|
|
526
|
+
scoring every row with its routed fold model. Details of what
|
|
527
|
+
happened are stored in ``refresh_info_``.
|
|
528
|
+
|
|
529
|
+
Args:
|
|
530
|
+
X: Full updated training data, with the same feature columns as
|
|
531
|
+
``fit``.
|
|
532
|
+
y: Full updated target.
|
|
533
|
+
ids: Explicit ID array when X does not contain an ID column.
|
|
534
|
+
strategy: ``"append"`` or ``"assign"``.
|
|
535
|
+
**fit_params: Passed to the underlying estimator's ``fit`` (per-
|
|
536
|
+
sample arrays such as ``sample_weight`` are sliced per fold).
|
|
537
|
+
|
|
538
|
+
Returns:
|
|
539
|
+
self
|
|
540
|
+
|
|
541
|
+
Raises:
|
|
542
|
+
ValueError: If the model cannot be refreshed safely (loaded from a
|
|
543
|
+
file written before refresh support, or fitted with a partial
|
|
544
|
+
or leaky custom splitter), the feature columns differ from
|
|
545
|
+
``fit``, or a known ID/group would have to change fold.
|
|
546
|
+
"""
|
|
547
|
+
return refresh_impl(self, X, y, ids=ids, strategy=strategy, fit_params=fit_params)
|
|
548
|
+
|
|
549
|
+
@staticmethod
|
|
550
|
+
def _validated_id_kind(id_array: np.ndarray) -> str:
|
|
551
|
+
"""Kind of the training IDs; mixed-type IDs cannot be routed reliably."""
|
|
552
|
+
kind = id_kind(id_array)
|
|
553
|
+
if kind == "mixed":
|
|
554
|
+
types = sorted({type(v).__name__ for v in id_array.tolist()})
|
|
555
|
+
raise ValueError(
|
|
556
|
+
f"IDs mix several types ({', '.join(types)}). Fold routing matches IDs "
|
|
557
|
+
"by value and type, so use a single ID type (e.g. convert all IDs to str)."
|
|
558
|
+
)
|
|
559
|
+
return kind
|
|
560
|
+
|
|
561
|
+
def _training_id_kind(self) -> str:
|
|
562
|
+
"""``id_kind`` of the training IDs (derived from id_to_fold_ for old artifacts)."""
|
|
563
|
+
if not hasattr(self, "_id_kind_"):
|
|
564
|
+
self._id_kind_ = id_kind(list(self.id_to_fold_.keys()))
|
|
565
|
+
return self._id_kind_
|
|
566
|
+
|
|
567
|
+
def _check_predict_ids(self, id_array: np.ndarray) -> None:
|
|
568
|
+
"""Raise (strict) or warn when prediction IDs cannot match training IDs."""
|
|
569
|
+
if self.id_to_fold_:
|
|
570
|
+
check_id_kind(self._training_id_kind(), id_array, strict=getattr(self, "strict", True))
|
|
571
|
+
|
|
572
|
+
def _extract_predict_features(self, X: Any, ids: Any | None = None):
|
|
573
|
+
"""Extract features and IDs for prediction, stripping group_col."""
|
|
574
|
+
X_features, id_array, _ = extract_ids_and_features(X, self.id_col, ids=ids)
|
|
575
|
+
self._check_predict_ids(id_array)
|
|
576
|
+
if (
|
|
577
|
+
self.group_col is not None
|
|
578
|
+
and isinstance(X_features, pd.DataFrame)
|
|
579
|
+
and self.group_col in X_features.columns
|
|
580
|
+
):
|
|
581
|
+
X_features = X_features.drop(columns=[self.group_col])
|
|
582
|
+
return X_features, id_array
|
|
583
|
+
|
|
584
|
+
def _predict_impl(self, X: Any, *, ids: Any | None = None) -> np.ndarray:
|
|
585
|
+
"""Shared predict implementation."""
|
|
586
|
+
check_is_fitted(self)
|
|
587
|
+
X_features, id_array = self._extract_predict_features(X, ids)
|
|
588
|
+
routing: dict[str, Any] = {}
|
|
589
|
+
result = dispatch_predict(
|
|
590
|
+
self.models_,
|
|
591
|
+
self.general_model_,
|
|
592
|
+
X_features,
|
|
593
|
+
self.id_to_fold_,
|
|
594
|
+
id_array,
|
|
595
|
+
"predict",
|
|
596
|
+
routing=routing,
|
|
597
|
+
)
|
|
598
|
+
self.last_routing_ = routing
|
|
599
|
+
return result
|
|
600
|
+
|
|
601
|
+
def _predict_proba_impl(self, X: Any, *, ids: Any | None = None) -> np.ndarray:
|
|
602
|
+
"""Shared predict_proba implementation."""
|
|
603
|
+
check_is_fitted(self)
|
|
604
|
+
if not hasattr(self.general_model_, "predict_proba"):
|
|
605
|
+
raise AttributeError(
|
|
606
|
+
f"The underlying estimator {type(self.estimator).__name__} "
|
|
607
|
+
"does not implement predict_proba"
|
|
608
|
+
)
|
|
609
|
+
X_features, id_array = self._extract_predict_features(X, ids)
|
|
610
|
+
routing: dict[str, Any] = {}
|
|
611
|
+
result = dispatch_predict(
|
|
612
|
+
self.models_,
|
|
613
|
+
self.general_model_,
|
|
614
|
+
X_features,
|
|
615
|
+
self.id_to_fold_,
|
|
616
|
+
id_array,
|
|
617
|
+
"predict_proba",
|
|
618
|
+
classes=getattr(self, "classes_", None),
|
|
619
|
+
routing=routing,
|
|
620
|
+
)
|
|
621
|
+
self.last_routing_ = routing
|
|
622
|
+
return result
|
|
623
|
+
|
|
624
|
+
def get_feature_names_out(self, input_features: Any = None) -> np.ndarray:
|
|
625
|
+
"""Return feature names seen during ``fit``.
|
|
626
|
+
|
|
627
|
+
Like scikit-learn, models fitted on data without string column
|
|
628
|
+
names (e.g. a numpy array) get generated names ``x0, x1, ...``.
|
|
629
|
+
|
|
630
|
+
Args:
|
|
631
|
+
input_features: Ignored. Present for sklearn API compatibility.
|
|
632
|
+
|
|
633
|
+
Returns:
|
|
634
|
+
Object array of feature name strings.
|
|
635
|
+
"""
|
|
636
|
+
check_is_fitted(self)
|
|
637
|
+
if hasattr(self, "feature_names_in_"):
|
|
638
|
+
return self.feature_names_in_
|
|
639
|
+
return np.asarray([f"x{i}" for i in range(self.n_features_in_)], dtype=object)
|
|
640
|
+
|
|
641
|
+
def get_fold_info(self, fold_idx: int) -> tuple[Any, np.ndarray, np.ndarray]:
|
|
642
|
+
"""Return model, OOS IDs, and OOS indices for a specific fold.
|
|
643
|
+
|
|
644
|
+
Args:
|
|
645
|
+
fold_idx: Zero-based fold index.
|
|
646
|
+
|
|
647
|
+
Returns:
|
|
648
|
+
A tuple of ``(fold_model, oos_ids, oos_indices)``.
|
|
649
|
+
|
|
650
|
+
Raises:
|
|
651
|
+
IndexError: If fold_idx is out of range.
|
|
652
|
+
"""
|
|
653
|
+
check_is_fitted(self)
|
|
654
|
+
if fold_idx < 0 or fold_idx >= len(self.models_):
|
|
655
|
+
raise IndexError(f"fold_idx {fold_idx} out of range for {len(self.models_)} folds")
|
|
656
|
+
return (
|
|
657
|
+
self.models_[fold_idx],
|
|
658
|
+
self.oos_ids_[fold_idx],
|
|
659
|
+
self.oos_index_[fold_idx],
|
|
660
|
+
)
|
|
661
|
+
|
|
662
|
+
# ------------------------------------------------------------------
|
|
663
|
+
# Passthrough properties for common estimator attributes
|
|
664
|
+
# ------------------------------------------------------------------
|
|
665
|
+
|
|
666
|
+
@property
|
|
667
|
+
def feature_importances_(self) -> np.ndarray:
|
|
668
|
+
"""Feature importances from the general model (tree-based estimators)."""
|
|
669
|
+
check_is_fitted(self)
|
|
670
|
+
return self.general_model_.feature_importances_
|
|
671
|
+
|
|
672
|
+
@property
|
|
673
|
+
def coef_(self) -> np.ndarray:
|
|
674
|
+
"""Coefficients from the general model (linear estimators)."""
|
|
675
|
+
check_is_fitted(self)
|
|
676
|
+
return self.general_model_.coef_
|
|
677
|
+
|
|
678
|
+
@property
|
|
679
|
+
def intercept_(self) -> np.ndarray:
|
|
680
|
+
"""Intercept from the general model (linear estimators)."""
|
|
681
|
+
check_is_fitted(self)
|
|
682
|
+
return self.general_model_.intercept_
|
|
683
|
+
|
|
684
|
+
# ------------------------------------------------------------------
|
|
685
|
+
# Additional sklearn-compatible methods
|
|
686
|
+
# ------------------------------------------------------------------
|
|
687
|
+
|
|
688
|
+
def _decision_function_impl(self, X: Any, *, ids: Any | None = None) -> np.ndarray:
|
|
689
|
+
"""Shared decision_function for SVMs and linear models."""
|
|
690
|
+
check_is_fitted(self)
|
|
691
|
+
if not hasattr(self.general_model_, "decision_function"):
|
|
692
|
+
raise AttributeError(
|
|
693
|
+
f"The underlying estimator {type(self.estimator).__name__} "
|
|
694
|
+
"does not implement decision_function"
|
|
695
|
+
)
|
|
696
|
+
X_features, id_array = self._extract_predict_features(X, ids)
|
|
697
|
+
routing: dict[str, Any] = {}
|
|
698
|
+
result = dispatch_predict(
|
|
699
|
+
self.models_,
|
|
700
|
+
self.general_model_,
|
|
701
|
+
X_features,
|
|
702
|
+
self.id_to_fold_,
|
|
703
|
+
id_array,
|
|
704
|
+
"decision_function",
|
|
705
|
+
routing=routing,
|
|
706
|
+
)
|
|
707
|
+
self.last_routing_ = routing
|
|
708
|
+
return result
|
|
709
|
+
|
|
710
|
+
def get_oos_predictions(self) -> dict[str, np.ndarray]:
|
|
711
|
+
"""Return the out-of-sample predictions generated during ``fit()``.
|
|
712
|
+
|
|
713
|
+
These are the actual out-of-sample predictions — each sample was predicted
|
|
714
|
+
by the fold model that never saw it. Only available immediately after
|
|
715
|
+
``fit()``; not persisted across ``save_model``/``load_model``.
|
|
716
|
+
|
|
717
|
+
Returns:
|
|
718
|
+
Dict with keys ``"ids"``, ``"predictions"``, ``"fold_indices"``,
|
|
719
|
+
and optionally ``"probabilities"``.
|
|
720
|
+
|
|
721
|
+
Raises:
|
|
722
|
+
ValueError: If called on a loaded model (predictions not persisted).
|
|
723
|
+
"""
|
|
724
|
+
check_is_fitted(self)
|
|
725
|
+
if not hasattr(self, "_oos_raw_preds_"):
|
|
726
|
+
raise ValueError(
|
|
727
|
+
"OOS predictions are only available immediately after fit(). "
|
|
728
|
+
"They are not persisted across save/load."
|
|
729
|
+
)
|
|
730
|
+
fold_lengths = [len(self.oos_ids_[i]) for i in range(len(self.models_))]
|
|
731
|
+
result = {
|
|
732
|
+
"ids": np.concatenate(self.oos_ids_),
|
|
733
|
+
"predictions": np.concatenate(self._oos_raw_preds_),
|
|
734
|
+
"fold_indices": np.repeat(np.arange(len(self.models_)), fold_lengths),
|
|
735
|
+
}
|
|
736
|
+
if self._oos_raw_probs_ is not None:
|
|
737
|
+
result["probabilities"] = np.vstack(self._oos_raw_probs_)
|
|
738
|
+
return result
|
|
739
|
+
|
|
740
|
+
|
|
741
|
+
class OOSClassifier(ClassifierMixin, MetaEstimatorMixin, _OOSBase):
|
|
742
|
+
"""K-fold out-of-sample wrapper for classifiers.
|
|
743
|
+
|
|
744
|
+
Trains ``cv`` clones of the base estimator, ensures every record is
|
|
745
|
+
predicted by a model that never saw it during training, and falls back
|
|
746
|
+
to a general model for unseen IDs.
|
|
747
|
+
|
|
748
|
+
Parameters
|
|
749
|
+
----------
|
|
750
|
+
estimator : estimator
|
|
751
|
+
A scikit-learn-compatible classifier implementing ``fit`` and
|
|
752
|
+
``predict`` (and optionally ``predict_proba``).
|
|
753
|
+
id_col : str, int, or None, default="id"
|
|
754
|
+
Column name or index for unique identifiers. ``None`` uses row
|
|
755
|
+
indices as IDs.
|
|
756
|
+
cv : int or CV splitter, default=5
|
|
757
|
+
Number of folds or a scikit-learn splitter instance.
|
|
758
|
+
random_state : int or None, default=None
|
|
759
|
+
Seed for the internal fold splitter.
|
|
760
|
+
stratified : bool, default=True
|
|
761
|
+
Use :class:`~sklearn.model_selection.StratifiedKFold` for binary
|
|
762
|
+
classification when ``cv`` is an integer.
|
|
763
|
+
verbose : int, default=0
|
|
764
|
+
Verbosity level. 0 = silent, 1 = progress bar (requires tqdm).
|
|
765
|
+
scoring : str, list, dict, or None, default=None
|
|
766
|
+
Metrics to compute on OOS folds: a metric name, a list of names, or
|
|
767
|
+
a dict mapping display names to names or to metric functions
|
|
768
|
+
``f(y_true, y_pred) -> float``. ``None`` uses defaults.
|
|
769
|
+
group_col : str or None, default=None
|
|
770
|
+
Column for group-aware fold splitting.
|
|
771
|
+
strict : bool, default=True
|
|
772
|
+
Raise instead of warn when the out-of-sample guarantee would be
|
|
773
|
+
silently broken (leaky or partial CV splitter, prediction IDs of a
|
|
774
|
+
different type than the training IDs) or a metric name is unknown.
|
|
775
|
+
|
|
776
|
+
Attributes
|
|
777
|
+
----------
|
|
778
|
+
models_ : list
|
|
779
|
+
Trained fold models.
|
|
780
|
+
general_model_ : estimator
|
|
781
|
+
Model trained on all data.
|
|
782
|
+
id_to_fold_ : dict
|
|
783
|
+
Mapping from ID to fold index.
|
|
784
|
+
classes_ : ndarray
|
|
785
|
+
Unique class labels.
|
|
786
|
+
cv_results_ : dict
|
|
787
|
+
Overall and per-fold metrics.
|
|
788
|
+
group_to_fold_ : dict or None
|
|
789
|
+
Mapping from group to fold index (``group_col`` only); used by
|
|
790
|
+
``refresh``.
|
|
791
|
+
refresh_info_ : dict
|
|
792
|
+
Summary of the last ``refresh`` call (only after ``refresh``).
|
|
793
|
+
n_features_in_ : int
|
|
794
|
+
Number of features seen during ``fit``.
|
|
795
|
+
feature_names_in_ : ndarray
|
|
796
|
+
Feature names (only when ``X`` has string column names).
|
|
797
|
+
last_routing_ : dict
|
|
798
|
+
Routing statistics of the most recent ``predict`` /
|
|
799
|
+
``predict_proba`` / ``decision_function`` call: ``n_rows``,
|
|
800
|
+
``n_seen``, ``n_general`` (rows with unseen IDs, scored by the
|
|
801
|
+
general model), ``share_general`` and per-fold ``fold_counts``.
|
|
802
|
+
Set by prediction calls only; see also ``routing_report``.
|
|
803
|
+
"""
|
|
804
|
+
|
|
805
|
+
def fit(self, X: Any, y: Any, *, ids: Any | None = None, **fit_params: Any) -> OOSClassifier:
|
|
806
|
+
"""Fit the OOS classifier.
|
|
807
|
+
|
|
808
|
+
Parameters
|
|
809
|
+
----------
|
|
810
|
+
X : array-like of shape (n_samples, n_features)
|
|
811
|
+
Training data. May include the ID column.
|
|
812
|
+
y : array-like of shape (n_samples,)
|
|
813
|
+
Target values.
|
|
814
|
+
ids : array-like, optional
|
|
815
|
+
Explicit ID array when ``X`` does not contain an ID column.
|
|
816
|
+
**fit_params
|
|
817
|
+
Parameters passed to the underlying estimator's ``fit``.
|
|
818
|
+
|
|
819
|
+
Returns
|
|
820
|
+
-------
|
|
821
|
+
self
|
|
822
|
+
"""
|
|
823
|
+
return self._fit_impl(X, y, ids=ids, **fit_params)
|
|
824
|
+
|
|
825
|
+
def predict(self, X: Any, *, ids: Any | None = None) -> np.ndarray:
|
|
826
|
+
"""Predict class labels using the appropriate fold model.
|
|
827
|
+
|
|
828
|
+
Parameters
|
|
829
|
+
----------
|
|
830
|
+
X : array-like
|
|
831
|
+
Input data.
|
|
832
|
+
ids : array-like, optional
|
|
833
|
+
Explicit ID array.
|
|
834
|
+
|
|
835
|
+
Returns
|
|
836
|
+
-------
|
|
837
|
+
ndarray of shape (n_samples,)
|
|
838
|
+
"""
|
|
839
|
+
return self._predict_impl(X, ids=ids)
|
|
840
|
+
|
|
841
|
+
def predict_proba(self, X: Any, *, ids: Any | None = None) -> np.ndarray:
|
|
842
|
+
"""Predict class probabilities using the appropriate fold model.
|
|
843
|
+
|
|
844
|
+
Parameters
|
|
845
|
+
----------
|
|
846
|
+
X : array-like
|
|
847
|
+
Input data.
|
|
848
|
+
ids : array-like, optional
|
|
849
|
+
Explicit ID array.
|
|
850
|
+
|
|
851
|
+
Returns
|
|
852
|
+
-------
|
|
853
|
+
ndarray of shape (n_samples, n_classes)
|
|
854
|
+
"""
|
|
855
|
+
return self._predict_proba_impl(X, ids=ids)
|
|
856
|
+
|
|
857
|
+
def decision_function(self, X: Any, *, ids: Any | None = None) -> np.ndarray:
|
|
858
|
+
"""Compute decision function using the appropriate fold model.
|
|
859
|
+
|
|
860
|
+
Available for estimators like SVMs and linear classifiers.
|
|
861
|
+
"""
|
|
862
|
+
return self._decision_function_impl(X, ids=ids)
|
|
863
|
+
|
|
864
|
+
def score(self, X: Any, y: Any, *, ids: Any | None = None, sample_weight: Any = None) -> float:
|
|
865
|
+
"""Return mean accuracy on the given data using fold-aware predictions."""
|
|
866
|
+
from sklearn.metrics import accuracy_score
|
|
867
|
+
|
|
868
|
+
preds = self.predict(X, ids=ids)
|
|
869
|
+
return accuracy_score(y, preds, sample_weight=sample_weight)
|
|
870
|
+
|
|
871
|
+
|
|
872
|
+
class OOSRegressor(RegressorMixin, MetaEstimatorMixin, _OOSBase):
|
|
873
|
+
"""K-fold out-of-sample wrapper for regressors.
|
|
874
|
+
|
|
875
|
+
Trains ``cv`` clones of the base estimator, ensures every record is
|
|
876
|
+
predicted by a model that never saw it during training, and falls back
|
|
877
|
+
to a general model for unseen IDs.
|
|
878
|
+
|
|
879
|
+
Parameters
|
|
880
|
+
----------
|
|
881
|
+
estimator : estimator
|
|
882
|
+
A scikit-learn-compatible regressor implementing ``fit`` and
|
|
883
|
+
``predict``.
|
|
884
|
+
id_col : str, int, or None, default="id"
|
|
885
|
+
Column name or index for unique identifiers. ``None`` uses row
|
|
886
|
+
indices as IDs.
|
|
887
|
+
cv : int or CV splitter, default=5
|
|
888
|
+
Number of folds or a scikit-learn splitter instance.
|
|
889
|
+
random_state : int or None, default=None
|
|
890
|
+
Seed for the internal fold splitter.
|
|
891
|
+
stratified : bool, default=True
|
|
892
|
+
Ignored for regressors; accepted for API consistency.
|
|
893
|
+
verbose : int, default=0
|
|
894
|
+
Verbosity level. 0 = silent, 1 = progress bar (requires tqdm).
|
|
895
|
+
scoring : str, list, dict, or None, default=None
|
|
896
|
+
Metrics to compute on OOS folds. ``None`` uses defaults.
|
|
897
|
+
group_col : str or None, default=None
|
|
898
|
+
Column for group-aware fold splitting.
|
|
899
|
+
strict : bool, default=True
|
|
900
|
+
Raise instead of warn when the out-of-sample guarantee would be
|
|
901
|
+
silently broken (leaky or partial CV splitter, prediction IDs of a
|
|
902
|
+
different type than the training IDs) or a metric name is unknown.
|
|
903
|
+
|
|
904
|
+
Attributes
|
|
905
|
+
----------
|
|
906
|
+
models_ : list
|
|
907
|
+
Trained fold models.
|
|
908
|
+
general_model_ : estimator
|
|
909
|
+
Model trained on all data.
|
|
910
|
+
id_to_fold_ : dict
|
|
911
|
+
Mapping from ID to fold index.
|
|
912
|
+
cv_results_ : dict
|
|
913
|
+
Overall and per-fold metrics.
|
|
914
|
+
group_to_fold_ : dict or None
|
|
915
|
+
Mapping from group to fold index (``group_col`` only); used by
|
|
916
|
+
``refresh``.
|
|
917
|
+
refresh_info_ : dict
|
|
918
|
+
Summary of the last ``refresh`` call (only after ``refresh``).
|
|
919
|
+
n_features_in_ : int
|
|
920
|
+
Number of features seen during ``fit``.
|
|
921
|
+
feature_names_in_ : ndarray
|
|
922
|
+
Feature names (only when ``X`` has string column names).
|
|
923
|
+
last_routing_ : dict
|
|
924
|
+
Routing statistics of the most recent ``predict`` /
|
|
925
|
+
``predict_proba`` / ``decision_function`` call: ``n_rows``,
|
|
926
|
+
``n_seen``, ``n_general`` (rows with unseen IDs, scored by the
|
|
927
|
+
general model), ``share_general`` and per-fold ``fold_counts``.
|
|
928
|
+
Set by prediction calls only; see also ``routing_report``.
|
|
929
|
+
"""
|
|
930
|
+
|
|
931
|
+
def fit(self, X: Any, y: Any, *, ids: Any | None = None, **fit_params: Any) -> OOSRegressor:
|
|
932
|
+
"""Fit the OOS regressor.
|
|
933
|
+
|
|
934
|
+
Parameters
|
|
935
|
+
----------
|
|
936
|
+
X : array-like of shape (n_samples, n_features)
|
|
937
|
+
Training data. May include the ID column.
|
|
938
|
+
y : array-like of shape (n_samples,)
|
|
939
|
+
Target values.
|
|
940
|
+
ids : array-like, optional
|
|
941
|
+
Explicit ID array when ``X`` does not contain an ID column.
|
|
942
|
+
**fit_params
|
|
943
|
+
Parameters passed to the underlying estimator's ``fit``.
|
|
944
|
+
|
|
945
|
+
Returns
|
|
946
|
+
-------
|
|
947
|
+
self
|
|
948
|
+
"""
|
|
949
|
+
return self._fit_impl(X, y, ids=ids, **fit_params)
|
|
950
|
+
|
|
951
|
+
def predict(self, X: Any, *, ids: Any | None = None) -> np.ndarray:
|
|
952
|
+
"""Predict target values using the appropriate fold model.
|
|
953
|
+
|
|
954
|
+
Parameters
|
|
955
|
+
----------
|
|
956
|
+
X : array-like
|
|
957
|
+
Input data.
|
|
958
|
+
ids : array-like, optional
|
|
959
|
+
Explicit ID array.
|
|
960
|
+
|
|
961
|
+
Returns
|
|
962
|
+
-------
|
|
963
|
+
ndarray of shape (n_samples,)
|
|
964
|
+
"""
|
|
965
|
+
return self._predict_impl(X, ids=ids)
|
|
966
|
+
|
|
967
|
+
def decision_function(self, X: Any, *, ids: Any | None = None) -> np.ndarray:
|
|
968
|
+
"""Compute decision function using the appropriate fold model.
|
|
969
|
+
|
|
970
|
+
Available for estimators like SVMs and linear regressors with
|
|
971
|
+
``decision_function``.
|
|
972
|
+
"""
|
|
973
|
+
return self._decision_function_impl(X, ids=ids)
|
|
974
|
+
|
|
975
|
+
def score(self, X: Any, y: Any, *, ids: Any | None = None, sample_weight: Any = None) -> float:
|
|
976
|
+
"""Return R^2 score on the given data using fold-aware predictions."""
|
|
977
|
+
from sklearn.metrics import r2_score
|
|
978
|
+
|
|
979
|
+
preds = self.predict(X, ids=ids)
|
|
980
|
+
return r2_score(y, preds, sample_weight=sample_weight)
|
|
981
|
+
|
|
982
|
+
|
|
983
|
+
def OOSModel(estimator: Any, **kwargs: Any) -> OOSClassifier | OOSRegressor:
|
|
984
|
+
"""Factory that returns an OOSClassifier or OOSRegressor.
|
|
985
|
+
|
|
986
|
+
Inspects whether the estimator is a classifier (via ``sklearn.base.is_classifier``)
|
|
987
|
+
and returns the appropriate wrapper class.
|
|
988
|
+
|
|
989
|
+
Args:
|
|
990
|
+
estimator: A scikit-learn-compatible estimator.
|
|
991
|
+
**kwargs: Passed to the wrapper constructor (id_col, cv, etc.).
|
|
992
|
+
|
|
993
|
+
Returns:
|
|
994
|
+
An OOSClassifier if the estimator is a classifier, otherwise
|
|
995
|
+
an OOSRegressor.
|
|
996
|
+
"""
|
|
997
|
+
if is_classifier(estimator):
|
|
998
|
+
return OOSClassifier(estimator, **kwargs)
|
|
999
|
+
return OOSRegressor(estimator, **kwargs)
|