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,547 @@
|
|
|
1
|
+
"""Diagnostics: conformal interval coverage, routing and distribution shift.
|
|
2
|
+
|
|
3
|
+
Pure functions returning pandas DataFrames or dicts, with no plotting
|
|
4
|
+
dependencies. The interval diagnostics are also exposed as thin methods on
|
|
5
|
+
``OOSConformalRegressor``; ``routing_report``, ``drift_report`` and
|
|
6
|
+
``classifier_two_sample_test`` are public functions.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
import pandas as pd
|
|
15
|
+
from scipy import stats
|
|
16
|
+
from sklearn.base import clone
|
|
17
|
+
from sklearn.utils.validation import check_is_fitted
|
|
18
|
+
|
|
19
|
+
from ._prediction import routing_stats
|
|
20
|
+
from ._validation import check_id_kind, extract_ids_and_features, id_kind, validate_target
|
|
21
|
+
|
|
22
|
+
_DEFAULT_ALPHAS = (0.01, 0.05, 0.10, 0.20, 0.32, 0.50)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def coverage_curve(
|
|
26
|
+
model: Any,
|
|
27
|
+
X: Any,
|
|
28
|
+
y: Any,
|
|
29
|
+
*,
|
|
30
|
+
ids: Any | None = None,
|
|
31
|
+
alphas: Any | None = None,
|
|
32
|
+
) -> pd.DataFrame:
|
|
33
|
+
"""Empirical coverage and mean width across a grid of alphas.
|
|
34
|
+
|
|
35
|
+
Rides on multi-alpha intervals — the model is not refit.
|
|
36
|
+
|
|
37
|
+
Args:
|
|
38
|
+
model: A fitted ``OOSConformalRegressor``.
|
|
39
|
+
X: Input data.
|
|
40
|
+
y: True targets.
|
|
41
|
+
ids: Explicit ID array.
|
|
42
|
+
alphas: Iterable of miscoverage rates. Defaults to
|
|
43
|
+
``(0.01, 0.05, 0.10, 0.20, 0.32, 0.50)``.
|
|
44
|
+
|
|
45
|
+
Returns:
|
|
46
|
+
DataFrame with columns ``alpha``, ``target_coverage``,
|
|
47
|
+
``empirical_coverage``, ``mean_width`` — one row per alpha.
|
|
48
|
+
"""
|
|
49
|
+
alpha_grid = _DEFAULT_ALPHAS if alphas is None else tuple(alphas)
|
|
50
|
+
y_arr = validate_target(y)
|
|
51
|
+
rows = []
|
|
52
|
+
for a in alpha_grid:
|
|
53
|
+
intervals = model.predict_interval(X, ids=ids, alpha=a)
|
|
54
|
+
covered = (y_arr >= intervals[:, 0]) & (y_arr <= intervals[:, 1])
|
|
55
|
+
rows.append(
|
|
56
|
+
{
|
|
57
|
+
"alpha": a,
|
|
58
|
+
"target_coverage": 1 - a,
|
|
59
|
+
"empirical_coverage": float(covered.mean()),
|
|
60
|
+
"mean_width": float((intervals[:, 1] - intervals[:, 0]).mean()),
|
|
61
|
+
}
|
|
62
|
+
)
|
|
63
|
+
return pd.DataFrame(rows)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def conditional_coverage(
|
|
67
|
+
model: Any,
|
|
68
|
+
X: Any,
|
|
69
|
+
y: Any,
|
|
70
|
+
*,
|
|
71
|
+
ids: Any | None = None,
|
|
72
|
+
by: str | None = None,
|
|
73
|
+
bins: int = 10,
|
|
74
|
+
alpha: float | None = None,
|
|
75
|
+
) -> pd.DataFrame:
|
|
76
|
+
"""Coverage and mean width per bin of a conditioning variable.
|
|
77
|
+
|
|
78
|
+
Reveals conditional under-coverage that marginal coverage hides —
|
|
79
|
+
the failure mode Mondrian conformal fixes.
|
|
80
|
+
|
|
81
|
+
Args:
|
|
82
|
+
model: A fitted ``OOSConformalRegressor``.
|
|
83
|
+
X: Input data.
|
|
84
|
+
y: True targets.
|
|
85
|
+
ids: Explicit ID array.
|
|
86
|
+
by: Conditioning variable: ``None`` resolves to the Mondrian
|
|
87
|
+
binning variable when Mondrian is fitted, otherwise
|
|
88
|
+
``"prediction"``; ``"prediction"`` bins by the point
|
|
89
|
+
prediction; ``"difficulty"`` bins by predicted residual
|
|
90
|
+
magnitude (requires a fitted residual predictor); a column
|
|
91
|
+
name bins by that feature.
|
|
92
|
+
bins: Number of quantile bins for numeric variables. Categorical
|
|
93
|
+
variables bin by category.
|
|
94
|
+
alpha: Override miscoverage rate. None uses the fitted alpha.
|
|
95
|
+
|
|
96
|
+
Returns:
|
|
97
|
+
DataFrame with columns ``bin``, ``bin_lower``, ``bin_upper``,
|
|
98
|
+
``n``, ``coverage``, ``mean_width``. For categorical variables,
|
|
99
|
+
``bin`` holds the category and the edge columns are NaN.
|
|
100
|
+
"""
|
|
101
|
+
y_arr = validate_target(y)
|
|
102
|
+
intervals = model.predict_interval(X, ids=ids, alpha=alpha)
|
|
103
|
+
covered = (y_arr >= intervals[:, 0]) & (y_arr <= intervals[:, 1])
|
|
104
|
+
widths = intervals[:, 1] - intervals[:, 0]
|
|
105
|
+
values = _resolve_by(model, X, ids, by)
|
|
106
|
+
|
|
107
|
+
if values.dtype.kind in ("O", "U", "S"):
|
|
108
|
+
values = values.astype(str)
|
|
109
|
+
rows = []
|
|
110
|
+
for cat in np.unique(values):
|
|
111
|
+
mask = values == cat
|
|
112
|
+
rows.append(
|
|
113
|
+
{
|
|
114
|
+
"bin": cat,
|
|
115
|
+
"bin_lower": np.nan,
|
|
116
|
+
"bin_upper": np.nan,
|
|
117
|
+
"n": int(mask.sum()),
|
|
118
|
+
"coverage": float(covered[mask].mean()),
|
|
119
|
+
"mean_width": float(widths[mask].mean()),
|
|
120
|
+
}
|
|
121
|
+
)
|
|
122
|
+
return pd.DataFrame(rows)
|
|
123
|
+
|
|
124
|
+
values = np.asarray(values, dtype=float)
|
|
125
|
+
edges = np.unique(np.quantile(values, np.linspace(0, 1, bins + 1)))
|
|
126
|
+
idx = np.clip(np.digitize(values, edges[1:-1]), 0, len(edges) - 2)
|
|
127
|
+
rows = []
|
|
128
|
+
for b in range(len(edges) - 1):
|
|
129
|
+
mask = idx == b
|
|
130
|
+
if not mask.any():
|
|
131
|
+
continue
|
|
132
|
+
rows.append(
|
|
133
|
+
{
|
|
134
|
+
"bin": b,
|
|
135
|
+
"bin_lower": float(edges[b]),
|
|
136
|
+
"bin_upper": float(edges[b + 1]),
|
|
137
|
+
"n": int(mask.sum()),
|
|
138
|
+
"coverage": float(covered[mask].mean()),
|
|
139
|
+
"mean_width": float(widths[mask].mean()),
|
|
140
|
+
}
|
|
141
|
+
)
|
|
142
|
+
return pd.DataFrame(rows)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _resolve_by(model: Any, X: Any, ids: Any | None, by: str | None) -> np.ndarray:
|
|
146
|
+
"""Resolve the conditioning variable (see ``conditional_coverage``)."""
|
|
147
|
+
if by is None:
|
|
148
|
+
by = model.mondrian if getattr(model, "mondrian", None) is not None else "prediction"
|
|
149
|
+
if by == "prediction":
|
|
150
|
+
return np.asarray(model.predict(X, ids=ids))
|
|
151
|
+
if by == "difficulty":
|
|
152
|
+
if not hasattr(model, "residual_predictor_"):
|
|
153
|
+
raise ValueError(
|
|
154
|
+
"by='difficulty' requires a fitted residual predictor "
|
|
155
|
+
"(use normalize=True or mondrian='difficulty')"
|
|
156
|
+
)
|
|
157
|
+
return np.asarray(model.residual_predictor_.predict(X, ids=ids))
|
|
158
|
+
X_features, _, _ = extract_ids_and_features(X, model.id_col, ids=ids)
|
|
159
|
+
if by not in X_features.columns:
|
|
160
|
+
raise ValueError(f"conditioning column '{by}' not found in X")
|
|
161
|
+
return X_features[by].to_numpy()
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
# ----------------------------------------------------------------------
|
|
165
|
+
# Routing
|
|
166
|
+
# ----------------------------------------------------------------------
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _router(model: Any) -> tuple[dict[Any, Any], int | None]:
|
|
170
|
+
"""Find the ID lookup a fitted wrapper routes predictions with.
|
|
171
|
+
|
|
172
|
+
Returns:
|
|
173
|
+
``(lookup, n_folds)``: the mapping from training ID to fold index
|
|
174
|
+
(or, for bagging PU, to its row) and the number of fold models
|
|
175
|
+
(None when routing is not per fold).
|
|
176
|
+
"""
|
|
177
|
+
if hasattr(model, "meta_models_"): # stacking (its final_estimator_ is the meta-model)
|
|
178
|
+
return model.id_to_fold_, len(model.meta_models_)
|
|
179
|
+
if hasattr(model, "final_estimator_"): # OOSPipeline
|
|
180
|
+
return _router(model.final_estimator_)
|
|
181
|
+
if hasattr(model, "pu_estimator_"): # OOSPUClassifier
|
|
182
|
+
if getattr(model, "method", None) == "bagging":
|
|
183
|
+
return model._bag_id_to_row_, None
|
|
184
|
+
return _router(model.pu_estimator_)
|
|
185
|
+
inner = getattr(model, "oos_classifier_", None)
|
|
186
|
+
if inner is None:
|
|
187
|
+
inner = getattr(model, "oos_regressor_", None)
|
|
188
|
+
if inner is None:
|
|
189
|
+
inner = getattr(model, "lower_regressor_", None)
|
|
190
|
+
if inner is not None: # calibrated / conformal / CQR wrappers
|
|
191
|
+
return _router(inner)
|
|
192
|
+
if hasattr(model, "id_to_fold_") and hasattr(model, "models_"):
|
|
193
|
+
return model.id_to_fold_, len(model.models_)
|
|
194
|
+
raise TypeError(f"{type(model).__name__} is not a fitted outofsample wrapper with ID routing")
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def routing_report(model: Any, X: Any, *, ids: Any | None = None) -> dict[str, Any]:
|
|
198
|
+
"""Report how prediction rows would be routed, without predicting.
|
|
199
|
+
|
|
200
|
+
Rows whose ID was seen during training are scored by the fold model
|
|
201
|
+
that held them out (out-of-sample); rows with unseen IDs are scored by
|
|
202
|
+
the general model. A high ``share_general`` on data you expected to
|
|
203
|
+
overlap with the training set usually means an ID mismatch (e.g. IDs
|
|
204
|
+
re-keyed or re-typed upstream); on genuinely new data it is expected.
|
|
205
|
+
|
|
206
|
+
Works for every fitted wrapper (``OOSClassifier``, ``OOSRegressor``,
|
|
207
|
+
``OOSTransformer``, ``OOSCalibratedClassifier``,
|
|
208
|
+
``OOSConformalRegressor``, ``OOSConformalQuantileRegressor``,
|
|
209
|
+
``OOSConformalClassifier``, ``OOSPUClassifier``, the stacking
|
|
210
|
+
estimators, ``OOSPipeline``),
|
|
211
|
+
including models restored with ``load_model``. The statistics match
|
|
212
|
+
the ``last_routing_`` attribute that a prediction call on the same rows
|
|
213
|
+
records.
|
|
214
|
+
|
|
215
|
+
Args:
|
|
216
|
+
model: A fitted outofsample wrapper.
|
|
217
|
+
X: Input data containing the ID column (or pass ``ids``).
|
|
218
|
+
ids: Explicit ID array when ``X`` does not contain an ID column.
|
|
219
|
+
|
|
220
|
+
Returns:
|
|
221
|
+
Dict with ``n_rows``, ``n_seen``, ``n_general``, ``share_general``
|
|
222
|
+
and ``fold_counts`` (``{fold: n_rows}``; empty for bagging PU, whose
|
|
223
|
+
out-of-bag routing is not per fold).
|
|
224
|
+
|
|
225
|
+
Raises:
|
|
226
|
+
TypeError: If ``model`` is not a fitted outofsample wrapper.
|
|
227
|
+
ValueError: Under ``strict=True``, if the IDs cannot match the
|
|
228
|
+
training IDs' type (the same check prediction applies).
|
|
229
|
+
"""
|
|
230
|
+
if not hasattr(model, "steps"): # OOSPipeline is not a BaseEstimator
|
|
231
|
+
check_is_fitted(model)
|
|
232
|
+
lookup, n_folds = _router(model)
|
|
233
|
+
_X_features, id_array, _ = extract_ids_and_features(X, model.id_col, ids=ids)
|
|
234
|
+
if lookup:
|
|
235
|
+
check_id_kind(id_kind(list(lookup.keys())), id_array, strict=getattr(model, "strict", True))
|
|
236
|
+
if n_folds is None:
|
|
237
|
+
folds = np.fromiter(
|
|
238
|
+
(0 if id_ in lookup else -1 for id_ in id_array.tolist()),
|
|
239
|
+
dtype=np.int64,
|
|
240
|
+
count=len(id_array),
|
|
241
|
+
)
|
|
242
|
+
else:
|
|
243
|
+
folds = np.fromiter(
|
|
244
|
+
(lookup.get(id_, -1) for id_ in id_array.tolist()),
|
|
245
|
+
dtype=np.int64,
|
|
246
|
+
count=len(id_array),
|
|
247
|
+
)
|
|
248
|
+
return routing_stats(folds, n_folds)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
# ----------------------------------------------------------------------
|
|
252
|
+
# Distribution shift
|
|
253
|
+
# ----------------------------------------------------------------------
|
|
254
|
+
|
|
255
|
+
#: PSI thresholds for the ``severity`` column of ``drift_report``.
|
|
256
|
+
PSI_MODERATE = 0.1
|
|
257
|
+
PSI_MAJOR = 0.25
|
|
258
|
+
_PSI_EPS = 1e-4
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _feature_frames(
|
|
262
|
+
X_reference: Any,
|
|
263
|
+
X_current: Any,
|
|
264
|
+
model: Any | None,
|
|
265
|
+
id_col: str | int | None,
|
|
266
|
+
group_col: str | None,
|
|
267
|
+
) -> tuple[pd.DataFrame, pd.DataFrame]:
|
|
268
|
+
"""Strip ID/group columns and align the two frames' feature columns."""
|
|
269
|
+
if model is not None:
|
|
270
|
+
id_col = getattr(model, "id_col", id_col) if id_col is None else id_col
|
|
271
|
+
group_col = getattr(model, "group_col", group_col) if group_col is None else group_col
|
|
272
|
+
frames = []
|
|
273
|
+
for X in (X_reference, X_current):
|
|
274
|
+
df = X if isinstance(X, pd.DataFrame) else pd.DataFrame(X)
|
|
275
|
+
if id_col is not None:
|
|
276
|
+
df, _, _ = extract_ids_and_features(df, id_col)
|
|
277
|
+
if group_col is not None and group_col in df.columns:
|
|
278
|
+
df = df.drop(columns=[group_col])
|
|
279
|
+
frames.append(df)
|
|
280
|
+
ref, cur = frames
|
|
281
|
+
missing = [c for c in ref.columns if c not in cur.columns]
|
|
282
|
+
if missing:
|
|
283
|
+
raise ValueError(f"X_current is missing reference columns: {missing}")
|
|
284
|
+
return ref, cur[list(ref.columns)]
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _is_numeric(series: pd.Series) -> bool:
|
|
288
|
+
return (
|
|
289
|
+
pd.api.types.is_numeric_dtype(series) and not pd.api.types.is_bool_dtype(series)
|
|
290
|
+
) or pd.api.types.is_datetime64_any_dtype(series)
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _as_float(series: pd.Series) -> np.ndarray:
|
|
294
|
+
"""Numeric (or datetime) column as float with NaN for missing values."""
|
|
295
|
+
if pd.api.types.is_datetime64_any_dtype(series):
|
|
296
|
+
values = series.to_numpy(dtype="datetime64[ns]").astype("int64").astype(float)
|
|
297
|
+
values[series.isna().to_numpy()] = np.nan
|
|
298
|
+
return values
|
|
299
|
+
return pd.to_numeric(series, errors="coerce").to_numpy(dtype=float, na_value=np.nan)
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _psi(ref_counts: np.ndarray, cur_counts: np.ndarray) -> float:
|
|
303
|
+
"""Population stability index of two count vectors over the same bins."""
|
|
304
|
+
p = np.clip(ref_counts / max(ref_counts.sum(), 1), _PSI_EPS, None)
|
|
305
|
+
q = np.clip(cur_counts / max(cur_counts.sum(), 1), _PSI_EPS, None)
|
|
306
|
+
return float(np.sum((q - p) * np.log(q / p)))
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _numeric_drift(ref: np.ndarray, cur: np.ndarray, bins: int) -> dict[str, Any]:
|
|
310
|
+
ref_ok, cur_ok = ref[~np.isnan(ref)], cur[~np.isnan(cur)]
|
|
311
|
+
if len(ref_ok) == 0 or len(cur_ok) == 0:
|
|
312
|
+
return {"psi": np.nan, "test": "ks", "statistic": np.nan, "p_value": np.nan}
|
|
313
|
+
# Quantile bins of the reference; outer bins are open-ended
|
|
314
|
+
edges = np.unique(np.quantile(ref_ok, np.linspace(0, 1, bins + 1))[1:-1])
|
|
315
|
+
n_bins = len(edges) + 1
|
|
316
|
+
ref_counts = np.bincount(np.searchsorted(edges, ref_ok, side="right"), minlength=n_bins)
|
|
317
|
+
cur_counts = np.bincount(np.searchsorted(edges, cur_ok, side="right"), minlength=n_bins)
|
|
318
|
+
# Missing values form their own bin
|
|
319
|
+
ref_counts = np.append(ref_counts, len(ref) - len(ref_ok))
|
|
320
|
+
cur_counts = np.append(cur_counts, len(cur) - len(cur_ok))
|
|
321
|
+
ks = stats.ks_2samp(ref_ok, cur_ok)
|
|
322
|
+
return {
|
|
323
|
+
"psi": _psi(ref_counts, cur_counts),
|
|
324
|
+
"test": "ks",
|
|
325
|
+
"statistic": float(ks.statistic),
|
|
326
|
+
"p_value": float(ks.pvalue),
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _categorical_drift(ref: pd.Series, cur: pd.Series) -> dict[str, Any]:
|
|
331
|
+
ref_str = ref.astype(object).where(ref.notna(), "<missing>").astype(str)
|
|
332
|
+
cur_str = cur.astype(object).where(cur.notna(), "<missing>").astype(str)
|
|
333
|
+
categories = sorted(set(ref_str.unique()) | set(cur_str.unique()))
|
|
334
|
+
ref_counts = ref_str.value_counts().reindex(categories, fill_value=0).to_numpy()
|
|
335
|
+
cur_counts = cur_str.value_counts().reindex(categories, fill_value=0).to_numpy()
|
|
336
|
+
if len(categories) < 2:
|
|
337
|
+
statistic, p_value = 0.0, 1.0
|
|
338
|
+
else:
|
|
339
|
+
result = stats.chi2_contingency(np.vstack([ref_counts, cur_counts]))
|
|
340
|
+
statistic, p_value = float(result[0]), float(result[1])
|
|
341
|
+
return {
|
|
342
|
+
"psi": _psi(ref_counts, cur_counts),
|
|
343
|
+
"test": "chi2",
|
|
344
|
+
"statistic": statistic,
|
|
345
|
+
"p_value": p_value,
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _severity(psi: float) -> str:
|
|
350
|
+
if np.isnan(psi):
|
|
351
|
+
return "unknown"
|
|
352
|
+
if psi >= PSI_MAJOR:
|
|
353
|
+
return "major"
|
|
354
|
+
if psi >= PSI_MODERATE:
|
|
355
|
+
return "moderate"
|
|
356
|
+
return "none"
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def drift_report(
|
|
360
|
+
X_reference: Any,
|
|
361
|
+
X_current: Any,
|
|
362
|
+
*,
|
|
363
|
+
model: Any | None = None,
|
|
364
|
+
id_col: str | int | None = None,
|
|
365
|
+
group_col: str | None = None,
|
|
366
|
+
bins: int = 10,
|
|
367
|
+
) -> pd.DataFrame:
|
|
368
|
+
"""Per-feature distribution shift between training and scoring data.
|
|
369
|
+
|
|
370
|
+
For every feature column, compares the reference sample (typically
|
|
371
|
+
the training data) with the current sample (the data being scored):
|
|
372
|
+
|
|
373
|
+
- **PSI** (population stability index) over the reference's quantile
|
|
374
|
+
bins for numeric features (outer bins open-ended), or over the
|
|
375
|
+
categories for categorical ones; missing values are a bin of their
|
|
376
|
+
own and empty bins are smoothed to a proportion of ``1e-4``.
|
|
377
|
+
- A two-sample test: Kolmogorov-Smirnov for numeric features (on the
|
|
378
|
+
non-missing values), chi-square on the category counts for
|
|
379
|
+
categorical features (bool, object, string and category dtypes).
|
|
380
|
+
- The share of missing values in each sample and its change.
|
|
381
|
+
- ``severity`` from the conventional PSI thresholds: ``"none"`` below
|
|
382
|
+
0.1, ``"moderate"`` from 0.1, ``"major"`` from 0.25 (``"unknown"``
|
|
383
|
+
when a sample has no non-missing values).
|
|
384
|
+
|
|
385
|
+
p-values are per feature and not adjusted for multiple testing; with
|
|
386
|
+
large samples tiny, irrelevant shifts are "significant", so read them
|
|
387
|
+
together with PSI. Nothing is stored on the model: pass the reference
|
|
388
|
+
data explicitly.
|
|
389
|
+
|
|
390
|
+
Args:
|
|
391
|
+
X_reference: Reference data (DataFrame or array).
|
|
392
|
+
X_current: Data to compare against the reference; must contain the
|
|
393
|
+
reference's feature columns.
|
|
394
|
+
model: Optional fitted wrapper whose ``id_col`` and ``group_col``
|
|
395
|
+
are dropped from both samples (explicit arguments win).
|
|
396
|
+
id_col: ID column to drop (name or position), or None.
|
|
397
|
+
group_col: Group column to drop, or None.
|
|
398
|
+
bins: Number of quantile bins for numeric features.
|
|
399
|
+
|
|
400
|
+
Returns:
|
|
401
|
+
DataFrame with one row per feature (in reference column order) and
|
|
402
|
+
columns ``feature``, ``kind``, ``psi``, ``severity``, ``test``,
|
|
403
|
+
``statistic``, ``p_value``, ``missing_reference``,
|
|
404
|
+
``missing_current``, ``missing_delta``.
|
|
405
|
+
"""
|
|
406
|
+
if not isinstance(bins, int) or isinstance(bins, bool) or bins < 2:
|
|
407
|
+
raise ValueError(f"bins must be an integer >= 2, got {bins!r}")
|
|
408
|
+
ref_df, cur_df = _feature_frames(X_reference, X_current, model, id_col, group_col)
|
|
409
|
+
rows = []
|
|
410
|
+
for col in ref_df.columns:
|
|
411
|
+
ref, cur = ref_df[col], cur_df[col]
|
|
412
|
+
if _is_numeric(ref) and _is_numeric(cur):
|
|
413
|
+
kind = "numeric"
|
|
414
|
+
result = _numeric_drift(_as_float(ref), _as_float(cur), bins)
|
|
415
|
+
else:
|
|
416
|
+
kind = "categorical"
|
|
417
|
+
result = _categorical_drift(ref, cur)
|
|
418
|
+
miss_ref = float(ref.isna().mean())
|
|
419
|
+
miss_cur = float(cur.isna().mean())
|
|
420
|
+
rows.append(
|
|
421
|
+
{
|
|
422
|
+
"feature": col,
|
|
423
|
+
"kind": kind,
|
|
424
|
+
"psi": result["psi"],
|
|
425
|
+
"severity": _severity(result["psi"]),
|
|
426
|
+
"test": result["test"],
|
|
427
|
+
"statistic": result["statistic"],
|
|
428
|
+
"p_value": result["p_value"],
|
|
429
|
+
"missing_reference": miss_ref,
|
|
430
|
+
"missing_current": miss_cur,
|
|
431
|
+
"missing_delta": miss_cur - miss_ref,
|
|
432
|
+
}
|
|
433
|
+
)
|
|
434
|
+
return pd.DataFrame(rows)
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def _encode_for_default(df: pd.DataFrame) -> pd.DataFrame:
|
|
438
|
+
"""Prepare mixed-type columns for HistGradientBoostingClassifier."""
|
|
439
|
+
out = {}
|
|
440
|
+
for col in df.columns:
|
|
441
|
+
series = df[col]
|
|
442
|
+
if pd.api.types.is_datetime64_any_dtype(series):
|
|
443
|
+
out[col] = _as_float(series)
|
|
444
|
+
elif _is_numeric(series):
|
|
445
|
+
out[col] = series
|
|
446
|
+
else:
|
|
447
|
+
out[col] = series.astype(object).where(series.notna(), None).astype("category")
|
|
448
|
+
return pd.DataFrame(out, index=df.index)
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def classifier_two_sample_test(
|
|
452
|
+
X_reference: Any,
|
|
453
|
+
X_current: Any,
|
|
454
|
+
*,
|
|
455
|
+
estimator: Any | None = None,
|
|
456
|
+
model: Any | None = None,
|
|
457
|
+
id_col: str | int | None = None,
|
|
458
|
+
group_col: str | None = None,
|
|
459
|
+
cv: int = 5,
|
|
460
|
+
random_state: int | None = None,
|
|
461
|
+
n_top_features: int = 10,
|
|
462
|
+
) -> dict[str, Any]:
|
|
463
|
+
"""Classifier two-sample test for multivariate distribution shift.
|
|
464
|
+
|
|
465
|
+
Trains a domain classifier to tell reference rows (label 0) from
|
|
466
|
+
current rows (label 1) and scores every row out-of-sample with
|
|
467
|
+
stratified ``cv``-fold cross-validation. If the samples come from the
|
|
468
|
+
same distribution the out-of-sample AUC is about 0.5; an AUC well above
|
|
469
|
+
0.5 means the classifier found a difference — including interactions
|
|
470
|
+
between features that per-feature tests miss.
|
|
471
|
+
|
|
472
|
+
The p-value is the one-sided Mann-Whitney U test of the current rows'
|
|
473
|
+
OOS scores against the reference rows' (the U statistic is the AUC
|
|
474
|
+
times ``n_reference * n_current``). Scores from different folds come
|
|
475
|
+
from different models, so it is an approximation; prefer the AUC as an
|
|
476
|
+
effect size and the p-value as a screen.
|
|
477
|
+
|
|
478
|
+
Args:
|
|
479
|
+
X_reference: Reference data (typically the training data).
|
|
480
|
+
X_current: Data to compare (typically the data being scored).
|
|
481
|
+
estimator: Classifier with ``predict_proba`` or
|
|
482
|
+
``decision_function``. Defaults to
|
|
483
|
+
``HistGradientBoostingClassifier`` with categorical support
|
|
484
|
+
(non-numeric columns are converted to ``category``; custom
|
|
485
|
+
estimators receive the columns unchanged).
|
|
486
|
+
model: Optional fitted wrapper whose ``id_col`` and ``group_col``
|
|
487
|
+
are dropped from both samples.
|
|
488
|
+
id_col: ID column to drop, or None.
|
|
489
|
+
group_col: Group column to drop, or None.
|
|
490
|
+
cv: Number of stratified folds.
|
|
491
|
+
random_state: Seed for the folds (and the default estimator).
|
|
492
|
+
n_top_features: Number of features listed in ``top_features``.
|
|
493
|
+
|
|
494
|
+
Returns:
|
|
495
|
+
Dict with ``auc``, ``p_value``, ``n_reference``, ``n_current`` and
|
|
496
|
+
``top_features`` — a Series of the largest feature importances of
|
|
497
|
+
the domain classifier refitted on all rows, or None when the
|
|
498
|
+
estimator exposes neither ``feature_importances_`` nor ``coef_``
|
|
499
|
+
(the default does not; pass e.g. a ``RandomForestClassifier`` to
|
|
500
|
+
get them).
|
|
501
|
+
"""
|
|
502
|
+
from sklearn.ensemble import HistGradientBoostingClassifier
|
|
503
|
+
from sklearn.metrics import roc_auc_score
|
|
504
|
+
from sklearn.model_selection import StratifiedKFold, cross_val_predict
|
|
505
|
+
|
|
506
|
+
ref_df, cur_df = _feature_frames(X_reference, X_current, model, id_col, group_col)
|
|
507
|
+
X_all = pd.concat([ref_df, cur_df], ignore_index=True)
|
|
508
|
+
y_all = np.concatenate([np.zeros(len(ref_df), dtype=int), np.ones(len(cur_df), dtype=int)])
|
|
509
|
+
if estimator is None:
|
|
510
|
+
X_all = _encode_for_default(X_all)
|
|
511
|
+
est: Any = HistGradientBoostingClassifier(
|
|
512
|
+
categorical_features="from_dtype", random_state=random_state
|
|
513
|
+
)
|
|
514
|
+
else:
|
|
515
|
+
est = clone(estimator)
|
|
516
|
+
|
|
517
|
+
splitter = StratifiedKFold(n_splits=cv, shuffle=True, random_state=random_state)
|
|
518
|
+
method = "predict_proba" if hasattr(est, "predict_proba") else "decision_function"
|
|
519
|
+
scores = cross_val_predict(est, X_all, y_all, cv=splitter, method=method)
|
|
520
|
+
if scores.ndim == 2:
|
|
521
|
+
scores = scores[:, 1]
|
|
522
|
+
auc = float(roc_auc_score(y_all, scores))
|
|
523
|
+
p_value = float(
|
|
524
|
+
stats.mannwhitneyu(scores[y_all == 1], scores[y_all == 0], alternative="greater").pvalue
|
|
525
|
+
)
|
|
526
|
+
|
|
527
|
+
top_features = None
|
|
528
|
+
importances = None
|
|
529
|
+
if estimator is not None: # the default estimator exposes no importances
|
|
530
|
+
full = clone(est).fit(X_all, y_all)
|
|
531
|
+
importances = getattr(full, "feature_importances_", None)
|
|
532
|
+
if importances is None and hasattr(full, "coef_"):
|
|
533
|
+
importances = np.abs(np.ravel(full.coef_))
|
|
534
|
+
if importances is not None and len(importances) == X_all.shape[1]:
|
|
535
|
+
top_features = (
|
|
536
|
+
pd.Series(importances, index=X_all.columns, name="importance")
|
|
537
|
+
.sort_values(ascending=False)
|
|
538
|
+
.head(n_top_features)
|
|
539
|
+
)
|
|
540
|
+
|
|
541
|
+
return {
|
|
542
|
+
"auc": auc,
|
|
543
|
+
"p_value": p_value,
|
|
544
|
+
"n_reference": len(ref_df),
|
|
545
|
+
"n_current": len(cur_df),
|
|
546
|
+
"top_features": top_features,
|
|
547
|
+
}
|