outofsample 1.1.0__tar.gz
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-1.1.0/LICENSE +28 -0
- outofsample-1.1.0/PKG-INFO +522 -0
- outofsample-1.1.0/README.md +474 -0
- outofsample-1.1.0/pyproject.toml +65 -0
- outofsample-1.1.0/setup.cfg +4 -0
- outofsample-1.1.0/src/outofsample/__init__.py +45 -0
- outofsample-1.1.0/src/outofsample/_calibration.py +1011 -0
- outofsample-1.1.0/src/outofsample/_compat.py +208 -0
- outofsample-1.1.0/src/outofsample/_conformal_classifier.py +418 -0
- outofsample-1.1.0/src/outofsample/_convenience.py +786 -0
- outofsample-1.1.0/src/outofsample/_cqr.py +440 -0
- outofsample-1.1.0/src/outofsample/_diagnostics.py +547 -0
- outofsample-1.1.0/src/outofsample/_estimators.py +999 -0
- outofsample-1.1.0/src/outofsample/_intervals.py +1147 -0
- outofsample-1.1.0/src/outofsample/_metrics.py +239 -0
- outofsample-1.1.0/src/outofsample/_persistence.py +1036 -0
- outofsample-1.1.0/src/outofsample/_prediction.py +162 -0
- outofsample-1.1.0/src/outofsample/_pu.py +951 -0
- outofsample-1.1.0/src/outofsample/_refresh.py +395 -0
- outofsample-1.1.0/src/outofsample/_stacking.py +598 -0
- outofsample-1.1.0/src/outofsample/_transformer.py +362 -0
- outofsample-1.1.0/src/outofsample/_validation.py +272 -0
- outofsample-1.1.0/src/outofsample/py.typed +0 -0
- outofsample-1.1.0/src/outofsample.egg-info/PKG-INFO +522 -0
- outofsample-1.1.0/src/outofsample.egg-info/SOURCES.txt +54 -0
- outofsample-1.1.0/src/outofsample.egg-info/dependency_links.txt +1 -0
- outofsample-1.1.0/src/outofsample.egg-info/requires.txt +33 -0
- outofsample-1.1.0/src/outofsample.egg-info/top_level.txt +1 -0
- outofsample-1.1.0/tests/test_calibration.py +638 -0
- outofsample-1.1.0/tests/test_classifier.py +445 -0
- outofsample-1.1.0/tests/test_conformal_classifier.py +221 -0
- outofsample-1.1.0/tests/test_convenience.py +124 -0
- outofsample-1.1.0/tests/test_cqr.py +215 -0
- outofsample-1.1.0/tests/test_diagnostics.py +424 -0
- outofsample-1.1.0/tests/test_examples.py +38 -0
- outofsample-1.1.0/tests/test_fold_integrity.py +173 -0
- outofsample-1.1.0/tests/test_group_col.py +216 -0
- outofsample-1.1.0/tests/test_id_types.py +133 -0
- outofsample-1.1.0/tests/test_intervals.py +922 -0
- outofsample-1.1.0/tests/test_metrics.py +266 -0
- outofsample-1.1.0/tests/test_multioutput.py +66 -0
- outofsample-1.1.0/tests/test_oos_invariants.py +232 -0
- outofsample-1.1.0/tests/test_persistence.py +570 -0
- outofsample-1.1.0/tests/test_persistence_skops.py +344 -0
- outofsample-1.1.0/tests/test_pipeline.py +367 -0
- outofsample-1.1.0/tests/test_pipeline_nested.py +353 -0
- outofsample-1.1.0/tests/test_pu.py +543 -0
- outofsample-1.1.0/tests/test_refit.py +103 -0
- outofsample-1.1.0/tests/test_refresh.py +443 -0
- outofsample-1.1.0/tests/test_regressor.py +77 -0
- outofsample-1.1.0/tests/test_shap.py +203 -0
- outofsample-1.1.0/tests/test_sklearn.py +235 -0
- outofsample-1.1.0/tests/test_stacking.py +395 -0
- outofsample-1.1.0/tests/test_transformer.py +212 -0
- outofsample-1.1.0/tests/test_validation.py +82 -0
- outofsample-1.1.0/tests/test_venn_abers.py +120 -0
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
BSD 3-Clause License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026, Caleb Dame
|
|
4
|
+
|
|
5
|
+
Redistribution and use in source and binary forms, with or without
|
|
6
|
+
modification, are permitted provided that the following conditions are met:
|
|
7
|
+
|
|
8
|
+
1. Redistributions of source code must retain the above copyright notice, this
|
|
9
|
+
list of conditions and the following disclaimer.
|
|
10
|
+
|
|
11
|
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
|
12
|
+
this list of conditions and the following disclaimer in the documentation
|
|
13
|
+
and/or other materials provided with the distribution.
|
|
14
|
+
|
|
15
|
+
3. Neither the name of the copyright holder nor the names of its
|
|
16
|
+
contributors may be used to endorse or promote products derived from
|
|
17
|
+
this software without specific prior written permission.
|
|
18
|
+
|
|
19
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
20
|
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
21
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
22
|
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
23
|
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
24
|
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
25
|
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
26
|
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
27
|
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
28
|
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@@ -0,0 +1,522 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: outofsample
|
|
3
|
+
Version: 1.1.0
|
|
4
|
+
Summary: Out-of-sample prediction wrappers for scikit-learn estimators
|
|
5
|
+
Author: Caleb Dame
|
|
6
|
+
License-Expression: BSD-3-Clause
|
|
7
|
+
Project-URL: Repository, https://github.com/calebdame/outofsample
|
|
8
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
9
|
+
Classifier: Intended Audience :: Developers
|
|
10
|
+
Classifier: Intended Audience :: Science/Research
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
17
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
18
|
+
Requires-Python: >=3.10
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
License-File: LICENSE
|
|
21
|
+
Requires-Dist: numpy>=1.23
|
|
22
|
+
Requires-Dist: pandas>=1.5
|
|
23
|
+
Requires-Dist: scikit-learn>=1.2
|
|
24
|
+
Requires-Dist: joblib>=1.2
|
|
25
|
+
Requires-Dist: scipy>=1.10
|
|
26
|
+
Provides-Extra: xgboost
|
|
27
|
+
Requires-Dist: xgboost; extra == "xgboost"
|
|
28
|
+
Provides-Extra: lightgbm
|
|
29
|
+
Requires-Dist: lightgbm; extra == "lightgbm"
|
|
30
|
+
Provides-Extra: catboost
|
|
31
|
+
Requires-Dist: catboost; extra == "catboost"
|
|
32
|
+
Provides-Extra: progress
|
|
33
|
+
Requires-Dist: tqdm; extra == "progress"
|
|
34
|
+
Provides-Extra: skops
|
|
35
|
+
Requires-Dist: skops>=0.10; extra == "skops"
|
|
36
|
+
Provides-Extra: all
|
|
37
|
+
Requires-Dist: xgboost; extra == "all"
|
|
38
|
+
Requires-Dist: lightgbm; extra == "all"
|
|
39
|
+
Requires-Dist: catboost; extra == "all"
|
|
40
|
+
Requires-Dist: tqdm; extra == "all"
|
|
41
|
+
Requires-Dist: skops>=0.10; extra == "all"
|
|
42
|
+
Provides-Extra: dev
|
|
43
|
+
Requires-Dist: pytest; extra == "dev"
|
|
44
|
+
Requires-Dist: pytest-cov; extra == "dev"
|
|
45
|
+
Requires-Dist: ruff; extra == "dev"
|
|
46
|
+
Requires-Dist: mypy; extra == "dev"
|
|
47
|
+
Dynamic: license-file
|
|
48
|
+
|
|
49
|
+
# outofsample
|
|
50
|
+
|
|
51
|
+
Scikit-learn-compatible wrappers that guarantee every prediction is made by a model that never saw the row during training. Designed for production tabular ML where the full dataset needs scores.
|
|
52
|
+
|
|
53
|
+
## Install
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
pip install outofsample
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Quick Start
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
from outofsample import OOSClassifier
|
|
63
|
+
from sklearn.ensemble import RandomForestClassifier
|
|
64
|
+
|
|
65
|
+
model = OOSClassifier(RandomForestClassifier(), id_col="id", cv=5)
|
|
66
|
+
model.fit(X, y)
|
|
67
|
+
|
|
68
|
+
predictions = model.predict(X) # every row scored by a model that never saw it
|
|
69
|
+
probabilities = model.predict_proba(X)
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## How It Works
|
|
73
|
+
|
|
74
|
+
Trains K fold models. Each row is predicted by the fold model that held it out. A general model trained on all data handles unseen IDs.
|
|
75
|
+
|
|
76
|
+
```
|
|
77
|
+
Training data Fold 0 model Fold 1 model General model
|
|
78
|
+
ID=1 ───────> held out ──────> trained on ───> trained on
|
|
79
|
+
ID=2 ───────> trained on ────> held out ──────> trained on
|
|
80
|
+
ID=3 ───────> trained on ────> trained on ───> trained on (new)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Works with any sklearn-compatible estimator: RandomForest, XGBoost, LightGBM, CatBoost, pipelines, etc.
|
|
84
|
+
|
|
85
|
+
## OOSPipeline
|
|
86
|
+
|
|
87
|
+
Chain transformers and estimators with guaranteed identical fold assignments across all steps:
|
|
88
|
+
|
|
89
|
+
```python
|
|
90
|
+
from outofsample import OOSPipeline
|
|
91
|
+
from sklearn.preprocessing import StandardScaler
|
|
92
|
+
|
|
93
|
+
pipe = OOSPipeline(
|
|
94
|
+
steps=[("scaler", StandardScaler()), ("clf", RandomForestClassifier())],
|
|
95
|
+
id_col="id", cv=5,
|
|
96
|
+
)
|
|
97
|
+
pipe.fit(X, y)
|
|
98
|
+
pipe.predict(X)
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Target-dependent steps such as `TargetEncoder` are cross-fitted in a nested way (`nested="auto"`, the default): for every outer fold, the chain from the first target-dependent step onwards is refitted on the other folds with inner cross-fitting, so no model on a training row's prediction path — transformer or final fold model — has seen that fold's targets, directly or through features. Unseen IDs use the regular general chain. Each nested step costs about `K * K` extra fits; pipelines without target-dependent steps are unaffected.
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
from sklearn.preprocessing import TargetEncoder
|
|
105
|
+
|
|
106
|
+
pipe = OOSPipeline(
|
|
107
|
+
steps=[("encoder", TargetEncoder()), ("clf", RandomForestClassifier())],
|
|
108
|
+
id_col="id", cv=5,
|
|
109
|
+
)
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
Transformers that accept `y=None` but use the target when given (e.g. `SelectKBest`) cannot be detected — pass `nested=True` to nest every step. Nesting needs a plain, `OOSClassifier` or `OOSRegressor` final step.
|
|
113
|
+
|
|
114
|
+
Supports `OOSCalibratedClassifier`, `OOSConformalRegressor`, `OOSConformalQuantileRegressor` and `OOSConformalClassifier` as final steps:
|
|
115
|
+
|
|
116
|
+
```python
|
|
117
|
+
from outofsample import OOSCalibratedClassifier, OOSConformalRegressor
|
|
118
|
+
|
|
119
|
+
# Calibrated probabilities
|
|
120
|
+
OOSPipeline(
|
|
121
|
+
steps=[("scaler", StandardScaler()),
|
|
122
|
+
("clf", OOSCalibratedClassifier(RandomForestClassifier(), calibration_method="auto"))],
|
|
123
|
+
id_col="id", cv=5,
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
# Prediction intervals
|
|
127
|
+
OOSPipeline(
|
|
128
|
+
steps=[("scaler", StandardScaler()),
|
|
129
|
+
("reg", OOSConformalRegressor(GradientBoostingRegressor(), alpha=0.1, normalize=True))],
|
|
130
|
+
id_col="id", cv=5,
|
|
131
|
+
)
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
## Probability Calibration
|
|
135
|
+
|
|
136
|
+
Cross-calibrated probability estimates. Both the base model and calibrator are fully out-of-sample:
|
|
137
|
+
|
|
138
|
+
```python
|
|
139
|
+
from outofsample import OOSCalibratedClassifier
|
|
140
|
+
|
|
141
|
+
model = OOSCalibratedClassifier(
|
|
142
|
+
RandomForestClassifier(),
|
|
143
|
+
id_col="id", cv=5,
|
|
144
|
+
calibration_method="auto", # picks best from platt/beta/isotonic/temperature
|
|
145
|
+
)
|
|
146
|
+
model.fit(X, y)
|
|
147
|
+
calibrated_probs = model.predict_proba(X)
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
| Method | Description |
|
|
151
|
+
|---|---|
|
|
152
|
+
| `"auto"` | Fits all methods, picks best by Brier score |
|
|
153
|
+
| `"platt"` (default) | Platt scaling (2 params) |
|
|
154
|
+
| `"beta"` | Beta calibration (3 params, captures asymmetry) |
|
|
155
|
+
| `"isotonic"` | Non-parametric, monotonic |
|
|
156
|
+
| `"temperature"` | Single scaling parameter |
|
|
157
|
+
|
|
158
|
+
Calibration strategies: `calibration_cv="cross"` (default), `int` for CV sub-folds, `"hybrid"` for blended.
|
|
159
|
+
|
|
160
|
+
## Conformal Prediction Intervals
|
|
161
|
+
|
|
162
|
+
Distribution-free prediction intervals with finite-sample coverage guarantees:
|
|
163
|
+
|
|
164
|
+
```python
|
|
165
|
+
from outofsample import OOSConformalRegressor
|
|
166
|
+
|
|
167
|
+
model = OOSConformalRegressor(
|
|
168
|
+
GradientBoostingRegressor(),
|
|
169
|
+
id_col="id", cv=5,
|
|
170
|
+
alpha=0.1, # 90% intervals
|
|
171
|
+
normalize=True, # adaptive widths (wider in uncertain regions)
|
|
172
|
+
)
|
|
173
|
+
model.fit(X, y)
|
|
174
|
+
|
|
175
|
+
intervals = model.predict_interval(X) # (n, 2): [lower, upper]
|
|
176
|
+
model.coverage(X, y) # verify ~90%
|
|
177
|
+
model.interval_width(X) # per-sample widths
|
|
178
|
+
|
|
179
|
+
model.predict_interval(X, alpha=0.05) # any alpha at predict time — no refit
|
|
180
|
+
|
|
181
|
+
model.coverage_curve(X, y) # coverage/width across alphas
|
|
182
|
+
model.conditional_coverage(X, y, by="feat1") # per-bin coverage diagnostics
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
| Parameter | Description |
|
|
186
|
+
|---|---|
|
|
187
|
+
| `alpha` | Miscoverage rate (0.1 = 90% intervals) |
|
|
188
|
+
| `normalize` | Adaptive widths via OOS residual prediction |
|
|
189
|
+
| `symmetric` | `False` for independent upper/lower scaling |
|
|
190
|
+
| `conformal_cv` | `"cross"`, `"hybrid"`, or int for sub-fold quantiles |
|
|
191
|
+
| `mondrian` | Bin-conditional coverage: `"difficulty"` or a feature column — coverage holds within each bin |
|
|
192
|
+
| `interval_method` | `"quantile"` (default) or `"cv_plus"` (Barber et al. CV+; jackknife+ via `cv="loo"`) |
|
|
193
|
+
|
|
194
|
+
## Conformalized Quantile Regression
|
|
195
|
+
|
|
196
|
+
Adaptive intervals from quantile models, with the conformal coverage guarantee (Romano et al., 2019). Lower (`alpha/2`) and upper (`1 - alpha/2`) quantile models are fitted out-of-sample on shared folds and their band is widened or shrunk by the conformal quantile of the OOS scores `max(q_lo - y, y - q_hi)`:
|
|
197
|
+
|
|
198
|
+
```python
|
|
199
|
+
from outofsample import OOSConformalQuantileRegressor
|
|
200
|
+
from sklearn.ensemble import HistGradientBoostingRegressor
|
|
201
|
+
|
|
202
|
+
model = OOSConformalQuantileRegressor(
|
|
203
|
+
HistGradientBoostingRegressor(), # quantile loss configured automatically
|
|
204
|
+
id_col="id", cv=5, alpha=0.1,
|
|
205
|
+
)
|
|
206
|
+
model.fit(X, y)
|
|
207
|
+
model.predict_interval(X) # (n, 2), widths follow the local noise level
|
|
208
|
+
model.coverage(X, y)
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
The quantile level is set automatically for `GradientBoostingRegressor`, `HistGradientBoostingRegressor`, `QuantileRegressor`, LightGBM, XGBoost and CatBoost regressors (also as the last step of an sklearn `Pipeline`); otherwise pass `quantile_param` or explicit `lower_estimator` / `upper_estimator`. `symmetric=False` conformalizes the two tails separately. `predict_interval(X, alpha=...)` accepts any alpha (the margin is recomputed from the stored scores, so coverage holds), but the quantile models stay at the fitted levels, so refit for the tightest intervals at a very different alpha. `predict` returns the interval midpoint.
|
|
212
|
+
|
|
213
|
+
## Conformal Prediction Sets (Classification)
|
|
214
|
+
|
|
215
|
+
Sets of labels that contain the true class with probability at least `1 - alpha`, built from out-of-sample probabilities:
|
|
216
|
+
|
|
217
|
+
```python
|
|
218
|
+
from outofsample import OOSConformalClassifier
|
|
219
|
+
|
|
220
|
+
model = OOSConformalClassifier(
|
|
221
|
+
RandomForestClassifier(), id_col="id", cv=5,
|
|
222
|
+
alpha=0.1, method="aps", # "lac", "aps" or "raps"
|
|
223
|
+
)
|
|
224
|
+
model.fit(X, y)
|
|
225
|
+
model.predict_set(X) # (n, n_classes) booleans, columns = classes_
|
|
226
|
+
model.predict_set(X, return_labels=True) # list of label arrays
|
|
227
|
+
model.set_size(X)
|
|
228
|
+
model.coverage(X, y, alpha=0.05) # any alpha at predict time, no refit
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
| Parameter | Description |
|
|
232
|
+
|---|---|
|
|
233
|
+
| `method` | `"aps"` (adaptive prediction sets), `"raps"` (APS + rank penalty `lam * max(0, rank - k_reg)`, trims large sets), `"lac"` (`1 - p_y`, smallest average sets) |
|
|
234
|
+
| `randomized` | Randomized APS/RAPS scores for exact rather than conservative coverage (seeded by `random_state`) |
|
|
235
|
+
| `mondrian` | `"class"` for class-conditional coverage: every true class is covered at `1 - alpha` |
|
|
236
|
+
| `allow_empty` | `False` (default) replaces an empty set with the most probable label |
|
|
237
|
+
|
|
238
|
+
Both wrappers follow the package's routing: training IDs use the fold models that held them out and a conformal quantile from the other folds' scores; unseen IDs use the general models and the quantile of all scores. Both work as the final step of `OOSPipeline` and with `save_model` / `load_model`.
|
|
239
|
+
|
|
240
|
+
## Stacking
|
|
241
|
+
|
|
242
|
+
Leak-free stacking: base estimators produce out-of-sample predictions on shared folds (respecting `id_col` duplicates and `group_col`), and a meta-model is trained on them:
|
|
243
|
+
|
|
244
|
+
```python
|
|
245
|
+
from outofsample import OOSStackingClassifier
|
|
246
|
+
from sklearn.ensemble import RandomForestClassifier
|
|
247
|
+
from sklearn.linear_model import LogisticRegression
|
|
248
|
+
|
|
249
|
+
stack = OOSStackingClassifier(
|
|
250
|
+
estimators=[("rf", RandomForestClassifier()), ("lr", LogisticRegression())],
|
|
251
|
+
final_estimator=LogisticRegression(), # default; RidgeCV for OOSStackingRegressor
|
|
252
|
+
id_col="id", cv=5,
|
|
253
|
+
)
|
|
254
|
+
stack.fit(X, y)
|
|
255
|
+
stack.predict_proba(X) # training rows: out-of-sample stacked predictions
|
|
256
|
+
stack.get_oos_predictions() # same values, computed during fit
|
|
257
|
+
stack.transform(X) # the meta-features each row is scored with
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
Each training row in fold k is scored by the base models fitted without fold k and the fold-k meta-model. Plain stacking would train that meta-model on base predictions from models that saw fold k's targets (second-order leakage), so the fold-k meta-model is instead trained on *nested* cross-fitted base predictions: for every other fold j, the base estimators are refitted on the folds outside {k, j}. This costs `K * (K - 1)` extra fits per base estimator and needs `cv >= 3`; `nested=False` skips it but raises under `strict=True` because it leaks. Rows with unseen IDs go through the base general models and a general meta-model trained on the out-of-sample meta-features.
|
|
261
|
+
|
|
262
|
+
| Parameter | Description |
|
|
263
|
+
|---|---|
|
|
264
|
+
| `estimators` | List of `(name, estimator)` base models |
|
|
265
|
+
| `final_estimator` | Meta-model (`LogisticRegression()` / `RidgeCV()` by default) |
|
|
266
|
+
| `stack_method` | `"auto"` (`predict_proba` > `decision_function` > `predict`), or a method name; binary probabilities give one column per estimator |
|
|
267
|
+
| `passthrough` | Also feed the original features to the meta-model |
|
|
268
|
+
| `nested` | Nested cross-fitting of the meta-model's training features (default `True`, leak-free) |
|
|
269
|
+
|
|
270
|
+
## Positive-Unlabeled (PU) Learning
|
|
271
|
+
|
|
272
|
+
For data where only some positives are labeled and everything else is unlabeled (`s`: 1 = labeled positive, 0 = unlabeled):
|
|
273
|
+
|
|
274
|
+
```python
|
|
275
|
+
from outofsample import OOSPUClassifier
|
|
276
|
+
|
|
277
|
+
model = OOSPUClassifier(
|
|
278
|
+
RandomForestClassifier(), id_col="id", cv=5,
|
|
279
|
+
method="elkan-noto", # or "bagging"
|
|
280
|
+
c_estimator="auto", # propensity estimator picked by masked validation
|
|
281
|
+
)
|
|
282
|
+
model.fit(X, s)
|
|
283
|
+
|
|
284
|
+
model.predict_proba(X) # corrected P(y=1|x)
|
|
285
|
+
model.c_, model.c_ci_ # labeling propensity + bootstrap CI (asymmetric)
|
|
286
|
+
model.prior_, model.prior_ci_ # class prior + CI
|
|
287
|
+
model.predict_uncertainty(X) # per-sample [lower, upper] bands
|
|
288
|
+
```
|
|
289
|
+
|
|
290
|
+
| Parameter | Description |
|
|
291
|
+
|---|---|
|
|
292
|
+
| `method` | `"elkan-noto"` (OOS + calibrated scores → propensity correction), `"weighted"` (two-stage retrain on weighted duplicates — best ranking), or `"bagging"` (Mordelet–Vert ensemble with out-of-bag percentile uncertainty) |
|
|
293
|
+
| `c_estimator` | `"e1"` (mean), `"e3"` (max), `"quantile"`, or `"auto"` (masked-holdout selection) |
|
|
294
|
+
| `prior` | Known class prior; overrides estimation via the SCAR identity |
|
|
295
|
+
| `mask_frac` | Fraction of labeled positives hidden for internal validation |
|
|
296
|
+
| `refine_rounds` | Iterative pseudo-labeling: flip the most confident unlabeled rows to positive, CI-gated, with masked-holdout stopping |
|
|
297
|
+
|
|
298
|
+
Prediction sets and probability intervals:
|
|
299
|
+
|
|
300
|
+
```python
|
|
301
|
+
model.predict_set(X, alpha=0.1) # {0}/{1}/{0,1} sets; P(1 in set | y=1) >= 1-alpha under SCAR
|
|
302
|
+
# ({0} side is best-effort — no labeled negatives)
|
|
303
|
+
# with calibration_method="venn-abers":
|
|
304
|
+
model.predict_proba_interval(X) # calibrated [p0, p1] bands, c-CI adjusted
|
|
305
|
+
```
|
|
306
|
+
|
|
307
|
+
All CIs are percentile-based (asymmetric supported throughout). Internal validation metrics land in `pu_validation_`; refinement history in `refine_history_` and `flipped_ids_`.
|
|
308
|
+
|
|
309
|
+
## Group-Aware Splitting
|
|
310
|
+
|
|
311
|
+
For panel/longitudinal data where rows share a group identity (e.g., multiple observations per customer), use `group_col` to keep all rows from the same group in the same fold:
|
|
312
|
+
|
|
313
|
+
```python
|
|
314
|
+
model = OOSClassifier(
|
|
315
|
+
estimator, id_col="row_id", cv=5,
|
|
316
|
+
group_col="customer_id", # all rows per customer in same fold
|
|
317
|
+
)
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
Uses `StratifiedGroupKFold` when `stratified=True` (default for classifiers).
|
|
321
|
+
|
|
322
|
+
## Refreshing With New Data
|
|
323
|
+
|
|
324
|
+
`refresh` adds new rows and IDs to a fitted `OOSClassifier`, `OOSRegressor` or `OOSTransformer` without retraining every fold model. Pass the **full updated training set** (old rows plus new ones) — the package does not cache training data:
|
|
325
|
+
|
|
326
|
+
```python
|
|
327
|
+
model = OOSClassifier(RandomForestClassifier(), id_col="id", cv=5).fit(X, y)
|
|
328
|
+
|
|
329
|
+
model.refresh(X_all, y_all) # strategy="append" (default)
|
|
330
|
+
model.refresh(X_all, y_all, strategy="assign")
|
|
331
|
+
model.refresh_info_ # new IDs, new fold, which fold models / general model were refit
|
|
332
|
+
```
|
|
333
|
+
|
|
334
|
+
| | `"append"` (default) | `"assign"` |
|
|
335
|
+
|---|---|---|
|
|
336
|
+
| New IDs go to | one new fold | existing folds, by a stable hash of the ID (or group) |
|
|
337
|
+
| Training cost | general model only (1 fit) | every fold model whose training rows changed + general model |
|
|
338
|
+
| New fold's model | previous general model (never saw the new rows) | — |
|
|
339
|
+
| Existing fold models | unchanged, do not learn from the new rows | retrained on the current data when stale |
|
|
340
|
+
| Fold layout | one extra fold per refresh that adds IDs | unchanged |
|
|
341
|
+
|
|
342
|
+
Guarantees, for both strategies:
|
|
343
|
+
|
|
344
|
+
- No row is ever routed to a model that trained on its ID — or its group with `group_col`. IDs and groups seen before keep their fold; all rows of a new ID or group share a fold.
|
|
345
|
+
- Fold assignment of new IDs is deterministic: the same ID lands in the same fold in every process, independent of `random_state` and of Python hash randomization.
|
|
346
|
+
- Models whose training rows are unchanged are skipped, detected with row fingerprints (features, ID, group, target and per-sample fit params such as `sample_weight`) stored at `fit` and kept by `save_model`. A refresh with unchanged data is a no-op.
|
|
347
|
+
- The general model is retrained on all rows whenever anything changed, so unseen IDs use the newest model.
|
|
348
|
+
|
|
349
|
+
Limitations:
|
|
350
|
+
|
|
351
|
+
- `"assign"` with new IDs in every fold retrains every fold model; it saves work when changes are confined to a few folds (e.g. corrected labels). `"append"` keeps refreshes cheap, but older fold models grow stale and folds become uneven — call `fit` periodically to rebalance.
|
|
352
|
+
- A known ID or group must not change fold: moving an ID into a group held by another fold raises. Rows of old IDs missing from `X` are simply dropped from the training sets of the models that are retrained.
|
|
353
|
+
- Fingerprints are dtype-sensitive (e.g. `int` vs `float` after a CSV round-trip); such a change only causes extra refits, never leakage.
|
|
354
|
+
- `cv_results_` and `get_oos_predictions()` are recomputed on the refreshed data by scoring every row with its routed fold model.
|
|
355
|
+
- Models loaded from files written by earlier versions, or fitted with a custom splitter that does not hold every row out exactly once (`strict=False`), cannot be refreshed. Composite wrappers (`OOSCalibratedClassifier`, `OOSConformalRegressor`, `OOSConformalQuantileRegressor`, `OOSConformalClassifier`, `OOSPUClassifier`, `OOSStackingClassifier`, `OOSStackingRegressor`, `OOSPipeline`) raise `NotImplementedError`: their calibrators and conformal scores depend on every fold, so refit them with `fit`.
|
|
356
|
+
|
|
357
|
+
## Additional Features
|
|
358
|
+
|
|
359
|
+
**One-shot predictions:**
|
|
360
|
+
```python
|
|
361
|
+
from outofsample import predict_oos
|
|
362
|
+
result = predict_oos(estimator, X, y, id_col="id", cv=5, scoring=["accuracy"])
|
|
363
|
+
```
|
|
364
|
+
|
|
365
|
+
**OOS transformers:**
|
|
366
|
+
```python
|
|
367
|
+
from outofsample import OOSTransformer
|
|
368
|
+
oos_scaler = OOSTransformer(StandardScaler(), id_col="id", cv=5)
|
|
369
|
+
X_oos = oos_scaler.fit_transform(X, y)
|
|
370
|
+
```
|
|
371
|
+
|
|
372
|
+
**SHAP integration:**
|
|
373
|
+
```python
|
|
374
|
+
from outofsample import SHAPWrapper
|
|
375
|
+
sw = SHAPWrapper(fitted_model)
|
|
376
|
+
shap_values = sw.shap_values(X_features, ids) # fold-aware explanations
|
|
377
|
+
```
|
|
378
|
+
|
|
379
|
+
**Persistence** (all wrappers, including calibrated/conformal/PU/pipeline composites and stacking):
|
|
380
|
+
```python
|
|
381
|
+
from outofsample import save_model, load_model
|
|
382
|
+
save_model(model, "models/", name="RF", version="v1")
|
|
383
|
+
loaded = load_model("models/", name="RF", version="v1")
|
|
384
|
+
```
|
|
385
|
+
|
|
386
|
+
Two serializers are available. The default, `format="joblib"`, pickles the fitted estimators and wrapper state; `format="skops"` (`pip install "outofsample[skops]"`) stores the same objects with [skops](https://skops.readthedocs.io) and never unpickles anything:
|
|
387
|
+
|
|
388
|
+
```python
|
|
389
|
+
from outofsample import get_untrusted_types
|
|
390
|
+
|
|
391
|
+
save_model(model, "models/", name="RF", version="v1", format="skops")
|
|
392
|
+
|
|
393
|
+
get_untrusted_types("models/", name="RF", version="v1")
|
|
394
|
+
# ['sklearn.tree._tree.Tree'] -- inspect before trusting
|
|
395
|
+
loaded = load_model("models/", name="RF", version="v1", trusted=["sklearn.tree._tree.Tree"])
|
|
396
|
+
```
|
|
397
|
+
|
|
398
|
+
| | `format="joblib"` (default) | `format="skops"` |
|
|
399
|
+
|---|---|---|
|
|
400
|
+
| Loading untrusted files | Unsafe: unpickling can execute arbitrary code | No pickle; object types outside the skops defaults must be named in `trusted`, otherwise `load_model` raises `UntrustedTypesError` before deserializing anything |
|
|
401
|
+
| Supported models | Anything picklable | Anything skops can store; some types need trust: sklearn trees (`sklearn.tree._tree.Tree`, `...TreePredictor`), XGBoost, LightGBM and CatBoost models, custom CV splitters |
|
|
402
|
+
| Dependencies | none | `skops` |
|
|
403
|
+
| Older artifacts | All earlier artifacts load unchanged | n/a |
|
|
404
|
+
|
|
405
|
+
The serializer is recorded in the artifact metadata and detected by `load_model`. ID maps and bag data are stored as npz/JSON in both formats. In a skops artifact `.joblib` files are never opened, and a component saved with a different serializer is refused. numpy, scipy and scikit-learn types trusted by skops, this package's own types and `datetime` values are accepted without listing them. Trusting a type means trusting that restoring its attributes is harmless; only load joblib artifacts from sources you trust.
|
|
406
|
+
|
|
407
|
+
## Diagnostics
|
|
408
|
+
|
|
409
|
+
**Routing: how many rows get out-of-sample scores?** Rows whose ID was seen during training are scored by the fold model that held them out; rows with unseen IDs go to the general model. `routing_report` tells you the split without predicting, and every prediction call records the same statistics in `last_routing_`:
|
|
410
|
+
|
|
411
|
+
```python
|
|
412
|
+
from outofsample import routing_report
|
|
413
|
+
|
|
414
|
+
routing_report(model, X_score)
|
|
415
|
+
# {'n_rows': 80, 'n_seen': 50, 'n_general': 30, 'share_general': 0.375,
|
|
416
|
+
# 'fold_counts': {0: 13, 1: 9, 2: 16, 3: 12}}
|
|
417
|
+
|
|
418
|
+
model.predict(X_score)
|
|
419
|
+
model.last_routing_ # same dict, for the most recent predict/predict_proba/transform call
|
|
420
|
+
```
|
|
421
|
+
|
|
422
|
+
Works for every wrapper (calibrated, conformal, CQR, conformal sets, PU, stacking, `OOSPipeline`) and for models restored with `load_model`. A high `share_general` on data you expected to overlap the training set usually points to re-keyed or re-typed IDs.
|
|
423
|
+
|
|
424
|
+
**Distribution shift between training and scoring data:**
|
|
425
|
+
|
|
426
|
+
```python
|
|
427
|
+
from outofsample import drift_report, classifier_two_sample_test
|
|
428
|
+
|
|
429
|
+
drift_report(X_train, X_score, model=model) # per feature; drops the model's id/group columns
|
|
430
|
+
classifier_two_sample_test(X_train, X_score, model=model, random_state=0)
|
|
431
|
+
# {'auc': 0.51, 'p_value': 0.31, 'n_reference': ..., 'n_current': ..., 'top_features': None}
|
|
432
|
+
```
|
|
433
|
+
|
|
434
|
+
| Output | Meaning |
|
|
435
|
+
|---|---|
|
|
436
|
+
| `psi` | Population stability index over reference quantile bins (numeric) or categories; missing values get their own bin |
|
|
437
|
+
| `severity` | `"none"` (PSI < 0.1), `"moderate"` (0.1–0.25), `"major"` (≥ 0.25) |
|
|
438
|
+
| `test`, `statistic`, `p_value` | Kolmogorov-Smirnov (numeric) or chi-square (categorical), unadjusted |
|
|
439
|
+
| `missing_reference`, `missing_current`, `missing_delta` | Share of missing values and its change |
|
|
440
|
+
| `auc` (two-sample test) | Out-of-sample AUC of a domain classifier (reference vs current); ~0.5 means no detectable shift, and it catches joint shifts per-feature tests miss |
|
|
441
|
+
|
|
442
|
+
Nothing is stored on the model; pass the reference data explicitly.
|
|
443
|
+
|
|
444
|
+
## API Reference
|
|
445
|
+
|
|
446
|
+
### Classes
|
|
447
|
+
|
|
448
|
+
| Class | Description |
|
|
449
|
+
|---|---|
|
|
450
|
+
| `OOSClassifier` | K-fold OOS classifier wrapper |
|
|
451
|
+
| `OOSRegressor` | K-fold OOS regressor wrapper |
|
|
452
|
+
| `OOSTransformer` | K-fold OOS transformer wrapper |
|
|
453
|
+
| `OOSCalibratedClassifier` | Calibrated OOS classifier |
|
|
454
|
+
| `OOSConformalRegressor` | Conformal prediction intervals |
|
|
455
|
+
| `OOSConformalQuantileRegressor` | Conformalized quantile regression (adaptive intervals) |
|
|
456
|
+
| `OOSConformalClassifier` | Conformal prediction sets (LAC / APS / RAPS, class-conditional) |
|
|
457
|
+
| `OOSPUClassifier` | Positive-unlabeled learning with uncertainty |
|
|
458
|
+
| `OOSStackingClassifier` / `OOSStackingRegressor` | Leak-free stacking with nested cross-fitting |
|
|
459
|
+
| `OOSPipeline` | Chain steps with shared folds (nested cross-fitting for target-dependent steps) |
|
|
460
|
+
| `SHAPWrapper` | SHAP explainability adapter |
|
|
461
|
+
|
|
462
|
+
### Functions
|
|
463
|
+
|
|
464
|
+
| Function | Description |
|
|
465
|
+
|---|---|
|
|
466
|
+
| `OOSModel(estimator, **kw)` | Factory returning OOSClassifier or OOSRegressor |
|
|
467
|
+
| `predict_oos(estimator, X, y, ...)` | One-shot OOS predictions |
|
|
468
|
+
| `save_model` / `load_model` | Persistence (`format="joblib"` or `"skops"`) |
|
|
469
|
+
| `get_untrusted_types` | Types a skops artifact needs trusted before loading |
|
|
470
|
+
| `routing_report(model, X)` | Share of rows routed to fold models vs the general model |
|
|
471
|
+
| `drift_report(X_ref, X_cur)` | Per-feature PSI, KS/chi-square, missing-share shift |
|
|
472
|
+
| `classifier_two_sample_test(X_ref, X_cur)` | Domain-classifier AUC test for multivariate shift |
|
|
473
|
+
|
|
474
|
+
### Common Parameters
|
|
475
|
+
|
|
476
|
+
| Parameter | Type | Default | Description |
|
|
477
|
+
|---|---|---|---|
|
|
478
|
+
| `estimator` | estimator | required | Any sklearn-compatible estimator |
|
|
479
|
+
| `id_col` | str, int, None | `"id"` | Row identifier column |
|
|
480
|
+
| `cv` | int or splitter | `5` | Number of folds |
|
|
481
|
+
| `random_state` | int or None | `None` | Seed for splitting |
|
|
482
|
+
| `stratified` | bool | `True` | Stratified folds for classifiers |
|
|
483
|
+
| `group_col` | str or None | `None` | Group column for panel data |
|
|
484
|
+
| `scoring` | str, list, dict, None | `None` | Metric names, or a dict of names / functions `f(y_true, y_pred)` |
|
|
485
|
+
| `strict` | bool | `True` | Raise instead of warn when predictions would silently be in-sample (leaky/partial CV splitter, prediction IDs of a different type than training IDs, target-dependent `OOSPipeline` steps) or a metric name is unknown |
|
|
486
|
+
|
|
487
|
+
**Strict mode.** Every wrapper refuses, by default, situations that would quietly break the out-of-sample guarantee: a custom splitter that never holds some rows out (e.g. `TimeSeriesSplit`) or splits duplicate IDs across folds, prediction IDs whose type cannot match the training IDs (e.g. `"1"` vs `1`), and target-dependent transformer steps in `OOSPipeline` that cannot be cross-fitted in a nested way (with `nested=False`, a calibrated or conformal final step, or a splitter that does not hold every row out exactly once). Pass `strict=False` to downgrade these to warnings.
|
|
488
|
+
|
|
489
|
+
Conformal margins are infinite when a calibration set has fewer than `1/alpha - 1` residuals — no finite margin carries the coverage guarantee there; `fit` warns when it happens.
|
|
490
|
+
|
|
491
|
+
## Leakage gotchas
|
|
492
|
+
|
|
493
|
+
[docs/leakage-gotchas.md](docs/leakage-gotchas.md) walks through the common ways cross-validation leaks (preprocessing fitted before the split, duplicate IDs across folds, in-sample scoring, stacking, time order, tuning on the evaluation folds) and how the wrappers avoid each. [`examples/leakage_demo.py`](examples/leakage_demo.py) shows the effect on a pure-noise target: naive recipes score ROC AUC 0.77–1.00, the OOS wrappers about 0.5.
|
|
494
|
+
|
|
495
|
+
## Notebooks
|
|
496
|
+
|
|
497
|
+
See `notebooks/` for walkthrough guides:
|
|
498
|
+
|
|
499
|
+
1. **General Usage** — core API and OOSPipeline
|
|
500
|
+
2. **Calibration** — probability calibration methods and strategies
|
|
501
|
+
3. **Conformal Intervals** — constant, adaptive, and asymmetric intervals
|
|
502
|
+
4. **End-to-End** — full CLV pipeline with encoding, calibration, intervals, and SHAP
|
|
503
|
+
5. **PU Learning** — Elkan–Noto correction, bagging uncertainty, masked validation, refinement
|
|
504
|
+
|
|
505
|
+
## Development
|
|
506
|
+
|
|
507
|
+
```bash
|
|
508
|
+
git clone https://github.com/calebdame/outofsample.git
|
|
509
|
+
cd outofsample
|
|
510
|
+
conda create -n outofsample python=3.12 -y
|
|
511
|
+
conda activate outofsample
|
|
512
|
+
pip install -e ".[dev,all]"
|
|
513
|
+
pytest tests/
|
|
514
|
+
```
|
|
515
|
+
|
|
516
|
+
## Releasing
|
|
517
|
+
|
|
518
|
+
Tagging `v<version>` publishes to PyPI through GitHub Actions with trusted publishing (no stored token). See [docs/releasing.md](docs/releasing.md) for the one-time setup and the release steps.
|
|
519
|
+
|
|
520
|
+
## License
|
|
521
|
+
|
|
522
|
+
BSD 3-Clause (Caleb Dame)
|