evalsuite-python 0.8.5__py3-none-any.whl → 1.0.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.
- evalsuite/__init__.py +11 -0
- evalsuite/_evalci.py +251 -0
- evalsuite/api.py +37 -5
- evalsuite/cards.py +427 -0
- evalsuite/cli/main.py +49 -0
- evalsuite/core/result.py +84 -12
- evalsuite/harness.py +470 -0
- evalsuite/integrations.py +231 -0
- evalsuite/monitor.py +197 -0
- evalsuite/stats/compare.py +2 -1
- evalsuite/version.py +1 -1
- {evalsuite_python-0.8.5.dist-info → evalsuite_python-1.0.0.dist-info}/METADATA +18 -2
- {evalsuite_python-0.8.5.dist-info → evalsuite_python-1.0.0.dist-info}/RECORD +17 -12
- {evalsuite_python-0.8.5.dist-info → evalsuite_python-1.0.0.dist-info}/WHEEL +0 -0
- {evalsuite_python-0.8.5.dist-info → evalsuite_python-1.0.0.dist-info}/entry_points.txt +0 -0
- {evalsuite_python-0.8.5.dist-info → evalsuite_python-1.0.0.dist-info}/licenses/LICENSE +0 -0
- {evalsuite_python-0.8.5.dist-info → evalsuite_python-1.0.0.dist-info}/licenses/LICENSE-APACHE +0 -0
evalsuite/__init__.py
CHANGED
|
@@ -15,6 +15,7 @@ from .calibration import (
|
|
|
15
15
|
hosmer_lemeshow,
|
|
16
16
|
maximum_calibration_error,
|
|
17
17
|
)
|
|
18
|
+
from .cards import ReportCard, report_card
|
|
18
19
|
from .classification import (
|
|
19
20
|
accuracy,
|
|
20
21
|
average_precision,
|
|
@@ -63,8 +64,10 @@ from .core.exceptions import (
|
|
|
63
64
|
)
|
|
64
65
|
from .core.registry import MetricInfo, list_metrics, metric_info
|
|
65
66
|
from .core.result import EvaluationResult, MetricResult
|
|
67
|
+
from .harness import Leaderboard, leaderboard
|
|
66
68
|
from .llmsys import * # noqa: F403 (v0.5.0 LLM-systems functions, listed in llmsys.__all__)
|
|
67
69
|
from .llmsys import __all__ as _llmsys_all
|
|
70
|
+
from .monitor import Alert, Monitor, ks_drift, population_stability_index
|
|
68
71
|
from .regression import (
|
|
69
72
|
adjusted_r2,
|
|
70
73
|
explained_variance,
|
|
@@ -196,6 +199,8 @@ __all__ = [
|
|
|
196
199
|
"ClassificationReport",
|
|
197
200
|
"stats",
|
|
198
201
|
"roc_auc_ci",
|
|
202
|
+
"report_card",
|
|
203
|
+
"ReportCard",
|
|
199
204
|
"proportion_ci",
|
|
200
205
|
"paired_bootstrap_test",
|
|
201
206
|
"mcnemar_test",
|
|
@@ -230,6 +235,12 @@ __all__ = [
|
|
|
230
235
|
"cohen_kappa",
|
|
231
236
|
"confusion_matrix",
|
|
232
237
|
"evaluate",
|
|
238
|
+
"leaderboard",
|
|
239
|
+
"Monitor",
|
|
240
|
+
"Alert",
|
|
241
|
+
"population_stability_index",
|
|
242
|
+
"ks_drift",
|
|
243
|
+
"Leaderboard",
|
|
233
244
|
"explained_variance",
|
|
234
245
|
"f1",
|
|
235
246
|
"fbeta",
|
evalsuite/_evalci.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
"""Confidence intervals and baseline comparisons for :func:`evalsuite.evaluate`.
|
|
2
|
+
|
|
3
|
+
``ci="analytic"`` (the default) attaches closed-form intervals where a standard one exists and costs
|
|
4
|
+
nothing: Wilson intervals for proportions (accuracy, precision, recall, specificity, NPV), DeLong's interval
|
|
5
|
+
for binary ROC AUC, and Student-t intervals for metrics that are means of per-observation losses (Brier score,
|
|
6
|
+
log loss, MAE, MSE, mean bias error; RMSE from the MSE interval). ``ci="bootstrap"`` uses the paired percentile
|
|
7
|
+
bootstrap of :func:`evalsuite.compare` for every metric. A baseline (``baseline_pred`` / ``baseline_prob``)
|
|
8
|
+
adds paired tests against it: McNemar's test for accuracy, DeLong's test for binary ROC AUC and a paired
|
|
9
|
+
bootstrap test otherwise, with p-values adjusted within each metric (Holm).
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import inspect
|
|
15
|
+
import math
|
|
16
|
+
from typing import Any, Optional
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
|
|
20
|
+
from .core.exceptions import InputValidationError
|
|
21
|
+
from .core.result import EvaluationResult, MetricResult
|
|
22
|
+
|
|
23
|
+
_PROPORTIONS = {"precision", "recall", "specificity", "npv", "sensitivity", "ppv"}
|
|
24
|
+
_MEAN_LOSSES = {"brier_score", "log_loss", "mae", "mse", "rmse", "mean_bias_error"}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _t_quantile(level: float, df: int) -> float:
|
|
28
|
+
from scipy import stats
|
|
29
|
+
|
|
30
|
+
return float(stats.t.ppf(1 - (1 - level) / 2, df))
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _mean_ci(terms: np.ndarray, level: float) -> tuple[float, float]:
|
|
34
|
+
n = terms.shape[0]
|
|
35
|
+
if n < 2:
|
|
36
|
+
return math.nan, math.nan
|
|
37
|
+
m = float(np.mean(terms))
|
|
38
|
+
se = float(np.std(terms, ddof=1)) / math.sqrt(n)
|
|
39
|
+
q = _t_quantile(level, n - 1)
|
|
40
|
+
return m - q * se, m + q * se
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _analytic(
|
|
44
|
+
result: EvaluationResult,
|
|
45
|
+
y_true: Any,
|
|
46
|
+
y_pred: Any,
|
|
47
|
+
y_prob: Any,
|
|
48
|
+
level: float,
|
|
49
|
+
) -> dict[str, tuple[float, float, str]]:
|
|
50
|
+
"""Closed-form intervals for the metrics that have a standard one (unweighted data only)."""
|
|
51
|
+
from . import proportion_ci, roc_auc_ci
|
|
52
|
+
|
|
53
|
+
out: dict[str, tuple[float, float, str]] = {}
|
|
54
|
+
|
|
55
|
+
def wilson(k: int, n: int) -> Optional[tuple[float, float, str]]:
|
|
56
|
+
if n <= 0:
|
|
57
|
+
return None
|
|
58
|
+
ci = proportion_ci(int(k), int(n), level=level)
|
|
59
|
+
return ci.low, ci.high, "wilson"
|
|
60
|
+
|
|
61
|
+
if result.task == "classification":
|
|
62
|
+
cm = result.confusion_matrix
|
|
63
|
+
labels = list(result.labels or ())
|
|
64
|
+
for name, m in result.metrics.items():
|
|
65
|
+
if isinstance(m.value, np.ndarray):
|
|
66
|
+
continue
|
|
67
|
+
if name == "accuracy" and cm is not None:
|
|
68
|
+
c = wilson(int(np.trace(cm)), int(cm.sum()))
|
|
69
|
+
if c:
|
|
70
|
+
out[name] = c
|
|
71
|
+
elif name in _PROPORTIONS and cm is not None and m.params.get("average") == "binary":
|
|
72
|
+
pos = m.params.get("pos_label")
|
|
73
|
+
if pos not in labels:
|
|
74
|
+
continue
|
|
75
|
+
i = labels.index(pos)
|
|
76
|
+
tp = int(cm[i, i])
|
|
77
|
+
fp = int(cm[:, i].sum()) - tp
|
|
78
|
+
fn = int(cm[i, :].sum()) - tp
|
|
79
|
+
tn = int(cm.sum()) - tp - fp - fn
|
|
80
|
+
k, n = {
|
|
81
|
+
"precision": (tp, tp + fp),
|
|
82
|
+
"ppv": (tp, tp + fp),
|
|
83
|
+
"recall": (tp, tp + fn),
|
|
84
|
+
"sensitivity": (tp, tp + fn),
|
|
85
|
+
"specificity": (tn, tn + fp),
|
|
86
|
+
"npv": (tn, tn + fn),
|
|
87
|
+
}[name]
|
|
88
|
+
c = wilson(k, n)
|
|
89
|
+
if c:
|
|
90
|
+
out[name] = c
|
|
91
|
+
elif result.target_type == "binary" and y_prob is not None and np.ndim(y_prob) == 1:
|
|
92
|
+
pos = m.params.get("pos_label")
|
|
93
|
+
if name == "roc_auc":
|
|
94
|
+
ci = roc_auc_ci(y_true, y_prob, level=level, pos_label=pos)
|
|
95
|
+
out[name] = (ci.low, ci.high, "delong")
|
|
96
|
+
elif name in ("brier_score", "log_loss"):
|
|
97
|
+
yt = np.asarray(y_true)
|
|
98
|
+
positive = pos if pos is not None else (labels[-1] if labels else 1)
|
|
99
|
+
y = (yt == positive).astype(float)
|
|
100
|
+
p = np.asarray(y_prob, dtype=float)
|
|
101
|
+
if name == "brier_score":
|
|
102
|
+
terms = (p - y) ** 2
|
|
103
|
+
else:
|
|
104
|
+
eps = np.finfo(np.float64).eps
|
|
105
|
+
q = np.clip(p, eps, 1 - eps)
|
|
106
|
+
terms = -(y * np.log(q) + (1 - y) * np.log(1 - q))
|
|
107
|
+
lo, hi = _mean_ci(terms, level)
|
|
108
|
+
out[name] = (max(0.0, lo), hi, "t")
|
|
109
|
+
elif result.task == "regression" and np.ndim(y_true) == 1:
|
|
110
|
+
e = np.asarray(y_pred, dtype=float) - np.asarray(y_true, dtype=float)
|
|
111
|
+
for name in result.metrics:
|
|
112
|
+
if name == "mae":
|
|
113
|
+
lo, hi = _mean_ci(np.abs(e), level)
|
|
114
|
+
out[name] = (max(0.0, lo), hi, "t")
|
|
115
|
+
elif name in ("mse", "rmse"):
|
|
116
|
+
lo, hi = _mean_ci(e * e, level)
|
|
117
|
+
lo = max(0.0, lo)
|
|
118
|
+
out[name] = (lo, hi, "t") if name == "mse" else (math.sqrt(lo), math.sqrt(hi), "t (from MSE)")
|
|
119
|
+
elif name == "mean_bias_error":
|
|
120
|
+
lo, hi = _mean_ci(e, level)
|
|
121
|
+
out[name] = (lo, hi, "t")
|
|
122
|
+
return out
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _metric_kwargs(names: list[str], result: EvaluationResult) -> dict[str, dict[str, Any]]:
|
|
126
|
+
"""Options that reproduce each metric exactly as evaluate() computed it."""
|
|
127
|
+
from .stats._resolve import resolve_metric
|
|
128
|
+
|
|
129
|
+
out: dict[str, dict[str, Any]] = {}
|
|
130
|
+
for name in names:
|
|
131
|
+
fn, _ = resolve_metric(name)
|
|
132
|
+
accepted = set(inspect.signature(fn).parameters)
|
|
133
|
+
params = dict(result.metrics[name].params)
|
|
134
|
+
kw: dict[str, Any] = {
|
|
135
|
+
k: params[k] for k in ("average", "pos_label", "zero_division") if k in accepted and k in params
|
|
136
|
+
}
|
|
137
|
+
if "average" in kw and kw["average"] in ("auto",):
|
|
138
|
+
kw.pop("average")
|
|
139
|
+
out[name] = kw
|
|
140
|
+
return out
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def attach(
|
|
144
|
+
result: EvaluationResult,
|
|
145
|
+
y_true: Any,
|
|
146
|
+
y_pred: Any,
|
|
147
|
+
y_prob: Any,
|
|
148
|
+
*,
|
|
149
|
+
ci: Any,
|
|
150
|
+
level: float,
|
|
151
|
+
baseline_pred: Any,
|
|
152
|
+
baseline_prob: Any,
|
|
153
|
+
n_resamples: int,
|
|
154
|
+
random_state: Optional[int],
|
|
155
|
+
sample_weight: Any,
|
|
156
|
+
) -> EvaluationResult:
|
|
157
|
+
"""Return ``result`` with intervals in each metric's params (``ci_low``, ``ci_high``, ``ci_level``,
|
|
158
|
+
``ci_method``) and, with a baseline, the paired comparison (``baseline_*`` params and ``comparison``)."""
|
|
159
|
+
if ci in (None, False, "none"):
|
|
160
|
+
mode = "none"
|
|
161
|
+
elif ci is True or ci == "analytic":
|
|
162
|
+
mode = "analytic"
|
|
163
|
+
elif ci == "bootstrap":
|
|
164
|
+
mode = "bootstrap"
|
|
165
|
+
else:
|
|
166
|
+
raise InputValidationError("ci must be 'analytic' (default), 'bootstrap', or False.")
|
|
167
|
+
has_baseline = baseline_pred is not None or baseline_prob is not None
|
|
168
|
+
if mode == "none" and not has_baseline:
|
|
169
|
+
return result
|
|
170
|
+
names = [k for k, m in result.metrics.items() if not isinstance(m.value, np.ndarray)]
|
|
171
|
+
intervals: dict[str, tuple[float, float, str]] = {}
|
|
172
|
+
if mode == "analytic" and sample_weight is None:
|
|
173
|
+
intervals = _analytic(result, y_true, y_pred, y_prob, level)
|
|
174
|
+
comparison = None
|
|
175
|
+
if mode == "bootstrap" or has_baseline:
|
|
176
|
+
from .stats.compare import compare
|
|
177
|
+
|
|
178
|
+
preds: dict[str, Any] = {}
|
|
179
|
+
probs: dict[str, Any] = {}
|
|
180
|
+
if y_pred is not None:
|
|
181
|
+
preds["model"] = y_pred
|
|
182
|
+
if y_prob is not None:
|
|
183
|
+
probs["model"] = y_prob
|
|
184
|
+
if baseline_pred is not None:
|
|
185
|
+
preds["baseline"] = baseline_pred
|
|
186
|
+
if baseline_prob is not None:
|
|
187
|
+
probs["baseline"] = baseline_prob
|
|
188
|
+
from .stats.compare import _needs_prob
|
|
189
|
+
|
|
190
|
+
usable = [n for n in names if not has_baseline or ("baseline" in (probs if _needs_prob(n) else preds))]
|
|
191
|
+
if has_baseline and not usable:
|
|
192
|
+
raise InputValidationError(
|
|
193
|
+
"The baseline needs the same kind of input as the metrics: baseline_pred for label/value metrics, "
|
|
194
|
+
"baseline_prob for probability metrics."
|
|
195
|
+
)
|
|
196
|
+
comparison = compare(
|
|
197
|
+
y_true,
|
|
198
|
+
preds,
|
|
199
|
+
probabilities=probs,
|
|
200
|
+
metrics=usable,
|
|
201
|
+
baseline="baseline" if has_baseline else None,
|
|
202
|
+
level=level,
|
|
203
|
+
n_resamples=n_resamples,
|
|
204
|
+
random_state=random_state,
|
|
205
|
+
sample_weight=sample_weight,
|
|
206
|
+
metric_kwargs=_metric_kwargs(usable, result),
|
|
207
|
+
_allow_single=True,
|
|
208
|
+
)
|
|
209
|
+
if mode == "bootstrap" and comparison is not None:
|
|
210
|
+
for e in comparison.estimates:
|
|
211
|
+
if e["model"] == "model":
|
|
212
|
+
intervals[e["metric"]] = (e["low"], e["high"], "percentile bootstrap")
|
|
213
|
+
tests = {t["metric"]: t for t in comparison.tests} if comparison is not None and has_baseline else {}
|
|
214
|
+
base_values = (
|
|
215
|
+
{e["metric"]: e["estimate"] for e in comparison.estimates if e["model"] == "baseline"}
|
|
216
|
+
if tests and comparison is not None
|
|
217
|
+
else {}
|
|
218
|
+
)
|
|
219
|
+
metrics: dict[str, MetricResult] = {}
|
|
220
|
+
for key, m in result.metrics.items():
|
|
221
|
+
extra: dict[str, Any] = {}
|
|
222
|
+
if key in intervals:
|
|
223
|
+
lo, hi, method = intervals[key]
|
|
224
|
+
extra.update(ci_low=float(lo), ci_high=float(hi), ci_level=level, ci_method=method)
|
|
225
|
+
if key in tests:
|
|
226
|
+
t = tests[key]
|
|
227
|
+
extra.update(
|
|
228
|
+
baseline_value=float(base_values[key]),
|
|
229
|
+
baseline_difference=float(t["difference"]),
|
|
230
|
+
baseline_ci_low=float(t["ci_low"]),
|
|
231
|
+
baseline_ci_high=float(t["ci_high"]),
|
|
232
|
+
baseline_test=t["test"],
|
|
233
|
+
baseline_p_value=float(t["p_value"]),
|
|
234
|
+
baseline_p_adjusted=float(t["p_adjusted"]),
|
|
235
|
+
)
|
|
236
|
+
metrics[key] = MetricResult(m.metric, m.name, m.value, {**m.params, **extra}, m.labels) if extra else m
|
|
237
|
+
return EvaluationResult(
|
|
238
|
+
task=result.task,
|
|
239
|
+
metrics=metrics,
|
|
240
|
+
n_samples=result.n_samples,
|
|
241
|
+
target_type=result.target_type,
|
|
242
|
+
labels=result.labels,
|
|
243
|
+
confusion_matrix=result.confusion_matrix,
|
|
244
|
+
metadata={
|
|
245
|
+
**result.metadata,
|
|
246
|
+
"ci": mode,
|
|
247
|
+
"ci_level": level,
|
|
248
|
+
**({"n_resamples": n_resamples, "random_state": random_state} if comparison is not None else {}),
|
|
249
|
+
},
|
|
250
|
+
comparison=comparison,
|
|
251
|
+
)
|
evalsuite/api.py
CHANGED
|
@@ -138,8 +138,15 @@ def evaluate(
|
|
|
138
138
|
pos_label: Any = None,
|
|
139
139
|
sample_weight: Optional[ArrayLike] = None,
|
|
140
140
|
zero_division: ZeroDivision = "warn",
|
|
141
|
+
ci: Any = "analytic",
|
|
142
|
+
level: float = 0.95,
|
|
143
|
+
baseline_pred: Optional[ArrayLike] = None,
|
|
144
|
+
baseline_prob: Optional[ArrayLike] = None,
|
|
145
|
+
n_resamples: int = 1000,
|
|
146
|
+
random_state: Optional[int] = 0,
|
|
141
147
|
) -> EvaluationResult:
|
|
142
|
-
"""Evaluate predictions with a standard set of metrics (or the ``metrics`` you name)
|
|
148
|
+
"""Evaluate predictions with a standard set of metrics (or the ``metrics`` you name), with confidence
|
|
149
|
+
intervals and, given a baseline, paired significance tests against it.
|
|
143
150
|
|
|
144
151
|
The task is inferred when omitted: probabilities or integer/string labels mean classification, non-integer
|
|
145
152
|
numbers mean regression. Inputs are validated once and shared intermediate results (the confusion matrix)
|
|
@@ -149,6 +156,15 @@ def evaluate(
|
|
|
149
156
|
>>> r = es.evaluate([0, 1, 1, 0], [0, 1, 0, 0])
|
|
150
157
|
>>> round(r["accuracy"], 2)
|
|
151
158
|
0.75
|
|
159
|
+
|
|
160
|
+
Intervals (``level``, 95% by default) are in each metric's ``params`` (``ci_low``, ``ci_high``,
|
|
161
|
+
``ci_method``) and in every summary and export. ``ci="analytic"`` (default, no extra cost) gives closed-form
|
|
162
|
+
intervals where a standard one exists: Wilson for accuracy / precision / recall / specificity / NPV, DeLong
|
|
163
|
+
for binary ROC AUC, Student-t for mean losses (Brier, log loss, MAE, MSE, RMSE, mean bias).
|
|
164
|
+
``ci="bootstrap"`` gives paired percentile-bootstrap intervals for every metric (``n_resamples``, seeded by
|
|
165
|
+
``random_state``); ``ci=False`` turns them off. ``baseline_pred`` / ``baseline_prob`` (e.g. the current model)
|
|
166
|
+
add the difference, its interval and a paired test per metric (McNemar for accuracy, DeLong for ROC AUC,
|
|
167
|
+
paired bootstrap otherwise; Holm-adjusted), as ``baseline_*`` params and ``result.comparison``.
|
|
152
168
|
"""
|
|
153
169
|
if isinstance(y_true, (list, tuple)) and y_true and isinstance(y_true[0], dict):
|
|
154
170
|
raise UnsupportedTaskError(
|
|
@@ -162,14 +178,30 @@ def evaluate(
|
|
|
162
178
|
)
|
|
163
179
|
task = task or _infer_task(y_true, y_prob)
|
|
164
180
|
if task == "classification":
|
|
165
|
-
|
|
181
|
+
result = _evaluate_classification(
|
|
166
182
|
y_true, y_pred, y_prob, metrics, average, labels, pos_label, sample_weight, zero_division
|
|
167
183
|
)
|
|
168
|
-
|
|
184
|
+
elif task == "regression":
|
|
169
185
|
if y_pred is None:
|
|
170
186
|
raise InputValidationError("Regression evaluation needs y_pred.")
|
|
171
|
-
|
|
172
|
-
|
|
187
|
+
result = _evaluate_regression(y_true, y_pred, metrics, sample_weight)
|
|
188
|
+
else:
|
|
189
|
+
raise UnsupportedTaskError("task must be 'classification' or 'regression' in EvalSuite 0.1.")
|
|
190
|
+
from ._evalci import attach
|
|
191
|
+
|
|
192
|
+
return attach(
|
|
193
|
+
result,
|
|
194
|
+
y_true,
|
|
195
|
+
y_pred,
|
|
196
|
+
y_prob,
|
|
197
|
+
ci=ci,
|
|
198
|
+
level=level,
|
|
199
|
+
baseline_pred=baseline_pred,
|
|
200
|
+
baseline_prob=baseline_prob,
|
|
201
|
+
n_resamples=n_resamples,
|
|
202
|
+
random_state=random_state,
|
|
203
|
+
sample_weight=sample_weight,
|
|
204
|
+
)
|
|
173
205
|
|
|
174
206
|
|
|
175
207
|
def _metadata(**extra: Any) -> dict[str, Any]:
|