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
evalsuite/reporting.py ADDED
@@ -0,0 +1,241 @@
1
+ """Classification report: per-class precision, recall, F1, specificity and support, with averages."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import dataclass, field
7
+ from types import MappingProxyType
8
+ from typing import TYPE_CHECKING, Any, Optional, cast
9
+
10
+ import numpy as np
11
+
12
+ from .core.context import ClassificationContext
13
+ from .core.result import _fmt, _json_safe, _latex_escape, _latex_table
14
+ from .core.types import ArrayLike, ZeroDivision
15
+ from .core.validation import safe_divide, validate_zero_division
16
+
17
+ if TYPE_CHECKING:
18
+ import pandas as pd
19
+
20
+ __all__ = ["ClassificationReport", "classification_report"]
21
+
22
+ _COLUMNS = ("precision", "recall", "f1", "specificity", "support")
23
+
24
+
25
+ @dataclass(frozen=True, eq=False)
26
+ class ClassificationReport:
27
+ """Per-class rows plus summary rows (``accuracy``, ``micro avg``, ``macro avg``, ``weighted avg``)."""
28
+
29
+ target_type: str
30
+ rows: tuple[dict[str, Any], ...]
31
+ summary_rows: tuple[dict[str, Any], ...]
32
+ n_samples: int
33
+ params: Any = field(default_factory=dict)
34
+
35
+ def __post_init__(self) -> None:
36
+ object.__setattr__(self, "rows", tuple(MappingProxyType(dict(r)) for r in self.rows))
37
+ object.__setattr__(self, "summary_rows", tuple(MappingProxyType(dict(r)) for r in self.summary_rows))
38
+ object.__setattr__(self, "params", MappingProxyType(dict(self.params)))
39
+
40
+ def __getitem__(self, label: Any) -> Any:
41
+ """Row for a class label or a summary name (``"macro avg"``)."""
42
+ for row in (*self.rows, *self.summary_rows):
43
+ if row["label"] == label:
44
+ return row
45
+ raise KeyError(f"No row {label!r}. Labels: {[r['label'] for r in self.rows]}.")
46
+
47
+ def _table(self, digits: int) -> tuple[list[str], list[list[str]]]:
48
+ header = ["", "precision", "recall", "f1", "specificity", "support"]
49
+ out = []
50
+ for row in (*self.rows, *self.summary_rows):
51
+ cells = [str(row["label"])]
52
+ for col in _COLUMNS:
53
+ v = row.get(col)
54
+ if v is None:
55
+ cells.append("")
56
+ elif col == "support":
57
+ cells.append(str(int(v)) if float(v).is_integer() else _fmt(v, 2))
58
+ else:
59
+ cells.append(_fmt(v, digits))
60
+ out.append(cells)
61
+ return header, out
62
+
63
+ def summary(self, *, digits: int = 4) -> str:
64
+ """Fixed-width text table, like scikit-learn's report plus a specificity column."""
65
+ header, rows = self._table(digits)
66
+ widths = [max(len(header[i]), *(len(r[i]) for r in rows)) for i in range(len(header))]
67
+
68
+ def fmt(cells: list[str]) -> str:
69
+ return " ".join(c.ljust(widths[i]) if i == 0 else c.rjust(widths[i]) for i, c in enumerate(cells))
70
+
71
+ lines = [fmt(header), ""]
72
+ for i, r in enumerate(rows):
73
+ if i == len(self.rows):
74
+ lines.append("")
75
+ lines.append(fmt(r))
76
+ return "\n".join(lines)
77
+
78
+ def __repr__(self) -> str:
79
+ return self.summary()
80
+
81
+ def to_dict(self) -> dict[str, Any]:
82
+ return cast(
83
+ "dict[str, Any]",
84
+ _json_safe(
85
+ {
86
+ "target_type": self.target_type,
87
+ "n_samples": self.n_samples,
88
+ "params": dict(self.params),
89
+ "classes": [dict(r) for r in self.rows],
90
+ "summary": [dict(r) for r in self.summary_rows],
91
+ }
92
+ ),
93
+ )
94
+
95
+ def to_json(self, *, indent: Optional[int] = 2) -> str:
96
+ return json.dumps(self.to_dict(), indent=indent, allow_nan=False)
97
+
98
+ def to_dataframe(self) -> pd.DataFrame:
99
+ import pandas as pd
100
+
101
+ frame: pd.DataFrame = pd.DataFrame([dict(r) for r in (*self.rows, *self.summary_rows)]).set_index("label")
102
+ return frame
103
+
104
+ def to_csv(self, path: Optional[str] = None) -> str:
105
+ from .core.export import csv_text
106
+
107
+ rows = [
108
+ [r["label"], *(r.get(c) if r.get(c) is not None else float("nan") for c in _COLUMNS)]
109
+ for r in (*self.rows, *self.summary_rows)
110
+ ]
111
+ text = csv_text(["label", *_COLUMNS], rows)
112
+ if path is not None:
113
+ with open(path, "w", encoding="utf-8", newline="") as fh:
114
+ fh.write(text)
115
+ return text
116
+
117
+ def to_markdown(self, *, digits: int = 4) -> str:
118
+ header, rows = self._table(digits)
119
+ header[0] = "Class"
120
+ lines = ["| " + " | ".join(header) + " |", "| --- |" + " ---: |" * (len(header) - 1)]
121
+ lines += ["| " + " | ".join(r) + " |" for r in rows]
122
+ return "\n".join(lines)
123
+
124
+ def to_latex(self, *, digits: int = 4, caption: Optional[str] = None, label: Optional[str] = None) -> str:
125
+ header, rows = self._table(digits)
126
+ header = ["Class", "Precision", "Recall", "F1", "Specificity", "Support"]
127
+ return _latex_table(
128
+ header,
129
+ [[_latex_escape(c) for c in r] for r in rows],
130
+ caption=caption or "Classification report.",
131
+ label=label,
132
+ )
133
+
134
+ def to_html(self, *, digits: int = 4, caption: Optional[str] = None, full: bool = False) -> str:
135
+ from .core.export import html_document, html_table
136
+
137
+ header, rows = self._table(digits)
138
+ header[0] = "Class"
139
+ classes = [""] * len(self.rows) + ["avg"] * len(self.summary_rows)
140
+ table = html_table(header, rows, caption=caption or "Classification report", row_classes=classes)
141
+ meta = f"{self.target_type}, n = {self.n_samples}"
142
+ return html_document("EvalSuite classification report", table, meta) if full else table
143
+
144
+ def save(self, path: str, *, digits: int = 4) -> str:
145
+ """Save as .json .csv .md .tex .html or .txt (chosen by the extension)."""
146
+ from .core.export import save_as
147
+
148
+ return save_as(
149
+ path,
150
+ {
151
+ "json": self.to_json,
152
+ "csv": self.to_csv,
153
+ "markdown": lambda: self.to_markdown(digits=digits) + "\n",
154
+ "latex": lambda: self.to_latex(digits=digits) + "\n",
155
+ "html": lambda: self.to_html(digits=digits, full=True),
156
+ "text": lambda: self.summary(digits=digits) + "\n",
157
+ },
158
+ )
159
+
160
+
161
+ def classification_report(
162
+ y_true: ArrayLike,
163
+ y_pred: ArrayLike,
164
+ *,
165
+ labels: Optional[ArrayLike] = None,
166
+ sample_weight: Optional[ArrayLike] = None,
167
+ zero_division: ZeroDivision = "warn",
168
+ ) -> ClassificationReport:
169
+ """Per-class precision, recall, F1, specificity and support, plus accuracy (single-label targets),
170
+ micro (multilabel), macro and support-weighted averages. Values match scikit-learn's
171
+ ``classification_report`` where both define them; specificity is EvalSuite's addition.
172
+
173
+ >>> import evalsuite as es
174
+ >>> print(es.classification_report([0, 1, 1, 2], [0, 1, 2, 2])) # doctest: +SKIP
175
+ """
176
+ zd = validate_zero_division(zero_division)
177
+ ctx = ClassificationContext(y_true, y_pred, labels=labels, sample_weight=sample_weight)
178
+ c = ctx.counts
179
+ tp, fp, fn, tn, support = c["tp"], c["fp"], c["fn"], c["tn"], c["support"]
180
+ prec = safe_divide(tp, tp + fp, zero_division=zd, metric="Precision")
181
+ rec = safe_divide(tp, tp + fn, zero_division=zd, metric="Recall")
182
+ f1 = safe_divide(2 * tp, 2 * tp + fp + fn, zero_division=zd, metric="F1")
183
+ spec = safe_divide(tn, tn + fp, zero_division=zd, metric="Specificity")
184
+ rows = [
185
+ {
186
+ "label": lab,
187
+ "precision": float(p),
188
+ "recall": float(r),
189
+ "f1": float(f),
190
+ "specificity": float(s),
191
+ "support": float(n),
192
+ }
193
+ for lab, p, r, f, s, n in zip(ctx.labels.tolist(), prec, rec, f1, spec, support)
194
+ ]
195
+ total = float(support.sum())
196
+ summary: list[dict[str, Any]] = []
197
+ if ctx.target_type == "multilabel":
198
+ tps, fps, fns, tns = tp.sum(), fp.sum(), fn.sum(), tn.sum()
199
+ summary.append(
200
+ {
201
+ "label": "micro avg",
202
+ "precision": float(safe_divide(tps, tps + fps, zero_division=zd, metric="Precision")),
203
+ "recall": float(safe_divide(tps, tps + fns, zero_division=zd, metric="Recall")),
204
+ "f1": float(safe_divide(2 * tps, 2 * tps + fps + fns, zero_division=zd, metric="F1")),
205
+ "specificity": float(safe_divide(tns, tns + fps, zero_division=zd, metric="Specificity")),
206
+ "support": total,
207
+ }
208
+ )
209
+ else:
210
+ correct = float(np.trace(ctx.confusion_matrix))
211
+ summary.append(
212
+ {
213
+ "label": "accuracy",
214
+ "precision": None,
215
+ "recall": None,
216
+ "f1": correct / ctx.total_weight,
217
+ "specificity": None,
218
+ "support": ctx.total_weight,
219
+ }
220
+ )
221
+ stacked = np.vstack([prec, rec, f1, spec])
222
+ macro = stacked.mean(axis=1)
223
+ weighted = (stacked * support).sum(axis=1) / total if total > 0 else np.full(4, np.nan)
224
+ for name, vals in (("macro avg", macro), ("weighted avg", weighted)):
225
+ summary.append(
226
+ {
227
+ "label": name,
228
+ "precision": float(vals[0]),
229
+ "recall": float(vals[1]),
230
+ "f1": float(vals[2]),
231
+ "specificity": float(vals[3]),
232
+ "support": total,
233
+ }
234
+ )
235
+ return ClassificationReport(
236
+ ctx.target_type,
237
+ tuple(rows),
238
+ tuple(summary),
239
+ ctx.n,
240
+ {"zero_division": zero_division, "weighted": sample_weight is not None},
241
+ )
@@ -0,0 +1,46 @@
1
+ """Statistical evaluation: confidence intervals, paired tests, effect sizes, multiple comparisons, compare()."""
2
+
3
+ from .compare import ComparisonResult, compare
4
+ from .effect import adjust_pvalues, cliffs_delta, cohens_d, cramers_v, hedges_g
5
+ from .hypothesis import (
6
+ chi_square_test,
7
+ fisher_exact_test,
8
+ friedman_test,
9
+ kruskal_wallis_test,
10
+ mann_whitney_test,
11
+ paired_t_test,
12
+ shapiro_wilk_test,
13
+ t_test,
14
+ wilcoxon_test,
15
+ )
16
+ from .intervals import accuracy_ci, bootstrap_ci, proportion_ci, roc_auc_ci
17
+ from .paired import delong_test, mcnemar_test, paired_bootstrap_test
18
+ from .results import ConfidenceInterval, TestResult
19
+
20
+ __all__ = [
21
+ "ComparisonResult",
22
+ "ConfidenceInterval",
23
+ "TestResult",
24
+ "accuracy_ci",
25
+ "adjust_pvalues",
26
+ "bootstrap_ci",
27
+ "chi_square_test",
28
+ "cramers_v",
29
+ "fisher_exact_test",
30
+ "friedman_test",
31
+ "kruskal_wallis_test",
32
+ "mann_whitney_test",
33
+ "paired_t_test",
34
+ "shapiro_wilk_test",
35
+ "t_test",
36
+ "wilcoxon_test",
37
+ "cliffs_delta",
38
+ "cohens_d",
39
+ "compare",
40
+ "delong_test",
41
+ "hedges_g",
42
+ "mcnemar_test",
43
+ "paired_bootstrap_test",
44
+ "proportion_ci",
45
+ "roc_auc_ci",
46
+ ]
@@ -0,0 +1,229 @@
1
+ """Resolve metric names to functions and call them on index subsets."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import inspect
7
+ from collections.abc import Callable, Mapping
8
+ from typing import Any, Optional
9
+
10
+ import numpy as np
11
+ from numpy.typing import NDArray
12
+
13
+ from .._native import array_view, core
14
+ from ..core.exceptions import InputValidationError, StatisticalTestError
15
+ from ..core.validation import target_type, to_numpy
16
+
17
+ MetricFn = Callable[..., Any]
18
+
19
+ # Label metrics computed from the confusion matrix alone, all accepting sample_weight: on a resample they equal
20
+ # the same metric on the resample's distinct (true, predicted) pairs weighted by how often each occurs (tested
21
+ # bit for bit in tests/stats/test_resample_compression.py).
22
+ _CONFUSION_METRICS = frozenset(
23
+ {
24
+ "accuracy",
25
+ "balanced_accuracy",
26
+ "cohen_kappa",
27
+ "f1",
28
+ "fbeta",
29
+ "jaccard",
30
+ "mcc",
31
+ "npv",
32
+ "precision",
33
+ "recall",
34
+ "specificity",
35
+ }
36
+ )
37
+ _MAX_COMPRESSED_CLASSES = 64
38
+
39
+
40
+ def resolve_metric(metric: Any) -> tuple[MetricFn, str]:
41
+ """A metric function (``es.f1``) or its name (``"f1"``, ``"classification.f1"``)."""
42
+ if callable(metric):
43
+ return metric, getattr(metric, "__name__", "metric")
44
+ if isinstance(metric, str):
45
+ import evalsuite
46
+
47
+ name = metric.split(".")[-1]
48
+ fn = getattr(evalsuite, name, None)
49
+ if callable(fn) and name in {m.split(".")[-1] for m in evalsuite.list_metrics()}:
50
+ return fn, name
51
+ raise InputValidationError(
52
+ f"Unknown metric '{metric}'. Use a metric function or a name from list_metrics()."
53
+ )
54
+ raise InputValidationError("metric must be a metric function (e.g. es.f1) or its name (e.g. 'f1').")
55
+
56
+
57
+ def as_observations(x: Any, name: str) -> NDArray[Any]:
58
+ """Observations to resample along the first axis: 1-D/2-D arrays (labels, values, probabilities), stacks of
59
+ segmentation masks (3-D or more: images first), or per-image detection dicts / differently sized masks
60
+ (held in a 1-D object array)."""
61
+ if (
62
+ isinstance(x, (list, tuple))
63
+ and x
64
+ and (isinstance(x[0], Mapping) or (np.ndim(x[0]) >= 2 and len({np.shape(m) for m in x}) > 1))
65
+ ):
66
+ out = np.empty(len(x), dtype=object)
67
+ for i, v in enumerate(x):
68
+ out[i] = v
69
+ return out
70
+ arr = np.asarray(x.to_numpy() if hasattr(x, "to_numpy") else x)
71
+ if arr.ndim > 2:
72
+ if arr.shape[0] == 0:
73
+ raise InputValidationError(f"{name} is empty. Provide at least one observation.")
74
+ return arr
75
+ return to_numpy(x, name, allow_2d=True)
76
+
77
+
78
+ def as_items(x: Any, name: str) -> NDArray[Any]:
79
+ """A 1-D object array holding one item per observation, whatever each item is."""
80
+ if x is None or isinstance(x, (str, bytes)):
81
+ raise InputValidationError(f"{name} must be a list with one item per example.")
82
+ seq = list(x.tolist() if isinstance(x, np.ndarray) and x.dtype != object and x.ndim == 1 else x)
83
+ if not seq:
84
+ raise InputValidationError(f"{name} is empty. Provide at least one observation.")
85
+ out = np.empty(len(seq), dtype=object)
86
+ for i, v in enumerate(seq):
87
+ out[i] = v
88
+ return out
89
+
90
+
91
+ def is_categorical(y: NDArray[Any]) -> bool:
92
+ if y.ndim > 2 or (y.dtype == object and y.size and not isinstance(y.flat[0], (str, bytes))):
93
+ return False
94
+ try:
95
+ return target_type(y) in ("binary", "multiclass", "multilabel")
96
+ except Exception:
97
+ return False
98
+
99
+
100
+ class MetricCall:
101
+ """Evaluate ``fn(y_true[idx], second[idx], **kwargs)`` repeatedly on index subsets."""
102
+
103
+ def __init__(
104
+ self,
105
+ fn: MetricFn,
106
+ y_true: Any,
107
+ y_pred: Any = None,
108
+ y_prob: Any = None,
109
+ sample_weight: Any = None,
110
+ kwargs: Optional[dict[str, Any]] = None,
111
+ ) -> None:
112
+ if (y_pred is None) == (y_prob is None):
113
+ raise InputValidationError(
114
+ "Pass exactly one of y_pred (label/value metrics) or y_prob (probability metrics)."
115
+ )
116
+ self.fn = fn
117
+ second = y_pred if y_pred is not None else y_prob
118
+ self.items = bool(getattr(fn, "__evalsuite_items__", False))
119
+ if self.items:
120
+ # Text, retrieval and other item-level metrics: each observation is a whole item (a string, a list
121
+ # of references, a ranked list, an embedding matrix); resample items, never stratify by value.
122
+ self.y_true = as_items(y_true, "y_true")
123
+ self.second = as_items(second, "y_pred" if y_pred is not None else "y_prob")
124
+ else:
125
+ self.y_true = as_observations(y_true, "y_true")
126
+ self.second = as_observations(second, "y_pred" if y_pred is not None else "y_prob")
127
+ if self.second.shape[0] != self.y_true.shape[0]:
128
+ raise InputValidationError(
129
+ f"y_true and {'y_pred' if y_pred is not None else 'y_prob'} must contain the same number of "
130
+ f"observations. Received {self.y_true.shape[0]} and {self.second.shape[0]}."
131
+ )
132
+ self.n = self.y_true.shape[0]
133
+ if self.n < 2:
134
+ raise StatisticalTestError(
135
+ f"Resampling needs at least 2 observations; got {self.n}. An interval or test from a single "
136
+ "observation would have zero width and no meaning."
137
+ )
138
+ self.weight = None if sample_weight is None else to_numpy(sample_weight, "sample_weight")
139
+ self.kwargs = dict(kwargs or {})
140
+ params = inspect.signature(fn).parameters
141
+ self.categorical = not self.items and is_categorical(self.y_true)
142
+ # Keep every class in every resample so per-class and averaged metrics stay comparable.
143
+ if self.categorical and "labels" in params and "labels" not in self.kwargs and self.y_true.ndim == 1:
144
+ present = self.y_true if y_pred is None else np.concatenate([self.y_true, self.second])
145
+ with contextlib.suppress(TypeError): # incomparable labels: the metric reports it
146
+ self.kwargs["labels"] = np.unique(present)
147
+ if self.weight is not None and "sample_weight" not in params:
148
+ raise InputValidationError(f"{getattr(fn, '__name__', 'This metric')} does not accept sample_weight.")
149
+ self._codes: Optional[NDArray[np.uint32]] = None
150
+ self._labels: Optional[NDArray[Any]] = None
151
+ self._k = 0
152
+ if y_pred is not None:
153
+ self._setup_compression()
154
+
155
+ def _setup_compression(self) -> None:
156
+ """Enable counting-based evaluation for confusion-matrix metrics on unweighted 1-D labels: each
157
+ observation becomes one code (true class × k + predicted class), and a resample is summarised by how
158
+ often each code occurs, so the metric runs on at most k² weighted pairs instead of n observations."""
159
+ fn = self.fn
160
+ if (
161
+ getattr(fn, "__module__", "") != "evalsuite.classification.metrics"
162
+ or getattr(fn, "__name__", "") not in _CONFUSION_METRICS
163
+ or self.weight is not None
164
+ or not self.categorical
165
+ or self.y_true.ndim != 1
166
+ or self.second.ndim != 1
167
+ or self.y_true.dtype != self.second.dtype
168
+ or self.y_true.dtype.kind not in "biuU"
169
+ ):
170
+ return
171
+ try:
172
+ labels = np.unique(np.concatenate([self.y_true, self.second]))
173
+ except TypeError: # pragma: no cover - same-dtype arrays are comparable
174
+ return
175
+ k = labels.shape[0]
176
+ if k > _MAX_COMPRESSED_CLASSES:
177
+ return
178
+ t = np.searchsorted(labels, self.y_true)
179
+ p = np.searchsorted(labels, self.second)
180
+ self._codes = (t * k + p).astype(np.uint32)
181
+ self._labels = labels
182
+ self._k = k
183
+
184
+ @property
185
+ def compressible(self) -> bool:
186
+ return self._codes is not None
187
+
188
+ def code_counts(self, idx: NDArray[np.int64]) -> NDArray[np.int64]:
189
+ """How often each (true, predicted) code occurs among the observations ``idx``."""
190
+ if self._codes is None: # pragma: no cover - guarded by callers
191
+ raise RuntimeError("not compressible")
192
+ return np.bincount(self._codes[idx], minlength=self._k * self._k)
193
+
194
+ def batch_code_counts(self, indices: NDArray[np.int64]) -> Optional[NDArray[np.uint64]]:
195
+ """Code counts for every row of ``indices`` at once (compiled core), or None without it."""
196
+ if self._codes is None or core is None or indices.ndim != 2 or indices.shape[0] == 0:
197
+ return None
198
+ kk = self._k * self._k
199
+ codes, codes_v = array_view(self._codes, np.uint32)
200
+ idx, idx_v = array_view(indices, np.int64) # resample indices are int64 already: no copy
201
+ raw = core.code_counts(codes_v, kk, idx_v, idx.shape[0])
202
+ del codes, idx
203
+ counts: NDArray[np.uint64] = np.frombuffer(raw, dtype=np.uint64).reshape(indices.shape[0], kk)
204
+ return counts
205
+
206
+ def from_counts(self, counts: NDArray[Any], idx: Optional[NDArray[np.int64]] = None) -> float:
207
+ """The metric on observations summarised by ``counts`` (equal to calling it on them directly)."""
208
+ if self._labels is None: # pragma: no cover - guarded by callers
209
+ raise RuntimeError("not compressible")
210
+ nz = np.flatnonzero(counts)
211
+ if nz.shape[0] < 2 and idx is not None:
212
+ return self(idx, compress=False) # a single distinct pair: use the observations themselves
213
+ k = self._k
214
+ kw = dict(self.kwargs)
215
+ kw["sample_weight"] = counts[nz].astype(np.float64)
216
+ return float(self.fn(self._labels[nz // k], self._labels[nz % k], **kw))
217
+
218
+ def __call__(self, idx: Optional[NDArray[np.int64]] = None, *, compress: bool = True) -> float:
219
+ if compress and idx is not None and self._codes is not None:
220
+ return self.from_counts(self.code_counts(idx), idx)
221
+ if idx is None:
222
+ yt, s, w = self.y_true, self.second, self.weight
223
+ else:
224
+ yt, s = self.y_true[idx], self.second[idx]
225
+ w = None if self.weight is None else self.weight[idx]
226
+ kw = dict(self.kwargs)
227
+ if w is not None:
228
+ kw["sample_weight"] = w
229
+ return float(self.fn(yt, s, **kw))