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,338 @@
1
+ """Confidence intervals: bootstrap (percentile, basic, BCa), Wilson and Clopper-Pearson, DeLong."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import warnings
7
+ from typing import TYPE_CHECKING, Any, Literal, Optional
8
+
9
+ import numpy as np
10
+ from numpy.typing import NDArray
11
+
12
+ if TYPE_CHECKING:
13
+ from scipy import special, stats
14
+ else:
15
+ from .._lazy import lazy_module
16
+
17
+ special = lazy_module("scipy.special")
18
+ stats = lazy_module("scipy.stats")
19
+
20
+ from ..core.exceptions import EvalSuiteError, InputValidationError, StatisticalTestError
21
+ from ..core.types import ArrayLike
22
+ from ..core.validation import to_numpy
23
+ from ._resolve import MetricCall, resolve_metric
24
+ from .results import ConfidenceInterval
25
+
26
+ __all__ = ["accuracy_ci", "bootstrap_ci", "proportion_ci", "roc_auc_ci"]
27
+
28
+ BootstrapMethod = Literal["percentile", "basic", "bca"]
29
+ MAX_FAILED_FRACTION = 0.1
30
+
31
+
32
+ def _check_level(level: float) -> float:
33
+ if not (isinstance(level, (int, float)) and 0 < level < 1):
34
+ raise InputValidationError("level must be between 0 and 1, for example 0.95.")
35
+ return float(level)
36
+
37
+
38
+ def _check_resamples(n_resamples: int) -> int:
39
+ if not isinstance(n_resamples, (int, np.integer)) or n_resamples < 100:
40
+ raise InputValidationError("n_resamples must be an integer of at least 100 (1000 or more recommended).")
41
+ return int(n_resamples)
42
+
43
+
44
+ def resample_indices(
45
+ n: int, n_resamples: int, rng: np.random.Generator, strata: Optional[NDArray[Any]] = None
46
+ ) -> NDArray[np.int64]:
47
+ """(n_resamples, n) indices drawn with replacement, optionally within strata (keeps class balance)."""
48
+ if strata is None:
49
+ return rng.integers(0, n, size=(n_resamples, n))
50
+ out = np.empty((n_resamples, n), dtype=np.int64)
51
+ pos = 0
52
+ for value in np.unique(strata, axis=0) if strata.ndim > 1 else np.unique(strata):
53
+ members = np.flatnonzero(np.all(strata == value, axis=1) if strata.ndim > 1 else strata == value)
54
+ k = members.shape[0]
55
+ out[:, pos : pos + k] = members[rng.integers(0, k, size=(n_resamples, k))]
56
+ pos += k
57
+ return out
58
+
59
+
60
+ def bootstrap_distribution(call: MetricCall, indices: NDArray[np.int64]) -> tuple[NDArray[np.float64], int]:
61
+ """Metric value on each resample; resamples where the metric is undefined become NaN."""
62
+ values = np.empty(indices.shape[0])
63
+ failed = 0
64
+ # Confusion-matrix metrics: count every resample's (true, predicted) pairs in one compiled pass.
65
+ counts = call.batch_code_counts(indices)
66
+ with warnings.catch_warnings():
67
+ warnings.simplefilter("ignore") # zero-division warnings inside resamples are expected noise
68
+ for b, idx in enumerate(indices):
69
+ try:
70
+ values[b] = call(idx) if counts is None else call.from_counts(counts[b], idx)
71
+ except EvalSuiteError:
72
+ values[b] = np.nan
73
+ failed += 1
74
+ return values, failed
75
+
76
+
77
+ def _jackknife(call: MetricCall, n: int, rng: np.random.Generator, groups: int) -> NDArray[np.float64]:
78
+ """Leave-one-out (or leave-one-group-out for large n) estimates for the BCa acceleration."""
79
+ blocks = [np.array([i]) for i in range(n)] if n <= groups else np.array_split(rng.permutation(n), groups)
80
+ everything = np.arange(n)
81
+ out = np.empty(len(blocks))
82
+ # Confusion-matrix metrics: the counts without a block are the full counts minus the block's.
83
+ full = call.code_counts(everything) if call.compressible else None
84
+ with warnings.catch_warnings():
85
+ warnings.simplefilter("ignore")
86
+ for j, block in enumerate(blocks):
87
+ try:
88
+ if full is not None:
89
+ counts = full - call.code_counts(block)
90
+ if np.count_nonzero(counts) >= 2:
91
+ out[j] = call.from_counts(counts)
92
+ continue
93
+ keep = np.setdiff1d(everything, block, assume_unique=True)
94
+ out[j] = call(keep, compress=False)
95
+ except EvalSuiteError:
96
+ out[j] = np.nan
97
+ return out
98
+
99
+
100
+ def bootstrap_ci(
101
+ metric: Any,
102
+ y_true: ArrayLike,
103
+ y_pred: Optional[ArrayLike] = None,
104
+ *,
105
+ y_prob: Optional[ArrayLike] = None,
106
+ sample_weight: Optional[ArrayLike] = None,
107
+ level: float = 0.95,
108
+ method: BootstrapMethod = "bca",
109
+ n_resamples: int = 2000,
110
+ random_state: Optional[int] = None,
111
+ stratify: Optional[bool] = None,
112
+ jackknife_groups: int = 1000,
113
+ **metric_kwargs: Any,
114
+ ) -> ConfidenceInterval:
115
+ """Bootstrap confidence interval for any metric.
116
+
117
+ ``metric`` is a metric function (``es.f1``) or its name (``"f1"``). Pass ``y_pred`` for label/value
118
+ metrics or ``y_prob`` for probability metrics; extra keyword arguments go to the metric (for example
119
+ ``average="macro"``). Resampling is stratified by class for classification targets unless
120
+ ``stratify=False``, so every resample contains every class. For classification metrics that accept
121
+ ``labels``, the full label set is fixed across resamples.
122
+
123
+ ``method``: ``"bca"`` (bias-corrected and accelerated; default, Efron 1987), ``"percentile"`` or
124
+ ``"basic"``. Set ``random_state`` for reproducible intervals. Resamples on which the metric is undefined
125
+ are counted in ``params["failed_resamples"]``; more than 10% raises :class:`StatisticalTestError`.
126
+
127
+ References: Efron B. Better bootstrap confidence intervals. JASA. 1987;82(397):171-185.
128
+ Efron B, Tibshirani RJ. An Introduction to the Bootstrap. Chapman & Hall; 1993.
129
+ """
130
+ level = _check_level(level)
131
+ n_resamples = _check_resamples(n_resamples)
132
+ if method not in ("percentile", "basic", "bca"):
133
+ raise InputValidationError("method must be 'bca', 'percentile' or 'basic'.")
134
+ fn, name = resolve_metric(metric)
135
+ call = MetricCall(fn, y_true, y_pred, y_prob, sample_weight, metric_kwargs)
136
+ estimate = call()
137
+ rng = np.random.default_rng(random_state)
138
+ use_strata = call.categorical if stratify is None else bool(stratify)
139
+ idx = resample_indices(call.n, n_resamples, rng, call.y_true if use_strata else None)
140
+ boot, failed = bootstrap_distribution(call, idx)
141
+ if failed > MAX_FAILED_FRACTION * n_resamples:
142
+ raise StatisticalTestError(
143
+ f"The metric was undefined on {failed} of {n_resamples} bootstrap resamples. The sample is probably "
144
+ "too small or too imbalanced for a reliable bootstrap interval."
145
+ )
146
+ alpha = 1 - level
147
+ valid = boot[~np.isnan(boot)]
148
+ params: dict[str, Any] = {
149
+ "n_resamples": n_resamples,
150
+ "random_state": random_state,
151
+ "stratified": use_strata,
152
+ "failed_resamples": failed,
153
+ **{k: v for k, v in metric_kwargs.items()},
154
+ }
155
+ if method == "percentile":
156
+ low, high = np.quantile(valid, [alpha / 2, 1 - alpha / 2])
157
+ elif method == "basic":
158
+ q_low, q_high = np.quantile(valid, [alpha / 2, 1 - alpha / 2])
159
+ low, high = 2 * estimate - q_high, 2 * estimate - q_low
160
+ else:
161
+ low, high, extra = _bca(call, valid, estimate, alpha, rng, jackknife_groups)
162
+ params.update(extra)
163
+ return ConfidenceInterval(estimate, float(low), float(high), level, f"bootstrap-{method}", name, params)
164
+
165
+
166
+ def _bca(
167
+ call: MetricCall,
168
+ boot: NDArray[np.float64],
169
+ estimate: float,
170
+ alpha: float,
171
+ rng: np.random.Generator,
172
+ groups: int,
173
+ ) -> tuple[float, float, dict[str, Any]]:
174
+ # bias correction: share of the bootstrap distribution below the estimate (ties count half)
175
+ share = (np.sum(boot < estimate) + 0.5 * np.sum(boot == estimate)) / boot.shape[0]
176
+ if share <= 0 or share >= 1:
177
+ warnings.warn(
178
+ "BCa is undefined because the estimate lies outside the bootstrap distribution; "
179
+ "returning the percentile interval.",
180
+ RuntimeWarning,
181
+ stacklevel=3,
182
+ )
183
+ low, high = np.quantile(boot, [alpha / 2, 1 - alpha / 2])
184
+ return float(low), float(high), {"bca_fallback": "percentile"}
185
+ z0 = special.ndtri(share)
186
+ jack = _jackknife(call, call.n, rng, groups)
187
+ jack = jack[~np.isnan(jack)]
188
+ diffs = jack.mean() - jack
189
+ denom = 6.0 * np.sum(diffs**2) ** 1.5
190
+ accel = float(np.sum(diffs**3) / denom) if denom > 0 else 0.0
191
+ probs = []
192
+ for z_alpha in (special.ndtri(alpha / 2), special.ndtri(1 - alpha / 2)):
193
+ num = z0 + z_alpha
194
+ probs.append(special.ndtr(z0 + num / (1 - accel * num)))
195
+ low, high = np.quantile(boot, probs)
196
+ return float(low), float(high), {"bias_correction": float(z0), "acceleration": accel}
197
+
198
+
199
+ def proportion_ci(
200
+ successes: int,
201
+ n: int,
202
+ *,
203
+ level: float = 0.95,
204
+ method: Literal["wilson", "clopper-pearson", "normal"] = "wilson",
205
+ ) -> ConfidenceInterval:
206
+ """Confidence interval for a proportion ``successes / n``.
207
+
208
+ ``"wilson"`` (default; good coverage even for small n or extreme proportions), ``"clopper-pearson"``
209
+ (exact, conservative) or ``"normal"`` (Wald; shown for comparison, not recommended).
210
+
211
+ References: Wilson EB. JASA. 1927;22(158):209-212. Clopper CJ, Pearson ES. Biometrika. 1934;26(4):404-413.
212
+ Brown LD, Cai TT, DasGupta A. Interval estimation for a binomial proportion. Stat Sci. 2001;16(2):101-133.
213
+ """
214
+ level = _check_level(level)
215
+ if not (isinstance(n, (int, np.integer)) and n > 0):
216
+ raise InputValidationError("n must be a positive integer.")
217
+ if not (0 <= successes <= n):
218
+ raise InputValidationError("successes must be between 0 and n.")
219
+ p = successes / n
220
+ alpha = 1 - level
221
+ z = float(special.ndtri(1 - alpha / 2))
222
+ if method == "wilson":
223
+ denom = 1 + z**2 / n
224
+ centre = (p + z**2 / (2 * n)) / denom
225
+ half = z * math.sqrt(p * (1 - p) / n + z**2 / (4 * n**2)) / denom
226
+ low, high = centre - half, centre + half
227
+ elif method == "clopper-pearson":
228
+ # Beta quantiles via the inverse regularised incomplete beta function (what scipy.stats.beta.ppf uses).
229
+ low = 0.0 if successes == 0 else special.betaincinv(successes, n - successes + 1, alpha / 2)
230
+ high = 1.0 if successes == n else special.betaincinv(successes + 1, n - successes, 1 - alpha / 2)
231
+ elif method == "normal":
232
+ half = z * math.sqrt(p * (1 - p) / n)
233
+ low, high = max(0.0, p - half), min(1.0, p + half)
234
+ else:
235
+ raise InputValidationError("method must be 'wilson', 'clopper-pearson' or 'normal'.")
236
+ return ConfidenceInterval(
237
+ p, float(low), float(high), level, method, "proportion", {"successes": int(successes), "n": int(n)}
238
+ )
239
+
240
+
241
+ def accuracy_ci(
242
+ y_true: ArrayLike,
243
+ y_pred: ArrayLike,
244
+ *,
245
+ level: float = 0.95,
246
+ method: Literal["wilson", "clopper-pearson", "normal"] = "wilson",
247
+ ) -> ConfidenceInterval:
248
+ """Analytic confidence interval for accuracy (a proportion of correct predictions)."""
249
+ yt = to_numpy(y_true, "y_true", allow_2d=True)
250
+ yp = to_numpy(y_pred, "y_pred", allow_2d=True)
251
+ if yt.shape != yp.shape:
252
+ raise InputValidationError(f"y_true has shape {yt.shape} but y_pred has shape {yp.shape}.")
253
+ correct = (yt == yp).all(axis=1) if yt.ndim == 2 else yt == yp
254
+ ci = proportion_ci(int(np.count_nonzero(correct)), int(correct.shape[0]), level=level, method=method)
255
+ return ConfidenceInterval(ci.estimate, ci.low, ci.high, level, method, "accuracy", ci.params)
256
+
257
+
258
+ # ---- DeLong ---------------------------------------------------------------------------------------
259
+ def delong_placements(
260
+ y: NDArray[np.float64], scores: NDArray[np.float64]
261
+ ) -> tuple[NDArray[np.float64], NDArray[np.float64], NDArray[np.float64]]:
262
+ """AUCs and structural components for k score columns (Sun & Xu fast DeLong).
263
+
264
+ Returns (auc[k], v10[k, m], v01[k, n]) where m/n are the numbers of positives/negatives.
265
+ """
266
+ pos = scores[:, y == 1]
267
+ neg = scores[:, y == 0]
268
+ m, n = pos.shape[1], neg.shape[1]
269
+ if m == 0 or n == 0:
270
+ from ..core.exceptions import MetricInputError
271
+
272
+ raise MetricInputError("DeLong's method needs at least one positive and one negative observation.")
273
+ tx = np.apply_along_axis(stats.rankdata, 1, pos)
274
+ ty = np.apply_along_axis(stats.rankdata, 1, neg)
275
+ tz = np.apply_along_axis(stats.rankdata, 1, np.concatenate([pos, neg], axis=1))
276
+ auc = (tz[:, :m].sum(axis=1) - m * (m + 1) / 2) / (m * n)
277
+ v10 = (tz[:, :m] - tx) / n
278
+ v01 = 1.0 - (tz[:, m:] - ty) / m
279
+ return auc, v10, v01
280
+
281
+
282
+ def delong_covariance(v10: NDArray[np.float64], v01: NDArray[np.float64]) -> NDArray[np.float64]:
283
+ m, n = v10.shape[1], v01.shape[1]
284
+ s10 = np.atleast_2d(np.cov(v10)) if m > 1 else np.zeros((v10.shape[0],) * 2)
285
+ s01 = np.atleast_2d(np.cov(v01)) if n > 1 else np.zeros((v01.shape[0],) * 2)
286
+ cov: NDArray[np.float64] = s10 / m + s01 / n
287
+ return cov
288
+
289
+
290
+ def binary_scores(
291
+ y_true: ArrayLike, y_prob: ArrayLike, pos_label: Any
292
+ ) -> tuple[NDArray[np.float64], NDArray[np.float64]]:
293
+ yt = to_numpy(y_true, "y_true")
294
+ s = to_numpy(y_prob, "y_prob").astype(np.float64)
295
+ if s.shape[0] != yt.shape[0]:
296
+ raise InputValidationError(
297
+ "y_true and y_prob must contain the same number of observations. "
298
+ f"Received {yt.shape[0]} and {s.shape[0]}."
299
+ )
300
+ labels = np.unique(yt)
301
+ if labels.shape[0] > 2:
302
+ raise InputValidationError("DeLong's method is for binary targets.")
303
+ if pos_label is None:
304
+ if not set(labels.tolist()) <= {0, 1}:
305
+ raise InputValidationError(f"Labels are {labels.tolist()}; specify pos_label=...")
306
+ pos_label = 1
307
+ return (yt == pos_label).astype(np.float64), s
308
+
309
+
310
+ def roc_auc_ci(
311
+ y_true: ArrayLike,
312
+ y_prob: ArrayLike,
313
+ *,
314
+ level: float = 0.95,
315
+ pos_label: Any = None,
316
+ ) -> ConfidenceInterval:
317
+ """DeLong confidence interval for a binary ROC AUC (normal approximation, clipped to [0, 1]).
318
+
319
+ Reference: DeLong ER, DeLong DM, Clarke-Pearson DL. Comparing the areas under two or more correlated
320
+ receiver operating characteristic curves: a nonparametric approach. Biometrics. 1988;44(3):837-845.
321
+ Sun X, Xu W. Fast implementation of DeLong's algorithm. IEEE Signal Process Lett. 2014;21(11):1389-1393.
322
+ """
323
+ level = _check_level(level)
324
+ y, s = binary_scores(y_true, y_prob, pos_label)
325
+ auc, v10, v01 = delong_placements(y, s[None, :])
326
+ var = float(delong_covariance(v10, v01)[0, 0])
327
+ se = np.sqrt(var)
328
+ z = special.ndtri(1 - (1 - level) / 2)
329
+ a = float(auc[0])
330
+ return ConfidenceInterval(
331
+ a,
332
+ max(0.0, a - z * se),
333
+ min(1.0, a + z * se),
334
+ level,
335
+ "delong",
336
+ "roc_auc",
337
+ {"standard_error": float(se), "n_positive": int(y.sum()), "n_negative": int((1 - y).sum())},
338
+ )
@@ -0,0 +1,214 @@
1
+ """Paired tests for comparing two models evaluated on the same observations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any, Literal, Optional
6
+
7
+ import numpy as np
8
+
9
+ if TYPE_CHECKING:
10
+ from scipy import special, stats
11
+ else:
12
+ from .._lazy import lazy_module
13
+
14
+ special = lazy_module("scipy.special")
15
+ stats = lazy_module("scipy.stats")
16
+
17
+ from ..core.exceptions import InputValidationError
18
+ from ..core.types import ArrayLike
19
+ from ..core.validation import to_numpy
20
+ from ._resolve import MetricCall, resolve_metric
21
+ from .intervals import (
22
+ _check_level,
23
+ _check_resamples,
24
+ binary_scores,
25
+ bootstrap_distribution,
26
+ delong_covariance,
27
+ delong_placements,
28
+ resample_indices,
29
+ )
30
+ from .results import ConfidenceInterval, TestResult
31
+
32
+ __all__ = ["delong_test", "mcnemar_test", "paired_bootstrap_test"]
33
+
34
+
35
+ def mcnemar_test(
36
+ y_true: ArrayLike,
37
+ y_pred_a: ArrayLike,
38
+ y_pred_b: ArrayLike,
39
+ *,
40
+ exact: Optional[bool] = None,
41
+ correction: bool = True,
42
+ ) -> TestResult:
43
+ """McNemar's test: do two classifiers have the same error rate on the same observations?
44
+
45
+ Uses only discordant pairs: b = A right & B wrong, c = A wrong & B right. ``exact=None`` (default) uses
46
+ the exact binomial test when b + c < 25 and the chi-squared test otherwise (with Edwards' continuity
47
+ correction unless ``correction=False``). ``estimate`` is the accuracy difference A − B.
48
+
49
+ References: McNemar Q. Psychometrika. 1947;12(2):153-157. Edwards AL. Psychometrika. 1948;13:185-187.
50
+ Dietterich TG. Approximate statistical tests for comparing supervised classification learning
51
+ algorithms. Neural Comput. 1998;10(7):1895-1923.
52
+ """
53
+ yt = to_numpy(y_true, "y_true", allow_2d=True)
54
+ a = to_numpy(y_pred_a, "y_pred_a", allow_2d=True)
55
+ b_ = to_numpy(y_pred_b, "y_pred_b", allow_2d=True)
56
+ if not (yt.shape == a.shape == b_.shape):
57
+ raise InputValidationError(
58
+ f"y_true, y_pred_a and y_pred_b must have the same shape; got {yt.shape}, {a.shape}, {b_.shape}."
59
+ )
60
+ ok_a = (yt == a).all(axis=1) if yt.ndim == 2 else yt == a
61
+ ok_b = (yt == b_).all(axis=1) if yt.ndim == 2 else yt == b_
62
+ b = int(np.count_nonzero(ok_a & ~ok_b))
63
+ c = int(np.count_nonzero(~ok_a & ok_b))
64
+ n_disc = b + c
65
+ use_exact = n_disc < 25 if exact is None else bool(exact)
66
+ estimate = (b - c) / yt.shape[0]
67
+ params = {"b": b, "c": c, "n": int(yt.shape[0])}
68
+ if n_disc == 0:
69
+ return TestResult(
70
+ "mcnemar-exact" if use_exact else "mcnemar",
71
+ 0.0,
72
+ 1.0,
73
+ estimate=estimate,
74
+ params={**params, "note": "no discordant pairs: the classifiers agree on every observation"},
75
+ )
76
+ if use_exact:
77
+ p = min(1.0, 2 * float(special.bdtr(min(b, c), n_disc, 0.5)))
78
+ return TestResult("mcnemar-exact", float(min(b, c)), float(p), estimate=estimate, params=params)
79
+ stat = (abs(b - c) - (1 if correction else 0)) ** 2 / n_disc
80
+ p = float(special.chdtrc(1, stat))
81
+ return TestResult(
82
+ "mcnemar", float(stat), float(p), estimate=estimate, params={**params, "continuity_correction": correction}
83
+ )
84
+
85
+
86
+ def delong_test(
87
+ y_true: ArrayLike,
88
+ y_prob_a: ArrayLike,
89
+ y_prob_b: ArrayLike,
90
+ *,
91
+ pos_label: Any = None,
92
+ level: float = 0.95,
93
+ ) -> TestResult:
94
+ """DeLong's test for two correlated ROC AUCs (same observations, two models). ``estimate`` is AUC_A − AUC_B
95
+ and ``ci`` its confidence interval.
96
+
97
+ Reference: DeLong ER, DeLong DM, Clarke-Pearson DL. Biometrics. 1988;44(3):837-845.
98
+ """
99
+ level = _check_level(level)
100
+ y, sa = binary_scores(y_true, y_prob_a, pos_label)
101
+ _, sb = binary_scores(y_true, y_prob_b, pos_label)
102
+ if sb.shape != sa.shape:
103
+ raise InputValidationError("y_prob_a and y_prob_b must have the same length.")
104
+ auc, v10, v01 = delong_placements(y, np.vstack([sa, sb]))
105
+ cov = delong_covariance(v10, v01)
106
+ diff = float(auc[0] - auc[1])
107
+ var = float(cov[0, 0] + cov[1, 1] - 2 * cov[0, 1])
108
+ if var <= 0:
109
+ z, p = 0.0, 1.0
110
+ se = 0.0
111
+ else:
112
+ se = float(np.sqrt(var))
113
+ z = diff / se
114
+ p = float(2 * special.ndtr(-abs(z)))
115
+ zc = special.ndtri(1 - (1 - level) / 2)
116
+ ci = ConfidenceInterval(diff, diff - zc * se, diff + zc * se, level, "delong", "roc_auc_difference")
117
+ return TestResult(
118
+ "delong",
119
+ z,
120
+ p,
121
+ estimate=diff,
122
+ ci=ci,
123
+ params={"auc_a": float(auc[0]), "auc_b": float(auc[1]), "standard_error": se},
124
+ )
125
+
126
+
127
+ def paired_bootstrap_test(
128
+ metric: Any,
129
+ y_true: ArrayLike,
130
+ y_pred_a: Optional[ArrayLike] = None,
131
+ y_pred_b: Optional[ArrayLike] = None,
132
+ *,
133
+ y_prob_a: Optional[ArrayLike] = None,
134
+ y_prob_b: Optional[ArrayLike] = None,
135
+ sample_weight: Optional[ArrayLike] = None,
136
+ n_resamples: int = 2000,
137
+ level: float = 0.95,
138
+ random_state: Optional[int] = None,
139
+ stratify: Optional[bool] = None,
140
+ alternative: Literal["two-sided", "greater", "less"] = "two-sided",
141
+ **metric_kwargs: Any,
142
+ ) -> TestResult:
143
+ """Paired bootstrap test for any metric: is metric(A) − metric(B) different from 0?
144
+
145
+ Both models are evaluated on the same resampled observations. The p-value uses the shifted bootstrap
146
+ distribution (difference re-centred on 0 under the null), with the +1 correction so it is never 0:
147
+ p = (1 + #{|δ* − δ̂| ≥ |δ̂|}) / (B + 1) for a two-sided test. ``ci`` is the percentile interval of δ*.
148
+
149
+ Reference: Efron B, Tibshirani RJ. An Introduction to the Bootstrap. Chapman & Hall; 1993, ch. 16.
150
+ """
151
+ level = _check_level(level)
152
+ n_resamples = _check_resamples(n_resamples)
153
+ if alternative not in ("two-sided", "greater", "less"):
154
+ raise InputValidationError("alternative must be 'two-sided', 'greater' or 'less'.")
155
+ fn, name = resolve_metric(metric)
156
+ by_prob = y_prob_a is not None or y_prob_b is not None
157
+ if by_prob and (y_prob_a is None or y_prob_b is None or y_pred_a is not None or y_pred_b is not None):
158
+ raise InputValidationError("Give either y_pred_a and y_pred_b, or y_prob_a and y_prob_b.")
159
+ if not by_prob and (y_pred_a is None or y_pred_b is None):
160
+ raise InputValidationError("Give either y_pred_a and y_pred_b, or y_prob_a and y_prob_b.")
161
+ if by_prob:
162
+ call_a = MetricCall(fn, y_true, None, y_prob_a, sample_weight, metric_kwargs)
163
+ call_b = MetricCall(fn, y_true, None, y_prob_b, sample_weight, metric_kwargs)
164
+ else:
165
+ call_a = MetricCall(fn, y_true, y_pred_a, None, sample_weight, metric_kwargs)
166
+ call_b = MetricCall(fn, y_true, y_pred_b, None, sample_weight, metric_kwargs)
167
+ if call_a.kwargs.get("labels") is not None and call_b.kwargs.get("labels") is not None:
168
+ shared = np.union1d(call_a.kwargs["labels"], call_b.kwargs["labels"])
169
+ call_a.kwargs["labels"] = call_b.kwargs["labels"] = shared
170
+ observed = call_a() - call_b()
171
+ rng = np.random.default_rng(random_state)
172
+ use_strata = call_a.categorical if stratify is None else bool(stratify)
173
+ idx = resample_indices(call_a.n, n_resamples, rng, call_a.y_true if use_strata else None)
174
+ da, fa = bootstrap_distribution(call_a, idx)
175
+ db, fb = bootstrap_distribution(call_b, idx)
176
+ diff = da - db
177
+ diff = diff[~np.isnan(diff)]
178
+ centred = diff - observed
179
+ if alternative == "two-sided":
180
+ extreme = np.sum(np.abs(centred) >= abs(observed))
181
+ elif alternative == "greater":
182
+ extreme = np.sum(centred >= observed)
183
+ else:
184
+ extreme = np.sum(centred <= observed)
185
+ p = (1 + extreme) / (diff.shape[0] + 1)
186
+ alpha = 1 - level
187
+ low, high = np.quantile(diff, [alpha / 2, 1 - alpha / 2])
188
+ ci = ConfidenceInterval(
189
+ observed,
190
+ float(low),
191
+ float(high),
192
+ level,
193
+ "bootstrap-percentile",
194
+ f"{name}_difference",
195
+ {"n_resamples": n_resamples, "random_state": random_state},
196
+ )
197
+ return TestResult(
198
+ "paired-bootstrap",
199
+ observed,
200
+ float(p),
201
+ alternative=alternative,
202
+ estimate=observed,
203
+ ci=ci,
204
+ params={
205
+ "metric": name,
206
+ "n_resamples": n_resamples,
207
+ "random_state": random_state,
208
+ "stratified": use_strata,
209
+ "failed_resamples": int(max(fa, fb)),
210
+ "metric_a": call_a(),
211
+ "metric_b": call_b(),
212
+ **metric_kwargs,
213
+ },
214
+ )
@@ -0,0 +1,129 @@
1
+ """Result types for intervals and statistical tests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ from collections.abc import Mapping
8
+ from dataclasses import dataclass, field
9
+ from types import MappingProxyType
10
+ from typing import Any, Optional, cast
11
+
12
+ from ..core.result import _json_safe
13
+
14
+ __all__ = ["ConfidenceInterval", "TestResult"]
15
+
16
+
17
+ def _f(x: float, digits: int = 4) -> str:
18
+ return "NaN" if math.isnan(x) else f"{x:.{digits}f}"
19
+
20
+
21
+ @dataclass(frozen=True, eq=False)
22
+ class ConfidenceInterval:
23
+ """A point estimate with a confidence interval.
24
+
25
+ ``method`` names the procedure (for example ``"bootstrap-bca"``, ``"wilson"``, ``"delong"``) and
26
+ ``params`` records everything needed to reproduce it (resamples, random state, failed resamples...).
27
+ """
28
+
29
+ estimate: float
30
+ low: float
31
+ high: float
32
+ level: float
33
+ method: str
34
+ metric: str = ""
35
+ params: Mapping[str, Any] = field(default_factory=dict)
36
+
37
+ def __post_init__(self) -> None:
38
+ for name in ("estimate", "low", "high", "level"):
39
+ object.__setattr__(self, name, float(getattr(self, name)))
40
+ object.__setattr__(self, "params", MappingProxyType(dict(self.params)))
41
+
42
+ def __float__(self) -> float:
43
+ return self.estimate
44
+
45
+ def __iter__(self): # type: ignore[no-untyped-def]
46
+ """Unpack as ``low, high``."""
47
+ return iter((self.low, self.high))
48
+
49
+ @property
50
+ def width(self) -> float:
51
+ return self.high - self.low
52
+
53
+ def contains(self, value: float) -> bool:
54
+ return self.low <= value <= self.high
55
+
56
+ def __repr__(self) -> str:
57
+ pct = round(self.level * 100, 6)
58
+ label = f"{self.metric} " if self.metric else ""
59
+ return f"{label}{_f(self.estimate)} [{pct:g}% CI {_f(self.low)}, {_f(self.high)}] ({self.method})"
60
+
61
+ def format(self, digits: int = 3) -> str:
62
+ """``0.812 (95% CI 0.774–0.846)``: the form most journals expect."""
63
+ pct = round(self.level * 100, 6)
64
+ return f"{self.estimate:.{digits}f} ({pct:g}% CI {self.low:.{digits}f}–{self.high:.{digits}f})"
65
+
66
+ def to_dict(self) -> dict[str, Any]:
67
+ return cast(
68
+ "dict[str, Any]",
69
+ _json_safe(
70
+ {
71
+ "metric": self.metric,
72
+ "estimate": self.estimate,
73
+ "low": self.low,
74
+ "high": self.high,
75
+ "level": self.level,
76
+ "method": self.method,
77
+ "params": dict(self.params),
78
+ }
79
+ ),
80
+ )
81
+
82
+ def to_json(self, *, indent: Optional[int] = 2) -> str:
83
+ return json.dumps(self.to_dict(), indent=indent, allow_nan=False)
84
+
85
+
86
+ @dataclass(frozen=True, eq=False)
87
+ class TestResult:
88
+ """Outcome of a statistical test: statistic, p-value and what was tested."""
89
+
90
+ __test__ = False # not a pytest test class
91
+
92
+ test: str
93
+ statistic: float
94
+ p_value: float
95
+ alternative: str = "two-sided"
96
+ estimate: Optional[float] = None
97
+ ci: Optional[ConfidenceInterval] = None
98
+ params: Mapping[str, Any] = field(default_factory=dict)
99
+
100
+ def __post_init__(self) -> None:
101
+ object.__setattr__(self, "statistic", float(self.statistic))
102
+ object.__setattr__(self, "p_value", float(self.p_value))
103
+ if self.estimate is not None:
104
+ object.__setattr__(self, "estimate", float(self.estimate))
105
+ object.__setattr__(self, "params", MappingProxyType(dict(self.params)))
106
+
107
+ def significant(self, alpha: float = 0.05) -> bool:
108
+ return self.p_value < alpha
109
+
110
+ def __repr__(self) -> str:
111
+ est = f", estimate={_f(self.estimate)}" if self.estimate is not None else ""
112
+ p = "p<0.0001" if self.p_value < 1e-4 else f"p={self.p_value:.4f}"
113
+ return f"TestResult({self.test}: statistic={_f(self.statistic)}, {p}{est})"
114
+
115
+ def to_dict(self) -> dict[str, Any]:
116
+ out = {
117
+ "test": self.test,
118
+ "statistic": self.statistic,
119
+ "p_value": self.p_value,
120
+ "alternative": self.alternative,
121
+ "estimate": self.estimate,
122
+ "params": dict(self.params),
123
+ }
124
+ if self.ci is not None:
125
+ out["ci"] = self.ci.to_dict()
126
+ return cast("dict[str, Any]", _json_safe(out))
127
+
128
+ def to_json(self, *, indent: Optional[int] = 2) -> str:
129
+ return json.dumps(self.to_dict(), indent=indent, allow_nan=False)