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,342 @@
1
+ """Diagnostic-accuracy metrics for binary tests and risk models.
2
+
3
+ All functions take a binary reference standard ``y_true`` and binary test results ``y_pred`` (or predicted
4
+ risks ``y_prob`` for decision curves). The positive class is ``pos_label`` (default 1 for 0/1 labels).
5
+
6
+ Ratios that divide by zero are reported honestly: ``x / 0`` with ``x > 0`` is ``inf`` and ``0 / 0`` is NaN,
7
+ always with an :class:`~evalsuite.core.exceptions.UndefinedMetricWarning`. They are never replaced by 0,
8
+ because a likelihood ratio of 0 would mean the opposite of an infinite one.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import math
14
+ import warnings
15
+ from typing import Any, Optional
16
+
17
+ import numpy as np
18
+
19
+ from ..classification._common import positive_index
20
+ from ..core.context import ClassificationContext
21
+ from ..core.exceptions import InputValidationError, UndefinedMetricWarning, UnsupportedTaskError
22
+ from ..core.registry import register
23
+ from ..core.result import MetricResult
24
+ from ..core.types import ArrayLike, ZeroDivision
25
+ from ..core.validation import safe_divide, validate_zero_division
26
+
27
+ __all__ = [
28
+ "diagnostic_odds_ratio",
29
+ "lr_negative",
30
+ "lr_positive",
31
+ "net_benefit",
32
+ "ppv",
33
+ "sensitivity",
34
+ "youden_j",
35
+ ]
36
+
37
+ _C = "clinical"
38
+ _REF_ALTMAN = "Altman DG, Bland JM. Diagnostic tests 1: sensitivity and specificity. BMJ. 1994;308(6943):1552."
39
+ _REF_ALTMAN2 = "Altman DG, Bland JM. Diagnostic tests 2: predictive values. BMJ. 1994;309(6947):102."
40
+ _REF_DEEKS = "Deeks JJ, Altman DG. Diagnostic tests 4: likelihood ratios. BMJ. 2004;329(7458):168-169."
41
+ _REF_SIMEL = (
42
+ "Simel DL, Samsa GP, Matchar DB. Likelihood ratios with confidence: sample size estimation for "
43
+ "diagnostic test studies. J Clin Epidemiol. 1991;44(8):763-770."
44
+ )
45
+ _REF_GLAS = (
46
+ "Glas AS, Lijmer JG, Prins MH, Bonsel GJ, Bossuyt PMM. The diagnostic odds ratio: a single indicator "
47
+ "of test performance. J Clin Epidemiol. 2003;56(11):1129-1135."
48
+ )
49
+ _REF_YOUDEN = "Youden WJ. Index for rating diagnostic tests. Cancer. 1950;3(1):32-35."
50
+ _REF_VICKERS = (
51
+ "Vickers AJ, Elkin EB. Decision curve analysis: a novel method for evaluating prediction models. "
52
+ "Med Decis Making. 2006;26(6):565-574."
53
+ )
54
+
55
+
56
+ def binary_counts(
57
+ y_true: ArrayLike,
58
+ y_pred: ArrayLike,
59
+ *,
60
+ pos_label: Any = None,
61
+ sample_weight: Optional[ArrayLike] = None,
62
+ ) -> tuple[float, float, float, float]:
63
+ """``(tp, fp, fn, tn)`` for the positive class (weighted if ``sample_weight`` is given)."""
64
+ ctx = ClassificationContext(y_true, y_pred, sample_weight=sample_weight)
65
+ if ctx.target_type not in ("binary",):
66
+ raise UnsupportedTaskError(
67
+ f"Diagnostic metrics are defined for binary outcomes; this target is {ctx.target_type}."
68
+ )
69
+ idx = positive_index(ctx, pos_label)
70
+ if idx is None:
71
+ return 0.0, 0.0, 0.0, float(ctx.total_weight)
72
+ c = ctx.counts
73
+ return tuple(float(c[k][idx]) for k in ("tp", "fp", "fn", "tn")) # type: ignore[return-value]
74
+
75
+
76
+ def _ratio(num: float, den: float, what: str) -> float:
77
+ if den != 0:
78
+ return num / den
79
+ value = math.inf if num > 0 else math.nan
80
+ warnings.warn(
81
+ f"{what} is {'infinite' if num > 0 else 'undefined (0/0)'} for this input because its denominator is "
82
+ "zero; returning " + ("inf." if num > 0 else "NaN."),
83
+ UndefinedMetricWarning,
84
+ stacklevel=3,
85
+ )
86
+ return value
87
+
88
+
89
+ def _params(pos_label: Any) -> dict[str, Any]:
90
+ return {"pos_label": 1 if pos_label is None else pos_label}
91
+
92
+
93
+ @register(
94
+ category=_C,
95
+ task="binary",
96
+ name="Sensitivity",
97
+ definition="Of the people with the condition, the proportion the test calls positive (true positive rate).",
98
+ formula="TP / (TP + FN)",
99
+ range="[0, 1]",
100
+ input_requirements=("y_true", "y_pred"),
101
+ references=(_REF_ALTMAN,),
102
+ )
103
+ def sensitivity(
104
+ y_true: ArrayLike,
105
+ y_pred: ArrayLike,
106
+ *,
107
+ pos_label: Any = None,
108
+ sample_weight: Optional[ArrayLike] = None,
109
+ zero_division: ZeroDivision = "warn",
110
+ ) -> MetricResult:
111
+ """Sensitivity (recall of the positive class)."""
112
+ tp, _fp, fn, _tn = binary_counts(y_true, y_pred, pos_label=pos_label, sample_weight=sample_weight)
113
+ zd = validate_zero_division(zero_division)
114
+ value = float(safe_divide(tp, tp + fn, zero_division=zd, metric="Sensitivity"))
115
+ return MetricResult(
116
+ "sensitivity", "Sensitivity", value, {**_params(pos_label), "zero_division": zero_division}
117
+ )
118
+
119
+
120
+ @register(
121
+ category=_C,
122
+ task="binary",
123
+ name="Positive predictive value",
124
+ definition="Of the people the test calls positive, the proportion who have the condition. Depends on "
125
+ "prevalence.",
126
+ formula="TP / (TP + FP)",
127
+ range="[0, 1]",
128
+ input_requirements=("y_true", "y_pred"),
129
+ references=(_REF_ALTMAN2,),
130
+ )
131
+ def ppv(
132
+ y_true: ArrayLike,
133
+ y_pred: ArrayLike,
134
+ *,
135
+ pos_label: Any = None,
136
+ sample_weight: Optional[ArrayLike] = None,
137
+ zero_division: ZeroDivision = "warn",
138
+ ) -> MetricResult:
139
+ """Positive predictive value (precision of the positive class)."""
140
+ tp, fp, _fn, _tn = binary_counts(y_true, y_pred, pos_label=pos_label, sample_weight=sample_weight)
141
+ zd = validate_zero_division(zero_division)
142
+ value = float(safe_divide(tp, tp + fp, zero_division=zd, metric="PPV"))
143
+ return MetricResult("ppv", "PPV", value, {**_params(pos_label), "zero_division": zero_division})
144
+
145
+
146
+ def _sens_spec(tp: float, fp: float, fn: float, tn: float) -> tuple[float, float]:
147
+ sens = tp / (tp + fn) if tp + fn else math.nan
148
+ spec = tn / (tn + fp) if tn + fp else math.nan
149
+ return sens, spec
150
+
151
+
152
+ def _need_both_classes(tp: float, fp: float, fn: float, tn: float, what: str) -> None:
153
+ if tp + fn == 0 or tn + fp == 0:
154
+ raise InputValidationError(
155
+ f"{what} needs both people with and without the condition in y_true; "
156
+ f"got {tp + fn:g} positive and {tn + fp:g} negative."
157
+ )
158
+
159
+
160
+ @register(
161
+ category=_C,
162
+ task="binary",
163
+ name="Positive likelihood ratio",
164
+ definition="How much a positive result raises the odds of the condition: sensitivity / (1 − specificity).",
165
+ formula="LR+ = sensitivity / (1 − specificity)",
166
+ range="[0, ∞)",
167
+ input_requirements=("y_true", "y_pred"),
168
+ references=(_REF_DEEKS, _REF_SIMEL),
169
+ )
170
+ def lr_positive(
171
+ y_true: ArrayLike,
172
+ y_pred: ArrayLike,
173
+ *,
174
+ pos_label: Any = None,
175
+ sample_weight: Optional[ArrayLike] = None,
176
+ ) -> MetricResult:
177
+ """Positive likelihood ratio. ``inf`` (with a warning) when specificity is 1 and sensitivity > 0."""
178
+ tp, fp, fn, tn = binary_counts(y_true, y_pred, pos_label=pos_label, sample_weight=sample_weight)
179
+ _need_both_classes(tp, fp, fn, tn, "LR+")
180
+ sens, spec = _sens_spec(tp, fp, fn, tn)
181
+ return MetricResult("lr_positive", "LR+", _ratio(sens, 1 - spec, "LR+"), _params(pos_label))
182
+
183
+
184
+ @register(
185
+ category=_C,
186
+ task="binary",
187
+ name="Negative likelihood ratio",
188
+ definition="How much a negative result lowers the odds of the condition: (1 − sensitivity) / specificity.",
189
+ formula="LR− = (1 − sensitivity) / specificity",
190
+ range="[0, ∞)",
191
+ input_requirements=("y_true", "y_pred"),
192
+ references=(_REF_DEEKS, _REF_SIMEL),
193
+ higher_is_better=False,
194
+ )
195
+ def lr_negative(
196
+ y_true: ArrayLike,
197
+ y_pred: ArrayLike,
198
+ *,
199
+ pos_label: Any = None,
200
+ sample_weight: Optional[ArrayLike] = None,
201
+ ) -> MetricResult:
202
+ """Negative likelihood ratio. ``inf`` (with a warning) when specificity is 0 and sensitivity < 1."""
203
+ tp, fp, fn, tn = binary_counts(y_true, y_pred, pos_label=pos_label, sample_weight=sample_weight)
204
+ _need_both_classes(tp, fp, fn, tn, "LR−")
205
+ sens, spec = _sens_spec(tp, fp, fn, tn)
206
+ return MetricResult("lr_negative", "LR−", _ratio(1 - sens, spec, "LR−"), _params(pos_label))
207
+
208
+
209
+ @register(
210
+ category=_C,
211
+ task="binary",
212
+ name="Diagnostic odds ratio",
213
+ definition="Odds of a positive test in people with the condition divided by the odds in people without it.",
214
+ formula="DOR = (TP · TN) / (FP · FN) = LR+ / LR−",
215
+ range="[0, ∞)",
216
+ input_requirements=("y_true", "y_pred"),
217
+ references=(_REF_GLAS,),
218
+ )
219
+ def diagnostic_odds_ratio(
220
+ y_true: ArrayLike,
221
+ y_pred: ArrayLike,
222
+ *,
223
+ pos_label: Any = None,
224
+ sample_weight: Optional[ArrayLike] = None,
225
+ correction: float = 0.0,
226
+ ) -> MetricResult:
227
+ """Diagnostic odds ratio. ``correction=0.5`` adds 0.5 to every cell when any cell is zero (Haldane–Anscombe),
228
+ which keeps the estimate finite; the default 0 reports ``inf`` or NaN with a warning instead."""
229
+ tp, fp, fn, tn = binary_counts(y_true, y_pred, pos_label=pos_label, sample_weight=sample_weight)
230
+ _need_both_classes(tp, fp, fn, tn, "The diagnostic odds ratio")
231
+ if correction < 0:
232
+ raise InputValidationError("correction must be 0 or positive (0.5 is the usual choice).")
233
+ applied = bool(correction) and min(tp, fp, fn, tn) == 0
234
+ if applied:
235
+ tp, fp, fn, tn = (v + correction for v in (tp, fp, fn, tn))
236
+ value = _ratio(tp * tn, fp * fn, "The diagnostic odds ratio")
237
+ return MetricResult(
238
+ "diagnostic_odds_ratio",
239
+ "DOR",
240
+ value,
241
+ {**_params(pos_label), "correction": correction, "correction_applied": applied},
242
+ )
243
+
244
+
245
+ @register(
246
+ category=_C,
247
+ task="binary",
248
+ name="Youden's J",
249
+ definition="Sensitivity + specificity − 1: 0 for a test no better than chance, 1 for a perfect test.",
250
+ formula="J = sensitivity + specificity − 1",
251
+ range="[−1, 1]",
252
+ input_requirements=("y_true", "y_pred"),
253
+ references=(_REF_YOUDEN,),
254
+ )
255
+ def youden_j(
256
+ y_true: ArrayLike,
257
+ y_pred: ArrayLike,
258
+ *,
259
+ pos_label: Any = None,
260
+ sample_weight: Optional[ArrayLike] = None,
261
+ ) -> MetricResult:
262
+ """Youden's J statistic (informedness) for a binary test."""
263
+ tp, fp, fn, tn = binary_counts(y_true, y_pred, pos_label=pos_label, sample_weight=sample_weight)
264
+ _need_both_classes(tp, fp, fn, tn, "Youden's J")
265
+ sens, spec = _sens_spec(tp, fp, fn, tn)
266
+ return MetricResult("youden_j", "Youden's J", sens + spec - 1, _params(pos_label))
267
+
268
+
269
+ def _binary_risk(
270
+ y_true: ArrayLike, y_prob: ArrayLike, pos_label: Any, sample_weight: Optional[ArrayLike]
271
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
272
+ ctx = ClassificationContext(y_true, None, y_prob=y_prob, sample_weight=sample_weight)
273
+ if ctx.target_type != "binary":
274
+ raise UnsupportedTaskError("Decision curves are defined for binary outcomes.")
275
+ idx = positive_index(ctx, pos_label)
276
+ pos = ctx.labels[idx] if idx is not None else None
277
+ y = (ctx.y_true == pos).astype(np.float64) if pos is not None else np.zeros(ctx.n)
278
+ return y, np.asarray(ctx.y_prob, dtype=np.float64), np.asarray(ctx.weights, dtype=np.float64)
279
+
280
+
281
+ def _check_thresholds(t: ArrayLike) -> np.ndarray:
282
+ arr = np.atleast_1d(np.asarray(t, dtype=np.float64))
283
+ if arr.ndim != 1 or arr.size == 0 or np.any(~np.isfinite(arr)) or np.any((arr <= 0) | (arr >= 1)):
284
+ raise InputValidationError("Threshold probabilities must be strictly between 0 and 1.")
285
+ return arr
286
+
287
+
288
+ def net_benefit_curve(
289
+ y: np.ndarray, p: np.ndarray, w: np.ndarray, thresholds: np.ndarray
290
+ ) -> tuple[np.ndarray, np.ndarray]:
291
+ """Net benefit of the model and of treating everyone at each threshold (treat when risk ≥ threshold).
292
+
293
+ Sorting once and using cumulative sums makes this O((n + k) log n) for k thresholds and O(n) memory."""
294
+ n = w.sum()
295
+ order = np.argsort(p, kind="mergesort")
296
+ p_sorted = p[order]
297
+ wy = (w * y)[order]
298
+ w0 = (w * (1 - y))[order]
299
+ # cumulative weight of observations strictly below each cut point, from the low-risk end
300
+ below_pos = np.concatenate([[0.0], np.cumsum(wy)])
301
+ below_neg = np.concatenate([[0.0], np.cumsum(w0)])
302
+ k = np.searchsorted(p_sorted, thresholds, side="left")
303
+ tp = below_pos[-1] - below_pos[k]
304
+ fp = below_neg[-1] - below_neg[k]
305
+ odds = thresholds / (1 - thresholds)
306
+ model = tp / n - fp / n * odds
307
+ prevalence = float(below_pos[-1] / n)
308
+ treat_all = prevalence - (1 - prevalence) * odds
309
+ return model, treat_all
310
+
311
+
312
+ @register(
313
+ category=_C,
314
+ task="binary",
315
+ name="Net benefit",
316
+ definition="Clinical value of acting on the model at a threshold probability: true positives per person "
317
+ "minus false positives per person weighted by the odds of the threshold.",
318
+ formula="NB(pₜ) = TP/n − FP/n · pₜ / (1 − pₜ)",
319
+ range="(−∞, prevalence]",
320
+ input_requirements=("y_true", "y_prob", "threshold"),
321
+ references=(_REF_VICKERS,),
322
+ )
323
+ def net_benefit(
324
+ y_true: ArrayLike,
325
+ y_prob: ArrayLike,
326
+ *,
327
+ threshold: float,
328
+ pos_label: Any = None,
329
+ sample_weight: Optional[ArrayLike] = None,
330
+ ) -> MetricResult:
331
+ """Net benefit at one threshold probability (treat when predicted risk ≥ threshold)."""
332
+ y, p, w = _binary_risk(y_true, y_prob, pos_label, sample_weight)
333
+ t = _check_thresholds(threshold)
334
+ if t.size != 1:
335
+ raise InputValidationError("threshold must be a single probability; use decision_curve() for many.")
336
+ # one threshold: a single pass, no sort (net_benefit_curve sorts once for many thresholds)
337
+ treat = p >= t[0]
338
+ n = w.sum()
339
+ tp = float(np.sum(w * y, where=treat))
340
+ fp = float(np.sum(w * (1 - y), where=treat))
341
+ value = float(tp / n - fp / n * float(t[0] / (1 - t[0])))
342
+ return MetricResult("net_benefit", "Net benefit", value, {**_params(pos_label), "threshold": float(t[0])})