metric-diff 0.1.0a1__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.
@@ -0,0 +1,670 @@
1
+ """Adapters that call each metric library the way a user would.
2
+
3
+ Every backend receives already-prepared numpy arrays:
4
+
5
+ * ``y_true``: int64 labels
6
+ * ``y_pred``: int64 labels (1-D) or float scores (1-D binary, 2-D multiclass)
7
+
8
+ ``opts`` holds settings that metric-diff aligns while looking for a cause.
9
+ An empty ``opts`` means "call the library with its own defaults". Known keys:
10
+
11
+ * ``average``: averaging for multiclass metrics
12
+ * ``threshold``: decision threshold for binary label metrics
13
+ * ``multi_class``: sklearn multiclass AUROC strategy
14
+ * ``exact_thresholds``: Keras AUC uses every distinct score as a threshold (not 200 bins)
15
+ * ``pr_summation``: Keras PR-AUC summation method ("majoring" equals average precision)
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import importlib.util
21
+ import os
22
+ import sys
23
+ import warnings
24
+ from typing import Callable
25
+
26
+ import numpy as np
27
+
28
+ from .inputs import LABEL_METRICS
29
+
30
+ # What each library does when you don't pass `average` (multiclass).
31
+ # Used in explanations; tests check it against the installed versions.
32
+ DEFAULT_AVERAGE: dict[str, dict[str, str]] = {
33
+ "sklearn": {
34
+ "accuracy": "micro (accuracy_score has no `average`)",
35
+ "precision": "'binary' (raises an error on multiclass data)",
36
+ "recall": "'binary' (raises an error on multiclass data)",
37
+ "f1": "'binary' (raises an error on multiclass data)",
38
+ "auroc": "'macro', but multi_class='raise' (raises an error on multiclass data)",
39
+ "average_precision": "'macro'",
40
+ },
41
+ "torchmetrics": {
42
+ "accuracy": "'macro' (macro accuracy = sklearn balanced_accuracy_score)",
43
+ "precision": "'macro'",
44
+ "recall": "'macro'",
45
+ "f1": "'macro'",
46
+ "auroc": "'macro'",
47
+ "average_precision": "'macro'",
48
+ },
49
+ "torcheval": {
50
+ "accuracy": "'micro'",
51
+ "precision": "'micro'",
52
+ "recall": "'micro'",
53
+ "f1": "'micro'",
54
+ "auroc": "'macro'",
55
+ "average_precision": "'macro'",
56
+ },
57
+ "keras": {
58
+ "accuracy": "micro (CategoricalAccuracy)",
59
+ "precision": "Precision() thresholds every class column at 0.5 like multi-label data, not argmax",
60
+ "recall": "Recall() thresholds every class column at 0.5 like multi-label data, not argmax",
61
+ "f1": "F1Score(average=None) returns one score per class",
62
+ "auroc": "AUC() flattens all classes into one binary problem (micro), using 200 thresholds",
63
+ "average_precision": "AUC(curve='PR') flattens all classes into one binary problem",
64
+ },
65
+ "evaluate": {
66
+ "accuracy": "micro (wraps sklearn accuracy_score)",
67
+ "precision": "'binary' (wraps sklearn; raises an error on multiclass data)",
68
+ "recall": "'binary' (wraps sklearn; raises an error on multiclass data)",
69
+ "f1": "'binary' (wraps sklearn; raises an error on multiclass data)",
70
+ "auroc": "needs evaluate.load('roc_auc', 'multiclass') and multi_class='ovr'",
71
+ "average_precision": "no such metric",
72
+ },
73
+ }
74
+
75
+ _ALL3 = {"micro", "macro", "weighted"}
76
+ # Which `average` values each library accepts for multiclass data (checked by a test).
77
+ SUPPORTED_AVERAGES: dict[str, dict[str, set[str]]] = {
78
+ "sklearn": {"accuracy": {"micro", "macro"}, "precision": _ALL3, "recall": _ALL3, "f1": _ALL3,
79
+ "auroc": _ALL3, "average_precision": _ALL3},
80
+ "torchmetrics": {"accuracy": _ALL3, "precision": _ALL3, "recall": _ALL3, "f1": _ALL3,
81
+ "auroc": {"macro", "weighted"}, "average_precision": {"macro", "weighted"}},
82
+ "torcheval": {"accuracy": {"micro", "macro"}, "precision": _ALL3, "recall": _ALL3, "f1": _ALL3,
83
+ "auroc": {"macro"}, "average_precision": {"macro"}},
84
+ "keras": {"accuracy": {"micro"}, "precision": {"micro", "macro"}, "recall": {"micro", "macro"},
85
+ "f1": _ALL3, "auroc": {"macro"}, "average_precision": {"macro"}},
86
+ "evaluate": {"accuracy": {"micro"}, "precision": _ALL3, "recall": _ALL3, "f1": _ALL3,
87
+ "auroc": _ALL3},
88
+ }
89
+
90
+ _TORCH_NAMES = {
91
+ "accuracy": "Accuracy", "precision": "Precision", "recall": "Recall",
92
+ "f1": "F1Score", "auroc": "AUROC",
93
+ }
94
+
95
+
96
+ TASKS = ("classification", "regression", "segmentation")
97
+
98
+
99
+ def task_family(task: str) -> str:
100
+ return "classification" if task in ("binary", "multiclass") else task
101
+
102
+
103
+ class Backend:
104
+ name: str = ""
105
+ module: str = ""
106
+ tasks: tuple = TASKS # which kinds of metrics this library is compared on by default
107
+
108
+ def available(self) -> bool:
109
+ return importlib.util.find_spec(self.module) is not None
110
+
111
+ def compute(self, metric: str, task: str, y_true: np.ndarray, y_pred: np.ndarray,
112
+ num_classes: int, opts: dict) -> float:
113
+ raise NotImplementedError
114
+
115
+ def stateful(self, metric: str, task: str, num_classes: int, opts: dict):
116
+ """Return an object with ``update(y_true, y_pred)`` and ``compute() -> float``,
117
+ or None if the library has no accumulating metric objects."""
118
+ return None
119
+
120
+ def unsupported(self, metric: str, task: str, opts: dict) -> str | None:
121
+ """Why this library can't honour a requested setting (beyond `average`), or None."""
122
+ return None
123
+
124
+ def version(self) -> str:
125
+ try:
126
+ from importlib.metadata import version
127
+
128
+ return version({"sklearn": "scikit-learn"}.get(self.module, self.module))
129
+ except Exception: # pragma: no cover
130
+ return "?"
131
+
132
+
133
+ class SklearnBackend(Backend):
134
+ """scikit-learn, the reference implementation.
135
+
136
+ sklearn's label metrics need hard labels, so scores are turned into labels the way most
137
+ users do it: ``y_pred >= threshold`` (default 0.5) for binary, ``argmax`` for multiclass.
138
+ """
139
+
140
+ name = "sklearn"
141
+ module = "sklearn"
142
+
143
+ def compute(self, metric, task, y_true, y_pred, num_classes, opts):
144
+ import sklearn.metrics as skm
145
+
146
+ if task == "regression":
147
+ if metric == "rmse":
148
+ return float(np.sqrt(skm.mean_squared_error(y_true, y_pred)))
149
+ fn = {"r2": skm.r2_score, "mae": skm.mean_absolute_error, "mse": skm.mean_squared_error,
150
+ "mape": skm.mean_absolute_percentage_error}[metric]
151
+ return float(fn(y_true, y_pred))
152
+
153
+ avg = opts.get("average")
154
+ if metric == "accuracy" and opts.get("top_k"):
155
+ return float(skm.top_k_accuracy_score(y_true, y_pred, k=opts["top_k"],
156
+ labels=list(range(num_classes))))
157
+ if metric in LABEL_METRICS:
158
+ if y_pred.dtype.kind == "f":
159
+ if y_pred.ndim == 1:
160
+ y_pred = (y_pred >= opts.get("threshold", 0.5)).astype(np.int64)
161
+ else:
162
+ y_pred = y_pred.argmax(axis=1)
163
+ if metric == "accuracy":
164
+ if avg in (None, "micro"):
165
+ return float(skm.accuracy_score(y_true, y_pred))
166
+ if avg == "macro":
167
+ return float(skm.balanced_accuracy_score(y_true, y_pred))
168
+ raise ValueError(f"sklearn has no accuracy with average={avg!r}")
169
+ fn = {"precision": skm.precision_score, "recall": skm.recall_score,
170
+ "f1": skm.f1_score}[metric]
171
+ kw = {"average": avg} if avg else {}
172
+ if task == "multiclass" and opts.get("explicit_classes"):
173
+ kw["labels"] = list(range(num_classes)) # how sklearn users say "there are C classes"
174
+ zd = opts.get("zero_division", 0) # sklearn's default "warn" behaves as 0
175
+ return float(fn(y_true, y_pred, zero_division=np.nan if zd == "nan" else zd, **kw))
176
+
177
+ if metric == "auroc":
178
+ if task == "binary":
179
+ return float(skm.roc_auc_score(y_true, y_pred))
180
+ if num_classes == 2 and opts.get("multi_class", "raise") != "raise":
181
+ # Two score columns (a binary model with a softmax head): sklearn wants the
182
+ # positive-class column. One-vs-rest AUROC is the same for both columns.
183
+ return float(skm.roc_auc_score(y_true, y_pred[:, 1]))
184
+ kw = {"average": avg} if avg else {}
185
+ return float(skm.roc_auc_score(
186
+ y_true, y_pred, multi_class=opts.get("multi_class", "raise"),
187
+ labels=list(range(num_classes)), **kw))
188
+
189
+ if metric == "average_precision":
190
+ if task == "binary":
191
+ return float(skm.average_precision_score(y_true, y_pred))
192
+ kw = {"average": avg} if avg else {}
193
+ onehot = np.eye(num_classes, dtype=np.int64)[y_true]
194
+ return float(skm.average_precision_score(onehot, y_pred, **kw))
195
+
196
+ raise ValueError(metric) # pragma: no cover
197
+
198
+ def unsupported(self, metric, task, opts):
199
+ if opts.get("top_k") and opts.get("average") not in (None, "micro"):
200
+ return "top_k_accuracy_score has no `average` (micro only)"
201
+ return None
202
+
203
+
204
+ def _tensors(y_true, y_pred):
205
+ import torch
206
+
207
+ target = torch.as_tensor(y_true, dtype=torch.long)
208
+ if y_pred.dtype.kind == "f":
209
+ preds = torch.as_tensor(y_pred, dtype=torch.float32)
210
+ else:
211
+ preds = torch.as_tensor(y_pred, dtype=torch.long)
212
+ return target, preds
213
+
214
+
215
+ def _float_tensors(y_true, y_pred):
216
+ """Regression inputs in float32, the dtype people train and evaluate in."""
217
+ import torch
218
+
219
+ return (torch.as_tensor(y_true, dtype=torch.float32),
220
+ torch.as_tensor(y_pred, dtype=torch.float32))
221
+
222
+
223
+ def _torch_kwargs(metric, task, num_classes, opts, lib="torchmetrics"):
224
+ kw = {}
225
+ if task == "binary":
226
+ if metric in LABEL_METRICS and "threshold" in opts:
227
+ kw["threshold"] = opts["threshold"]
228
+ else:
229
+ kw["num_classes"] = num_classes
230
+ if "average" in opts:
231
+ kw["average"] = opts["average"]
232
+ if metric == "accuracy" and opts.get("top_k"):
233
+ kw["top_k" if lib == "torchmetrics" else "k"] = opts["top_k"]
234
+ if lib == "torchmetrics" and metric in ("precision", "recall", "f1") and "zero_division" in opts:
235
+ kw["zero_division"] = opts["zero_division"]
236
+ return kw
237
+
238
+
239
+ def _r2_force_finite(value, y_true, y_pred):
240
+ """What sklearn's force_finite=True does for a constant target: 1.0 if perfect, else 0.0."""
241
+ if value != value or value in (float("inf"), float("-inf")):
242
+ return 1.0 if np.allclose(y_true, y_pred) else 0.0
243
+ return value
244
+
245
+
246
+ def _always_zero_division(lib, metric, opts):
247
+ if metric in ("precision", "recall", "f1") and opts.get("zero_division", 0) != 0:
248
+ return f"{lib} has no zero_division setting (always 0)"
249
+ return None
250
+
251
+
252
+ class _TorchStateful:
253
+ """Wraps a torchmetrics / torcheval metric object."""
254
+
255
+ def __init__(self, obj, metric, regression=False):
256
+ self.obj, self.metric, self.regression = obj, metric, regression
257
+
258
+ def update(self, y_true, y_pred):
259
+ if self.regression:
260
+ target, preds = _float_tensors(y_true, y_pred)
261
+ self.obj.update(preds, target)
262
+ return
263
+ target, preds = _tensors(y_true, y_pred)
264
+ if self.metric not in LABEL_METRICS:
265
+ preds = preds.float()
266
+ self.obj.update(preds, target) # both libraries take (preds/input, target)
267
+
268
+ def compute(self) -> float:
269
+ return float(self.obj.compute())
270
+
271
+
272
+ class TorchmetricsBackend(Backend):
273
+ name = "torchmetrics"
274
+ module = "torchmetrics"
275
+
276
+ def compute(self, metric, task, y_true, y_pred, num_classes, opts):
277
+ if task == "regression":
278
+ import torchmetrics.functional as R
279
+
280
+ target, preds = _float_tensors(y_true, y_pred)
281
+ if metric == "rmse":
282
+ return float(R.mean_squared_error(preds, target, squared=False))
283
+ fn = {"r2": R.r2_score, "mae": R.mean_absolute_error, "mse": R.mean_squared_error,
284
+ "mape": R.mean_absolute_percentage_error}[metric]
285
+ return float(fn(preds, target))
286
+
287
+ import torchmetrics.functional.classification as F
288
+
289
+ target, preds = _tensors(y_true, y_pred)
290
+ if metric not in LABEL_METRICS:
291
+ preds = preds.float()
292
+ name = {"f1": "f1_score", "auroc": "auroc"}.get(metric, metric)
293
+ fn = getattr(F, f"{task}_{name}")
294
+ return float(fn(preds, target, **_torch_kwargs(metric, task, num_classes, opts)))
295
+
296
+ def stateful(self, metric, task, num_classes, opts):
297
+ if task == "regression":
298
+ import torchmetrics.regression as R
299
+
300
+ if metric == "r2":
301
+ obj = R.R2Score()
302
+ elif metric == "rmse":
303
+ obj = R.MeanSquaredError(squared=False)
304
+ else:
305
+ obj = {"mae": R.MeanAbsoluteError, "mse": R.MeanSquaredError,
306
+ "mape": R.MeanAbsolutePercentageError}[metric]()
307
+ return _TorchStateful(obj, metric, regression=True)
308
+
309
+ import torchmetrics.classification as C
310
+
311
+ cls_name = _TORCH_NAMES.get(metric, "AveragePrecision")
312
+ cls = getattr(C, f"{task.capitalize()}{cls_name}")
313
+ return _TorchStateful(cls(**_torch_kwargs(metric, task, num_classes, opts)), metric)
314
+
315
+ def unsupported(self, metric, task, opts):
316
+ if opts.get("zero_division") == "nan":
317
+ return "zero_division must be 0 or 1 in torchmetrics"
318
+ return None
319
+
320
+
321
+ class TorchevalBackend(Backend):
322
+ name = "torcheval"
323
+ module = "torcheval"
324
+ tasks = ("classification", "regression")
325
+
326
+ def compute(self, metric, task, y_true, y_pred, num_classes, opts):
327
+ import torcheval.metrics.functional as F
328
+
329
+ if task == "regression":
330
+ target, preds = _float_tensors(y_true, y_pred)
331
+ fn = {"r2": F.r2_score, "mse": F.mean_squared_error}[metric]
332
+ value = float(fn(preds, target))
333
+ return _r2_force_finite(value, y_true, y_pred) if metric == "r2" and opts.get("r2_force_finite") else value
334
+
335
+ target, preds = _tensors(y_true, y_pred)
336
+ if metric not in LABEL_METRICS:
337
+ preds = preds.float()
338
+ name = {"f1": "f1_score", "average_precision": "auprc"}.get(metric, metric)
339
+ fn = getattr(F, f"{task}_{name}")
340
+ return float(fn(preds, target, **_torch_kwargs(metric, task, num_classes, opts, "torcheval")))
341
+
342
+ def stateful(self, metric, task, num_classes, opts):
343
+ import torcheval.metrics as M
344
+
345
+ if task == "regression":
346
+ obj = {"r2": M.R2Score, "mse": M.MeanSquaredError}[metric]()
347
+ return _TorchStateful(obj, metric, regression=True)
348
+
349
+ cls_name = {"average_precision": "AUPRC"}.get(metric, _TORCH_NAMES.get(metric))
350
+ cls = getattr(M, f"{task.capitalize()}{cls_name}")
351
+ return _TorchStateful(cls(**_torch_kwargs(metric, task, num_classes, opts, "torcheval")), metric)
352
+
353
+ def unsupported(self, metric, task, opts):
354
+ if task == "regression" and metric not in ("r2", "mse"):
355
+ return f"torcheval has no {metric} metric"
356
+ return _always_zero_division("torcheval", metric, opts)
357
+
358
+
359
+ _MAX_KERAS_THRESHOLDS = 5000
360
+ _KERAS_CHUNK = 4096
361
+
362
+
363
+ def _ensure_keras_backend() -> None:
364
+ """Use Keras' torch backend when TensorFlow isn't installed, without overriding a user choice."""
365
+ if "keras" in sys.modules or "KERAS_BACKEND" in os.environ:
366
+ return
367
+ if importlib.util.find_spec("tensorflow") is None and importlib.util.find_spec("torch") is not None:
368
+ os.environ["KERAS_BACKEND"] = "torch"
369
+
370
+
371
+ class _KerasStateful:
372
+ def __init__(self, objs, metric, task, num_classes, opts):
373
+ self.objs, self.metric, self.task = objs, metric, task
374
+ self.num_classes, self.opts = num_classes, opts
375
+
376
+ def _arrays(self, y_true, y_pred):
377
+ if self.task == "regression":
378
+ yt, yp = y_true.astype(np.float32), y_pred.astype(np.float32)
379
+ if yt.ndim == 1 and (self.metric == "r2" or self.opts.get("column_vector")):
380
+ yt, yp = yt[:, None], yp[:, None] # R2Score needs (n, outputs); keep the user's shape
381
+ return yt, yp
382
+ if self.task == "binary":
383
+ yt = y_true.astype(np.float32)
384
+ yp = y_pred.astype(np.float32)
385
+ if self.metric == "f1": # F1Score needs (n, 1)
386
+ yt, yp = yt[:, None], yp[:, None]
387
+ return yt, yp
388
+ yt = np.eye(self.num_classes, dtype=np.float32)[y_true]
389
+ yp = (np.eye(self.num_classes, dtype=np.float32)[y_pred] if y_pred.ndim == 1
390
+ else y_pred.astype(np.float32))
391
+ return yt, yp
392
+
393
+ def update(self, y_true, y_pred):
394
+ yt, yp = self._arrays(y_true, y_pred)
395
+ for start in range(0, len(yt), _KERAS_CHUNK): # AUC memory is thresholds x samples
396
+ sl = slice(start, start + _KERAS_CHUNK)
397
+ for o in self.objs:
398
+ o.update_state(yt[sl], yp[sl])
399
+
400
+ def compute(self) -> float:
401
+ import keras
402
+
403
+ values = [np.asarray(keras.ops.convert_to_numpy(o.result()), dtype=np.float64) for o in self.objs]
404
+ if len(values) > 1: # per-class objects for macro precision/recall
405
+ return float(np.mean([v.item() for v in values]))
406
+ v = values[0]
407
+ if v.size != 1:
408
+ raise ValueError(f"returned {v.size} values, one per class (average=None by default)")
409
+ value = float(v.item())
410
+ if self.metric == "mape" and self.opts.get("mape_fraction"):
411
+ value /= 100.0
412
+ return value
413
+
414
+
415
+ class KerasBackend(Backend):
416
+ """Keras 3 metrics (any Keras backend; torch is used when TensorFlow isn't installed).
417
+
418
+ Keras metric objects are stateful, so ``compute`` is a single ``update_state`` + ``result``.
419
+ Multiclass y_true is one-hot encoded, as Keras expects.
420
+ """
421
+
422
+ name = "keras"
423
+ module = "keras"
424
+
425
+ def available(self) -> bool:
426
+ if importlib.util.find_spec("keras") is None:
427
+ return False
428
+ return any(importlib.util.find_spec(m) is not None for m in ("torch", "tensorflow", "jax"))
429
+
430
+ def compute(self, metric, task, y_true, y_pred, num_classes, opts):
431
+ s = self.stateful(metric, task, num_classes, opts, scores=y_pred)
432
+ s.update(y_true, y_pred)
433
+ return s.compute()
434
+
435
+ def stateful(self, metric, task, num_classes, opts, scores=None):
436
+ _ensure_keras_backend()
437
+ import keras
438
+
439
+ M = keras.metrics
440
+ avg = opts.get("average")
441
+ thr = opts.get("threshold")
442
+
443
+ if task == "regression":
444
+ obj = {"r2": M.R2Score, "mae": M.MeanAbsoluteError, "mse": M.MeanSquaredError,
445
+ "rmse": M.RootMeanSquaredError, "mape": M.MeanAbsolutePercentageError}[metric]()
446
+ return _KerasStateful([obj], metric, task, num_classes, opts)
447
+
448
+ if metric in ("auroc", "average_precision"):
449
+ kw = {}
450
+ if metric == "average_precision":
451
+ kw["curve"] = "PR"
452
+ if "pr_summation" in opts:
453
+ kw["summation_method"] = opts["pr_summation"]
454
+ if opts.get("exact_thresholds") and scores is not None:
455
+ t = np.unique(np.asarray(scores, dtype=np.float32))
456
+ if len(t) > _MAX_KERAS_THRESHOLDS: # keep memory bounded on big data
457
+ t = np.unique(np.quantile(t, np.linspace(0, 1, _MAX_KERAS_THRESHOLDS)).astype(np.float32))
458
+ t = t[(t > 0) & (t < 1)]
459
+ kw["thresholds"] = t.tolist()
460
+ if task == "multiclass" and avg is not None:
461
+ if avg != "macro":
462
+ raise ValueError(f"Keras AUC has no average={avg!r}")
463
+ kw.update(multi_label=True, num_labels=num_classes)
464
+ objs = [M.AUC(**kw)]
465
+ elif metric == "accuracy":
466
+ if task == "binary":
467
+ objs = [M.BinaryAccuracy(threshold=0.5 if thr is None else thr)]
468
+ elif avg not in (None, "micro"):
469
+ raise ValueError(f"Keras has no accuracy with average={avg!r}")
470
+ elif opts.get("top_k"):
471
+ objs = [M.TopKCategoricalAccuracy(k=opts["top_k"])]
472
+ else:
473
+ objs = [M.CategoricalAccuracy()]
474
+ elif metric in ("precision", "recall"):
475
+ cls = M.Precision if metric == "precision" else M.Recall
476
+ if task == "binary":
477
+ objs = [cls(thresholds=thr)]
478
+ elif avg is None:
479
+ objs = [cls()]
480
+ elif avg == "micro":
481
+ objs = [cls(top_k=1)]
482
+ elif avg == "macro":
483
+ objs = [cls(top_k=1, class_id=k) for k in range(num_classes)]
484
+ else:
485
+ raise ValueError(f"metric-diff does not map Keras {metric} average={avg!r}")
486
+ else: # f1
487
+ if task == "binary":
488
+ objs = [M.F1Score(threshold=thr)]
489
+ else:
490
+ objs = [M.F1Score(average=avg)]
491
+ return _KerasStateful(objs, metric, task, num_classes, opts)
492
+
493
+ def unsupported(self, metric, task, opts):
494
+ return _always_zero_division("keras", metric, opts)
495
+
496
+
497
+ _EVALUATE_NAMES = {"accuracy": "accuracy", "precision": "precision", "recall": "recall", "f1": "f1",
498
+ "auroc": "roc_auc", "r2": "r_squared", "mae": "mae", "mse": "mse", "rmse": "mse",
499
+ "mape": "mape"}
500
+ _EVALUATE_CACHE: dict[tuple, object] = {}
501
+
502
+
503
+ def _load_evaluate(name: str, config: str | None = None):
504
+ """evaluate.load() fetches the metric script from the Hugging Face Hub (cached after the
505
+ first time) and takes ~2 s even when cached, so keep loaded metrics for the process."""
506
+ key = (name, config)
507
+ if key not in _EVALUATE_CACHE:
508
+ import evaluate
509
+
510
+ try:
511
+ evaluate.logging.disable_progress_bar()
512
+ except Exception: # pragma: no cover - older versions
513
+ pass
514
+ try:
515
+ _EVALUATE_CACHE[key] = evaluate.load(name, config) if config else evaluate.load(name)
516
+ except Exception as exc:
517
+ raise RuntimeError(f"could not load evaluate metric {name!r} (it is downloaded from the "
518
+ f"Hugging Face Hub the first time): {exc}") from None
519
+ return _EVALUATE_CACHE[key]
520
+
521
+
522
+ class _EvaluateStateful:
523
+ """evaluate metrics accumulate with add_batch() and finish with compute()."""
524
+
525
+ def __init__(self, backend, metric, task, num_classes, opts):
526
+ self.backend, self.metric, self.task = backend, metric, task
527
+ self.num_classes, self.opts = num_classes, opts
528
+ self.module, self.kwargs, self.key = backend._module(metric, task, opts)
529
+
530
+ def update(self, y_true, y_pred):
531
+ refs, preds = self.backend._inputs(self.metric, self.task, y_true, y_pred, self.opts)
532
+ self.module.add_batch(references=refs, **{self.key: preds})
533
+
534
+ def compute(self) -> float:
535
+ out = self.module.compute(**self.kwargs)
536
+ return self.backend._value(self.metric, out)
537
+
538
+
539
+ class EvaluateBackend(Backend):
540
+ """Hugging Face `evaluate`. Most of its metrics wrap scikit-learn, with their own input
541
+ handling (float32 / int32 features) and some own implementations (r_squared)."""
542
+
543
+ name = "evaluate"
544
+ module = "evaluate"
545
+
546
+ def unsupported(self, metric, task, opts):
547
+ if metric == "average_precision":
548
+ return "evaluate has no average precision metric"
549
+ if task == "regression" and opts.get("multi_output"):
550
+ return "metric-diff does not map evaluate multi-output regression yet"
551
+ if opts.get("top_k"):
552
+ return "evaluate has no top-k accuracy"
553
+ return _always_zero_division("evaluate", metric, opts)
554
+
555
+ def _module(self, metric, task, opts):
556
+ """(loaded metric, compute kwargs, name of the predictions argument)"""
557
+ kwargs = {}
558
+ if metric == "auroc" and task == "multiclass" and opts.get("num_classes_for_labels") == 2 \
559
+ and opts.get("multi_class", "raise") != "raise":
560
+ return _load_evaluate("roc_auc"), kwargs, "prediction_scores_col1"
561
+ if metric == "auroc":
562
+ module = _load_evaluate("roc_auc", "multiclass" if task == "multiclass" else None)
563
+ if task == "multiclass":
564
+ kwargs["multi_class"] = opts.get("multi_class", "raise")
565
+ if opts.get("average"):
566
+ kwargs["average"] = opts["average"]
567
+ return module, kwargs, "prediction_scores"
568
+ module = _load_evaluate(_EVALUATE_NAMES[metric])
569
+ if metric == "rmse":
570
+ kwargs["squared"] = False
571
+ if metric in ("precision", "recall", "f1"):
572
+ if opts.get("average"):
573
+ kwargs["average"] = opts["average"]
574
+ if task == "multiclass" and opts.get("explicit_classes"):
575
+ kwargs["labels"] = list(range(opts["num_classes_for_labels"]))
576
+ if metric == "accuracy" and opts.get("average") not in (None, "micro"):
577
+ raise ValueError(f"evaluate accuracy has no average={opts['average']!r}")
578
+ return module, kwargs, "predictions"
579
+
580
+ def _inputs(self, metric, task, y_true, y_pred, opts):
581
+ if task == "regression":
582
+ return y_true.tolist(), y_pred.tolist()
583
+ if metric in LABEL_METRICS and y_pred.dtype.kind == "f":
584
+ if y_pred.ndim == 1:
585
+ y_pred = (y_pred >= opts.get("threshold", 0.5)).astype(np.int64)
586
+ else:
587
+ y_pred = y_pred.argmax(axis=1)
588
+ return y_true.tolist(), y_pred.tolist()
589
+
590
+ def _value(self, metric, out) -> float:
591
+ if isinstance(out, dict):
592
+ out = next(iter(out.values()))
593
+ return float(out)
594
+
595
+ def compute(self, metric, task, y_true, y_pred, num_classes, opts):
596
+ opts = {**opts, "num_classes_for_labels": num_classes}
597
+ module, kwargs, key = self._module(metric, task, opts)
598
+ refs, preds = self._inputs(metric, task, y_true, y_pred, opts)
599
+ if key == "prediction_scores_col1": # binary roc_auc on the positive-class column
600
+ key, preds = "prediction_scores", [row[1] for row in preds]
601
+ value = self._value(metric, module.compute(references=refs, **{key: preds}, **kwargs))
602
+ if metric == "r2" and opts.get("r2_force_finite"):
603
+ value = _r2_force_finite(value, y_true, y_pred)
604
+ return value
605
+
606
+ def stateful(self, metric, task, num_classes, opts):
607
+ return _EvaluateStateful(self, metric, task, num_classes, {**opts, "num_classes_for_labels": num_classes})
608
+
609
+
610
+ class MonaiBackend(Backend):
611
+ """MONAI, the standard library for medical image segmentation (segmentation metrics only)."""
612
+
613
+ name = "monai"
614
+ module = "monai"
615
+ tasks = ("segmentation",)
616
+
617
+ def unsupported(self, metric, task, opts):
618
+ return "MONAI is compared on segmentation metrics only"
619
+
620
+
621
+ ALL_BACKENDS: dict[str, Callable[[], Backend]] = {
622
+ "sklearn": SklearnBackend,
623
+ "torchmetrics": TorchmetricsBackend,
624
+ "torcheval": TorchevalBackend,
625
+ "keras": KerasBackend,
626
+ "evaluate": EvaluateBackend,
627
+ "monai": MonaiBackend,
628
+ }
629
+
630
+
631
+ def resolve(names: list[str] | None) -> list[Backend]:
632
+ if names is None:
633
+ backends = [cls() for cls in ALL_BACKENDS.values()]
634
+ return [b for b in backends if b.available()]
635
+ out = []
636
+ for n in names:
637
+ if n not in ALL_BACKENDS:
638
+ raise ValueError(f"unknown backend {n!r}; choose from {', '.join(ALL_BACKENDS)}")
639
+ b = ALL_BACKENDS[n]()
640
+ if not b.available():
641
+ extra = n if n in ("keras", "evaluate", "monai") else "torch"
642
+ raise ImportError(f"backend {n!r} is not installed (pip install 'metric-diff[{extra}]')")
643
+ out.append(b)
644
+ return out
645
+
646
+
647
+ def _short_error(exc: Exception) -> str:
648
+ msg = str(exc).strip().splitlines()[0] if str(exc).strip() else type(exc).__name__
649
+ return f"{type(exc).__name__}: {msg[:160]}"
650
+
651
+
652
+ def safe_call(fn, *args) -> tuple[float | None, str | None]:
653
+ """Run fn(*args); return (value, None) or (None, short error message)."""
654
+ with warnings.catch_warnings():
655
+ warnings.simplefilter("ignore")
656
+ try:
657
+ value = fn(*args)
658
+ except Exception as exc: # libraries raise many different types
659
+ return None, _short_error(exc)
660
+ if value != value: # NaN
661
+ return None, "returned NaN"
662
+ return value, None
663
+
664
+
665
+ def safe_compute(backend: Backend, metric: str, task: str, *rest) -> tuple[float | None, str | None]:
666
+ if task == "segmentation":
667
+ from . import segmentation
668
+
669
+ return safe_call(segmentation.compute, backend.name, metric, *rest)
670
+ return safe_call(backend.compute, metric, task, *rest)