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.
Files changed (72) hide show
  1. evalsuite/__init__.py +268 -0
  2. evalsuite/__main__.py +5 -0
  3. evalsuite/_bench_metrics.py +2080 -0
  4. evalsuite/_core.pyd +0 -0
  5. evalsuite/_lazy.py +32 -0
  6. evalsuite/_native.py +60 -0
  7. evalsuite/api.py +275 -0
  8. evalsuite/benchmarks.py +946 -0
  9. evalsuite/calibration.py +392 -0
  10. evalsuite/classification/__init__.py +51 -0
  11. evalsuite/classification/_common.py +111 -0
  12. evalsuite/classification/metrics.py +945 -0
  13. evalsuite/cli/__init__.py +5 -0
  14. evalsuite/cli/main.py +606 -0
  15. evalsuite/clinical/__init__.py +18 -0
  16. evalsuite/clinical/metrics.py +342 -0
  17. evalsuite/clinical/report.py +366 -0
  18. evalsuite/core/__init__.py +1 -0
  19. evalsuite/core/context.py +199 -0
  20. evalsuite/core/exceptions.py +52 -0
  21. evalsuite/core/export.py +100 -0
  22. evalsuite/core/registry.py +90 -0
  23. evalsuite/core/result.py +379 -0
  24. evalsuite/core/types.py +23 -0
  25. evalsuite/core/validation.py +256 -0
  26. evalsuite/llmsys/__init__.py +189 -0
  27. evalsuite/llmsys/_common.py +215 -0
  28. evalsuite/llmsys/agents.py +384 -0
  29. evalsuite/llmsys/code.py +923 -0
  30. evalsuite/llmsys/efficiency.py +346 -0
  31. evalsuite/llmsys/longcontext.py +361 -0
  32. evalsuite/llmsys/multilingual.py +339 -0
  33. evalsuite/llmsys/robustness.py +504 -0
  34. evalsuite/llmsys/safety.py +509 -0
  35. evalsuite/llmsys/uncertainty.py +229 -0
  36. evalsuite/plot.py +651 -0
  37. evalsuite/py.typed +0 -0
  38. evalsuite/regression/__init__.py +41 -0
  39. evalsuite/regression/metrics.py +629 -0
  40. evalsuite/reporting.py +241 -0
  41. evalsuite/stats/__init__.py +46 -0
  42. evalsuite/stats/_resolve.py +229 -0
  43. evalsuite/stats/compare.py +420 -0
  44. evalsuite/stats/effect.py +159 -0
  45. evalsuite/stats/hypothesis.py +593 -0
  46. evalsuite/stats/intervals.py +338 -0
  47. evalsuite/stats/paired.py +214 -0
  48. evalsuite/stats/results.py +129 -0
  49. evalsuite/text/__init__.py +154 -0
  50. evalsuite/text/_common.py +97 -0
  51. evalsuite/text/factuality.py +469 -0
  52. evalsuite/text/generation.py +1346 -0
  53. evalsuite/text/judge.py +556 -0
  54. evalsuite/text/qa.py +108 -0
  55. evalsuite/text/rag.py +235 -0
  56. evalsuite/text/reasoning.py +215 -0
  57. evalsuite/text/report.py +158 -0
  58. evalsuite/text/retrieval.py +238 -0
  59. evalsuite/text/semantic.py +499 -0
  60. evalsuite/text/spice.py +162 -0
  61. evalsuite/text/structured.py +793 -0
  62. evalsuite/version.py +3 -0
  63. evalsuite/vision/__init__.py +47 -0
  64. evalsuite/vision/detection.py +696 -0
  65. evalsuite/vision/segmentation.py +1028 -0
  66. evalsuite_python-0.6.0.dist-info/METADATA +509 -0
  67. evalsuite_python-0.6.0.dist-info/RECORD +72 -0
  68. evalsuite_python-0.6.0.dist-info/WHEEL +4 -0
  69. evalsuite_python-0.6.0.dist-info/entry_points.txt +2 -0
  70. evalsuite_python-0.6.0.dist-info/licenses/LICENSE +21 -0
  71. evalsuite_python-0.6.0.dist-info/licenses/LICENSE-APACHE +191 -0
  72. evalsuite_python-0.6.0.dist-info/sboms/evalsuite-py.cyclonedx.json +576 -0
