evalsuite-python 0.6.0__cp39-abi3-win_arm64.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 +268 -0
- evalsuite/__main__.py +5 -0
- evalsuite/_bench_metrics.py +2080 -0
- evalsuite/_core.pyd +0 -0
- evalsuite/_lazy.py +32 -0
- evalsuite/_native.py +60 -0
- evalsuite/api.py +275 -0
- evalsuite/benchmarks.py +946 -0
- evalsuite/calibration.py +392 -0
- evalsuite/classification/__init__.py +51 -0
- evalsuite/classification/_common.py +111 -0
- evalsuite/classification/metrics.py +945 -0
- evalsuite/cli/__init__.py +5 -0
- evalsuite/cli/main.py +606 -0
- evalsuite/clinical/__init__.py +18 -0
- evalsuite/clinical/metrics.py +342 -0
- evalsuite/clinical/report.py +366 -0
- evalsuite/core/__init__.py +1 -0
- evalsuite/core/context.py +199 -0
- evalsuite/core/exceptions.py +52 -0
- evalsuite/core/export.py +100 -0
- evalsuite/core/registry.py +90 -0
- evalsuite/core/result.py +379 -0
- evalsuite/core/types.py +23 -0
- evalsuite/core/validation.py +256 -0
- evalsuite/llmsys/__init__.py +189 -0
- evalsuite/llmsys/_common.py +215 -0
- evalsuite/llmsys/agents.py +384 -0
- evalsuite/llmsys/code.py +923 -0
- evalsuite/llmsys/efficiency.py +346 -0
- evalsuite/llmsys/longcontext.py +361 -0
- evalsuite/llmsys/multilingual.py +339 -0
- evalsuite/llmsys/robustness.py +504 -0
- evalsuite/llmsys/safety.py +509 -0
- evalsuite/llmsys/uncertainty.py +229 -0
- evalsuite/plot.py +651 -0
- evalsuite/py.typed +0 -0
- evalsuite/regression/__init__.py +41 -0
- evalsuite/regression/metrics.py +629 -0
- evalsuite/reporting.py +241 -0
- evalsuite/stats/__init__.py +46 -0
- evalsuite/stats/_resolve.py +229 -0
- evalsuite/stats/compare.py +420 -0
- evalsuite/stats/effect.py +159 -0
- evalsuite/stats/hypothesis.py +593 -0
- evalsuite/stats/intervals.py +338 -0
- evalsuite/stats/paired.py +214 -0
- evalsuite/stats/results.py +129 -0
- evalsuite/text/__init__.py +154 -0
- evalsuite/text/_common.py +97 -0
- evalsuite/text/factuality.py +469 -0
- evalsuite/text/generation.py +1346 -0
- evalsuite/text/judge.py +556 -0
- evalsuite/text/qa.py +108 -0
- evalsuite/text/rag.py +235 -0
- evalsuite/text/reasoning.py +215 -0
- evalsuite/text/report.py +158 -0
- evalsuite/text/retrieval.py +238 -0
- evalsuite/text/semantic.py +499 -0
- evalsuite/text/spice.py +162 -0
- evalsuite/text/structured.py +793 -0
- evalsuite/version.py +3 -0
- evalsuite/vision/__init__.py +47 -0
- evalsuite/vision/detection.py +696 -0
- evalsuite/vision/segmentation.py +1028 -0
- evalsuite_python-0.6.0.dist-info/METADATA +509 -0
- evalsuite_python-0.6.0.dist-info/RECORD +72 -0
- evalsuite_python-0.6.0.dist-info/WHEEL +4 -0
- evalsuite_python-0.6.0.dist-info/entry_points.txt +2 -0
- evalsuite_python-0.6.0.dist-info/licenses/LICENSE +21 -0
- evalsuite_python-0.6.0.dist-info/licenses/LICENSE-APACHE +191 -0
- evalsuite_python-0.6.0.dist-info/sboms/evalsuite-py.cyclonedx.json +576 -0
evalsuite/plot.py
ADDED
|
@@ -0,0 +1,651 @@
|
|
|
1
|
+
"""Publication-ready plots (optional dependency: ``pip install "evalsuite-python[plot]"``).
|
|
2
|
+
|
|
3
|
+
Every function draws on ``ax`` (or a new figure), returns the matplotlib ``Axes`` and computes its numbers
|
|
4
|
+
with EvalSuite's own metrics, so the plot and the reported values always agree. Several models can be passed
|
|
5
|
+
as a dict ``{name: values}``; they get distinct colours *and* line styles, so plots stay readable in
|
|
6
|
+
greyscale. Matplotlib is imported only when a plot function is called.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from collections.abc import Mapping
|
|
12
|
+
from typing import TYPE_CHECKING, Any, Optional, Union, cast
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
|
|
16
|
+
from .core.exceptions import InputValidationError, OptionalDependencyError
|
|
17
|
+
from .core.types import ArrayLike
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING:
|
|
20
|
+
from matplotlib.axes import Axes
|
|
21
|
+
|
|
22
|
+
from .stats.compare import ComparisonResult
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"calibration",
|
|
26
|
+
"comparison",
|
|
27
|
+
"confusion_matrix",
|
|
28
|
+
"decision_curve",
|
|
29
|
+
"detection_pr",
|
|
30
|
+
"per_class",
|
|
31
|
+
"pr",
|
|
32
|
+
"residuals",
|
|
33
|
+
"roc",
|
|
34
|
+
"segmentation",
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
Scores = Union[ArrayLike, Mapping[str, ArrayLike]]
|
|
38
|
+
_STYLES = ("-", "--", "-.", ":")
|
|
39
|
+
_MARKERS = ("o", "s", "^", "D", "v", "P")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _plt() -> Any:
|
|
43
|
+
try:
|
|
44
|
+
import matplotlib.pyplot as plt
|
|
45
|
+
except ImportError as exc:
|
|
46
|
+
raise OptionalDependencyError("matplotlib", "plot", "Plotting") from exc
|
|
47
|
+
return plt
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _axes(ax: Optional[Axes], figsize: tuple[float, float] = (5.0, 4.2)) -> Axes:
|
|
51
|
+
if ax is not None:
|
|
52
|
+
return ax
|
|
53
|
+
_, new_ax = _plt().subplots(figsize=figsize, layout="constrained")
|
|
54
|
+
return cast("Axes", new_ax)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _models(values: Scores, label: Optional[str]) -> list[tuple[Optional[str], Any]]:
|
|
58
|
+
if isinstance(values, Mapping):
|
|
59
|
+
if not values:
|
|
60
|
+
raise InputValidationError("Pass at least one model.")
|
|
61
|
+
return [(str(k), v) for k, v in values.items()]
|
|
62
|
+
return [(label, values)]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _style(i: int) -> dict[str, Any]:
|
|
66
|
+
return {"linestyle": _STYLES[i % len(_STYLES)], "linewidth": 1.8}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def roc(
|
|
70
|
+
y_true: ArrayLike,
|
|
71
|
+
y_prob: Scores,
|
|
72
|
+
*,
|
|
73
|
+
ax: Optional[Axes] = None,
|
|
74
|
+
label: Optional[str] = None,
|
|
75
|
+
pos_label: Any = None,
|
|
76
|
+
sample_weight: Optional[ArrayLike] = None,
|
|
77
|
+
chance: bool = True,
|
|
78
|
+
) -> Axes:
|
|
79
|
+
"""ROC curve(s) for binary probabilities, with the AUC in the legend.
|
|
80
|
+
|
|
81
|
+
``y_prob``: P(positive) for one model, or ``{name: probabilities}`` for several.
|
|
82
|
+
"""
|
|
83
|
+
from .classification.metrics import roc_auc, roc_curve
|
|
84
|
+
|
|
85
|
+
ax = _axes(ax)
|
|
86
|
+
for i, (name, prob) in enumerate(_models(y_prob, label)):
|
|
87
|
+
fpr, tpr, _ = roc_curve(y_true, prob, pos_label=pos_label, sample_weight=sample_weight)
|
|
88
|
+
auc = float(roc_auc(y_true, prob, pos_label=pos_label, sample_weight=sample_weight))
|
|
89
|
+
ax.plot(
|
|
90
|
+
fpr, tpr, drawstyle="steps-post", label=f"{name + ': ' if name else ''}AUC = {auc:.3f}", **_style(i)
|
|
91
|
+
)
|
|
92
|
+
if chance:
|
|
93
|
+
ax.plot([0, 1], [0, 1], color="0.6", linewidth=1, linestyle=":", label="chance")
|
|
94
|
+
ax.set(
|
|
95
|
+
xlabel="False positive rate (1 − specificity)",
|
|
96
|
+
ylabel="True positive rate (sensitivity)",
|
|
97
|
+
title="ROC curve",
|
|
98
|
+
xlim=(-0.01, 1.01),
|
|
99
|
+
ylim=(-0.01, 1.01),
|
|
100
|
+
)
|
|
101
|
+
ax.set_aspect("equal")
|
|
102
|
+
ax.legend(loc="lower right", frameon=False)
|
|
103
|
+
return ax
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def pr(
|
|
107
|
+
y_true: ArrayLike,
|
|
108
|
+
y_prob: Scores,
|
|
109
|
+
*,
|
|
110
|
+
ax: Optional[Axes] = None,
|
|
111
|
+
label: Optional[str] = None,
|
|
112
|
+
pos_label: Any = None,
|
|
113
|
+
sample_weight: Optional[ArrayLike] = None,
|
|
114
|
+
chance: bool = True,
|
|
115
|
+
) -> Axes:
|
|
116
|
+
"""Precision-recall curve(s) with average precision in the legend; the chance line is the prevalence."""
|
|
117
|
+
from .classification.metrics import _binary_target, _ctx, average_precision, pr_curve
|
|
118
|
+
|
|
119
|
+
ax = _axes(ax)
|
|
120
|
+
for i, (name, prob) in enumerate(_models(y_prob, label)):
|
|
121
|
+
prec, rec, _ = pr_curve(y_true, prob, pos_label=pos_label, sample_weight=sample_weight)
|
|
122
|
+
ap = float(average_precision(y_true, prob, pos_label=pos_label, sample_weight=sample_weight))
|
|
123
|
+
ax.plot(
|
|
124
|
+
rec, prec, drawstyle="steps-post", label=f"{name + ': ' if name else ''}AP = {ap:.3f}", **_style(i)
|
|
125
|
+
)
|
|
126
|
+
if chance:
|
|
127
|
+
first = _models(y_prob, label)[0][1]
|
|
128
|
+
ctx = _ctx(y_true, None, y_prob=first, sample_weight=sample_weight)
|
|
129
|
+
prevalence = float(np.average(_binary_target(ctx, pos_label), weights=ctx.weights))
|
|
130
|
+
ax.axhline(prevalence, color="0.6", linewidth=1, linestyle=":", label=f"chance ({prevalence:.2f})")
|
|
131
|
+
ax.set(
|
|
132
|
+
xlabel="Recall (sensitivity)",
|
|
133
|
+
ylabel="Precision (PPV)",
|
|
134
|
+
title="Precision-recall curve",
|
|
135
|
+
xlim=(-0.01, 1.01),
|
|
136
|
+
ylim=(-0.01, 1.03),
|
|
137
|
+
)
|
|
138
|
+
ax.legend(loc="lower left", frameon=False)
|
|
139
|
+
return ax
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def confusion_matrix(
|
|
143
|
+
y_true: ArrayLike,
|
|
144
|
+
y_pred: ArrayLike,
|
|
145
|
+
*,
|
|
146
|
+
ax: Optional[Axes] = None,
|
|
147
|
+
labels: Optional[ArrayLike] = None,
|
|
148
|
+
normalize: Optional[str] = None,
|
|
149
|
+
sample_weight: Optional[ArrayLike] = None,
|
|
150
|
+
cmap: str = "Blues",
|
|
151
|
+
colorbar: bool = True,
|
|
152
|
+
) -> Axes:
|
|
153
|
+
"""Annotated confusion matrix (rows: true, columns: predicted). ``normalize``: None, "true", "pred", "all"."""
|
|
154
|
+
from .classification.metrics import confusion_matrix as cm_fn
|
|
155
|
+
from .core.validation import resolve_labels, to_numpy
|
|
156
|
+
|
|
157
|
+
cm = np.asarray(cm_fn(y_true, y_pred, labels=labels, sample_weight=sample_weight, normalize=normalize)) # type: ignore[arg-type]
|
|
158
|
+
names = (
|
|
159
|
+
to_numpy(labels, "labels")
|
|
160
|
+
if labels is not None
|
|
161
|
+
else resolve_labels(to_numpy(y_true, "y_true"), to_numpy(y_pred, "y_pred"), None)
|
|
162
|
+
).tolist()
|
|
163
|
+
k = cm.shape[0]
|
|
164
|
+
ax = _axes(ax, (max(3.6, 0.7 * k + 2.4), max(3.2, 0.7 * k + 1.8)))
|
|
165
|
+
image = ax.imshow(cm, cmap=cmap, vmin=0, vmax=1 if normalize else None)
|
|
166
|
+
threshold = (cm.max() + cm.min()) / 2
|
|
167
|
+
integral = normalize is None and np.all(np.mod(cm, 1) == 0)
|
|
168
|
+
for i in range(k):
|
|
169
|
+
for j in range(k):
|
|
170
|
+
text = f"{int(cm[i, j])}" if integral else f"{cm[i, j]:.2f}"
|
|
171
|
+
ax.text(
|
|
172
|
+
j,
|
|
173
|
+
i,
|
|
174
|
+
text,
|
|
175
|
+
ha="center",
|
|
176
|
+
va="center",
|
|
177
|
+
fontsize=9,
|
|
178
|
+
color="white" if cm[i, j] > threshold else "black",
|
|
179
|
+
)
|
|
180
|
+
ax.set(
|
|
181
|
+
xticks=range(k),
|
|
182
|
+
yticks=range(k),
|
|
183
|
+
xticklabels=names,
|
|
184
|
+
yticklabels=names,
|
|
185
|
+
xlabel="Predicted label",
|
|
186
|
+
ylabel="True label",
|
|
187
|
+
title="Confusion matrix" + (f" (normalised by {normalize})" if normalize else ""),
|
|
188
|
+
)
|
|
189
|
+
if colorbar:
|
|
190
|
+
ax.figure.colorbar(image, ax=ax, fraction=0.046, pad=0.04)
|
|
191
|
+
return ax
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def calibration(
|
|
195
|
+
y_true: ArrayLike,
|
|
196
|
+
y_prob: Scores,
|
|
197
|
+
*,
|
|
198
|
+
ax: Optional[Axes] = None,
|
|
199
|
+
label: Optional[str] = None,
|
|
200
|
+
n_bins: int = 10,
|
|
201
|
+
strategy: str = "uniform",
|
|
202
|
+
pos_label: Any = None,
|
|
203
|
+
sample_weight: Optional[ArrayLike] = None,
|
|
204
|
+
legend_loc: str = "below",
|
|
205
|
+
) -> Axes:
|
|
206
|
+
"""Reliability diagram: observed frequency against mean predicted probability per bin, with ECE and Brier
|
|
207
|
+
score in the legend; the diagonal is perfect calibration.
|
|
208
|
+
|
|
209
|
+
``legend_loc="below"`` (default) puts the legend under the axes so it never covers the curves; any
|
|
210
|
+
matplotlib location (e.g. ``"upper left"``) places it inside instead."""
|
|
211
|
+
from .classification.metrics import brier_score, calibration_curve, expected_calibration_error
|
|
212
|
+
|
|
213
|
+
ax = _axes(ax)
|
|
214
|
+
ax.plot([0, 1], [0, 1], color="0.6", linewidth=1, linestyle=":", label="perfect calibration")
|
|
215
|
+
kw = {"n_bins": n_bins, "strategy": strategy, "pos_label": pos_label, "sample_weight": sample_weight}
|
|
216
|
+
for i, (name, prob) in enumerate(_models(y_prob, label)):
|
|
217
|
+
frac, mean_p, _ = calibration_curve(y_true, prob, **kw)
|
|
218
|
+
ece = float(expected_calibration_error(y_true, prob, **kw))
|
|
219
|
+
brier = float(brier_score(y_true, prob, pos_label=pos_label, sample_weight=sample_weight))
|
|
220
|
+
ax.plot(
|
|
221
|
+
mean_p,
|
|
222
|
+
frac,
|
|
223
|
+
marker=_MARKERS[i % len(_MARKERS)],
|
|
224
|
+
markersize=4,
|
|
225
|
+
label=f"{name + ': ' if name else ''}ECE = {ece:.3f}, Brier = {brier:.3f}",
|
|
226
|
+
**_style(i),
|
|
227
|
+
)
|
|
228
|
+
ax.set(
|
|
229
|
+
xlabel="Mean predicted probability",
|
|
230
|
+
ylabel="Observed frequency of positives",
|
|
231
|
+
title="Calibration",
|
|
232
|
+
xlim=(-0.01, 1.01),
|
|
233
|
+
ylim=(-0.01, 1.01),
|
|
234
|
+
)
|
|
235
|
+
ax.set_aspect("equal")
|
|
236
|
+
if legend_loc == "below":
|
|
237
|
+
ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.14), frameon=False, fontsize="small")
|
|
238
|
+
else:
|
|
239
|
+
ax.legend(loc=legend_loc, frameon=False) # type: ignore[call-overload]
|
|
240
|
+
return ax
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def residuals(
|
|
244
|
+
y_true: ArrayLike,
|
|
245
|
+
y_pred: ArrayLike,
|
|
246
|
+
*,
|
|
247
|
+
ax: Optional[Axes] = None,
|
|
248
|
+
kind: str = "residuals",
|
|
249
|
+
) -> Axes:
|
|
250
|
+
"""Regression diagnostics. ``kind="residuals"``: residual (predicted − true) against predicted value;
|
|
251
|
+
``kind="predicted"``: predicted against true with the identity line. RMSE and R² in the title."""
|
|
252
|
+
from .regression.metrics import _Inputs, r2, rmse
|
|
253
|
+
|
|
254
|
+
inp = _Inputs(y_true, y_pred, None)
|
|
255
|
+
if inp.multi:
|
|
256
|
+
raise InputValidationError("residuals() plots single-output targets; pass one output column at a time.")
|
|
257
|
+
yt, yp = inp.y_true[:, 0], inp.y_pred[:, 0]
|
|
258
|
+
ax = _axes(ax)
|
|
259
|
+
stats = f"RMSE = {float(rmse(yt, yp)):.3g}, R² = {float(r2(yt, yp)):.3f}"
|
|
260
|
+
if kind == "residuals":
|
|
261
|
+
ax.scatter(yp, yp - yt, s=14, alpha=0.7, edgecolors="none")
|
|
262
|
+
ax.axhline(0, color="0.4", linewidth=1)
|
|
263
|
+
ax.set(xlabel="Predicted value", ylabel="Residual (predicted − true)", title=f"Residuals ({stats})")
|
|
264
|
+
elif kind == "predicted":
|
|
265
|
+
lo, hi = float(min(np.min(yt), np.min(yp))), float(max(np.max(yt), np.max(yp)))
|
|
266
|
+
ax.scatter(yt, yp, s=14, alpha=0.7, edgecolors="none")
|
|
267
|
+
ax.plot([lo, hi], [lo, hi], color="0.4", linewidth=1, linestyle=":", label="y = x")
|
|
268
|
+
ax.set(xlabel="True value", ylabel="Predicted value", title=f"Predicted vs true ({stats})")
|
|
269
|
+
ax.legend(loc="upper left", frameon=False)
|
|
270
|
+
else:
|
|
271
|
+
raise InputValidationError("kind must be 'residuals' or 'predicted'.")
|
|
272
|
+
return ax
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def comparison(
|
|
276
|
+
result: ComparisonResult,
|
|
277
|
+
*,
|
|
278
|
+
metrics: Optional[list[str]] = None,
|
|
279
|
+
ax: Optional[Axes] = None,
|
|
280
|
+
) -> Axes:
|
|
281
|
+
"""Forest plot of an :func:`evalsuite.compare` result: each model's estimate with its confidence interval,
|
|
282
|
+
grouped by metric; the best model per metric is drawn filled."""
|
|
283
|
+
names = list(metrics or result.metrics)
|
|
284
|
+
unknown = [m for m in names if m not in result.metrics]
|
|
285
|
+
if unknown:
|
|
286
|
+
raise InputValidationError(f"Metric(s) {unknown} were not compared. Compared: {list(result.metrics)}.")
|
|
287
|
+
rows = [(m, model) for m in names for model in result.models]
|
|
288
|
+
ax = _axes(ax, (6.0, max(2.5, 0.38 * len(rows) + 1.2)))
|
|
289
|
+
for y_pos, (metric, model) in enumerate(rows):
|
|
290
|
+
est = result.estimate(model, metric)
|
|
291
|
+
best = result.best(metric) == model
|
|
292
|
+
ax.errorbar(
|
|
293
|
+
est["estimate"],
|
|
294
|
+
y_pos,
|
|
295
|
+
xerr=[[est["estimate"] - est["low"]], [est["high"] - est["estimate"]]],
|
|
296
|
+
fmt="o",
|
|
297
|
+
capsize=3,
|
|
298
|
+
color="C0",
|
|
299
|
+
markerfacecolor="C0" if best else "white",
|
|
300
|
+
markersize=6,
|
|
301
|
+
)
|
|
302
|
+
ax.set_yticks(range(len(rows)), [f"{metric} · {model}" for metric, model in rows])
|
|
303
|
+
ax.invert_yaxis()
|
|
304
|
+
level = round(result.settings["level"] * 100, 6)
|
|
305
|
+
ax.set(xlabel=f"Estimate with {level:g}% CI (filled: best per metric)", title="Model comparison")
|
|
306
|
+
ax.grid(axis="x", color="0.9")
|
|
307
|
+
return ax
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def decision_curve(
|
|
311
|
+
y_true: ArrayLike,
|
|
312
|
+
y_prob: Scores,
|
|
313
|
+
*,
|
|
314
|
+
ax: Optional[Axes] = None,
|
|
315
|
+
label: Optional[str] = None,
|
|
316
|
+
thresholds: Optional[ArrayLike] = None,
|
|
317
|
+
pos_label: Any = None,
|
|
318
|
+
sample_weight: Optional[ArrayLike] = None,
|
|
319
|
+
ylim: Optional[tuple[float, float]] = None,
|
|
320
|
+
) -> Axes:
|
|
321
|
+
"""Decision curve: net benefit against threshold probability for each model, with *treat all* and
|
|
322
|
+
*treat none* references (Vickers & Elkin 2006). Values come from :func:`evalsuite.decision_curve`.
|
|
323
|
+
|
|
324
|
+
By default the y-axis runs from a little below 0 to a little above the prevalence, where the
|
|
325
|
+
clinically meaningful part of the curve lies; pass ``ylim`` to change it."""
|
|
326
|
+
from .clinical.report import decision_curve as _dc
|
|
327
|
+
|
|
328
|
+
models = dict(_models(y_prob, label))
|
|
329
|
+
names = [n if n is not None else "model" for n in models]
|
|
330
|
+
dc = _dc(
|
|
331
|
+
y_true,
|
|
332
|
+
dict(zip(names, models.values())),
|
|
333
|
+
thresholds=thresholds,
|
|
334
|
+
pos_label=pos_label,
|
|
335
|
+
sample_weight=sample_weight,
|
|
336
|
+
)
|
|
337
|
+
ax = _axes(ax)
|
|
338
|
+
t = dc.thresholds
|
|
339
|
+
for i, name in enumerate(dc.net_benefit):
|
|
340
|
+
ax.plot(t, dc.net_benefit[name], label=name, **_style(i))
|
|
341
|
+
ax.plot(t, dc.treat_all, color="0.45", linewidth=1.2, linestyle="--", label="treat all")
|
|
342
|
+
ax.plot(t, dc.treat_none, color="0.2", linewidth=1.2, linestyle=":", label="treat none")
|
|
343
|
+
top = max(dc.prevalence, max(float(np.nanmax(v)) for v in dc.net_benefit.values()))
|
|
344
|
+
ax.set(
|
|
345
|
+
xlabel="Threshold probability",
|
|
346
|
+
ylabel="Net benefit",
|
|
347
|
+
title="Decision curve",
|
|
348
|
+
xlim=(float(t[0]), float(t[-1])),
|
|
349
|
+
ylim=ylim if ylim is not None else (-0.05 * max(top, 0.05), top * 1.1 + 0.01),
|
|
350
|
+
)
|
|
351
|
+
ax.legend(loc="upper right", frameon=False)
|
|
352
|
+
return ax
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def per_class(
|
|
356
|
+
result: Any,
|
|
357
|
+
*,
|
|
358
|
+
ax: Optional[Axes] = None,
|
|
359
|
+
class_names: Optional[Mapping[Any, str]] = None,
|
|
360
|
+
sort: bool = False,
|
|
361
|
+
metric: str = "dice",
|
|
362
|
+
) -> Axes:
|
|
363
|
+
"""Horizontal bar chart of per-class scores, with the macro mean as a reference line.
|
|
364
|
+
|
|
365
|
+
``result`` is any metric computed with ``average=None`` (e.g. ``es.iou(..., average=None)`` or
|
|
366
|
+
``es.f1(..., average=None)``), a :class:`SegmentationReport` (``metric`` picks the column: ``"dice"``,
|
|
367
|
+
``"iou"``, ``"boundary_iou"``, ``"hd95"`` or ``"assd"``) or a :class:`DetectionReport` (AP per class).
|
|
368
|
+
Undefined classes (NaN) are labelled "n/a"."""
|
|
369
|
+
rows = getattr(result, "rows", None)
|
|
370
|
+
if isinstance(rows, tuple) and rows and "class" in rows[0]:
|
|
371
|
+
if metric not in rows[0]:
|
|
372
|
+
raise InputValidationError(
|
|
373
|
+
f"Unknown metric {metric!r}; use one of dice, iou, boundary_iou, hd95, assd."
|
|
374
|
+
)
|
|
375
|
+
values = np.array([r[metric] for r in rows], dtype=np.float64)
|
|
376
|
+
labels: list[Any] = [r["class"] for r in rows]
|
|
377
|
+
default_names = [str(r["name"]) for r in rows]
|
|
378
|
+
title = {"iou": "IoU", "boundary_iou": "Boundary IoU", "hd95": "HD95", "assd": "ASSD"}.get(metric, "Dice")
|
|
379
|
+
elif isinstance(getattr(result, "per_class", None), Mapping):
|
|
380
|
+
labels = list(result.per_class)
|
|
381
|
+
values = np.array([result.per_class[c] for c in labels], dtype=np.float64)
|
|
382
|
+
default_names = [str(c) for c in labels]
|
|
383
|
+
title = "AP@[.50:.95]"
|
|
384
|
+
elif isinstance(getattr(result, "value", None), np.ndarray) and result.labels is not None:
|
|
385
|
+
values = np.asarray(result.value, dtype=np.float64)
|
|
386
|
+
labels = list(result.labels)
|
|
387
|
+
default_names = [str(c) for c in labels]
|
|
388
|
+
title = result.name
|
|
389
|
+
else:
|
|
390
|
+
raise InputValidationError(
|
|
391
|
+
"per_class() needs a per-class result (a metric computed with average=None) "
|
|
392
|
+
"or a segmentation or detection report."
|
|
393
|
+
)
|
|
394
|
+
names = [str(class_names.get(c, d)) if class_names else d for c, d in zip(labels, default_names)]
|
|
395
|
+
order = np.argsort(np.nan_to_num(values, nan=-np.inf)) if sort else np.arange(values.size)[::-1]
|
|
396
|
+
ax = _axes(ax, (5.0, max(2.4, 0.38 * values.size + 1.2)))
|
|
397
|
+
finite = np.isfinite(values)
|
|
398
|
+
ax.barh(np.arange(values.size), np.where(finite, values, 0)[order], color="#2a6fb0")
|
|
399
|
+
for y, i in enumerate(order):
|
|
400
|
+
ax.text(
|
|
401
|
+
values[i] if finite[i] else 0,
|
|
402
|
+
y,
|
|
403
|
+
f" {values[i]:.3f}" if finite[i] else " n/a",
|
|
404
|
+
va="center",
|
|
405
|
+
fontsize=8,
|
|
406
|
+
)
|
|
407
|
+
if finite.any():
|
|
408
|
+
ax.axvline(float(np.nanmean(values[finite])), color="0.3", linestyle="--", linewidth=1, label="macro mean")
|
|
409
|
+
ax.legend(loc="lower right", frameon=False)
|
|
410
|
+
ax.set(yticks=np.arange(values.size), yticklabels=[names[i] for i in order], xlabel=title)
|
|
411
|
+
ax.set_title(f"{title} per class")
|
|
412
|
+
upper = float(np.nanmax(values[finite])) if finite.any() else 1.0
|
|
413
|
+
ax.set_xlim(0, max(1.0, upper * 1.15) if upper <= 1 else upper * 1.15)
|
|
414
|
+
return ax
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def segmentation(
|
|
418
|
+
image: Optional[ArrayLike],
|
|
419
|
+
y_true: ArrayLike,
|
|
420
|
+
y_pred: ArrayLike,
|
|
421
|
+
*,
|
|
422
|
+
ax: Optional[Axes] = None,
|
|
423
|
+
alpha: float = 0.45,
|
|
424
|
+
class_names: Optional[Mapping[int, str]] = None,
|
|
425
|
+
ignore_index: Optional[int] = None,
|
|
426
|
+
) -> Axes:
|
|
427
|
+
"""One image with the predicted mask as a colour overlay and the true class boundaries as contours, so
|
|
428
|
+
over- and under-segmentation are visible at a glance. Dice and IoU (macro, excluding background) are in
|
|
429
|
+
the title. ``image`` may be None (masks only), grey-scale or RGB."""
|
|
430
|
+
from .vision.segmentation import dice as dice_fn
|
|
431
|
+
from .vision.segmentation import iou as iou_fn
|
|
432
|
+
|
|
433
|
+
plt = _plt()
|
|
434
|
+
t = np.asarray(y_true)
|
|
435
|
+
pr = np.asarray(y_pred)
|
|
436
|
+
if t.ndim != 2 or t.shape != pr.shape:
|
|
437
|
+
raise InputValidationError(
|
|
438
|
+
"segmentation() plots one 2-D image: y_true and y_pred must be equal 2-D masks."
|
|
439
|
+
)
|
|
440
|
+
ax = _axes(ax, (5.0, 5.0 * t.shape[0] / max(t.shape[1], 1)))
|
|
441
|
+
if image is not None:
|
|
442
|
+
img = np.asarray(image)
|
|
443
|
+
ax.imshow(img, cmap="gray" if img.ndim == 2 else None)
|
|
444
|
+
else:
|
|
445
|
+
ax.imshow(np.ones(t.shape), cmap="gray", vmin=0, vmax=1)
|
|
446
|
+
classes = sorted(
|
|
447
|
+
int(c) for c in np.unique(np.concatenate([t.ravel(), pr.ravel()])) if c != 0 and c != ignore_index
|
|
448
|
+
)
|
|
449
|
+
cmap = plt.get_cmap("tab10")
|
|
450
|
+
overlay = np.zeros((*t.shape, 4))
|
|
451
|
+
for i, c in enumerate(classes):
|
|
452
|
+
color = cmap(i % 10)
|
|
453
|
+
overlay[pr == c] = (*color[:3], alpha)
|
|
454
|
+
if np.any(t == c):
|
|
455
|
+
ax.contour((t == c).astype(float), levels=[0.5], colors=[color[:3]], linewidths=1.6)
|
|
456
|
+
ax.plot(
|
|
457
|
+
[],
|
|
458
|
+
[],
|
|
459
|
+
color=color[:3],
|
|
460
|
+
linewidth=6,
|
|
461
|
+
alpha=0.6,
|
|
462
|
+
label=str(class_names.get(c, c)) if class_names else str(c),
|
|
463
|
+
)
|
|
464
|
+
ax.imshow(overlay)
|
|
465
|
+
if classes:
|
|
466
|
+
d = float(dice_fn(t, pr, ignore_index=ignore_index, include_background=False))
|
|
467
|
+
j = float(iou_fn(t, pr, ignore_index=ignore_index, include_background=False))
|
|
468
|
+
ax.set_title(f"Prediction (fill) vs truth (outline): Dice {d:.3f}, IoU {j:.3f}", fontsize=9)
|
|
469
|
+
ax.legend(loc="upper right", fontsize=7, frameon=True, title="class", title_fontsize=7)
|
|
470
|
+
ax.set_axis_off()
|
|
471
|
+
return ax
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def detection_pr(
|
|
475
|
+
y_true: Any,
|
|
476
|
+
y_pred: Any,
|
|
477
|
+
*,
|
|
478
|
+
ax: Optional[Axes] = None,
|
|
479
|
+
iou_threshold: float = 0.5,
|
|
480
|
+
box_format: str = "xyxy",
|
|
481
|
+
class_names: Optional[Mapping[int, str]] = None,
|
|
482
|
+
max_classes: int = 10,
|
|
483
|
+
) -> Axes:
|
|
484
|
+
"""Precision-recall curves per class for object detection (COCO 101-point interpolation) at one IoU
|
|
485
|
+
threshold, with each class's AP in the legend; classes beyond ``max_classes`` (by AP) are omitted."""
|
|
486
|
+
from .vision.detection import detection_pr_curve
|
|
487
|
+
|
|
488
|
+
curves = detection_pr_curve(y_true, y_pred, iou_threshold=iou_threshold, box_format=box_format) # type: ignore[arg-type]
|
|
489
|
+
if not curves:
|
|
490
|
+
raise InputValidationError("No class has ground-truth boxes; nothing to plot.")
|
|
491
|
+
ranked = sorted(curves.items(), key=lambda kv: -float(np.mean(kv[1][1])))[:max_classes]
|
|
492
|
+
ax = _axes(ax)
|
|
493
|
+
for i, (c, (rc, pr)) in enumerate(ranked):
|
|
494
|
+
name = class_names.get(c, str(c)) if class_names else str(c)
|
|
495
|
+
ax.plot(rc, pr, label=f"{name}: AP = {float(np.mean(pr)):.3f}", **_style(i))
|
|
496
|
+
m = float(np.mean([np.mean(p) for _, (_, p) in curves.items()]))
|
|
497
|
+
ax.set(
|
|
498
|
+
xlabel="Recall",
|
|
499
|
+
ylabel="Precision",
|
|
500
|
+
title=f"Detection PR curves @IoU {iou_threshold:g} (mAP = {m:.3f})",
|
|
501
|
+
xlim=(0, 1.01),
|
|
502
|
+
ylim=(0, 1.02),
|
|
503
|
+
)
|
|
504
|
+
ax.legend(loc="lower left", frameon=False, fontsize="small")
|
|
505
|
+
return ax
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
# ---------------------------------------------------------------- v0.4.0: preferences and text
|
|
509
|
+
def _rating_fit(method: str, rows: list[Any]) -> Any:
|
|
510
|
+
from .text.judge import bradley_terry, elo_ratings
|
|
511
|
+
|
|
512
|
+
if method == "bradley_terry":
|
|
513
|
+
return bradley_terry(rows, scale="elo")
|
|
514
|
+
if method == "elo":
|
|
515
|
+
return elo_ratings(rows)
|
|
516
|
+
raise InputValidationError("method must be 'bradley_terry' or 'elo'.")
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
def ratings(
|
|
520
|
+
comparisons: Any,
|
|
521
|
+
*,
|
|
522
|
+
method: str = "bradley_terry",
|
|
523
|
+
n_resamples: int = 200,
|
|
524
|
+
level: float = 0.95,
|
|
525
|
+
random_state: Optional[int] = 0,
|
|
526
|
+
ax: Optional[Axes] = None,
|
|
527
|
+
) -> Axes:
|
|
528
|
+
"""Leaderboard of model ratings from pairwise ``(model_a, model_b, outcome)`` comparisons, with percentile
|
|
529
|
+
bootstrap intervals over comparisons (Chatbot Arena style). ``method``: ``"bradley_terry"`` (Elo scale) or
|
|
530
|
+
``"elo"`` (online Elo). Resamples on which the Bradley–Terry fit does not exist are skipped and counted in
|
|
531
|
+
the x-axis label."""
|
|
532
|
+
rows = list(comparisons)
|
|
533
|
+
point = _rating_fit(method, rows)
|
|
534
|
+
names = list(point.labels or ())
|
|
535
|
+
est = np.asarray(point.value, dtype=float)
|
|
536
|
+
rng = np.random.default_rng(random_state)
|
|
537
|
+
boot, failed = [], 0
|
|
538
|
+
for _ in range(int(n_resamples)):
|
|
539
|
+
sample = [rows[i] for i in rng.integers(0, len(rows), len(rows))]
|
|
540
|
+
try:
|
|
541
|
+
r = _rating_fit(method, sample)
|
|
542
|
+
except InputValidationError:
|
|
543
|
+
failed += 1
|
|
544
|
+
continue
|
|
545
|
+
lookup = dict(zip(r.labels or (), np.asarray(r.value, dtype=float)))
|
|
546
|
+
boot.append([lookup.get(n, np.nan) for n in names])
|
|
547
|
+
order = np.argsort(est)
|
|
548
|
+
ax = _axes(ax, (5.5, max(2.6, 0.45 * len(names) + 1.2)))
|
|
549
|
+
y = np.arange(len(names))
|
|
550
|
+
if boot:
|
|
551
|
+
b = np.asarray(boot)
|
|
552
|
+
a = (1 - level) / 2
|
|
553
|
+
lo, hi = np.nanquantile(b, a, axis=0), np.nanquantile(b, 1 - a, axis=0)
|
|
554
|
+
ax.errorbar(
|
|
555
|
+
est[order],
|
|
556
|
+
y,
|
|
557
|
+
xerr=[est[order] - lo[order], hi[order] - est[order]],
|
|
558
|
+
fmt="o",
|
|
559
|
+
color="#2a6fb0",
|
|
560
|
+
ecolor="0.45",
|
|
561
|
+
capsize=3,
|
|
562
|
+
)
|
|
563
|
+
else:
|
|
564
|
+
ax.plot(est[order], y, "o", color="#2a6fb0")
|
|
565
|
+
ax.set_yticks(y, [str(names[i]) for i in order])
|
|
566
|
+
title = "Bradley–Terry rating" if method == "bradley_terry" else "Elo rating"
|
|
567
|
+
note = f"{int(level * 100)}% bootstrap CI, {len(boot)} resamples" + (f", {failed} skipped" if failed else "")
|
|
568
|
+
ax.set(xlabel=f"{title} ({note})", title=f"{title}s from {len(rows)} comparisons")
|
|
569
|
+
ax.grid(axis="x", alpha=0.3)
|
|
570
|
+
return ax
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
def win_matrix(comparisons: Any, *, ax: Optional[Axes] = None, annotate: bool = True) -> Axes:
|
|
574
|
+
"""Heatmap of pairwise win rates: cell (row, column) is how often the row model beat the column model (ties
|
|
575
|
+
count half); blank where the two were never compared."""
|
|
576
|
+
from .text.judge import _comparisons
|
|
577
|
+
|
|
578
|
+
names, rows = _comparisons(comparisons)
|
|
579
|
+
m = len(names)
|
|
580
|
+
wins, games = np.zeros((m, m)), np.zeros((m, m))
|
|
581
|
+
for a, b, o in rows:
|
|
582
|
+
wins[a, b] += o
|
|
583
|
+
wins[b, a] += 1 - o
|
|
584
|
+
games[a, b] += 1
|
|
585
|
+
games[b, a] += 1
|
|
586
|
+
with np.errstate(invalid="ignore", divide="ignore"):
|
|
587
|
+
rate = np.where(games > 0, wins / np.where(games > 0, games, 1), np.nan)
|
|
588
|
+
order = np.argsort(-np.nanmean(np.where(np.eye(m, dtype=bool), np.nan, rate), axis=1)) # strongest first
|
|
589
|
+
rate = rate[np.ix_(order, order)]
|
|
590
|
+
names = [names[i] for i in order]
|
|
591
|
+
ax = _axes(ax, (1.2 + 0.7 * m, 0.9 + 0.6 * m))
|
|
592
|
+
im = ax.imshow(rate, cmap="RdBu", vmin=0, vmax=1)
|
|
593
|
+
ax.set_xticks(range(m), [str(n) for n in names], rotation=45, ha="right")
|
|
594
|
+
ax.set_yticks(range(m), [str(n) for n in names])
|
|
595
|
+
if annotate:
|
|
596
|
+
for i in range(m):
|
|
597
|
+
for j in range(m):
|
|
598
|
+
if not np.isnan(rate[i, j]):
|
|
599
|
+
ax.text(
|
|
600
|
+
j,
|
|
601
|
+
i,
|
|
602
|
+
f"{rate[i, j]:.2f}",
|
|
603
|
+
ha="center",
|
|
604
|
+
va="center",
|
|
605
|
+
fontsize=8,
|
|
606
|
+
color="white" if abs(rate[i, j] - 0.5) > 0.3 else "black",
|
|
607
|
+
)
|
|
608
|
+
ax.figure.colorbar(im, ax=ax, label="win rate (row vs column)")
|
|
609
|
+
ax.set_title("Pairwise win rates")
|
|
610
|
+
return ax
|
|
611
|
+
|
|
612
|
+
|
|
613
|
+
def text_scores(
|
|
614
|
+
references: Any,
|
|
615
|
+
predictions: Mapping[str, Any],
|
|
616
|
+
*,
|
|
617
|
+
metric: Any = "token_f1",
|
|
618
|
+
ax: Optional[Axes] = None,
|
|
619
|
+
**metric_kwargs: Any,
|
|
620
|
+
) -> Axes:
|
|
621
|
+
"""Distribution of a per-example text metric for several systems (box plots with the mean marked), e.g.
|
|
622
|
+
``metric="rouge_l"``, ``"token_f1"``, ``"meteor"``, ``"sentence_bleu"`` or ``"bertscore"`` (with
|
|
623
|
+
embeddings). Pair it with ``es.compare`` for intervals and tests."""
|
|
624
|
+
from .stats._resolve import resolve_metric
|
|
625
|
+
|
|
626
|
+
fn, name = resolve_metric(metric)
|
|
627
|
+
import inspect
|
|
628
|
+
|
|
629
|
+
if "average" not in inspect.signature(fn).parameters:
|
|
630
|
+
raise InputValidationError(
|
|
631
|
+
f"{name} is a corpus-level metric without per-example scores; use e.g. sentence_bleu, rouge_l, "
|
|
632
|
+
"token_f1 or meteor, or es.compare for corpus metrics."
|
|
633
|
+
)
|
|
634
|
+
if not isinstance(predictions, Mapping) or not predictions:
|
|
635
|
+
raise InputValidationError("predictions must be a dict of system name -> predictions.")
|
|
636
|
+
data, labels = [], []
|
|
637
|
+
for sys_name, preds in predictions.items():
|
|
638
|
+
res = fn(references, preds, average=None, **metric_kwargs)
|
|
639
|
+
vals = np.asarray(res.value, dtype=float)
|
|
640
|
+
if vals.ndim != 1:
|
|
641
|
+
raise InputValidationError(f"{name} does not give one score per example.")
|
|
642
|
+
data.append(vals[~np.isnan(vals)])
|
|
643
|
+
labels.append(str(sys_name))
|
|
644
|
+
ax = _axes(ax, (1.6 + 1.1 * len(labels), 4.2))
|
|
645
|
+
ax.boxplot(
|
|
646
|
+
data, showmeans=True, meanprops={"marker": "D", "markerfacecolor": "#d9822b", "markeredgecolor": "#d9822b"}
|
|
647
|
+
)
|
|
648
|
+
ax.set_xticks(range(1, len(labels) + 1), labels)
|
|
649
|
+
ax.set(ylabel=f"{res.name} per example", title=f"{res.name} by system (diamond = mean)")
|
|
650
|
+
ax.grid(axis="y", alpha=0.3)
|
|
651
|
+
return ax
|
evalsuite/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Regression metrics."""
|
|
2
|
+
|
|
3
|
+
from .metrics import (
|
|
4
|
+
adjusted_r2,
|
|
5
|
+
explained_variance,
|
|
6
|
+
huber_loss,
|
|
7
|
+
mae,
|
|
8
|
+
mape,
|
|
9
|
+
max_error,
|
|
10
|
+
mean_bias_error,
|
|
11
|
+
median_absolute_error,
|
|
12
|
+
mse,
|
|
13
|
+
msle,
|
|
14
|
+
quantile_loss,
|
|
15
|
+
r2,
|
|
16
|
+
rae,
|
|
17
|
+
rmse,
|
|
18
|
+
rmsle,
|
|
19
|
+
rse,
|
|
20
|
+
smape,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"adjusted_r2",
|
|
25
|
+
"explained_variance",
|
|
26
|
+
"huber_loss",
|
|
27
|
+
"mae",
|
|
28
|
+
"mape",
|
|
29
|
+
"max_error",
|
|
30
|
+
"mean_bias_error",
|
|
31
|
+
"median_absolute_error",
|
|
32
|
+
"mse",
|
|
33
|
+
"msle",
|
|
34
|
+
"quantile_loss",
|
|
35
|
+
"r2",
|
|
36
|
+
"rae",
|
|
37
|
+
"rmse",
|
|
38
|
+
"rmsle",
|
|
39
|
+
"rse",
|
|
40
|
+
"smape",
|
|
41
|
+
]
|