evalsuite-python 0.5.2__py3-none-any.whl → 0.5.4__py3-none-any.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/core/context.py +18 -0
- evalsuite/core/validation.py +27 -6
- evalsuite/llmsys/_common.py +45 -16
- evalsuite/llmsys/efficiency.py +3 -4
- evalsuite/llmsys/multilingual.py +25 -13
- evalsuite/regression/metrics.py +22 -5
- evalsuite/stats/effect.py +10 -8
- evalsuite/stats/hypothesis.py +216 -35
- evalsuite/stats/intervals.py +8 -6
- evalsuite/stats/paired.py +4 -4
- evalsuite/text/_common.py +4 -1
- evalsuite/text/generation.py +125 -51
- evalsuite/text/judge.py +23 -5
- evalsuite/text/semantic.py +25 -5
- evalsuite/version.py +1 -1
- evalsuite/vision/segmentation.py +33 -13
- {evalsuite_python-0.5.2.dist-info → evalsuite_python-0.5.4.dist-info}/METADATA +49 -39
- {evalsuite_python-0.5.2.dist-info → evalsuite_python-0.5.4.dist-info}/RECORD +22 -21
- evalsuite_python-0.5.4.dist-info/licenses/LICENSE-APACHE +191 -0
- {evalsuite_python-0.5.2.dist-info → evalsuite_python-0.5.4.dist-info}/WHEEL +0 -0
- {evalsuite_python-0.5.2.dist-info → evalsuite_python-0.5.4.dist-info}/entry_points.txt +0 -0
- {evalsuite_python-0.5.2.dist-info → evalsuite_python-0.5.4.dist-info}/licenses/LICENSE +0 -0
evalsuite/core/context.py
CHANGED
|
@@ -92,7 +92,23 @@ class ClassificationContext:
|
|
|
92
92
|
def _index(self) -> dict[Any, int]:
|
|
93
93
|
return {lab.item() if hasattr(lab, "item") else lab: i for i, lab in enumerate(self.labels)}
|
|
94
94
|
|
|
95
|
+
@cached_property
|
|
96
|
+
def _contiguous_int_labels(self) -> Optional[int]:
|
|
97
|
+
"""The first label when labels are consecutive integers lo, lo+1, …; encoding is then y − lo."""
|
|
98
|
+
lab = self.labels
|
|
99
|
+
if (
|
|
100
|
+
lab.dtype.kind in "iu"
|
|
101
|
+
and lab.size
|
|
102
|
+
and np.array_equal(lab, np.arange(int(lab[0]), int(lab[0]) + lab.size))
|
|
103
|
+
):
|
|
104
|
+
return int(lab[0])
|
|
105
|
+
return None
|
|
106
|
+
|
|
95
107
|
def encode(self, y: NDArray[Any]) -> NDArray[np.int64]:
|
|
108
|
+
lo = self._contiguous_int_labels
|
|
109
|
+
if lo is not None and y.dtype.kind in "iu":
|
|
110
|
+
yi = y.astype(np.int64, copy=False)
|
|
111
|
+
return yi - lo if lo else yi
|
|
96
112
|
sorted_labels = np.all(self.labels[:-1] <= self.labels[1:]) if self.labels.dtype != object else False
|
|
97
113
|
if sorted_labels:
|
|
98
114
|
return np.searchsorted(self.labels, y).astype(np.int64)
|
|
@@ -123,6 +139,8 @@ class ClassificationContext:
|
|
|
123
139
|
)
|
|
124
140
|
k = self.labels.shape[0]
|
|
125
141
|
flat = self.true_idx * k + self.pred_idx
|
|
142
|
+
if self.sample_weight is None: # integer counting is faster than summing unit weights
|
|
143
|
+
return np.bincount(flat, minlength=k * k).reshape(k, k).astype(np.float64)
|
|
126
144
|
return np.bincount(flat, weights=self.weights, minlength=k * k).reshape(k, k).astype(np.float64)
|
|
127
145
|
|
|
128
146
|
@cached_property
|
evalsuite/core/validation.py
CHANGED
|
@@ -65,7 +65,7 @@ def _label_kind(arr: NDArray[Any]) -> str:
|
|
|
65
65
|
|
|
66
66
|
|
|
67
67
|
def check_finite(arr: NDArray[Any], name: str) -> None:
|
|
68
|
-
if
|
|
68
|
+
if arr.dtype.kind in "fc" and not np.all(np.isfinite(arr)): # integers and booleans are always finite
|
|
69
69
|
n_nan = int(np.isnan(arr).sum())
|
|
70
70
|
n_inf = int(np.isinf(arr).sum())
|
|
71
71
|
raise InputValidationError(
|
|
@@ -104,25 +104,38 @@ def unique_labels(y: NDArray[Any]) -> NDArray[Any]:
|
|
|
104
104
|
are found with one marking pass instead of a sort, which is several times faster on large arrays."""
|
|
105
105
|
if y.size and np.issubdtype(y.dtype, np.integer):
|
|
106
106
|
lo, hi = int(y.min()), int(y.max())
|
|
107
|
+
if hi - lo <= 1: # min and max are themselves the labels (the binary case): no counting pass
|
|
108
|
+
return np.array([lo] if hi == lo else [lo, hi], dtype=y.dtype)
|
|
107
109
|
if lo > -(2**62) and hi < 2**62 and hi - lo <= max(1024, y.size):
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
110
|
+
flat = y.ravel()
|
|
111
|
+
# bincount counts in one pass; offsets in int64 so small dtypes cannot overflow.
|
|
112
|
+
counts = np.bincount(flat if lo == 0 and flat.dtype.itemsize <= 8 else flat.astype(np.int64) - lo)
|
|
113
|
+
return (np.flatnonzero(counts).astype(np.int64) + lo).astype(y.dtype)
|
|
111
114
|
return np.unique(y)
|
|
112
115
|
|
|
113
116
|
|
|
117
|
+
def _has_fraction(y: NDArray[Any]) -> bool:
|
|
118
|
+
"""Whether any value is non-integral. Real-valued targets almost always show it in the first few values,
|
|
119
|
+
so a short leading chunk is checked before the whole array."""
|
|
120
|
+
flat = y.ravel()
|
|
121
|
+
head = flat[:1024]
|
|
122
|
+
if not np.all(np.mod(head, 1) == 0):
|
|
123
|
+
return True
|
|
124
|
+
return flat.size > head.size and not np.all(np.mod(flat[head.size :], 1) == 0)
|
|
125
|
+
|
|
126
|
+
|
|
114
127
|
def target_type(y: NDArray[Any]) -> TargetType:
|
|
115
128
|
"""Infer the type of a label array."""
|
|
116
129
|
if y.ndim == 2:
|
|
117
130
|
if y.shape[1] > 1 and np.isin(y, (0, 1)).all():
|
|
118
131
|
return "multilabel"
|
|
119
|
-
if np.issubdtype(y.dtype, np.floating) and
|
|
132
|
+
if np.issubdtype(y.dtype, np.floating) and _has_fraction(y):
|
|
120
133
|
return "continuous" # multi-output regression
|
|
121
134
|
raise InputValidationError(
|
|
122
135
|
"2-D targets must be a binary indicator matrix (0/1, one column per label) for multilabel tasks; "
|
|
123
136
|
f"received shape {y.shape} with values other than 0 and 1."
|
|
124
137
|
)
|
|
125
|
-
if np.issubdtype(y.dtype, np.floating) and
|
|
138
|
+
if np.issubdtype(y.dtype, np.floating) and _has_fraction(y):
|
|
126
139
|
return "continuous"
|
|
127
140
|
try:
|
|
128
141
|
n_unique = unique_labels(y).shape[0]
|
|
@@ -147,6 +160,14 @@ def resolve_labels(
|
|
|
147
160
|
f"y_true has {_label_kind(y_true)} labels but y_pred has {_label_kind(y_pred)} labels; "
|
|
148
161
|
"use the same label type in both (for example map class names to integers first)."
|
|
149
162
|
)
|
|
163
|
+
if (
|
|
164
|
+
y_pred is not None
|
|
165
|
+
and np.issubdtype(y_true.dtype, np.integer)
|
|
166
|
+
and np.issubdtype(y_pred.dtype, np.integer)
|
|
167
|
+
and y_true.dtype == y_pred.dtype
|
|
168
|
+
):
|
|
169
|
+
# Union of each array's labels: no concatenated copy of the data.
|
|
170
|
+
return np.union1d(unique_labels(y_true), unique_labels(y_pred)).astype(y_true.dtype)
|
|
150
171
|
present = y_true if y_pred is None else np.concatenate([y_true, y_pred])
|
|
151
172
|
try:
|
|
152
173
|
return unique_labels(present)
|
evalsuite/llmsys/_common.py
CHANGED
|
@@ -60,12 +60,15 @@ def floats(x: Any, name: str, *, lo: Optional[float] = None, hi: Optional[float]
|
|
|
60
60
|
raise InputValidationError(f"{name} must contain numbers.") from exc
|
|
61
61
|
if a.ndim != 1:
|
|
62
62
|
raise InputValidationError(f"{name} must be one-dimensional (one number per example).")
|
|
63
|
-
if
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
63
|
+
if a.size:
|
|
64
|
+
# min and max propagate NaN and ±inf, so two reductions check finiteness and both bounds.
|
|
65
|
+
mn, mx = float(a.min()), float(a.max())
|
|
66
|
+
if not (math.isfinite(mn) and math.isfinite(mx)):
|
|
67
|
+
raise InputValidationError(f"{name} contains NaN or infinite values.")
|
|
68
|
+
if lo is not None and mn < lo:
|
|
69
|
+
raise InputValidationError(f"{name} must be >= {lo}.")
|
|
70
|
+
if hi is not None and mx > hi:
|
|
71
|
+
raise InputValidationError(f"{name} must be <= {hi}.")
|
|
69
72
|
return a
|
|
70
73
|
|
|
71
74
|
|
|
@@ -113,19 +116,45 @@ def by_group(values: np.ndarray, groups: Optional[Sequence[Any]], name: str = "g
|
|
|
113
116
|
return out
|
|
114
117
|
|
|
115
118
|
|
|
116
|
-
def
|
|
117
|
-
"""
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
119
|
+
def quantiles(a: np.ndarray, qs: Sequence[float]) -> list[float]:
|
|
120
|
+
"""Percentiles ``qs`` (0-100, linear interpolation, identical to ``np.percentile``) from one partition."""
|
|
121
|
+
n = a.size
|
|
122
|
+
pos = [(n - 1) * q / 100.0 for q in qs]
|
|
123
|
+
lo = [int(np.floor(h)) for h in pos]
|
|
124
|
+
kth = sorted({k for i in lo for k in (i, min(i + 1, n - 1))})
|
|
125
|
+
part = np.partition(a, kth)
|
|
126
|
+
out = []
|
|
127
|
+
for h, i in zip(pos, lo):
|
|
128
|
+
v0, v1 = float(part[i]), float(part[min(i + 1, n - 1)])
|
|
129
|
+
out.append(v0 + (h - i) * (v1 - v0))
|
|
130
|
+
return out
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def summary(a: np.ndarray, extra: Sequence[float] = ()) -> dict[str, float]:
|
|
134
|
+
"""Mean, standard deviation, min, max and the p50/p90/p95/p99 percentiles (linear interpolation), plus any
|
|
135
|
+
``extra`` percentiles under keys ``p<q>``; all order statistics come from one partition."""
|
|
136
|
+
qs = [50.0, 90.0, 95.0, 99.0, *[q for q in extra if q not in (0.0, 50.0, 90.0, 95.0, 99.0, 100.0)]]
|
|
137
|
+
v = quantiles(a, qs)
|
|
138
|
+
by_q = dict(zip(qs, v))
|
|
139
|
+
mean = float(a.mean())
|
|
140
|
+
if a.size > 1:
|
|
141
|
+
c = a - mean
|
|
142
|
+
std = math.sqrt(float(np.dot(c, c)) / (a.size - 1))
|
|
143
|
+
else:
|
|
144
|
+
std = 0.0
|
|
145
|
+
out = {
|
|
146
|
+
"mean": mean,
|
|
147
|
+
"std": std,
|
|
122
148
|
"min": float(a.min()),
|
|
123
149
|
"max": float(a.max()),
|
|
124
|
-
"p50":
|
|
125
|
-
"p90":
|
|
126
|
-
"p95":
|
|
127
|
-
"p99":
|
|
150
|
+
"p50": by_q[50.0],
|
|
151
|
+
"p90": by_q[90.0],
|
|
152
|
+
"p95": by_q[95.0],
|
|
153
|
+
"p99": by_q[99.0],
|
|
128
154
|
}
|
|
155
|
+
for q in extra:
|
|
156
|
+
out[f"p{q:g}"] = float(a.min()) if q == 0 else float(a.max()) if q == 100 else by_q[q]
|
|
157
|
+
return out
|
|
129
158
|
|
|
130
159
|
|
|
131
160
|
def lists_of(x: Any, name: str) -> list[list[Any]]:
|
evalsuite/llmsys/efficiency.py
CHANGED
|
@@ -119,10 +119,9 @@ def latency_percentiles(latencies: Any, *, unit: str = "s", percentile: float =
|
|
|
119
119
|
x = floats(latencies, "latencies", lo=0)
|
|
120
120
|
if not 0 <= percentile <= 100:
|
|
121
121
|
raise InputValidationError("percentile must be in [0, 100].")
|
|
122
|
-
s = summary(x)
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
)
|
|
122
|
+
s = summary(x, extra=(percentile,))
|
|
123
|
+
value = s[f"p{percentile:g}"]
|
|
124
|
+
return MetricResult("latency_percentiles", f"p{percentile:g} latency", value, {"unit": unit, **s})
|
|
126
125
|
|
|
127
126
|
|
|
128
127
|
@register(
|
evalsuite/llmsys/multilingual.py
CHANGED
|
@@ -64,6 +64,15 @@ _REF_MARCHISIO = (
|
|
|
64
64
|
)
|
|
65
65
|
|
|
66
66
|
|
|
67
|
+
def _str_array(x: Any, name: str) -> np.ndarray:
|
|
68
|
+
"""Labels as a NumPy string array (each value's ``str``)."""
|
|
69
|
+
if isinstance(x, np.ndarray) and x.dtype.kind == "U" and x.ndim == 1:
|
|
70
|
+
if x.size == 0:
|
|
71
|
+
seq(x, name) # raises the usual empty-input error
|
|
72
|
+
return x
|
|
73
|
+
return np.asarray([str(v) for v in seq(x, name)], dtype=str)
|
|
74
|
+
|
|
75
|
+
|
|
67
76
|
@register(
|
|
68
77
|
category=_C,
|
|
69
78
|
task="language-identification",
|
|
@@ -75,21 +84,24 @@ _REF_MARCHISIO = (
|
|
|
75
84
|
references=(_REF_LANGID,),
|
|
76
85
|
)
|
|
77
86
|
def language_id_accuracy(true_languages: Any, predicted_languages: Any) -> MetricResult:
|
|
78
|
-
t =
|
|
79
|
-
p =
|
|
87
|
+
t = _str_array(true_languages, "true_languages")
|
|
88
|
+
p = _str_array(predicted_languages, "predicted_languages")
|
|
80
89
|
same_length(("true_languages", t), ("predicted_languages", p))
|
|
81
|
-
labels
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
90
|
+
# One encoding of both arrays, then a confusion matrix by bincount (labels in sorted order).
|
|
91
|
+
labels_arr, codes = np.unique(np.concatenate([t, p]), return_inverse=True)
|
|
92
|
+
k = labels_arr.shape[0]
|
|
93
|
+
n = t.shape[0]
|
|
94
|
+
cm = np.bincount(codes[:n] * k + codes[n:], minlength=k * k).reshape(k, k)
|
|
95
|
+
tp = np.diag(cm)
|
|
96
|
+
fp = cm.sum(axis=0) - tp
|
|
97
|
+
fn = cm.sum(axis=1) - tp
|
|
98
|
+
denom = 2 * tp + fp + fn
|
|
99
|
+
f1s = np.where(tp > 0, 2 * tp / np.maximum(denom, 1), 0.0)
|
|
100
|
+
labels = labels_arr.tolist()
|
|
101
|
+
recall = {lab: int(tp[i]) / int(tp[i] + fn[i]) for i, lab in enumerate(labels) if tp[i] + fn[i]}
|
|
102
|
+
acc = float(tp.sum() / n)
|
|
91
103
|
return MetricResult(
|
|
92
|
-
"language_id_accuracy", "Language-ID accuracy", acc, {"macro_f1": float(
|
|
104
|
+
"language_id_accuracy", "Language-ID accuracy", acc, {"macro_f1": float(f1s.mean()), "recall": recall}
|
|
93
105
|
)
|
|
94
106
|
|
|
95
107
|
|
evalsuite/regression/metrics.py
CHANGED
|
@@ -80,6 +80,18 @@ class _Inputs:
|
|
|
80
80
|
def error(self) -> FloatArray:
|
|
81
81
|
return self.y_pred - self.y_true
|
|
82
82
|
|
|
83
|
+
@cached_property
|
|
84
|
+
def sq_error(self) -> FloatArray:
|
|
85
|
+
"""Squared errors, shared by MSE, RMSE and R² when evaluate() computes them together."""
|
|
86
|
+
e = self.error
|
|
87
|
+
with np.errstate(over="ignore"):
|
|
88
|
+
return e * e
|
|
89
|
+
|
|
90
|
+
@cached_property
|
|
91
|
+
def mse_per_output(self) -> FloatArray:
|
|
92
|
+
with np.errstate(over="ignore"):
|
|
93
|
+
return self.mean(self.sq_error)
|
|
94
|
+
|
|
83
95
|
def mean(self, values: FloatArray) -> FloatArray:
|
|
84
96
|
"""Weighted mean over observations, per output column."""
|
|
85
97
|
if self.weight is None:
|
|
@@ -176,7 +188,7 @@ def mse(
|
|
|
176
188
|
) -> MetricResult:
|
|
177
189
|
"""Mean squared error."""
|
|
178
190
|
inp = _inputs(y_true, y_pred, sample_weight)
|
|
179
|
-
return _finish(inp.
|
|
191
|
+
return _finish(inp.mse_per_output, inp, multioutput, "mse", "MSE")
|
|
180
192
|
|
|
181
193
|
|
|
182
194
|
@register(
|
|
@@ -203,7 +215,7 @@ def rmse(
|
|
|
203
215
|
"""Root mean squared error (square root taken per output, then averaged)."""
|
|
204
216
|
inp = _inputs(y_true, y_pred, sample_weight)
|
|
205
217
|
with np.errstate(over="ignore"):
|
|
206
|
-
per_output = np.sqrt(inp.
|
|
218
|
+
per_output = np.sqrt(inp.mse_per_output)
|
|
207
219
|
if not np.all(np.isfinite(per_output)):
|
|
208
220
|
# Errors above ~1e154 overflow when squared although the RMSE itself is representable:
|
|
209
221
|
# rescale by the largest error and square again.
|
|
@@ -214,10 +226,15 @@ def rmse(
|
|
|
214
226
|
|
|
215
227
|
|
|
216
228
|
def _r2_per_output(inp: _Inputs) -> FloatArray:
|
|
217
|
-
w = inp.w[:, None]
|
|
218
|
-
ss_res = (w * inp.error**2).sum(0)
|
|
219
229
|
mean = inp.mean(inp.y_true)
|
|
220
|
-
|
|
230
|
+
dev = inp.y_true - mean
|
|
231
|
+
if inp.weight is None: # no array of unit weights to multiply by
|
|
232
|
+
ss_res = inp.sq_error.sum(0)
|
|
233
|
+
ss_tot = (dev * dev).sum(0)
|
|
234
|
+
else:
|
|
235
|
+
w = inp.weight[:, None]
|
|
236
|
+
ss_res = (w * inp.sq_error).sum(0)
|
|
237
|
+
ss_tot = (w * dev * dev).sum(0)
|
|
221
238
|
out = np.empty_like(ss_res)
|
|
222
239
|
const = ss_tot == 0
|
|
223
240
|
out[~const] = 1 - ss_res[~const] / ss_tot[~const]
|
evalsuite/stats/effect.py
CHANGED
|
@@ -93,8 +93,6 @@ def cramers_v(table: ArrayLike, *, bias_correction: bool = False) -> float:
|
|
|
93
93
|
References: Cramér H. Mathematical Methods of Statistics. Princeton; 1946. Bergsma W. A bias-correction for
|
|
94
94
|
Cramér's V and Tschuprow's T. J Korean Stat Soc. 2013;42(3):323-328.
|
|
95
95
|
"""
|
|
96
|
-
from scipy import stats
|
|
97
|
-
|
|
98
96
|
t = np.asarray(table, dtype=np.float64)
|
|
99
97
|
if t.ndim != 2 or min(t.shape) < 2:
|
|
100
98
|
raise InputValidationError("Give a contingency table with at least 2 rows and 2 columns.")
|
|
@@ -103,7 +101,10 @@ def cramers_v(table: ArrayLike, *, bias_correction: bool = False) -> float:
|
|
|
103
101
|
if np.any(t.sum(axis=0) == 0) or np.any(t.sum(axis=1) == 0):
|
|
104
102
|
raise StatisticalTestError("Cramér's V is undefined when a row or column total is zero.")
|
|
105
103
|
n = t.sum()
|
|
106
|
-
|
|
104
|
+
rows, cols = t.sum(axis=1), t.sum(axis=0)
|
|
105
|
+
expected = np.outer(rows, cols) / n
|
|
106
|
+
dev = t - expected
|
|
107
|
+
chi2 = float(np.sum(dev * dev / expected)) # uncorrected Pearson χ², as scipy.stats.chi2_contingency
|
|
107
108
|
r, k = t.shape
|
|
108
109
|
if not bias_correction:
|
|
109
110
|
return float(np.sqrt(chi2 / (n * (min(r, k) - 1))))
|
|
@@ -132,16 +133,17 @@ def adjust_pvalues(
|
|
|
132
133
|
Benjamini Y, Hochberg Y. J R Stat Soc B. 1995;57(1):289-300. Benjamini Y, Yekutieli D. Ann Stat.
|
|
133
134
|
2001;29(4):1165-1188.
|
|
134
135
|
"""
|
|
135
|
-
p = to_numpy(p_values, "p_values").astype(np.float64)
|
|
136
|
+
p = to_numpy(p_values, "p_values").astype(np.float64, copy=False)
|
|
136
137
|
check_finite(p, "p_values")
|
|
137
|
-
if np.
|
|
138
|
+
if float(np.min(p)) < 0 or float(np.max(p)) > 1:
|
|
138
139
|
raise InputValidationError("p-values must be between 0 and 1.")
|
|
139
140
|
m = p.shape[0]
|
|
141
|
+
if method == "bonferroni": # no ranking needed
|
|
142
|
+
bonf: NDArray[np.float64] = np.minimum(p * m, 1.0)
|
|
143
|
+
return bonf
|
|
140
144
|
order = np.argsort(p) # ties get the same adjusted value whatever their order
|
|
141
145
|
ranked = p[order]
|
|
142
|
-
if method == "
|
|
143
|
-
adj = np.minimum(ranked * m, 1)
|
|
144
|
-
elif method == "holm":
|
|
146
|
+
if method == "holm":
|
|
145
147
|
adj = np.minimum(np.maximum.accumulate(ranked * (m - np.arange(m))), 1)
|
|
146
148
|
elif method == "hochberg":
|
|
147
149
|
scaled = ranked * (m - np.arange(m))
|