evalsuite-python 0.6.0__cp39-abi3-win_arm64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- evalsuite/__init__.py +268 -0
- evalsuite/__main__.py +5 -0
- evalsuite/_bench_metrics.py +2080 -0
- evalsuite/_core.pyd +0 -0
- evalsuite/_lazy.py +32 -0
- evalsuite/_native.py +60 -0
- evalsuite/api.py +275 -0
- evalsuite/benchmarks.py +946 -0
- evalsuite/calibration.py +392 -0
- evalsuite/classification/__init__.py +51 -0
- evalsuite/classification/_common.py +111 -0
- evalsuite/classification/metrics.py +945 -0
- evalsuite/cli/__init__.py +5 -0
- evalsuite/cli/main.py +606 -0
- evalsuite/clinical/__init__.py +18 -0
- evalsuite/clinical/metrics.py +342 -0
- evalsuite/clinical/report.py +366 -0
- evalsuite/core/__init__.py +1 -0
- evalsuite/core/context.py +199 -0
- evalsuite/core/exceptions.py +52 -0
- evalsuite/core/export.py +100 -0
- evalsuite/core/registry.py +90 -0
- evalsuite/core/result.py +379 -0
- evalsuite/core/types.py +23 -0
- evalsuite/core/validation.py +256 -0
- evalsuite/llmsys/__init__.py +189 -0
- evalsuite/llmsys/_common.py +215 -0
- evalsuite/llmsys/agents.py +384 -0
- evalsuite/llmsys/code.py +923 -0
- evalsuite/llmsys/efficiency.py +346 -0
- evalsuite/llmsys/longcontext.py +361 -0
- evalsuite/llmsys/multilingual.py +339 -0
- evalsuite/llmsys/robustness.py +504 -0
- evalsuite/llmsys/safety.py +509 -0
- evalsuite/llmsys/uncertainty.py +229 -0
- evalsuite/plot.py +651 -0
- evalsuite/py.typed +0 -0
- evalsuite/regression/__init__.py +41 -0
- evalsuite/regression/metrics.py +629 -0
- evalsuite/reporting.py +241 -0
- evalsuite/stats/__init__.py +46 -0
- evalsuite/stats/_resolve.py +229 -0
- evalsuite/stats/compare.py +420 -0
- evalsuite/stats/effect.py +159 -0
- evalsuite/stats/hypothesis.py +593 -0
- evalsuite/stats/intervals.py +338 -0
- evalsuite/stats/paired.py +214 -0
- evalsuite/stats/results.py +129 -0
- evalsuite/text/__init__.py +154 -0
- evalsuite/text/_common.py +97 -0
- evalsuite/text/factuality.py +469 -0
- evalsuite/text/generation.py +1346 -0
- evalsuite/text/judge.py +556 -0
- evalsuite/text/qa.py +108 -0
- evalsuite/text/rag.py +235 -0
- evalsuite/text/reasoning.py +215 -0
- evalsuite/text/report.py +158 -0
- evalsuite/text/retrieval.py +238 -0
- evalsuite/text/semantic.py +499 -0
- evalsuite/text/spice.py +162 -0
- evalsuite/text/structured.py +793 -0
- evalsuite/version.py +3 -0
- evalsuite/vision/__init__.py +47 -0
- evalsuite/vision/detection.py +696 -0
- evalsuite/vision/segmentation.py +1028 -0
- evalsuite_python-0.6.0.dist-info/METADATA +509 -0
- evalsuite_python-0.6.0.dist-info/RECORD +72 -0
- evalsuite_python-0.6.0.dist-info/WHEEL +4 -0
- evalsuite_python-0.6.0.dist-info/entry_points.txt +2 -0
- evalsuite_python-0.6.0.dist-info/licenses/LICENSE +21 -0
- evalsuite_python-0.6.0.dist-info/licenses/LICENSE-APACHE +191 -0
- evalsuite_python-0.6.0.dist-info/sboms/evalsuite-py.cyclonedx.json +576 -0
|
@@ -0,0 +1,593 @@
|
|
|
1
|
+
"""Hypothesis tests for comparing scores, groups and categorical outcomes.
|
|
2
|
+
|
|
3
|
+
Each test returns a :class:`TestResult` with the statistic, p-value, an effect size in ``estimate`` (named in
|
|
4
|
+
``params["effect_size"]``) and, where standard, a confidence interval. SciPy is the reference: the common tests
|
|
5
|
+
compute the same statistics directly (one ranking pass, closed-form tails, cached Shapiro–Wilk weights) and are
|
|
6
|
+
tested to match SciPy, falling back to SciPy where it uses a different algorithm (exact permutation tests,
|
|
7
|
+
older Shapiro–Wilk); EvalSuite adds input validation, effect sizes and consistent results.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import functools
|
|
13
|
+
import math
|
|
14
|
+
import warnings
|
|
15
|
+
from typing import TYPE_CHECKING, Literal, Optional
|
|
16
|
+
|
|
17
|
+
import numpy as np
|
|
18
|
+
from numpy.typing import NDArray
|
|
19
|
+
|
|
20
|
+
if TYPE_CHECKING:
|
|
21
|
+
from scipy import special, stats
|
|
22
|
+
else:
|
|
23
|
+
from .._lazy import lazy_module
|
|
24
|
+
|
|
25
|
+
special = lazy_module("scipy.special")
|
|
26
|
+
stats = lazy_module("scipy.stats")
|
|
27
|
+
|
|
28
|
+
from ..core.exceptions import InputValidationError, StatisticalTestError
|
|
29
|
+
from ..core.types import ArrayLike
|
|
30
|
+
from ..core.validation import check_finite, to_numpy
|
|
31
|
+
from .intervals import _check_level
|
|
32
|
+
from .results import ConfidenceInterval, TestResult
|
|
33
|
+
|
|
34
|
+
__all__ = [
|
|
35
|
+
"chi_square_test",
|
|
36
|
+
"fisher_exact_test",
|
|
37
|
+
"friedman_test",
|
|
38
|
+
"kruskal_wallis_test",
|
|
39
|
+
"mann_whitney_test",
|
|
40
|
+
"paired_t_test",
|
|
41
|
+
"shapiro_wilk_test",
|
|
42
|
+
"t_test",
|
|
43
|
+
"wilcoxon_test",
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
Alternative = Literal["two-sided", "greater", "less"]
|
|
47
|
+
_ALTS = ("two-sided", "greater", "less")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _vec(x: ArrayLike, name: str, min_n: int = 2) -> NDArray[np.float64]:
|
|
51
|
+
a = to_numpy(x, name).astype(np.float64, copy=False)
|
|
52
|
+
check_finite(a, name)
|
|
53
|
+
if a.ndim != 1:
|
|
54
|
+
raise InputValidationError(f"{name} must be one-dimensional.")
|
|
55
|
+
if a.shape[0] < min_n:
|
|
56
|
+
raise StatisticalTestError(f"{name} needs at least {min_n} observations; got {a.shape[0]}.")
|
|
57
|
+
return a
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _alt(alternative: str) -> str:
|
|
61
|
+
if alternative not in _ALTS:
|
|
62
|
+
raise InputValidationError("alternative must be 'two-sided', 'greater' or 'less'.")
|
|
63
|
+
return alternative
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _mean_diff_ci(
|
|
67
|
+
diff: float, se: float, df: float, level: float, alternative: str, name: str
|
|
68
|
+
) -> ConfidenceInterval:
|
|
69
|
+
if alternative == "two-sided":
|
|
70
|
+
q = stats.t.ppf(1 - (1 - level) / 2, df)
|
|
71
|
+
lo, hi = diff - q * se, diff + q * se
|
|
72
|
+
elif alternative == "greater":
|
|
73
|
+
lo, hi = diff - stats.t.ppf(level, df) * se, math.inf
|
|
74
|
+
else:
|
|
75
|
+
lo, hi = -math.inf, diff + stats.t.ppf(level, df) * se
|
|
76
|
+
return ConfidenceInterval(diff, lo, hi, level, "t", name, {"df": float(df), "se": float(se)})
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _t_pvalue(t: float, df: float, alternative: str) -> float:
|
|
80
|
+
"""Student-t p-value for statistic ``t`` (identical to SciPy's t-tests)."""
|
|
81
|
+
if alternative == "two-sided":
|
|
82
|
+
return min(2.0 * float(special.stdtr(df, -abs(t))), 1.0)
|
|
83
|
+
if alternative == "less":
|
|
84
|
+
return float(special.stdtr(df, t))
|
|
85
|
+
return float(special.stdtr(df, -t))
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _z_pvalue(z: float, alternative: str) -> float:
|
|
89
|
+
if alternative == "two-sided":
|
|
90
|
+
return min(2.0 * float(special.ndtr(-abs(z))), 1.0)
|
|
91
|
+
if alternative == "less":
|
|
92
|
+
return float(special.ndtr(z))
|
|
93
|
+
return float(special.ndtr(-z))
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _rank_sums(
|
|
97
|
+
values: NDArray[np.float64], labels: NDArray[np.intp], k: int
|
|
98
|
+
) -> tuple[NDArray[np.float64], NDArray[np.intp]]:
|
|
99
|
+
"""Sum of average ranks (as ``scipy.stats.rankdata``) per label 0..k-1, and the tie-group sizes.
|
|
100
|
+
|
|
101
|
+
One unstable sort: tied values share their group's average rank, so their order does not matter, and the
|
|
102
|
+
per-label sums come from ``bincount`` without scattering ranks back to the input order."""
|
|
103
|
+
order = np.argsort(values)
|
|
104
|
+
sv = values[order]
|
|
105
|
+
n = sv.shape[0]
|
|
106
|
+
new = np.empty(n, dtype=bool)
|
|
107
|
+
new[0] = True
|
|
108
|
+
np.not_equal(sv[1:], sv[:-1], out=new[1:])
|
|
109
|
+
starts = np.flatnonzero(new)
|
|
110
|
+
sizes = np.diff(np.r_[starts, n])
|
|
111
|
+
avg = starts + (sizes + 1) / 2.0
|
|
112
|
+
ranks = avg[np.cumsum(new) - 1]
|
|
113
|
+
return np.bincount(labels[order], weights=ranks, minlength=k), sizes
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _signed_rank(nz: NDArray[np.float64]) -> tuple[float, float, NDArray[np.float64]]:
|
|
117
|
+
"""Wilcoxon signed-rank sums of the non-zero differences: (T+, T-, tie-group sizes)."""
|
|
118
|
+
sums, sizes = _rank_sums(np.abs(nz), (nz > 0).astype(np.intp), 2)
|
|
119
|
+
return float(sums[1]), float(sums[0]), sizes.astype(np.float64)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def t_test(
|
|
123
|
+
a: ArrayLike,
|
|
124
|
+
b: ArrayLike,
|
|
125
|
+
*,
|
|
126
|
+
equal_var: bool = False,
|
|
127
|
+
alternative: Alternative = "two-sided",
|
|
128
|
+
level: float = 0.95,
|
|
129
|
+
) -> TestResult:
|
|
130
|
+
"""Two-sample t-test for mean(a) − mean(b). Welch's test by default (``equal_var=False``), which does not
|
|
131
|
+
assume equal variances; ``equal_var=True`` gives Student's test. ``estimate`` is the mean difference with a
|
|
132
|
+
confidence interval; ``params["cohens_d"]`` is the standardised effect size.
|
|
133
|
+
|
|
134
|
+
References: Welch BL. Biometrika. 1947;34(1-2):28-35. Student. Biometrika. 1908;6(1):1-25.
|
|
135
|
+
"""
|
|
136
|
+
level = _check_level(level)
|
|
137
|
+
_alt(alternative)
|
|
138
|
+
x, y = _vec(a, "a"), _vec(b, "b")
|
|
139
|
+
n1, n2 = x.shape[0], y.shape[0]
|
|
140
|
+
m1, m2 = float(x.mean()), float(y.mean())
|
|
141
|
+
# Two-pass variances (as NumPy/SciPy compute them), each sample read once more.
|
|
142
|
+
v1 = float(np.dot(x - m1, x - m1)) / (n1 - 1)
|
|
143
|
+
v2 = float(np.dot(y - m2, y - m2)) / (n2 - 1)
|
|
144
|
+
if v1 == 0 and v2 == 0:
|
|
145
|
+
raise StatisticalTestError("The t-test is undefined: both samples have zero variance.")
|
|
146
|
+
if equal_var:
|
|
147
|
+
df = n1 + n2 - 2
|
|
148
|
+
sp2 = ((n1 - 1) * v1 + (n2 - 1) * v2) / df
|
|
149
|
+
se = math.sqrt(sp2 * (1 / n1 + 1 / n2))
|
|
150
|
+
else:
|
|
151
|
+
se = math.sqrt(v1 / n1 + v2 / n2)
|
|
152
|
+
df = (v1 / n1 + v2 / n2) ** 2 / ((v1 / n1) ** 2 / (n1 - 1) + (v2 / n2) ** 2 / (n2 - 1)) if se else math.nan
|
|
153
|
+
t = (m1 - m2) / se
|
|
154
|
+
# Student-t tail probabilities directly (what scipy.stats.ttest_ind returns), without re-reading the data.
|
|
155
|
+
p = _t_pvalue(t, df, alternative)
|
|
156
|
+
diff = m1 - m2
|
|
157
|
+
pooled = math.sqrt(((n1 - 1) * v1 + (n2 - 1) * v2) / (n1 + n2 - 2))
|
|
158
|
+
return TestResult(
|
|
159
|
+
"welch-t" if not equal_var else "student-t",
|
|
160
|
+
float(t),
|
|
161
|
+
p,
|
|
162
|
+
alternative=alternative,
|
|
163
|
+
estimate=diff,
|
|
164
|
+
ci=_mean_diff_ci(diff, se, df, level, alternative, "mean_difference"),
|
|
165
|
+
params={
|
|
166
|
+
"df": float(df),
|
|
167
|
+
"effect_size": "mean difference",
|
|
168
|
+
"cohens_d": diff / pooled if pooled else math.nan,
|
|
169
|
+
"n_a": n1,
|
|
170
|
+
"n_b": n2,
|
|
171
|
+
},
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def paired_t_test(
|
|
176
|
+
a: ArrayLike, b: ArrayLike, *, alternative: Alternative = "two-sided", level: float = 0.95
|
|
177
|
+
) -> TestResult:
|
|
178
|
+
"""Paired t-test for the mean of a − b (for example per-fold scores of two models on the same folds).
|
|
179
|
+
``estimate`` is the mean difference with a confidence interval; ``params["cohens_dz"]`` is d_z.
|
|
180
|
+
"""
|
|
181
|
+
level = _check_level(level)
|
|
182
|
+
x, y = _vec(a, "a"), _vec(b, "b")
|
|
183
|
+
if x.shape != y.shape:
|
|
184
|
+
raise InputValidationError(f"Paired samples must have the same length; got {x.shape[0]} and {y.shape[0]}.")
|
|
185
|
+
_alt(alternative)
|
|
186
|
+
d = x - y
|
|
187
|
+
n = d.shape[0]
|
|
188
|
+
diff = float(d.mean())
|
|
189
|
+
c = d - diff
|
|
190
|
+
sd = math.sqrt(float(np.dot(c, c)) / (n - 1))
|
|
191
|
+
if sd == 0:
|
|
192
|
+
raise StatisticalTestError("The paired t-test is undefined: every difference is identical.")
|
|
193
|
+
t = diff / (sd / math.sqrt(n))
|
|
194
|
+
return TestResult(
|
|
195
|
+
"paired-t",
|
|
196
|
+
t,
|
|
197
|
+
_t_pvalue(t, n - 1, alternative),
|
|
198
|
+
alternative=alternative,
|
|
199
|
+
estimate=diff,
|
|
200
|
+
ci=_mean_diff_ci(diff, sd / math.sqrt(n), n - 1, level, alternative, "mean_difference"),
|
|
201
|
+
params={"df": n - 1, "effect_size": "mean difference", "cohens_dz": diff / sd, "n": n},
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def mann_whitney_test(a: ArrayLike, b: ArrayLike, *, alternative: Alternative = "two-sided") -> TestResult:
|
|
206
|
+
"""Mann–Whitney U (Wilcoxon rank-sum) test. ``statistic`` is U for ``a``; ``estimate`` is the
|
|
207
|
+
rank-biserial correlation r = 2U/(n₁n₂) − 1 (equal to Cliff's delta), and ``params["auc"]`` = U/(n₁n₂)
|
|
208
|
+
= P(a > b) + ½P(a = b).
|
|
209
|
+
|
|
210
|
+
References: Mann HB, Whitney DR. Ann Math Stat. 1947;18(1):50-60. Kerby DS. Compr Psychol. 2014;3:11.IT.3.1.
|
|
211
|
+
"""
|
|
212
|
+
x, y = _vec(a, "a", 1), _vec(b, "b", 1)
|
|
213
|
+
_alt(alternative)
|
|
214
|
+
n1, n2 = x.shape[0], y.shape[0]
|
|
215
|
+
labels = np.zeros(n1 + n2, dtype=np.intp)
|
|
216
|
+
labels[n1:] = 1
|
|
217
|
+
sums, sizes = _rank_sums(np.concatenate([x, y]), labels, 2)
|
|
218
|
+
u = float(sums[0]) - n1 * (n1 + 1) / 2
|
|
219
|
+
ties = sizes[sizes > 1].astype(np.float64)
|
|
220
|
+
if (n1 <= 8 or n2 <= 8) and ties.size == 0:
|
|
221
|
+
# SciPy's method="auto" uses the exact null distribution here.
|
|
222
|
+
p = float(stats.mannwhitneyu(x, y, alternative=alternative, method="exact").pvalue)
|
|
223
|
+
else:
|
|
224
|
+
# Tie-corrected normal approximation with continuity correction, as scipy.stats.mannwhitneyu.
|
|
225
|
+
n = n1 + n2
|
|
226
|
+
s_ = math.sqrt(n1 * n2 / 12 * ((n + 1) - float(np.sum(ties**3 - ties)) / (n * (n - 1))))
|
|
227
|
+
num = u - n1 * n2 / 2
|
|
228
|
+
sign = 1.0 if alternative == "greater" else -1.0 if alternative == "less" else float(np.sign(num))
|
|
229
|
+
num -= 0.5 * sign
|
|
230
|
+
p = _z_pvalue(num / s_, alternative) if s_ > 0 else math.nan
|
|
231
|
+
return TestResult(
|
|
232
|
+
"mann-whitney",
|
|
233
|
+
u,
|
|
234
|
+
p,
|
|
235
|
+
alternative=alternative,
|
|
236
|
+
estimate=2 * u / (n1 * n2) - 1,
|
|
237
|
+
params={"effect_size": "rank-biserial correlation", "auc": u / (n1 * n2), "n_a": n1, "n_b": n2},
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _wilcoxon_fast(
|
|
242
|
+
d: NDArray[np.float64],
|
|
243
|
+
nz: NDArray[np.float64],
|
|
244
|
+
t_plus: float,
|
|
245
|
+
t_minus: float,
|
|
246
|
+
ties: NDArray[np.float64],
|
|
247
|
+
alternative: str,
|
|
248
|
+
zero_method: str,
|
|
249
|
+
) -> tuple[float, Optional[float]]:
|
|
250
|
+
"""SciPy's ``wilcoxon`` (method="auto", correction=False) from ranks already computed: the exact null
|
|
251
|
+
distribution without ties or zeros, the tie-corrected normal approximation otherwise. Returns p=None where
|
|
252
|
+
SciPy would run a permutation test (ties or zeros with n <= 13), other zero methods, or old SciPy. As in
|
|
253
|
+
SciPy, samples of more than 50 pairs always use the normal approximation."""
|
|
254
|
+
stat = min(t_plus, t_minus) if alternative == "two-sided" else t_plus
|
|
255
|
+
if zero_method != "wilcox":
|
|
256
|
+
return stat, None
|
|
257
|
+
n_zero = d.shape[0] - nz.shape[0]
|
|
258
|
+
has_ties = bool(np.any(ties > 1))
|
|
259
|
+
count = nz.shape[0]
|
|
260
|
+
if d.shape[0] <= 50 and not (has_ties or n_zero > 0):
|
|
261
|
+
try:
|
|
262
|
+
from scipy.stats._wilcoxon import WilcoxonDistribution
|
|
263
|
+
except ImportError: # SciPy < 1.12
|
|
264
|
+
return stat, None
|
|
265
|
+
dist = WilcoxonDistribution(np.asarray(count))
|
|
266
|
+
if alternative == "less":
|
|
267
|
+
p = float(dist.cdf(np.ceil(t_plus)))
|
|
268
|
+
elif alternative == "greater":
|
|
269
|
+
p = float(dist.sf(np.floor(t_plus)))
|
|
270
|
+
else:
|
|
271
|
+
p = float(np.clip(2 * min(dist.sf(np.floor(t_plus)), dist.cdf(np.ceil(t_plus))), 0, 1))
|
|
272
|
+
return stat, p
|
|
273
|
+
if d.shape[0] <= 13 and (has_ties or n_zero > 0):
|
|
274
|
+
return stat, None
|
|
275
|
+
mn = count * (count + 1.0) * 0.25
|
|
276
|
+
se = math.sqrt((count * (count + 1.0) * (2.0 * count + 1.0) - float(np.sum(ties**3 - ties)) / 2) / 24)
|
|
277
|
+
return stat, _z_pvalue((t_plus - mn) / se, alternative)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def wilcoxon_test(
|
|
281
|
+
a: ArrayLike,
|
|
282
|
+
b: ArrayLike,
|
|
283
|
+
*,
|
|
284
|
+
alternative: Alternative = "two-sided",
|
|
285
|
+
zero_method: Literal["wilcox", "pratt", "zsplit"] = "wilcox",
|
|
286
|
+
) -> TestResult:
|
|
287
|
+
"""Wilcoxon signed-rank test for paired samples (a − b). ``estimate`` is the matched-pairs rank-biserial
|
|
288
|
+
correlation (T⁺ − T⁻) / (T⁺ + T⁻) over the non-zero differences.
|
|
289
|
+
|
|
290
|
+
Reference: Wilcoxon F. Biometrics Bull. 1945;1(6):80-83.
|
|
291
|
+
"""
|
|
292
|
+
x, y = _vec(a, "a", 1), _vec(b, "b", 1)
|
|
293
|
+
if x.shape != y.shape:
|
|
294
|
+
raise InputValidationError(f"Paired samples must have the same length; got {x.shape[0]} and {y.shape[0]}.")
|
|
295
|
+
d = x - y
|
|
296
|
+
nz = d[d != 0]
|
|
297
|
+
if nz.shape[0] == 0:
|
|
298
|
+
raise StatisticalTestError("The Wilcoxon test is undefined: every difference is zero.")
|
|
299
|
+
_alt(alternative)
|
|
300
|
+
t_plus, t_minus, ties = _signed_rank(nz)
|
|
301
|
+
stat, p = _wilcoxon_fast(d, nz, t_plus, t_minus, ties, alternative, zero_method)
|
|
302
|
+
if p is None:
|
|
303
|
+
res = stats.wilcoxon(x, y, alternative=alternative, zero_method=zero_method)
|
|
304
|
+
stat, p = float(res.statistic), float(res.pvalue)
|
|
305
|
+
return TestResult(
|
|
306
|
+
"wilcoxon",
|
|
307
|
+
stat,
|
|
308
|
+
p,
|
|
309
|
+
alternative=alternative,
|
|
310
|
+
estimate=float((t_plus - t_minus) / (t_plus + t_minus)),
|
|
311
|
+
params={
|
|
312
|
+
"effect_size": "matched-pairs rank-biserial correlation",
|
|
313
|
+
"n": int(d.shape[0]),
|
|
314
|
+
"n_nonzero": int(nz.shape[0]),
|
|
315
|
+
"zero_method": zero_method,
|
|
316
|
+
},
|
|
317
|
+
)
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _groups(groups: tuple[ArrayLike, ...], min_groups: int, what: str) -> list[NDArray[np.float64]]:
|
|
321
|
+
if len(groups) < min_groups:
|
|
322
|
+
raise InputValidationError(f"{what} needs at least {min_groups} groups; got {len(groups)}.")
|
|
323
|
+
return [_vec(g, f"group {i + 1}", 1) for i, g in enumerate(groups)]
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def kruskal_wallis_test(*groups: ArrayLike) -> TestResult:
|
|
327
|
+
"""Kruskal–Wallis H test: do two or more independent groups come from the same distribution?
|
|
328
|
+
``estimate`` is epsilon-squared, H / ((n² − 1)/(n + 1)).
|
|
329
|
+
|
|
330
|
+
References: Kruskal WH, Wallis WA. JASA. 1952;47(260):583-621. Tomczak M, Tomczak E. Trends Sport Sci.
|
|
331
|
+
2014;1(21):19-25.
|
|
332
|
+
"""
|
|
333
|
+
gs = _groups(groups, 2, "The Kruskal–Wallis test")
|
|
334
|
+
sizes_g = np.array([g.shape[0] for g in gs])
|
|
335
|
+
n = int(sizes_g.sum())
|
|
336
|
+
labels = np.repeat(np.arange(len(gs), dtype=np.intp), sizes_g)
|
|
337
|
+
sums, ties = _rank_sums(np.concatenate(gs), labels, len(gs))
|
|
338
|
+
# H with the tie correction 1 − Σ(t³ − t)/(n³ − n), as scipy.stats.kruskal.
|
|
339
|
+
t = ties[ties > 1].astype(np.float64)
|
|
340
|
+
correction = 1.0 - float(np.sum(t**3 - t)) / (n**3 - n)
|
|
341
|
+
if correction == 0:
|
|
342
|
+
raise StatisticalTestError("The Kruskal–Wallis test is undefined: all values are identical.")
|
|
343
|
+
h = (12.0 / (n * (n + 1)) * float(np.sum(sums**2 / sizes_g)) - 3 * (n + 1)) / correction
|
|
344
|
+
return TestResult(
|
|
345
|
+
"kruskal-wallis",
|
|
346
|
+
h,
|
|
347
|
+
float(special.chdtrc(len(gs) - 1, h)),
|
|
348
|
+
estimate=h / ((n**2 - 1) / (n + 1)),
|
|
349
|
+
params={"df": len(gs) - 1, "effect_size": "epsilon-squared", "n": n, "k": len(gs)},
|
|
350
|
+
)
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def friedman_test(*groups: ArrayLike) -> TestResult:
|
|
354
|
+
"""Friedman test for three or more related samples (for example several models scored on the same
|
|
355
|
+
datasets or folds; each argument is one model's scores). ``estimate`` is Kendall's W = χ² / (n (k − 1)).
|
|
356
|
+
|
|
357
|
+
References: Friedman M. JASA. 1937;32(200):675-701. Demšar J. Statistical comparisons of classifiers over
|
|
358
|
+
multiple data sets. JMLR. 2006;7:1-30.
|
|
359
|
+
"""
|
|
360
|
+
gs = _groups(groups, 3, "The Friedman test")
|
|
361
|
+
n = gs[0].shape[0]
|
|
362
|
+
if any(g.shape[0] != n for g in gs):
|
|
363
|
+
raise InputValidationError("Every sample in the Friedman test needs the same number of blocks.")
|
|
364
|
+
if n < 2:
|
|
365
|
+
raise StatisticalTestError("The Friedman test needs at least two blocks.")
|
|
366
|
+
k = len(gs)
|
|
367
|
+
if k > 32:
|
|
368
|
+
res = stats.friedmanchisquare(*gs)
|
|
369
|
+
chi, p = float(res.statistic), float(res.pvalue)
|
|
370
|
+
else:
|
|
371
|
+
# Within-block average ranks by pairwise comparison (k is small): rank = 1 + #less + (#equal − 1)/2,
|
|
372
|
+
# and each tie group of size t contributes Σ(eq² − 1) = t³ − t; the statistic and tie correction are
|
|
373
|
+
# those of scipy.stats.friedmanchisquare.
|
|
374
|
+
data = np.stack(gs, axis=1)
|
|
375
|
+
less = np.zeros(data.shape)
|
|
376
|
+
eq = np.zeros(data.shape)
|
|
377
|
+
for j in range(k):
|
|
378
|
+
col = data[:, j : j + 1]
|
|
379
|
+
less += col < data
|
|
380
|
+
eq += col == data
|
|
381
|
+
ranks = 1.0 + less + (eq - 1.0) / 2.0
|
|
382
|
+
r = ranks.sum(axis=0)
|
|
383
|
+
c = 1.0 - float(np.sum(eq * eq - 1.0)) / (n * k * (k * k - 1))
|
|
384
|
+
if c == 0:
|
|
385
|
+
raise StatisticalTestError("The Friedman test is undefined: every block has all values tied.")
|
|
386
|
+
chi = (12.0 / (n * k * (k + 1)) * float(np.dot(r, r)) - 3.0 * n * (k + 1)) / c
|
|
387
|
+
p = float(special.chdtrc(k - 1, chi))
|
|
388
|
+
return TestResult(
|
|
389
|
+
"friedman",
|
|
390
|
+
chi,
|
|
391
|
+
p,
|
|
392
|
+
estimate=chi / (n * (k - 1)),
|
|
393
|
+
params={"df": k - 1, "effect_size": "Kendall's W", "n_blocks": n, "k": k},
|
|
394
|
+
)
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def shapiro_wilk_test(x: ArrayLike) -> TestResult:
|
|
398
|
+
"""Shapiro–Wilk test of normality (3 ≤ n ≤ 5000 for an accurate p-value).
|
|
399
|
+
|
|
400
|
+
Reference: Shapiro SS, Wilk MB. Biometrika. 1965;52(3-4):591-611.
|
|
401
|
+
"""
|
|
402
|
+
a = _vec(x, "x", 3)
|
|
403
|
+
if np.ptp(a) == 0:
|
|
404
|
+
raise StatisticalTestError("The Shapiro–Wilk test is undefined for constant data.")
|
|
405
|
+
fast = _shapiro_fast(a)
|
|
406
|
+
if fast is None:
|
|
407
|
+
res = stats.shapiro(a)
|
|
408
|
+
w, p = float(res.statistic), float(res.pvalue)
|
|
409
|
+
else:
|
|
410
|
+
w, p = fast
|
|
411
|
+
return TestResult("shapiro-wilk", w, p, params={"n": int(a.shape[0])})
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def _scipy_has_numpy_swilk() -> bool:
|
|
415
|
+
try:
|
|
416
|
+
from scipy.stats import _morestats
|
|
417
|
+
|
|
418
|
+
return hasattr(_morestats, "_swilk_w")
|
|
419
|
+
except ImportError: # pragma: no cover
|
|
420
|
+
return False
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
@functools.lru_cache(maxsize=64)
|
|
424
|
+
def _swilk_coefficients(n: int) -> NDArray[np.float64]:
|
|
425
|
+
"""Royston's (1992) Shapiro–Wilk weights for sample size n (n > 3), exactly as scipy.stats.shapiro computes
|
|
426
|
+
them in SciPy >= 1.12. They depend only on n, so they are computed once per size."""
|
|
427
|
+
vdot = getattr(np, "vecdot", np.dot)
|
|
428
|
+
i = np.arange(1, n + 1, dtype=np.float64)
|
|
429
|
+
m = special.ndtri((i - 3 / 8) / (n + 1 / 4))
|
|
430
|
+
u = n**-0.5
|
|
431
|
+
mtm = vdot(m, m)
|
|
432
|
+
c = mtm**-0.5 * m
|
|
433
|
+
mnm1, mn = m[-2], m[-1]
|
|
434
|
+
cnm1, cn = c[-2], c[-1]
|
|
435
|
+
an = cn + 0.221157 * u - 0.147981 * u**2 - 2.071190 * u**3 + 4.434685 * u**4 - 2.706056 * u**5
|
|
436
|
+
anm1 = cnm1 + 0.042981 * u - 0.293762 * u**2 - 1.752461 * u**3 + 5.682633 * u**4 - 3.582633 * u**5
|
|
437
|
+
phi = (
|
|
438
|
+
(mtm - 2 * mn**2) / (1 - 2 * an**2)
|
|
439
|
+
if n <= 5
|
|
440
|
+
else (mtm - 2 * mn**2 - 2 * mnm1**2) / (1 - 2 * an**2 - 2 * anm1**2)
|
|
441
|
+
)
|
|
442
|
+
a: NDArray[np.float64] = np.asarray(phi**-0.5 * m, dtype=np.float64)
|
|
443
|
+
if n > 5:
|
|
444
|
+
a[-2] = anm1
|
|
445
|
+
a[1] = -anm1
|
|
446
|
+
a[-1] = an
|
|
447
|
+
a[0] = -an
|
|
448
|
+
a.setflags(write=False)
|
|
449
|
+
return a
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def _shapiro_fast(x: NDArray[np.float64]) -> Optional[tuple[float, float]]:
|
|
453
|
+
"""scipy.stats.shapiro without its per-call overhead and with cached weights; None on SciPy < 1.12, whose
|
|
454
|
+
Fortran implementation (a different algorithm) is then used instead so results always match SciPy."""
|
|
455
|
+
if not _scipy_has_numpy_swilk():
|
|
456
|
+
return None
|
|
457
|
+
vdot = getattr(np, "vecdot", np.dot)
|
|
458
|
+
n = x.shape[0]
|
|
459
|
+
y = np.sort(x)
|
|
460
|
+
y -= x[n // 2] # SciPy subtracts this element (of the unsorted input) for numerical stability
|
|
461
|
+
if n == 3:
|
|
462
|
+
c = math.sqrt(2) / 2
|
|
463
|
+
a3 = np.array([-c, 0.0, c])
|
|
464
|
+
yc = y - y.mean()
|
|
465
|
+
w = min(max(float(vdot(a3, y) ** 2 / vdot(yc, yc)), 0.75), 1.0)
|
|
466
|
+
return w, min(max(1.0 - 6 / math.pi * math.acos(math.sqrt(w)), 0.0), 1.0)
|
|
467
|
+
a = _swilk_coefficients(n)
|
|
468
|
+
yc = y - y.mean()
|
|
469
|
+
w = float(vdot(a, y) ** 2 / vdot(yc, yc))
|
|
470
|
+
if n <= 11:
|
|
471
|
+
u = n
|
|
472
|
+
gamma = -2.273 + 0.459 * u
|
|
473
|
+
mu = 0.5440 - 0.39978 * u + 0.025054 * u**2 - 0.0006714 * u**3
|
|
474
|
+
sigma = math.exp(1.3822 - 0.77857 * u + 0.062767 * u**2 - 0.0020322 * u**3)
|
|
475
|
+
g = -math.log(gamma - math.log(1 - w))
|
|
476
|
+
else:
|
|
477
|
+
lu = math.log(n)
|
|
478
|
+
mu = -1.5861 - 0.31082 * lu - 0.083751 * lu**2 + 0.0038915 * lu**3
|
|
479
|
+
sigma = math.exp(-0.4803 - 0.082676 * lu + 0.0030302 * lu**2)
|
|
480
|
+
g = math.log(1 - w)
|
|
481
|
+
if n > 5000:
|
|
482
|
+
warnings.warn(
|
|
483
|
+
f"scipy.stats.shapiro: For N > 5000, computed p-value may not be accurate. Current N is {n}.",
|
|
484
|
+
UserWarning,
|
|
485
|
+
stacklevel=3,
|
|
486
|
+
)
|
|
487
|
+
return w, float(special.ndtr(-(g - mu) / sigma))
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def _table(table: ArrayLike) -> NDArray[np.float64]:
|
|
491
|
+
t = np.asarray(table, dtype=np.float64)
|
|
492
|
+
if t.ndim != 2 or t.shape[0] < 2 or t.shape[1] < 2:
|
|
493
|
+
raise InputValidationError("Give a contingency table with at least 2 rows and 2 columns.")
|
|
494
|
+
if np.any(~np.isfinite(t)) or np.any(t < 0):
|
|
495
|
+
raise InputValidationError("Contingency table counts must be finite and non-negative.")
|
|
496
|
+
return t
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
def chi_square_test(table: ArrayLike, *, correction: bool = True) -> TestResult:
|
|
500
|
+
"""Pearson's χ² test of independence for an r × c contingency table. Yates' continuity correction is
|
|
501
|
+
applied to 2 × 2 tables unless ``correction=False``. ``estimate`` is Cramér's V (from the uncorrected
|
|
502
|
+
statistic, as in :func:`cramers_v`); ``params["expected"]``
|
|
503
|
+
holds the expected counts (the approximation is doubtful when many are below 5).
|
|
504
|
+
|
|
505
|
+
Reference: Pearson K. Philos Mag. 1900;50(302):157-175. Cramér H. Mathematical Methods of Statistics. 1946.
|
|
506
|
+
"""
|
|
507
|
+
t = _table(table)
|
|
508
|
+
if np.any(t.sum(axis=0) == 0) or np.any(t.sum(axis=1) == 0):
|
|
509
|
+
raise StatisticalTestError("The χ² test is undefined when a row or column total is zero.")
|
|
510
|
+
# Same computation as scipy.stats.chi2_contingency, but the expected table is built once and serves both
|
|
511
|
+
# the (possibly Yates-corrected) test statistic and the uncorrected statistic behind Cramér's V.
|
|
512
|
+
n = float(t.sum())
|
|
513
|
+
expected = np.outer(t.sum(axis=1), t.sum(axis=0)) / n
|
|
514
|
+
dof = (t.shape[0] - 1) * (t.shape[1] - 1)
|
|
515
|
+
dev = t - expected
|
|
516
|
+
uncorrected = float(np.sum(dev * dev / expected))
|
|
517
|
+
if dof == 0:
|
|
518
|
+
chi2, p = 0.0, 1.0
|
|
519
|
+
else:
|
|
520
|
+
if correction and dof == 1:
|
|
521
|
+
adj = np.abs(dev) - np.minimum(0.5, np.abs(dev))
|
|
522
|
+
chi2 = float(np.sum(adj * adj / expected))
|
|
523
|
+
else:
|
|
524
|
+
chi2 = uncorrected
|
|
525
|
+
p = float(special.chdtrc(dof, chi2))
|
|
526
|
+
v = math.sqrt((uncorrected / n) / (min(t.shape) - 1))
|
|
527
|
+
return TestResult(
|
|
528
|
+
"chi-square",
|
|
529
|
+
float(chi2),
|
|
530
|
+
float(p),
|
|
531
|
+
estimate=v,
|
|
532
|
+
params={
|
|
533
|
+
"df": int(dof),
|
|
534
|
+
"effect_size": "Cramér's V",
|
|
535
|
+
"expected": np.asarray(expected).tolist(),
|
|
536
|
+
"yates_correction": bool(correction and t.shape == (2, 2)),
|
|
537
|
+
"min_expected": float(np.min(expected)),
|
|
538
|
+
},
|
|
539
|
+
)
|
|
540
|
+
|
|
541
|
+
|
|
542
|
+
def _fisher_p(a: int, b: int, c: int, d: int, alternative: str) -> float:
|
|
543
|
+
"""Fisher's exact test p-value for [[a, b], [c, d]] from the hypergeometric pmf in log space.
|
|
544
|
+
|
|
545
|
+
Only tables within 40 standard deviations of the mode are summed: anything farther has a probability below
|
|
546
|
+
e^-800 relative to the mode and underflows to zero anyway. Two-sided: tables no more probable than the
|
|
547
|
+
observed one (relative tolerance 1e-7, as R's fisher.test). Matches scipy.stats.fisher_exact to ~1e-12."""
|
|
548
|
+
n1, n2, n = a + b, c + d, a + c
|
|
549
|
+
total = n1 + n2
|
|
550
|
+
lo, hi = max(0, n - n2), min(n, n1)
|
|
551
|
+
mode = (n + 1) * (n1 + 1) // (total + 2)
|
|
552
|
+
sd = math.sqrt(max(n * (n1 / total) * (n2 / total) * (total - n) / max(total - 1, 1), 1.0))
|
|
553
|
+
wlo, whi = max(lo, int(mode - 40 * sd) - 2), min(hi, int(mode + 40 * sd) + 2)
|
|
554
|
+
x = np.arange(wlo, whi + 1, dtype=np.float64)
|
|
555
|
+
gl = special.gammaln
|
|
556
|
+
lp = -(gl(x + 1) + gl(n1 - x + 1) + gl(n - x + 1) + gl(n2 - n + x + 1))
|
|
557
|
+
w = np.exp(lp - lp.max())
|
|
558
|
+
tot = float(w.sum())
|
|
559
|
+
i = a - wlo
|
|
560
|
+
if alternative == "less":
|
|
561
|
+
p = 0.0 if i < 0 else 1.0 if i >= w.shape[0] else float(w[: i + 1].sum()) / tot
|
|
562
|
+
elif alternative == "greater":
|
|
563
|
+
p = 1.0 if i < 0 else 0.0 if i >= w.shape[0] else float(w[i:].sum()) / tot
|
|
564
|
+
else:
|
|
565
|
+
p = 0.0 if not 0 <= i < w.shape[0] else float(w[w <= w[i] * (1 + 1e-7)].sum()) / tot
|
|
566
|
+
return min(p, 1.0)
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
def fisher_exact_test(table: ArrayLike, *, alternative: Alternative = "two-sided") -> TestResult:
|
|
570
|
+
"""Fisher's exact test for a 2 × 2 table. ``estimate`` is the sample odds ratio (a·d)/(b·c).
|
|
571
|
+
|
|
572
|
+
Reference: Fisher RA. J R Stat Soc. 1922;85(1):87-94.
|
|
573
|
+
"""
|
|
574
|
+
t = _table(table)
|
|
575
|
+
if t.shape != (2, 2):
|
|
576
|
+
raise InputValidationError("Fisher's exact test here is for 2 × 2 tables.")
|
|
577
|
+
if not np.all(t == np.round(t)):
|
|
578
|
+
raise InputValidationError("Fisher's exact test needs integer counts.")
|
|
579
|
+
_alt(alternative)
|
|
580
|
+
a, b, c, d = (int(v) for v in t.ravel())
|
|
581
|
+
if 0 in (a + b, c + d, a + c, b + d):
|
|
582
|
+
odds, p = math.nan, 1.0 # a zero margin: as scipy.stats.fisher_exact
|
|
583
|
+
else:
|
|
584
|
+
odds = a * d / (b * c) if b > 0 and c > 0 else math.inf
|
|
585
|
+
p = _fisher_p(a, b, c, d, alternative)
|
|
586
|
+
return TestResult(
|
|
587
|
+
"fisher-exact",
|
|
588
|
+
float(odds),
|
|
589
|
+
float(p),
|
|
590
|
+
alternative=alternative,
|
|
591
|
+
estimate=float(odds),
|
|
592
|
+
params={"effect_size": "odds ratio"},
|
|
593
|
+
)
|