evalsuite-python 0.6.0__cp39-abi3-win_amd64.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,392 @@
1
+ """Calibration of predicted probabilities: maximum calibration error, calibration slope and intercept
2
+ (logistic recalibration) and the Hosmer–Lemeshow goodness-of-fit test.
3
+
4
+ The calibration curve, expected calibration error and Brier score live in :mod:`evalsuite.classification`
5
+ and are re-exported here for convenience.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from dataclasses import dataclass, field
12
+ from types import MappingProxyType
13
+ from typing import TYPE_CHECKING, Any, Literal, Optional, cast
14
+
15
+ import numpy as np
16
+ from numpy.typing import NDArray
17
+
18
+ if TYPE_CHECKING:
19
+ from scipy import stats
20
+ else:
21
+ from ._lazy import lazy_module
22
+
23
+ stats = lazy_module("scipy.stats")
24
+
25
+ from .classification.metrics import (
26
+ _binary_target,
27
+ _ctx,
28
+ brier_score,
29
+ calibration_curve,
30
+ expected_calibration_error,
31
+ )
32
+ from .core.exceptions import InputValidationError, StatisticalTestError, UnsupportedTaskError
33
+ from .core.export import PathLike, csv_text, html_document, html_table, save_as
34
+ from .core.registry import register
35
+ from .core.result import MetricResult, _fmt, _json_safe, _latex_escape, _latex_table
36
+ from .core.types import ArrayLike
37
+ from .stats.results import TestResult
38
+
39
+ if TYPE_CHECKING:
40
+ import pandas as pd
41
+
42
+ __all__ = [
43
+ "CalibrationReport",
44
+ "brier_score",
45
+ "calibration_report",
46
+ "calibration_curve",
47
+ "calibration_intercept",
48
+ "calibration_slope",
49
+ "expected_calibration_error",
50
+ "hosmer_lemeshow",
51
+ "maximum_calibration_error",
52
+ ]
53
+
54
+ _C = "calibration"
55
+ _EPS = 1e-15
56
+ _REF_VC = (
57
+ "Van Calster B, McLernon DJ, van Smeden M, Wynants L, Steyerberg EW. Calibration: the Achilles heel of "
58
+ "predictive analytics. BMC Med. 2019;17(1):230."
59
+ )
60
+ _REF_COX = "Cox DR. Two further applications of a model for binary regression. Biometrika. 1958;45(3-4):562-565."
61
+ _REF_HL = (
62
+ "Hosmer DW, Lemeshow S. Goodness of fit tests for the multiple logistic regression model. "
63
+ "Commun Stat Theory Methods. 1980;9(10):1043-1069."
64
+ )
65
+ _REF_NAEINI = (
66
+ "Naeini MP, Cooper GF, Hauskrecht M. Obtaining well calibrated probabilities using Bayesian binning. "
67
+ "AAAI 2015:2901-2907."
68
+ )
69
+
70
+
71
+ def _binary(
72
+ y_true: ArrayLike, y_prob: ArrayLike, pos_label: Any, sample_weight: Optional[ArrayLike]
73
+ ) -> tuple[NDArray[np.float64], NDArray[np.float64], NDArray[np.float64]]:
74
+ ctx = _ctx(y_true, None, y_prob=y_prob, sample_weight=sample_weight)
75
+ if ctx.target_type != "binary":
76
+ raise UnsupportedTaskError("Calibration measures here are for binary outcomes; use one-vs-rest per class.")
77
+ y = _binary_target(ctx, pos_label)
78
+ return y, np.asarray(ctx.y_prob, dtype=np.float64), np.asarray(ctx.weights, dtype=np.float64)
79
+
80
+
81
+ @register(
82
+ category=_C,
83
+ task="binary",
84
+ name="Maximum calibration error",
85
+ definition="Largest gap between observed frequency and mean predicted probability over probability bins.",
86
+ formula="MCE = max_b |acc_b − conf_b|",
87
+ range="[0, 1]",
88
+ input_requirements=("y_true", "y_prob"),
89
+ references=(_REF_NAEINI,),
90
+ higher_is_better=False,
91
+ )
92
+ def maximum_calibration_error(
93
+ y_true: ArrayLike,
94
+ y_prob: ArrayLike,
95
+ *,
96
+ n_bins: int = 10,
97
+ strategy: Literal["uniform", "quantile"] = "uniform",
98
+ pos_label: Any = None,
99
+ sample_weight: Optional[ArrayLike] = None,
100
+ ) -> MetricResult:
101
+ """Maximum calibration error over the non-empty bins of :func:`calibration_curve`."""
102
+ prob_true, prob_pred, _ = calibration_curve(
103
+ y_true, y_prob, n_bins=n_bins, strategy=strategy, pos_label=pos_label, sample_weight=sample_weight
104
+ )
105
+ return MetricResult(
106
+ "maximum_calibration_error",
107
+ "MCE",
108
+ float(np.max(np.abs(prob_true - prob_pred))),
109
+ {"n_bins": int(n_bins), "strategy": strategy},
110
+ )
111
+
112
+
113
+ def _logit(p: NDArray[np.float64]) -> NDArray[np.float64]:
114
+ q = np.clip(p, _EPS, 1 - _EPS)
115
+ return np.asarray(np.log(q / (1 - q)), dtype=np.float64)
116
+
117
+
118
+ def logistic_fit(
119
+ y: NDArray[np.float64],
120
+ x: NDArray[np.float64],
121
+ w: NDArray[np.float64],
122
+ *,
123
+ offset: bool,
124
+ max_iter: int = 100,
125
+ tol: float = 1e-12,
126
+ ) -> NDArray[np.float64]:
127
+ """Weighted maximum-likelihood logistic regression by Newton–Raphson.
128
+
129
+ ``offset=True`` fits ``logit P(y=1) = a + x`` (returns ``[a]``); otherwise ``logit P(y=1) = a + b·x``
130
+ (returns ``[a, b]``).
131
+ """
132
+ design = np.ones((x.shape[0], 1)) if offset else np.column_stack([np.ones_like(x), x])
133
+ off = x if offset else np.zeros_like(x)
134
+ beta = np.zeros(design.shape[1])
135
+ for _ in range(max_iter):
136
+ eta = design @ beta + off
137
+ mu = 1 / (1 + np.exp(-np.clip(eta, -700, 700)))
138
+ grad = design.T @ (w * (y - mu))
139
+ hess = (design * (w * mu * (1 - mu))[:, None]).T @ design
140
+ try:
141
+ step = np.linalg.solve(hess, grad)
142
+ except np.linalg.LinAlgError:
143
+ raise StatisticalTestError(
144
+ "The logistic recalibration model could not be fitted (singular information matrix); "
145
+ "the predictions may be constant or the outcome may be perfectly separated."
146
+ ) from None
147
+ beta = beta + step
148
+ if np.max(np.abs(step)) < tol:
149
+ return beta
150
+ raise StatisticalTestError(
151
+ "The logistic recalibration model did not converge; the outcome may be perfectly separated by the "
152
+ "predictions."
153
+ )
154
+
155
+
156
+ def _need_both(y: NDArray[np.float64], what: str) -> None:
157
+ if np.min(y) == np.max(y):
158
+ raise InputValidationError(f"{what} needs both outcomes (0 and 1) in y_true.")
159
+
160
+
161
+ @register(
162
+ category=_C,
163
+ task="binary",
164
+ name="Calibration slope",
165
+ definition="Slope b of the logistic recalibration model logit P(y=1) = a + b · logit(p). 1 is ideal; below "
166
+ "1 means predictions are too extreme (overfitting), above 1 too moderate.",
167
+ formula="logit P(y=1) = a + b · logit(p̂)",
168
+ range="(−∞, ∞), ideal 1",
169
+ input_requirements=("y_true", "y_prob"),
170
+ references=(_REF_COX, _REF_VC),
171
+ higher_is_better=None,
172
+ )
173
+ def calibration_slope(
174
+ y_true: ArrayLike,
175
+ y_prob: ArrayLike,
176
+ *,
177
+ pos_label: Any = None,
178
+ sample_weight: Optional[ArrayLike] = None,
179
+ ) -> MetricResult:
180
+ """Calibration slope (Cox 1958). Probabilities are clipped to [1e-15, 1 − 1e-15] before the logit."""
181
+ y, p, w = _binary(y_true, y_prob, pos_label, sample_weight)
182
+ _need_both(y, "The calibration slope")
183
+ a, b = logistic_fit(y, _logit(p), w, offset=False)
184
+ return MetricResult("calibration_slope", "Calibration slope", float(b), {"intercept": float(a)})
185
+
186
+
187
+ @register(
188
+ category=_C,
189
+ task="binary",
190
+ name="Calibration intercept",
191
+ definition="Calibration-in-the-large: intercept a of logit P(y=1) = a + logit(p) with the slope fixed at 1. "
192
+ "0 is ideal; negative means risks are overestimated on average, positive underestimated.",
193
+ formula="logit P(y=1) = a + logit(p̂) (offset)",
194
+ range="(−∞, ∞), ideal 0",
195
+ input_requirements=("y_true", "y_prob"),
196
+ references=(_REF_COX, _REF_VC),
197
+ higher_is_better=None,
198
+ )
199
+ def calibration_intercept(
200
+ y_true: ArrayLike,
201
+ y_prob: ArrayLike,
202
+ *,
203
+ pos_label: Any = None,
204
+ sample_weight: Optional[ArrayLike] = None,
205
+ ) -> MetricResult:
206
+ """Calibration intercept (calibration-in-the-large) with the logit of the predictions as an offset."""
207
+ y, p, w = _binary(y_true, y_prob, pos_label, sample_weight)
208
+ _need_both(y, "The calibration intercept")
209
+ (a,) = logistic_fit(y, _logit(p), w, offset=True)
210
+ return MetricResult("calibration_intercept", "Calibration intercept", float(a))
211
+
212
+
213
+ def hosmer_lemeshow(
214
+ y_true: ArrayLike,
215
+ y_prob: ArrayLike,
216
+ *,
217
+ n_groups: int = 10,
218
+ pos_label: Any = None,
219
+ ) -> TestResult:
220
+ """Hosmer–Lemeshow goodness-of-fit test for predicted risks.
221
+
222
+ Observations are sorted by predicted risk and split into ``n_groups`` groups of (nearly) equal size
223
+ ("deciles of risk"). The statistic Σ (O − E)² / (E (1 − E/nₖ)) is compared with χ² on ``n_groups − 2``
224
+ degrees of freedom (use ``n_groups`` degrees of freedom for an external validation set by reading
225
+ ``params["statistic"]``). A large p-value does not show that calibration is good, especially in small
226
+ samples; report the calibration curve, slope and intercept as well.
227
+ """
228
+ y, p, _ = _binary(y_true, y_prob, pos_label, None)
229
+ if not (isinstance(n_groups, (int, np.integer)) and n_groups >= 3):
230
+ raise InputValidationError("n_groups must be an integer of at least 3.")
231
+ if y.shape[0] < n_groups:
232
+ raise InputValidationError(f"Need at least n_groups={n_groups} observations; got {y.shape[0]}.")
233
+ order = np.argsort(p, kind="mergesort")
234
+ groups = np.array_split(order, n_groups)
235
+ observed = np.array([y[g].sum() for g in groups])
236
+ expected = np.array([p[g].sum() for g in groups])
237
+ sizes = np.array([g.shape[0] for g in groups], dtype=np.float64)
238
+ var = expected * (1 - expected / sizes)
239
+ if np.any(var <= 0):
240
+ raise StatisticalTestError(
241
+ "Hosmer–Lemeshow is undefined: a risk group has every predicted risk at 0 or 1. Use fewer groups."
242
+ )
243
+ stat = float(np.sum((observed - expected) ** 2 / var))
244
+ df = n_groups - 2
245
+ return TestResult(
246
+ "hosmer-lemeshow",
247
+ stat,
248
+ float(stats.chi2.sf(stat, df)),
249
+ params={
250
+ "df": df,
251
+ "n_groups": int(n_groups),
252
+ "observed": observed.tolist(),
253
+ "expected": expected.tolist(),
254
+ "group_sizes": sizes.astype(int).tolist(),
255
+ },
256
+ )
257
+
258
+
259
+ _REPORT_ROWS = (
260
+ ("brier_score", "Brier score", "0"),
261
+ ("expected_calibration_error", "ECE", "0"),
262
+ ("maximum_calibration_error", "MCE", "0"),
263
+ ("calibration_intercept", "Calibration intercept", "0"),
264
+ ("calibration_slope", "Calibration slope", "1"),
265
+ ("hosmer_lemeshow_statistic", "Hosmer–Lemeshow χ²", "–"),
266
+ ("hosmer_lemeshow_p", "Hosmer–Lemeshow p", "–"),
267
+ )
268
+
269
+
270
+ @dataclass(frozen=True, eq=False)
271
+ class CalibrationReport:
272
+ """Calibration of one model's predicted risks: Brier score, ECE, MCE, intercept, slope and Hosmer–Lemeshow,
273
+ plus the binned calibration curve (``curve``: prob_true, prob_pred, bin_weight)."""
274
+
275
+ values: Any
276
+ curve: Any
277
+ params: Any = field(default_factory=dict)
278
+
279
+ def __post_init__(self) -> None:
280
+ object.__setattr__(self, "values", MappingProxyType(dict(self.values)))
281
+ object.__setattr__(self, "params", MappingProxyType(dict(self.params)))
282
+
283
+ def __getitem__(self, name: str) -> float:
284
+ return float(self.values[name])
285
+
286
+ def _rows(self, digits: int) -> list[list[str]]:
287
+ return [[label, _fmt(self.values[k], digits), ideal] for k, label, ideal in _REPORT_ROWS]
288
+
289
+ def summary(self, *, digits: int = 4) -> str:
290
+ p = self.params
291
+ lines = [
292
+ f"EvalSuite calibration (n={p['n']}, {p['n_bins']} {p['strategy']} bins, HL {p['n_groups']} groups)"
293
+ ]
294
+ width = max(len(label) for _, label, _ in _REPORT_ROWS)
295
+ for k, label, ideal in _REPORT_ROWS:
296
+ lines.append(f" {label:<{width}} {_fmt(self.values[k], digits)} (ideal {ideal})")
297
+ return "\n".join(lines)
298
+
299
+ def __repr__(self) -> str:
300
+ return self.summary()
301
+
302
+ def to_dict(self) -> dict[str, Any]:
303
+ prob_true, prob_pred, weight = self.curve
304
+ return cast(
305
+ "dict[str, Any]",
306
+ _json_safe(
307
+ {
308
+ "values": dict(self.values),
309
+ "curve": {"prob_true": prob_true, "prob_pred": prob_pred, "bin_weight": weight},
310
+ "params": dict(self.params),
311
+ }
312
+ ),
313
+ )
314
+
315
+ def to_json(self, *, indent: Optional[int] = 2) -> str:
316
+ return json.dumps(self.to_dict(), indent=indent, allow_nan=False)
317
+
318
+ def to_dataframe(self) -> pd.DataFrame:
319
+ import pandas as pd
320
+
321
+ frame: pd.DataFrame = pd.DataFrame({"value": dict(self.values)})
322
+ return frame
323
+
324
+ def to_markdown(self, *, digits: int = 4) -> str:
325
+ lines = ["| Measure | Value | Ideal |", "| --- | ---: | ---: |"]
326
+ lines += ["| " + " | ".join(r) + " |" for r in self._rows(digits)]
327
+ return "\n".join(lines)
328
+
329
+ def to_latex(self, *, digits: int = 4, caption: Optional[str] = None, label: Optional[str] = None) -> str:
330
+ rows = [[_latex_escape(c) for c in r] for r in self._rows(digits)]
331
+ return _latex_table(["Measure", "Value", "Ideal"], rows, caption, label)
332
+
333
+ def to_csv(self, path: Optional[PathLike] = None) -> str:
334
+ text = csv_text(["measure", "value"], [[k, float(v)] for k, v in self.values.items()])
335
+ if path is not None:
336
+ with open(path, "w", encoding="utf-8", newline="") as fh:
337
+ fh.write(text)
338
+ return text
339
+
340
+ def to_html(self, *, digits: int = 4, full: bool = True) -> str:
341
+ body = html_table(["Measure", "Value", "Ideal"], self._rows(digits), caption="Calibration")
342
+ prob_true, prob_pred, weight = self.curve
343
+ body += "\n" + html_table(
344
+ ["Mean predicted", "Observed", "Weight"],
345
+ [[_fmt(a, digits), _fmt(b, digits), f"{w:g}"] for a, b, w in zip(prob_pred, prob_true, weight)],
346
+ caption="Calibration curve",
347
+ numeric=[True, True, True],
348
+ )
349
+ return html_document("EvalSuite calibration", body) if full else body
350
+
351
+ def save(self, path: PathLike) -> str:
352
+ return save_as(
353
+ path,
354
+ {
355
+ "json": self.to_json,
356
+ "csv": self.to_csv,
357
+ "markdown": self.to_markdown,
358
+ "latex": self.to_latex,
359
+ "html": self.to_html,
360
+ "text": self.summary,
361
+ },
362
+ )
363
+
364
+
365
+ def calibration_report(
366
+ y_true: ArrayLike,
367
+ y_prob: ArrayLike,
368
+ *,
369
+ n_bins: int = 10,
370
+ strategy: Literal["uniform", "quantile"] = "uniform",
371
+ n_groups: int = 10,
372
+ pos_label: Any = None,
373
+ ) -> CalibrationReport:
374
+ """Every calibration measure for binary predicted risks in one object (see :class:`CalibrationReport`)."""
375
+ kw: dict[str, Any] = {"n_bins": n_bins, "strategy": strategy, "pos_label": pos_label}
376
+ hl = hosmer_lemeshow(y_true, y_prob, n_groups=n_groups, pos_label=pos_label)
377
+ values = {
378
+ "brier_score": float(brier_score(y_true, y_prob, pos_label=pos_label)),
379
+ "expected_calibration_error": float(expected_calibration_error(y_true, y_prob, **kw)),
380
+ "maximum_calibration_error": float(maximum_calibration_error(y_true, y_prob, **kw)),
381
+ "calibration_intercept": float(calibration_intercept(y_true, y_prob, pos_label=pos_label)),
382
+ "calibration_slope": float(calibration_slope(y_true, y_prob, pos_label=pos_label)),
383
+ "hosmer_lemeshow_statistic": hl.statistic,
384
+ "hosmer_lemeshow_p": hl.p_value,
385
+ }
386
+ curve = calibration_curve(y_true, y_prob, **kw)
387
+ n = int(np.asarray(y_true).shape[0])
388
+ return CalibrationReport(
389
+ values,
390
+ curve,
391
+ {"n": n, "n_bins": n_bins, "strategy": strategy, "n_groups": n_groups, "hl_df": hl.params["df"]},
392
+ )
@@ -0,0 +1,51 @@
1
+ """Classification metrics."""
2
+
3
+ from .metrics import (
4
+ accuracy,
5
+ average_precision,
6
+ balanced_accuracy,
7
+ brier_score,
8
+ calibration_curve,
9
+ cohen_kappa,
10
+ confusion_matrix,
11
+ expected_calibration_error,
12
+ f1,
13
+ fbeta,
14
+ hamming_loss,
15
+ jaccard,
16
+ log_loss,
17
+ mcc,
18
+ npv,
19
+ pr_curve,
20
+ precision,
21
+ recall,
22
+ roc_auc,
23
+ roc_curve,
24
+ specificity,
25
+ top_k_accuracy,
26
+ )
27
+
28
+ __all__ = [
29
+ "accuracy",
30
+ "average_precision",
31
+ "balanced_accuracy",
32
+ "brier_score",
33
+ "calibration_curve",
34
+ "cohen_kappa",
35
+ "confusion_matrix",
36
+ "expected_calibration_error",
37
+ "f1",
38
+ "fbeta",
39
+ "hamming_loss",
40
+ "jaccard",
41
+ "log_loss",
42
+ "mcc",
43
+ "npv",
44
+ "pr_curve",
45
+ "precision",
46
+ "recall",
47
+ "roc_auc",
48
+ "roc_curve",
49
+ "specificity",
50
+ "top_k_accuracy",
51
+ ]
@@ -0,0 +1,111 @@
1
+ """Shared averaging logic for count-based classification metrics."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from typing import Any, Optional
7
+
8
+ import numpy as np
9
+
10
+ from ..core.context import ClassificationContext
11
+ from ..core.exceptions import InputValidationError, UnsupportedTaskError
12
+ from ..core.result import MetricResult
13
+ from ..core.types import FloatArray, ZeroDivision
14
+ from ..core.validation import safe_divide, validate_zero_division
15
+
16
+ CountFn = Callable[[FloatArray, FloatArray, FloatArray, FloatArray, ZeroDivision], FloatArray]
17
+
18
+ AVERAGES = ("auto", "binary", "micro", "macro", "weighted", "samples", None)
19
+
20
+
21
+ def resolve_average(ctx: ClassificationContext, average: Optional[str]) -> Optional[str]:
22
+ if average not in AVERAGES:
23
+ raise UnsupportedTaskError(
24
+ f"average={average!r} is not supported. Use one of: 'binary', 'micro', 'macro', 'weighted', "
25
+ "'samples' (multilabel) or None (per-class values)."
26
+ )
27
+ if average == "auto":
28
+ return "binary" if ctx.target_type == "binary" else "macro"
29
+ if average == "binary" and ctx.target_type != "binary":
30
+ raise UnsupportedTaskError(
31
+ f"average='binary' needs a binary target, but this target is {ctx.target_type} "
32
+ f"({len(ctx.labels)} labels). Choose average='macro', 'micro' or 'weighted', "
33
+ "or None for per-class values."
34
+ )
35
+ if average == "samples" and ctx.target_type != "multilabel":
36
+ raise UnsupportedTaskError("average='samples' is only defined for multilabel targets.")
37
+ return average
38
+
39
+
40
+ def positive_index(ctx: ClassificationContext, pos_label: Any) -> Optional[int]:
41
+ """Index of the positive class in ctx.labels, or None if it never occurs (all-negative data)."""
42
+ labels = ctx.labels
43
+ if pos_label is None:
44
+ if set(labels.tolist()) <= {0, 1, -1}:
45
+ pos_label = 1
46
+ else:
47
+ raise InputValidationError(
48
+ f"Labels are {labels.tolist()}; specify which one is positive with pos_label=..."
49
+ )
50
+ hits = np.flatnonzero(labels == pos_label)
51
+ if hits.size:
52
+ return int(hits[0])
53
+ if labels.shape[0] <= 1:
54
+ return None
55
+ raise InputValidationError(f"pos_label={pos_label!r} is not one of the labels {labels.tolist()}.")
56
+
57
+
58
+ def averaged(
59
+ ctx: ClassificationContext,
60
+ fn: CountFn,
61
+ *,
62
+ metric: str,
63
+ name: str,
64
+ average: Optional[str],
65
+ pos_label: Any = None,
66
+ zero_division: ZeroDivision = "warn",
67
+ extra_params: Optional[dict[str, Any]] = None,
68
+ ) -> MetricResult:
69
+ """Apply a vectorised count metric fn(tp, fp, fn, tn) with the requested averaging."""
70
+ zd = validate_zero_division(zero_division)
71
+ avg = resolve_average(ctx, average)
72
+ c = ctx.counts
73
+ params: dict[str, Any] = {"average": avg, "zero_division": zero_division, **(extra_params or {})}
74
+
75
+ if avg == "binary":
76
+ idx = positive_index(ctx, pos_label)
77
+ if idx is None:
78
+ tp = fp = fnn = np.zeros(1)
79
+ tn = np.array([ctx.total_weight])
80
+ else:
81
+ tp, fp, fnn, tn = (c[k][idx : idx + 1] for k in ("tp", "fp", "fn", "tn"))
82
+ params["pos_label"] = 1 if pos_label is None else pos_label
83
+ return MetricResult(metric, name, float(fn(tp, fp, fnn, tn, zd)[0]), params)
84
+
85
+ if avg == "micro":
86
+ tp_s, fp_s, fn_s, tn_s = (np.array([c[k].sum()]) for k in ("tp", "fp", "fn", "tn"))
87
+ return MetricResult(metric, name, float(fn(tp_s, fp_s, fn_s, tn_s, zd)[0]), params)
88
+
89
+ if avg == "samples":
90
+ w = ctx.weights
91
+ t = ctx.y_true.astype(bool)
92
+ if ctx.y_pred is None:
93
+ raise InputValidationError("This metric needs y_pred (predicted labels).")
94
+ p = ctx.y_pred.astype(bool)
95
+ per_sample = fn(
96
+ (t & p).sum(1).astype(float),
97
+ (~t & p).sum(1).astype(float),
98
+ (t & ~p).sum(1).astype(float),
99
+ (~t & ~p).sum(1).astype(float),
100
+ zd,
101
+ )
102
+ return MetricResult(metric, name, float(np.average(per_sample, weights=w)), params)
103
+
104
+ per_class = fn(c["tp"], c["fp"], c["fn"], c["tn"], zd)
105
+ if avg is None:
106
+ return MetricResult(metric, name, per_class, params, labels=tuple(ctx.labels.tolist()))
107
+ if avg == "macro":
108
+ return MetricResult(metric, name, float(np.mean(per_class)), params)
109
+ support = c["support"]
110
+ value = safe_divide((per_class * support).sum(), support.sum(), zero_division=zd, metric=name)
111
+ return MetricResult(metric, name, float(value), params)