@@ -0,0 +1,366 @@
1
+ """Diagnostic accuracy summary with confidence intervals, and decision curve analysis."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ from dataclasses import dataclass, field
8
+ from types import MappingProxyType
9
+ from typing import TYPE_CHECKING, Any, Optional, cast
10
+
11
+ import numpy as np
12
+ from numpy.typing import NDArray
13
+
14
+ if TYPE_CHECKING:
15
+ from scipy import special
16
+ else:
17
+ from .._lazy import lazy_module
18
+
19
+ special = lazy_module("scipy.special")
20
+
21
+ from ..core.exceptions import InputValidationError
22
+ from ..core.export import PathLike, csv_text, html_document, html_table, save_as
23
+ from ..core.result import _fmt, _json_safe, _latex_escape, _latex_table
24
+ from ..core.types import ArrayLike
25
+ from ..stats.intervals import _check_level, proportion_ci
26
+ from ..stats.results import ConfidenceInterval
27
+ from .metrics import _binary_risk, _check_thresholds, _need_both_classes, binary_counts, net_benefit_curve
28
+
29
+ if TYPE_CHECKING:
30
+ import pandas as pd
31
+
32
+ __all__ = ["DecisionCurve", "DiagnosticReport", "decision_curve", "diagnostic_report"]
33
+
34
+ _ROWS = (
35
+ ("sensitivity", "Sensitivity"),
36
+ ("specificity", "Specificity"),
37
+ ("ppv", "PPV"),
38
+ ("npv", "NPV"),
39
+ ("lr_positive", "LR+"),
40
+ ("lr_negative", "LR−"),
41
+ ("diagnostic_odds_ratio", "Diagnostic odds ratio"),
42
+ ("youden_j", "Youden's J"),
43
+ ("accuracy", "Accuracy"),
44
+ ("prevalence", "Prevalence"),
45
+ )
46
+
47
+
48
+ @dataclass(frozen=True, eq=False)
49
+ class DiagnosticReport:
50
+ """Every diagnostic accuracy measure for one binary test, each with a confidence interval.
51
+
52
+ Index it by name: ``report["lr_positive"]`` is a :class:`ConfidenceInterval`. ``counts`` holds the 2×2
53
+ table (``tp``, ``fp``, ``fn``, ``tn``).
54
+ """
55
+
56
+ estimates: Any
57
+ counts: Any
58
+ level: float
59
+ params: Any = field(default_factory=dict)
60
+
61
+ def __post_init__(self) -> None:
62
+ object.__setattr__(self, "estimates", MappingProxyType(dict(self.estimates)))
63
+ object.__setattr__(self, "counts", MappingProxyType(dict(self.counts)))
64
+ object.__setattr__(self, "params", MappingProxyType(dict(self.params)))
65
+
66
+ def __getitem__(self, name: str) -> ConfidenceInterval:
67
+ try:
68
+ return cast("ConfidenceInterval", self.estimates[name])
69
+ except KeyError:
70
+ raise KeyError(f"No measure {name!r}. Available: {', '.join(self.estimates)}.") from None
71
+
72
+ def __iter__(self): # type: ignore[no-untyped-def]
73
+ return iter(self.estimates)
74
+
75
+ def _rows(self, digits: int) -> list[list[str]]:
76
+ out = []
77
+ for key, label in _ROWS:
78
+ ci = self.estimates[key]
79
+ out.append([label, _fmt(ci.estimate, digits), _fmt(ci.low, digits), _fmt(ci.high, digits), ci.method])
80
+ return out
81
+
82
+ def _header(self) -> list[str]:
83
+ pct = f"{round(self.level * 100, 6):g}%"
84
+ return ["Measure", "Estimate", f"{pct} CI low", f"{pct} CI high", "Method"]
85
+
86
+ def summary(self, *, digits: int = 3) -> str:
87
+ c = self.counts
88
+ lines = [
89
+ f"EvalSuite diagnostic accuracy (n={int(c['tp'] + c['fp'] + c['fn'] + c['tn'])}, "
90
+ f"{round(self.level * 100, 6):g}% CIs)",
91
+ f" 2×2 table: TP={c['tp']:g} FP={c['fp']:g} FN={c['fn']:g} TN={c['tn']:g}",
92
+ ]
93
+ width = max(len(label) for _, label in _ROWS)
94
+ for key, label in _ROWS:
95
+ ci = self.estimates[key]
96
+ lines.append(
97
+ f" {label:<{width}} {_fmt(ci.estimate, digits)} "
98
+ f"({_fmt(ci.low, digits)}–{_fmt(ci.high, digits)}) {ci.method}"
99
+ )
100
+ return "\n".join(lines)
101
+
102
+ def __repr__(self) -> str:
103
+ return self.summary()
104
+
105
+ def to_dict(self) -> dict[str, Any]:
106
+ return cast(
107
+ "dict[str, Any]",
108
+ _json_safe(
109
+ {
110
+ "counts": dict(self.counts),
111
+ "level": self.level,
112
+ "measures": {k: v.to_dict() for k, v in self.estimates.items()},
113
+ "params": dict(self.params),
114
+ }
115
+ ),
116
+ )
117
+
118
+ def to_json(self, *, indent: Optional[int] = 2) -> str:
119
+ return json.dumps(self.to_dict(), indent=indent, allow_nan=False)
120
+
121
+ def to_dataframe(self) -> pd.DataFrame:
122
+ import pandas as pd
123
+
124
+ rows = [
125
+ {"measure": k, "estimate": v.estimate, "low": v.low, "high": v.high, "method": v.method}
126
+ for k, v in self.estimates.items()
127
+ ]
128
+ frame: pd.DataFrame = pd.DataFrame(rows).set_index("measure")
129
+ return frame
130
+
131
+ def to_markdown(self, *, digits: int = 3) -> str:
132
+ header = self._header()
133
+ lines = ["| " + " | ".join(header) + " |", "| --- | ---: | ---: | ---: | --- |"]
134
+ lines += ["| " + " | ".join(r) + " |" for r in self._rows(digits)]
135
+ return "\n".join(lines)
136
+
137
+ def to_latex(self, *, digits: int = 3, caption: Optional[str] = None, label: Optional[str] = None) -> str:
138
+ rows = [[_latex_escape(c) for c in r] for r in self._rows(digits)]
139
+ return _latex_table([_latex_escape(h) for h in self._header()], rows, caption, label)
140
+
141
+ def to_csv(self, path: Optional[PathLike] = None) -> str:
142
+ rows = [[k, v.estimate, v.low, v.high, v.level, v.method] for k, v in self.estimates.items()]
143
+ text = csv_text(["measure", "estimate", "low", "high", "level", "method"], rows)
144
+ if path is not None:
145
+ with open(path, "w", encoding="utf-8", newline="") as fh:
146
+ fh.write(text)
147
+ return text
148
+
149
+ def to_html(self, *, digits: int = 3, full: bool = True) -> str:
150
+ c = self.counts
151
+ body = html_table(self._header(), self._rows(digits), caption="Diagnostic accuracy")
152
+ body += "\n" + html_table(
153
+ ["", "Condition present", "Condition absent"],
154
+ [["Test positive", f"{c['tp']:g}", f"{c['fp']:g}"], ["Test negative", f"{c['fn']:g}", f"{c['tn']:g}"]],
155
+ caption="2×2 table",
156
+ )
157
+ return html_document("EvalSuite diagnostic accuracy", body) if full else body
158
+
159
+ def save(self, path: PathLike) -> str:
160
+ return save_as(
161
+ path,
162
+ {
163
+ "json": self.to_json,
164
+ "csv": self.to_csv,
165
+ "markdown": self.to_markdown,
166
+ "latex": self.to_latex,
167
+ "html": self.to_html,
168
+ "text": self.summary,
169
+ },
170
+ )
171
+
172
+
173
+ def _log_ratio_ci(est: float, se: float, z: float, level: float, method: str, name: str) -> ConfidenceInterval:
174
+ if not (math.isfinite(est) and est > 0 and math.isfinite(se)):
175
+ return ConfidenceInterval(est, math.nan, math.nan, level, method, name)
176
+ lo, hi = math.exp(math.log(est) - z * se), math.exp(math.log(est) + z * se)
177
+ return ConfidenceInterval(est, lo, hi, level, method, name, {"se_log": se})
178
+
179
+
180
+ def diagnostic_report(
181
+ y_true: ArrayLike,
182
+ y_pred: ArrayLike,
183
+ *,
184
+ pos_label: Any = None,
185
+ level: float = 0.95,
186
+ proportion_method: str = "wilson",
187
+ ) -> DiagnosticReport:
188
+ """Sensitivity, specificity, PPV, NPV, likelihood ratios, diagnostic odds ratio, Youden's J, accuracy and
189
+ prevalence for a binary test, each with a confidence interval.
190
+
191
+ Intervals: proportions use ``proportion_method`` (Wilson by default, or ``"clopper-pearson"``); likelihood
192
+ ratios use the log method of Simel et al. (1991); the diagnostic odds ratio uses Woolf's log method with
193
+ 0.5 added to every cell when one is zero; Youden's J uses the Wald interval from the independent
194
+ sensitivity and specificity variances, clipped to [−1, 1].
195
+ """
196
+ level = _check_level(level)
197
+ tp, fp, fn, tn = binary_counts(y_true, y_pred, pos_label=pos_label)
198
+ _need_both_classes(tp, fp, fn, tn, "A diagnostic report")
199
+ a, b, c, d = (round(v) for v in (tp, fp, fn, tn))
200
+ z = float(special.ndtri(1 - (1 - level) / 2))
201
+ method: Any = proportion_method
202
+
203
+ def prop(k: int, n: int, name: str) -> ConfidenceInterval:
204
+ if n == 0:
205
+ return ConfidenceInterval(math.nan, math.nan, math.nan, level, method, name)
206
+ ci = proportion_ci(k, n, level=level, method=method)
207
+ return ConfidenceInterval(ci.estimate, ci.low, ci.high, level, ci.method, name, ci.params)
208
+
209
+ n1, n0, n = a + c, b + d, a + b + c + d
210
+ sens, spec = a / n1, d / n0
211
+ est: dict[str, ConfidenceInterval] = {
212
+ "sensitivity": prop(a, n1, "sensitivity"),
213
+ "specificity": prop(d, n0, "specificity"),
214
+ "ppv": prop(a, a + b, "ppv"),
215
+ "npv": prop(d, c + d, "npv"),
216
+ }
217
+ lr_pos = sens / (1 - spec) if spec < 1 else (math.inf if sens > 0 else math.nan)
218
+ lr_neg = (1 - sens) / spec if spec > 0 else (math.inf if sens < 1 else math.nan)
219
+ se_pos = math.sqrt(1 / a - 1 / n1 + 1 / b - 1 / n0) if a and b else math.nan
220
+ se_neg = math.sqrt(1 / c - 1 / n1 + 1 / d - 1 / n0) if c and d else math.nan
221
+ est["lr_positive"] = _log_ratio_ci(lr_pos, se_pos, z, level, "log (Simel 1991)", "lr_positive")
222
+ est["lr_negative"] = _log_ratio_ci(lr_neg, se_neg, z, level, "log (Simel 1991)", "lr_negative")
223
+ corrected = min(a, b, c, d) == 0
224
+ ca, cb, cc, cd = (v + 0.5 for v in (a, b, c, d)) if corrected else (a, b, c, d)
225
+ dor = ca * cd / (cb * cc)
226
+ se_dor = math.sqrt(1 / ca + 1 / cb + 1 / cc + 1 / cd)
227
+ est["diagnostic_odds_ratio"] = _log_ratio_ci(
228
+ dor, se_dor, z, level, "log (Woolf" + (", +0.5 cells)" if corrected else ")"), "diagnostic_odds_ratio"
229
+ )
230
+ j = sens + spec - 1
231
+ se_j = math.sqrt(sens * (1 - sens) / n1 + spec * (1 - spec) / n0)
232
+ est["youden_j"] = ConfidenceInterval(
233
+ j, max(-1.0, j - z * se_j), min(1.0, j + z * se_j), level, "wald", "youden_j", {"se": se_j}
234
+ )
235
+ est["accuracy"] = prop(a + d, n, "accuracy")
236
+ est["prevalence"] = prop(n1, n, "prevalence")
237
+ return DiagnosticReport(
238
+ est,
239
+ {"tp": tp, "fp": fp, "fn": fn, "tn": tn},
240
+ level,
241
+ {"pos_label": 1 if pos_label is None else pos_label, "proportion_method": proportion_method},
242
+ )
243
+
244
+
245
+ @dataclass(frozen=True, eq=False)
246
+ class DecisionCurve:
247
+ """Net benefit of one or more models, of treating everyone and of treating no one, per threshold."""
248
+
249
+ thresholds: NDArray[np.float64]
250
+ net_benefit: Any # model name -> array
251
+ treat_all: NDArray[np.float64]
252
+ prevalence: float
253
+ n: int
254
+
255
+ def __post_init__(self) -> None:
256
+ for name in ("thresholds", "treat_all"):
257
+ arr = np.array(getattr(self, name), dtype=np.float64)
258
+ arr.setflags(write=False)
259
+ object.__setattr__(self, name, arr)
260
+ models = {}
261
+ for k, v in dict(self.net_benefit).items():
262
+ arr = np.array(v, dtype=np.float64)
263
+ arr.setflags(write=False)
264
+ models[k] = arr
265
+ object.__setattr__(self, "net_benefit", MappingProxyType(models))
266
+
267
+ @property
268
+ def treat_none(self) -> NDArray[np.float64]:
269
+ return np.zeros_like(self.thresholds)
270
+
271
+ def useful_range(self, model: Optional[str] = None) -> list[tuple[float, float]]:
272
+ """Threshold intervals where the model beats both treating everyone and treating no one."""
273
+ name = model if model is not None else next(iter(self.net_benefit))
274
+ nb = self.net_benefit[name]
275
+ better = (nb > self.treat_all) & (nb > 0)
276
+ ranges: list[tuple[float, float]] = []
277
+ start: Optional[int] = None
278
+ for i, ok in enumerate(better):
279
+ if ok and start is None:
280
+ start = i
281
+ if not ok and start is not None:
282
+ ranges.append((float(self.thresholds[start]), float(self.thresholds[i - 1])))
283
+ start = None
284
+ if start is not None:
285
+ ranges.append((float(self.thresholds[start]), float(self.thresholds[-1])))
286
+ return ranges
287
+
288
+ def to_dataframe(self) -> pd.DataFrame:
289
+ import pandas as pd
290
+
291
+ data: dict[str, Any] = {"threshold": self.thresholds}
292
+ for k, v in self.net_benefit.items():
293
+ data[f"net_benefit[{k}]"] = v
294
+ data["treat_all"] = self.treat_all
295
+ data["treat_none"] = self.treat_none
296
+ frame: pd.DataFrame = pd.DataFrame(data)
297
+ return frame
298
+
299
+ def to_dict(self) -> dict[str, Any]:
300
+ return cast(
301
+ "dict[str, Any]",
302
+ _json_safe(
303
+ {
304
+ "thresholds": self.thresholds,
305
+ "net_benefit": dict(self.net_benefit),
306
+ "treat_all": self.treat_all,
307
+ "prevalence": self.prevalence,
308
+ "n": self.n,
309
+ }
310
+ ),
311
+ )
312
+
313
+ def to_json(self, *, indent: Optional[int] = 2) -> str:
314
+ return json.dumps(self.to_dict(), indent=indent, allow_nan=False)
315
+
316
+ def to_csv(self, path: Optional[PathLike] = None) -> str:
317
+ names = list(self.net_benefit)
318
+ rows = [
319
+ [float(t), *(float(self.net_benefit[k][i]) for k in names), float(self.treat_all[i]), 0.0]
320
+ for i, t in enumerate(self.thresholds)
321
+ ]
322
+ text = csv_text(["threshold", *names, "treat_all", "treat_none"], rows)
323
+ if path is not None:
324
+ with open(path, "w", encoding="utf-8", newline="") as fh:
325
+ fh.write(text)
326
+ return text
327
+
328
+ def __repr__(self) -> str:
329
+ return (
330
+ f"DecisionCurve(models={list(self.net_benefit)}, thresholds={self.thresholds[0]:g}..."
331
+ f"{self.thresholds[-1]:g} ({self.thresholds.size}), prevalence={self.prevalence:.3f}, n={self.n})"
332
+ )
333
+
334
+
335
+ def decision_curve(
336
+ y_true: ArrayLike,
337
+ y_prob: Any,
338
+ *,
339
+ thresholds: Optional[ArrayLike] = None,
340
+ pos_label: Any = None,
341
+ sample_weight: Optional[ArrayLike] = None,
342
+ ) -> DecisionCurve:
343
+ """Decision curve analysis (Vickers & Elkin 2006).
344
+
345
+ ``y_prob`` is one array of predicted risks, or a dict ``{"model name": risks}`` to compare models.
346
+ ``thresholds`` defaults to 0.01, 0.02, …, 0.99. Treat-all net benefit is prevalence − (1 − prevalence) ·
347
+ pₜ / (1 − pₜ); treat-none is 0.
348
+ """
349
+ t = _check_thresholds(np.arange(1, 100) / 100 if thresholds is None else thresholds)
350
+ if not np.all(np.diff(t) > 0):
351
+ raise InputValidationError("thresholds must be strictly increasing.")
352
+ models = dict(y_prob) if isinstance(y_prob, dict) else {"model": y_prob}
353
+ if not models:
354
+ raise InputValidationError("Give at least one model's predicted risks.")
355
+ curves: dict[str, NDArray[np.float64]] = {}
356
+ treat_all: Optional[NDArray[np.float64]] = None
357
+ prevalence, n = 0.0, 0
358
+ for name, probs in models.items():
359
+ y, p, w = _binary_risk(y_true, probs, pos_label, sample_weight)
360
+ model, all_ = net_benefit_curve(y, p, w, t)
361
+ curves[str(name)] = model
362
+ treat_all = all_
363
+ prevalence, n = float((w * y).sum() / w.sum()), int(y.shape[0])
364
+ if treat_all is None: # pragma: no cover - models is non-empty
365
+ raise InputValidationError("Give at least one model's predicted risks.")
366
+ return DecisionCurve(t, curves, treat_all, prevalence, n)
@@ -0,0 +1 @@
1
+ """Core infrastructure: exceptions, validation, results, registry and evaluation context."""
@@ -0,0 +1,199 @@
1
+ """EvaluationContext: validate inputs once and cache shared intermediate results.
2
+
3
+ Every classification metric derives from per-class counts (TP, FP, FN, TN). The context computes the
4
+ confusion matrix once; ``evaluate()`` passes one context to all requested metrics, so ten metrics cost one
5
+ pass over the data.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from functools import cached_property
11
+ from typing import Any, Optional
12
+
13
+ import numpy as np
14
+ from numpy.typing import NDArray
15
+
16
+ from .exceptions import InputValidationError, UnsupportedTaskError
17
+ from .types import ArrayLike, FloatArray
18
+ from .validation import (
19
+ TargetType,
20
+ check_consistent_length,
21
+ check_finite,
22
+ resolve_labels,
23
+ target_type,
24
+ to_numpy,
25
+ validate_probabilities,
26
+ validate_sample_weight,
27
+ )
28
+
29
+ __all__ = ["ClassificationContext"]
30
+
31
+
32
+ class ClassificationContext:
33
+ """Validated classification inputs plus cached counts.
34
+
35
+ For binary and multiclass targets, ``labels`` defines the class order used by every per-class output and
36
+ by the columns of 2-D ``y_prob``. For multilabel targets, labels are column indices.
37
+ """
38
+
39
+ def __init__(
40
+ self,
41
+ y_true: ArrayLike,
42
+ y_pred: Optional[ArrayLike] = None,
43
+ *,
44
+ y_prob: Optional[ArrayLike] = None,
45
+ labels: Optional[ArrayLike] = None,
46
+ sample_weight: Optional[ArrayLike] = None,
47
+ ) -> None:
48
+ yt = to_numpy(y_true, "y_true", allow_2d=True)
49
+ yp = None if y_pred is None else to_numpy(y_pred, "y_pred", allow_2d=True)
50
+ check_finite(yt, "y_true")
51
+ if yp is not None:
52
+ check_finite(yp, "y_pred")
53
+ self.n = check_consistent_length(y_true=yt, y_pred=yp)
54
+ kind = target_type(yt)
55
+ if kind == "continuous":
56
+ raise UnsupportedTaskError(
57
+ "y_true contains non-integer numbers, which looks like a regression target. "
58
+ 'Use evalsuite.regression metrics or evaluate(..., task="regression").'
59
+ )
60
+ if yp is not None and yt.ndim != yp.ndim:
61
+ raise InputValidationError(
62
+ f"y_true has {yt.ndim} dimension(s) but y_pred has {yp.ndim}. Multilabel targets need both as "
63
+ "indicator matrices; single-label targets need both as 1-D label arrays."
64
+ )
65
+ if kind == "multilabel" and yp is not None:
66
+ if yp.shape[1] != yt.shape[1]:
67
+ raise InputValidationError(f"y_true has {yt.shape[1]} label columns but y_pred has {yp.shape[1]}.")
68
+ if not np.isin(yp, (0, 1)).all():
69
+ raise InputValidationError("Multilabel y_pred must be a 0/1 indicator matrix.")
70
+ self.target_type: TargetType = kind
71
+ self.y_true = yt
72
+ self.y_pred = yp
73
+ self.sample_weight = validate_sample_weight(sample_weight, self.n)
74
+ if kind == "multilabel":
75
+ self.labels: NDArray[Any] = np.arange(yt.shape[1])
76
+ else:
77
+ self.labels = resolve_labels(yt, yp, labels)
78
+ if labels is not None:
79
+ observed = np.unique(yt if yp is None else np.concatenate([yt, yp]))
80
+ missing = np.setdiff1d(observed, self.labels)
81
+ if missing.size:
82
+ raise InputValidationError(
83
+ f"y_true/y_pred contain label(s) {missing.tolist()} that are not in labels. "
84
+ "Include every label that occurs, or filter the data first."
85
+ )
86
+ if kind == "binary" and self.labels.shape[0] > 2:
87
+ self.target_type = "multiclass"
88
+ self._y_prob_raw = y_prob
89
+
90
+ # ---- encodings -------------------------------------------------------------------------------
91
+ @cached_property
92
+ def _index(self) -> dict[Any, int]:
93
+ return {lab.item() if hasattr(lab, "item") else lab: i for i, lab in enumerate(self.labels)}
94
+
95
+ @cached_property
96
+ def _contiguous_int_labels(self) -> Optional[int]:
97
+ """The first label when labels are consecutive integers lo, lo+1, …; encoding is then y − lo."""
98
+ lab = self.labels
99
+ if (
100
+ lab.dtype.kind in "iu"
101
+ and lab.size
102
+ and np.array_equal(lab, np.arange(int(lab[0]), int(lab[0]) + lab.size))
103
+ ):
104
+ return int(lab[0])
105
+ return None
106
+
107
+ def encode(self, y: NDArray[Any]) -> NDArray[np.int64]:
108
+ lo = self._contiguous_int_labels
109
+ if lo is not None and y.dtype.kind in "iu":
110
+ yi = y.astype(np.int64, copy=False)
111
+ return yi - lo if lo else yi
112
+ sorted_labels = np.all(self.labels[:-1] <= self.labels[1:]) if self.labels.dtype != object else False
113
+ if sorted_labels:
114
+ return np.searchsorted(self.labels, y).astype(np.int64)
115
+ idx = self._index
116
+ return np.fromiter((idx[v.item() if hasattr(v, "item") else v] for v in y), dtype=np.int64, count=len(y))
117
+
118
+ @cached_property
119
+ def true_idx(self) -> NDArray[np.int64]:
120
+ return self.encode(self.y_true)
121
+
122
+ @cached_property
123
+ def pred_idx(self) -> NDArray[np.int64]:
124
+ if self.y_pred is None:
125
+ raise InputValidationError("This metric needs y_pred (predicted labels).")
126
+ return self.encode(self.y_pred)
127
+
128
+ @cached_property
129
+ def weights(self) -> FloatArray:
130
+ return np.ones(self.n) if self.sample_weight is None else self.sample_weight
131
+
132
+ # ---- cached counts ---------------------------------------------------------------------------
133
+ @cached_property
134
+ def confusion_matrix(self) -> FloatArray:
135
+ """Rows: true labels; columns: predicted labels (weighted counts). Single-label targets only."""
136
+ if self.target_type == "multilabel":
137
+ raise UnsupportedTaskError(
138
+ "A single confusion matrix is not defined for multilabel targets; use multilabel_counts."
139
+ )
140
+ k = self.labels.shape[0]
141
+ flat = self.true_idx * k + self.pred_idx
142
+ if self.sample_weight is None: # integer counting is faster than summing unit weights
143
+ return np.bincount(flat, minlength=k * k).reshape(k, k).astype(np.float64)
144
+ return np.bincount(flat, weights=self.weights, minlength=k * k).reshape(k, k).astype(np.float64)
145
+
146
+ @cached_property
147
+ def counts(self) -> dict[str, FloatArray]:
148
+ """Per-class (or per-label) weighted tp, fp, fn, tn and support."""
149
+ if self.target_type == "multilabel":
150
+ if self.y_pred is None:
151
+ raise InputValidationError("This metric needs y_pred (predicted labels).")
152
+ w = self.weights[:, None]
153
+ t = self.y_true.astype(bool)
154
+ p = self.y_pred.astype(bool)
155
+ tp = ((t & p) * w).sum(0)
156
+ fp = ((~t & p) * w).sum(0)
157
+ fn = ((t & ~p) * w).sum(0)
158
+ tn = ((~t & ~p) * w).sum(0)
159
+ else:
160
+ cm = self.confusion_matrix
161
+ tp = np.diag(cm).copy()
162
+ fp = cm.sum(0) - tp
163
+ fn = cm.sum(1) - tp
164
+ tn = cm.sum() - tp - fp - fn
165
+ return {"tp": tp, "fp": fp, "fn": fn, "tn": tn, "support": tp + fn}
166
+
167
+ @cached_property
168
+ def total_weight(self) -> float:
169
+ return float(self.weights.sum())
170
+
171
+ # ---- probabilities ---------------------------------------------------------------------------
172
+ @cached_property
173
+ def y_prob(self) -> FloatArray:
174
+ if self._y_prob_raw is None:
175
+ raise InputValidationError(
176
+ "This metric needs predicted probabilities (y_prob): P(positive class) for binary tasks, "
177
+ "or one column per class in label order for multiclass tasks."
178
+ )
179
+ k = self.labels.shape[0]
180
+ p = validate_probabilities(
181
+ self._y_prob_raw,
182
+ self.n,
183
+ n_classes=None if self.target_type == "binary" else k,
184
+ rows_sum_to_one=self.target_type == "multiclass",
185
+ unit="label" if self.target_type == "multilabel" else "class",
186
+ )
187
+ if self.target_type == "binary" and p.ndim == 2:
188
+ if p.shape[1] != 2:
189
+ raise InputValidationError(
190
+ f"For binary tasks y_prob must be P(positive) or two columns; received {p.shape[1]} columns."
191
+ )
192
+ p = p[:, 1]
193
+ if self.target_type == "multiclass" and p.ndim == 1:
194
+ raise InputValidationError(
195
+ f"Multiclass tasks need y_prob with one column per class ({k} columns, in label order)."
196
+ )
197
+ if self.target_type == "multilabel" and (p.ndim != 2 or p.shape[1] != self.y_true.shape[1]):
198
+ raise InputValidationError("Multilabel y_prob must have one probability column per label.")
199
+ return p
@@ -0,0 +1,52 @@
1
+ """Exception hierarchy.
2
+
3
+ Every message says what failed, why, and how to fix it.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ __all__ = [
9
+ "EvalSuiteError",
10
+ "InputValidationError",
11
+ "MetricInputError",
12
+ "OptionalDependencyError",
13
+ "StatisticalTestError",
14
+ "UndefinedMetricWarning",
15
+ "UnsupportedTaskError",
16
+ ]
17
+
18
+
19
+ class EvalSuiteError(Exception):
20
+ """Base class for all EvalSuite errors."""
21
+
22
+
23
+ class InputValidationError(EvalSuiteError, ValueError):
24
+ """Inputs have the wrong shape, length, type or values."""
25
+
26
+
27
+ class MetricInputError(EvalSuiteError, ValueError):
28
+ """Inputs are valid arrays but outside the domain a metric is defined on."""
29
+
30
+
31
+ class UnsupportedTaskError(EvalSuiteError, ValueError):
32
+ """The requested task or averaging mode is not supported for this metric."""
33
+
34
+
35
+ class OptionalDependencyError(EvalSuiteError, ImportError):
36
+ """A feature needs an optional dependency that is not installed."""
37
+
38
+ def __init__(self, package: str, extra: str, feature: str) -> None:
39
+ super().__init__(
40
+ f"{feature} requires the optional dependency '{package}'. "
41
+ f'Install it with: pip install "evalsuite-python[{extra}]"'
42
+ )
43
+ self.package = package
44
+ self.extra = extra
45
+
46
+
47
+ class StatisticalTestError(EvalSuiteError, ValueError):
48
+ """A statistical procedure cannot be applied to the given data."""
49
+
50
+
51
+ class UndefinedMetricWarning(UserWarning):
52
+ """A metric is undefined for the input (for example a zero denominator)."""