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
outofsample/_metrics.py
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
"""Metrics computation using sklearn's scoring API.
|
|
2
|
+
|
|
3
|
+
Resolves the ``scoring`` parameter (string, list, dict, or None) into
|
|
4
|
+
metric functions and computes them from raw predictions. This avoids
|
|
5
|
+
needing an estimator+X pair that sklearn's scorer objects require.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import warnings
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
from sklearn.metrics import (
|
|
15
|
+
accuracy_score,
|
|
16
|
+
balanced_accuracy_score,
|
|
17
|
+
f1_score,
|
|
18
|
+
log_loss,
|
|
19
|
+
mean_absolute_error,
|
|
20
|
+
mean_squared_error,
|
|
21
|
+
precision_score,
|
|
22
|
+
r2_score,
|
|
23
|
+
recall_score,
|
|
24
|
+
roc_auc_score,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
# All known metric names and how to compute them from (y_true, y_pred, y_prob).
|
|
28
|
+
# Each callable takes (y_true, y_pred_or_prob, classes, averaging_kwargs).
|
|
29
|
+
_PRED_METRICS: dict[str, Any] = {
|
|
30
|
+
"accuracy": lambda yt, yp, _c, _a: accuracy_score(yt, yp),
|
|
31
|
+
"balanced_accuracy": lambda yt, yp, _c, _a: balanced_accuracy_score(yt, yp),
|
|
32
|
+
"f1": lambda yt, yp, _c, akw: f1_score(yt, yp, **akw, zero_division=0),
|
|
33
|
+
"f1_weighted": lambda yt, yp, _c, _a: f1_score(yt, yp, average="weighted", zero_division=0),
|
|
34
|
+
"f1_macro": lambda yt, yp, _c, _a: f1_score(yt, yp, average="macro", zero_division=0),
|
|
35
|
+
"precision": lambda yt, yp, _c, akw: precision_score(yt, yp, **akw, zero_division=0),
|
|
36
|
+
"precision_weighted": lambda yt, yp, _c, _a: precision_score(
|
|
37
|
+
yt, yp, average="weighted", zero_division=0
|
|
38
|
+
),
|
|
39
|
+
"recall": lambda yt, yp, _c, akw: recall_score(yt, yp, **akw, zero_division=0),
|
|
40
|
+
"recall_weighted": lambda yt, yp, _c, _a: recall_score(
|
|
41
|
+
yt, yp, average="weighted", zero_division=0
|
|
42
|
+
),
|
|
43
|
+
"r2": lambda yt, yp, _c, _a: r2_score(yt, yp),
|
|
44
|
+
"neg_mean_squared_error": lambda yt, yp, _c, _a: -mean_squared_error(yt, yp),
|
|
45
|
+
"neg_mean_absolute_error": lambda yt, yp, _c, _a: -mean_absolute_error(yt, yp),
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _roc_auc(yt: np.ndarray, yprob: np.ndarray, classes: Any, multi_class: str) -> float:
|
|
50
|
+
if classes is not None and len(classes) == 2:
|
|
51
|
+
# Probability columns follow the sorted class order: column 1 is
|
|
52
|
+
# the greater label, which roc_auc_score treats as positive
|
|
53
|
+
return roc_auc_score(yt, yprob[:, 1])
|
|
54
|
+
return roc_auc_score(yt, yprob, multi_class=multi_class, labels=classes)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
_PROB_METRICS: dict[str, Any] = {
|
|
58
|
+
"log_loss": lambda yt, yprob, c, _a: -log_loss(yt, yprob, labels=c),
|
|
59
|
+
"neg_log_loss": lambda yt, yprob, c, _a: -log_loss(yt, yprob, labels=c),
|
|
60
|
+
"roc_auc": lambda yt, yprob, c, _a: _roc_auc(yt, yprob, c, "ovr"),
|
|
61
|
+
"roc_auc_ovr": lambda yt, yprob, c, _a: _roc_auc(yt, yprob, c, "ovr"),
|
|
62
|
+
"roc_auc_ovo": lambda yt, yprob, c, _a: _roc_auc(yt, yprob, c, "ovo"),
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def resolve_scoring(
|
|
67
|
+
scoring: str | list[str] | dict[str, Any] | None,
|
|
68
|
+
is_classifier: bool,
|
|
69
|
+
*,
|
|
70
|
+
strict: bool = False,
|
|
71
|
+
) -> dict[str, str | Any]:
|
|
72
|
+
"""Resolve the ``scoring`` parameter into ``{display_name: metric_key}`` pairs.
|
|
73
|
+
|
|
74
|
+
Args:
|
|
75
|
+
scoring: A metric name, a list of names, or a dict mapping display
|
|
76
|
+
names to names or to metric functions ``f(y_true, y_pred) ->
|
|
77
|
+
float``. ``None`` uses sensible defaults. Unlike
|
|
78
|
+
``cross_validate``, sklearn scorer objects are not accepted:
|
|
79
|
+
metrics are computed from stored OOS predictions, without an
|
|
80
|
+
estimator/X pair.
|
|
81
|
+
is_classifier: Whether default metrics should be for classification.
|
|
82
|
+
strict: Raise ``ValueError`` on unknown metric names instead of
|
|
83
|
+
warning and skipping them.
|
|
84
|
+
|
|
85
|
+
Returns:
|
|
86
|
+
Dict mapping display names to metric keys (strings) or callables.
|
|
87
|
+
"""
|
|
88
|
+
if scoring is None:
|
|
89
|
+
return _default_metrics(is_classifier)
|
|
90
|
+
|
|
91
|
+
if isinstance(scoring, str):
|
|
92
|
+
resolved: dict[str, str | Any] = {scoring: scoring}
|
|
93
|
+
elif isinstance(scoring, (list, tuple)):
|
|
94
|
+
resolved = {name: name for name in scoring}
|
|
95
|
+
elif isinstance(scoring, dict):
|
|
96
|
+
resolved = dict(scoring)
|
|
97
|
+
else:
|
|
98
|
+
raise ValueError(
|
|
99
|
+
f"scoring must be a string, list, dict, or None, got {type(scoring).__name__}"
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
for display_name, metric in resolved.items():
|
|
103
|
+
if not isinstance(metric, str) and (hasattr(metric, "_score_func") or not callable(metric)):
|
|
104
|
+
raise TypeError(
|
|
105
|
+
f"scoring[{display_name!r}] must be a metric name or a metric function "
|
|
106
|
+
"f(y_true, y_pred) -> float, got "
|
|
107
|
+
f"{type(metric).__name__}. sklearn scorer objects (make_scorer / "
|
|
108
|
+
"get_scorer) are not supported; pass the underlying metric function, "
|
|
109
|
+
"e.g. sklearn.metrics.f1_score, or a lambda for extra arguments."
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
unknown = [
|
|
113
|
+
m
|
|
114
|
+
for m in resolved.values()
|
|
115
|
+
if isinstance(m, str) and m not in _PRED_METRICS and m not in _PROB_METRICS
|
|
116
|
+
]
|
|
117
|
+
if unknown:
|
|
118
|
+
supported = sorted([*_PRED_METRICS, *_PROB_METRICS])
|
|
119
|
+
if strict:
|
|
120
|
+
raise ValueError(
|
|
121
|
+
f"Unknown metric name(s) {unknown}. Supported: {supported}. "
|
|
122
|
+
"Pass strict=False to skip unknown metrics with a warning."
|
|
123
|
+
)
|
|
124
|
+
warnings.warn(
|
|
125
|
+
f"Unknown metric name(s) {unknown} will be skipped. Supported: {supported}",
|
|
126
|
+
UserWarning,
|
|
127
|
+
stacklevel=3,
|
|
128
|
+
)
|
|
129
|
+
return resolved
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _default_metrics(is_classifier: bool) -> dict[str, str]:
|
|
133
|
+
"""Return default metric name mappings for classification or regression."""
|
|
134
|
+
if is_classifier:
|
|
135
|
+
return {
|
|
136
|
+
"accuracy": "accuracy",
|
|
137
|
+
"balanced_accuracy": "balanced_accuracy",
|
|
138
|
+
"f1": "f1_weighted",
|
|
139
|
+
"precision": "precision_weighted",
|
|
140
|
+
"recall": "recall_weighted",
|
|
141
|
+
}
|
|
142
|
+
return {
|
|
143
|
+
"r2": "r2",
|
|
144
|
+
"neg_mean_squared_error": "neg_mean_squared_error",
|
|
145
|
+
"neg_mean_absolute_error": "neg_mean_absolute_error",
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def compute_fold_metrics(
|
|
150
|
+
y_true: np.ndarray,
|
|
151
|
+
y_pred: np.ndarray,
|
|
152
|
+
y_prob: np.ndarray | None,
|
|
153
|
+
is_classifier: bool,
|
|
154
|
+
scoring: str | list[str] | dict[str, Any] | None,
|
|
155
|
+
classes: np.ndarray | None = None,
|
|
156
|
+
) -> dict[str, float]:
|
|
157
|
+
"""Compute metrics for a single fold.
|
|
158
|
+
|
|
159
|
+
Args:
|
|
160
|
+
y_true: Ground truth labels/values.
|
|
161
|
+
y_pred: Predictions.
|
|
162
|
+
y_prob: Probability estimates (or None).
|
|
163
|
+
is_classifier: Whether the task is classification.
|
|
164
|
+
scoring: Either a pre-resolved dict from ``resolve_scoring()``, or
|
|
165
|
+
a raw scoring parameter (str, list, dict, None) that will be
|
|
166
|
+
resolved internally.
|
|
167
|
+
classes: Full sorted class labels of the fitted classifier. A fold's
|
|
168
|
+
``y_true`` can miss rare classes; without the full label set,
|
|
169
|
+
binary-vs-multiclass handling, ``log_loss`` and ``roc_auc``
|
|
170
|
+
would be decided from the fold alone. Falls back to the labels
|
|
171
|
+
in ``y_true`` when None.
|
|
172
|
+
|
|
173
|
+
Returns:
|
|
174
|
+
Dict of ``{display_name: metric_value}``.
|
|
175
|
+
"""
|
|
176
|
+
is_multioutput = np.asarray(y_true).ndim > 1
|
|
177
|
+
|
|
178
|
+
metric_map = scoring if isinstance(scoring, dict) else resolve_scoring(scoring, is_classifier)
|
|
179
|
+
|
|
180
|
+
# Multi-output: filter to only compatible metrics
|
|
181
|
+
if is_multioutput:
|
|
182
|
+
_MULTIOUTPUT_SAFE = {
|
|
183
|
+
"accuracy",
|
|
184
|
+
"f1",
|
|
185
|
+
"f1_weighted",
|
|
186
|
+
"f1_macro",
|
|
187
|
+
"precision",
|
|
188
|
+
"precision_weighted",
|
|
189
|
+
"recall",
|
|
190
|
+
"recall_weighted",
|
|
191
|
+
}
|
|
192
|
+
metric_map = {k: v for k, v in metric_map.items() if k in _MULTIOUTPUT_SAFE}
|
|
193
|
+
if not metric_map:
|
|
194
|
+
metric_map = {"accuracy": "accuracy"}
|
|
195
|
+
label_set = None
|
|
196
|
+
avg_kw: dict[str, Any] = {"average": "weighted"}
|
|
197
|
+
else:
|
|
198
|
+
label_set = np.asarray(classes) if classes is not None else np.unique(y_true)
|
|
199
|
+
if len(label_set) > 2:
|
|
200
|
+
avg_kw = {"average": "weighted"}
|
|
201
|
+
else:
|
|
202
|
+
# Positive class is the greater label, matching predict_proba[:, 1]
|
|
203
|
+
avg_kw = {"average": "binary", "pos_label": label_set[-1]}
|
|
204
|
+
results: dict[str, float] = {}
|
|
205
|
+
|
|
206
|
+
for display_name, metric_key in metric_map.items():
|
|
207
|
+
try:
|
|
208
|
+
if isinstance(metric_key, str):
|
|
209
|
+
val = _compute_metric(metric_key, y_true, y_pred, y_prob, label_set, avg_kw)
|
|
210
|
+
else:
|
|
211
|
+
val = metric_key(y_true, y_pred)
|
|
212
|
+
if val is not None:
|
|
213
|
+
results[display_name] = float(val)
|
|
214
|
+
except Exception as e:
|
|
215
|
+
warnings.warn(
|
|
216
|
+
f"Metric '{display_name}' failed: {e}",
|
|
217
|
+
RuntimeWarning,
|
|
218
|
+
stacklevel=2,
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
return results
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _compute_metric(
|
|
225
|
+
name: str,
|
|
226
|
+
y_true: np.ndarray,
|
|
227
|
+
y_pred: np.ndarray,
|
|
228
|
+
y_prob: np.ndarray | None,
|
|
229
|
+
classes: np.ndarray | None,
|
|
230
|
+
avg_kw: dict[str, Any],
|
|
231
|
+
) -> float | None:
|
|
232
|
+
"""Compute a single metric by its canonical name."""
|
|
233
|
+
if name in _PRED_METRICS:
|
|
234
|
+
return _PRED_METRICS[name](y_true, y_pred, classes, avg_kw)
|
|
235
|
+
|
|
236
|
+
if y_prob is not None and name in _PROB_METRICS:
|
|
237
|
+
return _PROB_METRICS[name](y_true, y_prob, classes, avg_kw)
|
|
238
|
+
|
|
239
|
+
return None
|