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
@@ -0,0 +1,1028 @@
1
+ """Semantic segmentation metrics: overlap (Dice, IoU, pixel accuracy) and boundary/surface metrics
2
+ (Boundary IoU, Hausdorff distance, HD95, average symmetric surface distance).
3
+
4
+ Input conventions (stated once, applied everywhere):
5
+
6
+ * ``y_true`` and ``y_pred`` are integer label masks with the same shape. A 2-D array is one image. For
7
+ three or more dimensions the **first axis indexes images** (``(N, H, W)`` or ``(N, D, H, W)``); pass a
8
+ single 3-D volume as ``volume[None]``. A list of arrays allows images of different sizes.
9
+ * Boolean masks are treated as labels {0, 1}.
10
+ * ``ignore_index`` pixels are excluded from every count (for example 255 for "void").
11
+ * ``aggregate="dataset"`` (default) sums pixel counts over all images before computing each class's score
12
+ (the standard for semantic segmentation benchmarks); ``"image"`` computes the score per image and averages
13
+ the images (the usual convention in medical imaging).
14
+ * A class absent from both the truth and the prediction has an undefined score. It is NaN per class and is
15
+ left out of the macro average (``empty="ignore"``); ``empty=1.0`` counts it as perfect instead.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import functools
21
+ import json
22
+ import math
23
+ import warnings
24
+ from collections.abc import Mapping, Sequence
25
+ from dataclasses import dataclass, field
26
+ from types import MappingProxyType
27
+ from typing import TYPE_CHECKING, Any, Literal, Optional, Union, cast
28
+
29
+ import numpy as np
30
+ from numpy.typing import NDArray
31
+
32
+ if TYPE_CHECKING:
33
+ from scipy import ndimage
34
+ else:
35
+ from .._lazy import lazy_module
36
+
37
+ ndimage = lazy_module("scipy.ndimage")
38
+
39
+ from ..core.exceptions import InputValidationError, UndefinedMetricWarning
40
+ from ..core.export import PathLike, csv_text, html_document, html_table, save_as
41
+ from ..core.registry import register
42
+ from ..core.result import MetricResult, _fmt, _json_safe, _latex_escape, _latex_table
43
+ from ..core.types import ArrayLike
44
+
45
+ if TYPE_CHECKING:
46
+ import pandas as pd
47
+
48
+ __all__ = [
49
+ "SegmentationReport",
50
+ "average_surface_distance",
51
+ "boundary_iou",
52
+ "dice",
53
+ "hausdorff_distance",
54
+ "iou",
55
+ "mean_pixel_accuracy",
56
+ "miou",
57
+ "pixel_accuracy",
58
+ "per_image_scores",
59
+ "segmentation_confusion",
60
+ "segmentation_report",
61
+ ]
62
+
63
+ _C = "segmentation"
64
+ Masks = Union[ArrayLike, Sequence[ArrayLike]]
65
+ Average = Optional[Literal["macro", "micro", "weighted"]]
66
+ Aggregate = Literal["dataset", "image"]
67
+ Empty = Union[Literal["ignore"], float]
68
+
69
+ _REF_DICE = "Dice LR. Measures of the amount of ecologic association between species. Ecology. 1945;26(3):297-302."
70
+ _REF_JACCARD = "Jaccard P. The distribution of the flora in the alpine zone. New Phytol. 1912;11(2):37-50."
71
+ _REF_VOC = (
72
+ "Everingham M, Van Gool L, Williams CKI, Winn J, Zisserman A. The PASCAL Visual Object Classes (VOC) "
73
+ "challenge. Int J Comput Vis. 2010;88(2):303-338."
74
+ )
75
+ _REF_LONG = (
76
+ "Long J, Shelhamer E, Darrell T. Fully convolutional networks for semantic segmentation. CVPR 2015:3431-3440."
77
+ )
78
+ _REF_BIOU = (
79
+ "Cheng B, Girshick R, Dollár P, Berg AC, Kirillov A. Boundary IoU: improving object-centric image "
80
+ "segmentation evaluation. CVPR 2021:15334-15342."
81
+ )
82
+ _REF_MAIER = (
83
+ "Maier-Hein L, Reinke A, Godau P, et al. Metrics reloaded: recommendations for image analysis validation. "
84
+ "Nat Methods. 2024;21(2):195-212."
85
+ )
86
+ _REF_HD = (
87
+ "Huttenlocher DP, Klanderman GA, Rucklidge WJ. Comparing images using the Hausdorff distance. IEEE Trans "
88
+ "Pattern Anal Mach Intell. 1993;15(9):850-863."
89
+ )
90
+
91
+
92
+ # ---- input handling ------------------------------------------------------------------------------
93
+ def _as_images(masks: Masks, name: str) -> list[NDArray[Any]]:
94
+ images = None
95
+ if isinstance(masks, (list, tuple)) or (isinstance(masks, np.ndarray) and masks.dtype == object):
96
+ images = [np.asarray(m) for m in masks]
97
+ if (
98
+ images
99
+ and isinstance(masks, (list, tuple))
100
+ and all(m.ndim == 1 for m in images)
101
+ and not any(isinstance(m, np.ndarray) for m in masks)
102
+ ):
103
+ images = None # a nested Python list of rows, e.g. [[1, 1], [0, 0]], is one 2-D mask
104
+ if images is None:
105
+ arr = np.asarray(masks)
106
+ if arr.ndim < 2:
107
+ raise InputValidationError(
108
+ f"{name} must be a 2-D mask, an array of masks with images on the first axis, or a list of masks; "
109
+ f"received shape {arr.shape}."
110
+ )
111
+ images = [arr] if arr.ndim == 2 else list(arr)
112
+ if not images:
113
+ raise InputValidationError(f"{name} contains no images.")
114
+ out = []
115
+ for i, m in enumerate(images):
116
+ if m.ndim < 2:
117
+ raise InputValidationError(f"{name}[{i}] must have at least 2 dimensions; received shape {m.shape}.")
118
+ if m.dtype == bool:
119
+ m = m.astype(np.int64)
120
+ if not np.issubdtype(m.dtype, np.integer):
121
+ if np.issubdtype(m.dtype, np.floating) and np.all(np.isfinite(m)) and np.all(m == np.round(m)):
122
+ m = m.astype(np.int64)
123
+ else:
124
+ raise InputValidationError(
125
+ f"{name} must contain integer class labels (or booleans); found dtype {m.dtype}. "
126
+ "Threshold or argmax probability maps first."
127
+ )
128
+ out.append(m)
129
+ return out
130
+
131
+
132
+ def _count(n: int, noun: str) -> str:
133
+ plural = noun + ("es" if noun.endswith("s") else "s")
134
+ return f"{n} {noun if n == 1 else plural}"
135
+
136
+
137
+ def _pairs(y_true: Masks, y_pred: Masks) -> list[tuple[NDArray[Any], NDArray[Any]]]:
138
+ t = _as_images(y_true, "y_true")
139
+ p = _as_images(y_pred, "y_pred")
140
+ if len(t) != len(p):
141
+ raise InputValidationError(f"y_true has {len(t)} images but y_pred has {len(p)}.")
142
+ for i, (a, b) in enumerate(zip(t, p)):
143
+ if a.shape != b.shape:
144
+ raise InputValidationError(f"Image {i}: y_true has shape {a.shape} but y_pred has shape {b.shape}.")
145
+ return list(zip(t, p))
146
+
147
+
148
+ def _classes(
149
+ pairs: list[tuple[NDArray[Any], NDArray[Any]]],
150
+ num_classes: Optional[int],
151
+ labels: Optional[Sequence[int]],
152
+ ignore_index: Optional[int],
153
+ include_background: bool,
154
+ ) -> NDArray[np.int64]:
155
+ if labels is not None:
156
+ cls = np.asarray(labels, dtype=np.int64)
157
+ if cls.ndim != 1 or cls.size == 0 or np.unique(cls).size != cls.size:
158
+ raise InputValidationError("labels must be a non-empty list of distinct class indices.")
159
+ else:
160
+ if num_classes is None:
161
+ top = -1
162
+ for a, b in pairs:
163
+ for m in (a, b):
164
+ valid = m[m != ignore_index] if ignore_index is not None else m
165
+ if valid.size:
166
+ top = max(top, int(valid.max()))
167
+ num_classes = top + 1
168
+ if num_classes < 1:
169
+ raise InputValidationError("num_classes must be at least 1.")
170
+ cls = np.arange(num_classes, dtype=np.int64)
171
+ if not include_background:
172
+ cls = cls[cls != 0]
173
+ if cls.size == 0:
174
+ raise InputValidationError("include_background=False leaves no classes to evaluate.")
175
+ for a, b in pairs:
176
+ for m, name in ((a, "y_true"), (b, "y_pred")):
177
+ valid = m if ignore_index is None else m[m != ignore_index]
178
+ if valid.size and int(valid.min()) < 0:
179
+ raise InputValidationError(f"{name} contains negative labels; use ignore_index for void pixels.")
180
+ if valid.size and num_classes is not None and labels is None and int(valid.max()) >= num_classes:
181
+ raise InputValidationError(
182
+ f"{name} contains label {int(valid.max())}, but num_classes={num_classes} allows 0 to "
183
+ f"{num_classes - 1}."
184
+ )
185
+ return cls
186
+
187
+
188
+ def segmentation_confusion(
189
+ y_true: Masks,
190
+ y_pred: Masks,
191
+ *,
192
+ num_classes: Optional[int] = None,
193
+ ignore_index: Optional[int] = None,
194
+ ) -> NDArray[np.int64]:
195
+ """Pixel confusion matrix summed over all images: rows are true classes, columns predicted classes."""
196
+ pairs = _pairs(y_true, y_pred)
197
+ cls = _classes(pairs, num_classes, None, ignore_index, True)
198
+ k = cls.size
199
+ total = np.zeros((k, k), dtype=np.int64)
200
+ for a, b in pairs:
201
+ total += _confusion(a, b, k, ignore_index)
202
+ return total
203
+
204
+
205
+ def _confusion(a: NDArray[Any], b: NDArray[Any], k: int, ignore_index: Optional[int]) -> NDArray[np.int64]:
206
+ t = a.ravel().astype(np.int64)
207
+ p = b.ravel().astype(np.int64)
208
+ keep = np.ones(t.shape, dtype=bool) if ignore_index is None else (t != ignore_index)
209
+ if ignore_index is not None:
210
+ # a prediction of the ignore label on a valid pixel is a wrong prediction of "no class"
211
+ p = np.where(p == ignore_index, k, p)
212
+ if np.any(t[keep] >= k) or np.any(p[keep] > k):
213
+ raise InputValidationError(f"Masks contain labels >= num_classes={k}.")
214
+ flat = t[keep] * (k + 1) + p[keep]
215
+ cm = np.bincount(flat, minlength=k * (k + 1)).reshape(k, k + 1)
216
+ return cm[:, :k].astype(np.int64)
217
+
218
+
219
+ def _per_image_counts(
220
+ pairs: list[tuple[NDArray[Any], NDArray[Any]]], cls: NDArray[np.int64], ignore_index: Optional[int]
221
+ ) -> tuple[NDArray[np.float64], NDArray[np.float64], NDArray[np.float64]]:
222
+ """tp, fp, fn per image and class, shape (n_images, n_classes)."""
223
+ k = max(int(np.max(cls)) + 1, 1)
224
+ for a, b in pairs:
225
+ for m in (a, b):
226
+ valid = m if ignore_index is None else m[m != ignore_index]
227
+ if valid.size:
228
+ k = max(k, int(valid.max()) + 1)
229
+ tp = np.zeros((len(pairs), cls.size))
230
+ fp = np.zeros_like(tp)
231
+ fn = np.zeros_like(tp)
232
+ for i, (a, b) in enumerate(pairs):
233
+ cm = _confusion(a, b, k, ignore_index)
234
+ diag = np.diag(cm)
235
+ # every valid true pixel of the class that is not predicted as the class is a miss, including pixels
236
+ # predicted as the ignore label (dropped from the confusion matrix columns)
237
+ t_valid = a.ravel() if ignore_index is None else a.ravel()[a.ravel() != ignore_index]
238
+ true_count = np.bincount(t_valid.astype(np.int64), minlength=k)[:k]
239
+ tp[i] = diag[cls]
240
+ fp[i] = cm.sum(0)[cls] - diag[cls]
241
+ fn[i] = true_count[cls] - diag[cls]
242
+ return tp, fp, fn
243
+
244
+
245
+ def _score(
246
+ tp: NDArray[np.float64],
247
+ fp: NDArray[np.float64],
248
+ fn: NDArray[np.float64],
249
+ kind: Literal["dice", "iou"],
250
+ ) -> NDArray[np.float64]:
251
+ den = (2 * tp + fp + fn) if kind == "dice" else (tp + fp + fn)
252
+ num = 2 * tp if kind == "dice" else tp
253
+ with np.errstate(divide="ignore", invalid="ignore"):
254
+ return np.where(den > 0, num / np.where(den > 0, den, 1), np.nan)
255
+
256
+
257
+ def _reduce(
258
+ per_class: NDArray[np.float64],
259
+ support: NDArray[np.float64],
260
+ average: Average,
261
+ empty: Empty,
262
+ name: str,
263
+ ) -> Union[float, NDArray[np.float64]]:
264
+ if empty != "ignore":
265
+ if not (isinstance(empty, (int, float)) and 0 <= float(empty) <= 1):
266
+ raise InputValidationError('empty must be "ignore" or a value in [0, 1] (usually 1.0).')
267
+ per_class = np.where(np.isnan(per_class), float(empty), per_class)
268
+ if average is None:
269
+ return per_class
270
+ if average == "macro":
271
+ if np.all(np.isnan(per_class)):
272
+ warnings.warn(
273
+ f"{name} is undefined: no class occurs in either mask.", UndefinedMetricWarning, stacklevel=4
274
+ )
275
+ return math.nan
276
+ return float(np.nanmean(per_class))
277
+ if average == "weighted":
278
+ ok = ~np.isnan(per_class)
279
+ if support[ok].sum() == 0:
280
+ return math.nan
281
+ return float(np.average(per_class[ok], weights=support[ok]))
282
+ raise InputValidationError("average must be 'macro', 'micro', 'weighted' or None.")
283
+
284
+
285
+ def _overlap(
286
+ kind: Literal["dice", "iou"],
287
+ name: str,
288
+ y_true: Masks,
289
+ y_pred: Masks,
290
+ *,
291
+ num_classes: Optional[int],
292
+ labels: Optional[Sequence[int]],
293
+ ignore_index: Optional[int],
294
+ average: Average,
295
+ aggregate: Aggregate,
296
+ include_background: bool,
297
+ empty: Empty,
298
+ ) -> MetricResult:
299
+ pairs = _pairs(y_true, y_pred)
300
+ cls = _classes(pairs, num_classes, labels, ignore_index, include_background)
301
+ tp, fp, fn = _per_image_counts(pairs, cls, ignore_index)
302
+ params: dict[str, Any] = {
303
+ "average": average,
304
+ "aggregate": aggregate,
305
+ "ignore_index": ignore_index,
306
+ "include_background": include_background,
307
+ "empty": empty,
308
+ "n_images": len(pairs),
309
+ }
310
+ if aggregate not in ("dataset", "image"):
311
+ raise InputValidationError("aggregate must be 'dataset' or 'image'.")
312
+ if average == "micro":
313
+ if aggregate == "dataset":
314
+ value = _score(np.array([tp.sum()]), np.array([fp.sum()]), np.array([fn.sum()]), kind)[0]
315
+ else:
316
+ value = float(np.nanmean(_score(tp.sum(1), fp.sum(1), fn.sum(1), kind)))
317
+ return MetricResult(kind, name, float(value), params)
318
+ support = (tp + fn).sum(0)
319
+ if aggregate == "dataset":
320
+ per_class = _score(tp.sum(0), fp.sum(0), fn.sum(0), kind)
321
+ else:
322
+ scores = _score(tp, fp, fn, kind)
323
+ if empty != "ignore":
324
+ scores = np.where(np.isnan(scores), float(empty), scores)
325
+ with warnings.catch_warnings():
326
+ warnings.simplefilter("ignore", RuntimeWarning)
327
+ per_class = np.nanmean(scores, axis=0)
328
+ value = _reduce(per_class, support, average, empty, name)
329
+ if isinstance(value, np.ndarray):
330
+ return MetricResult(kind, name, value, params, labels=tuple(int(c) for c in cls))
331
+ return MetricResult(kind, name, value, params)
332
+
333
+
334
+ @register(
335
+ category=_C,
336
+ task="segmentation",
337
+ name="Dice coefficient",
338
+ definition="Overlap between predicted and true region of a class: twice the intersection over the sum of "
339
+ "the two areas (identical to the F1 score on pixels).",
340
+ formula="Dice = 2|A ∩ B| / (|A| + |B|) = 2TP / (2TP + FP + FN)",
341
+ range="[0, 1]",
342
+ input_requirements=("y_true mask", "y_pred mask"),
343
+ references=(_REF_DICE, _REF_MAIER),
344
+ )
345
+ def dice(
346
+ y_true: Masks,
347
+ y_pred: Masks,
348
+ *,
349
+ num_classes: Optional[int] = None,
350
+ labels: Optional[Sequence[int]] = None,
351
+ ignore_index: Optional[int] = None,
352
+ average: Average = "macro",
353
+ aggregate: Aggregate = "dataset",
354
+ include_background: bool = True,
355
+ empty: Empty = "ignore",
356
+ ) -> MetricResult:
357
+ """Dice coefficient (Sørensen–Dice) per class.
358
+
359
+ ``average``: ``"macro"`` (mean over classes, default), ``"micro"`` (pooled pixels), ``"weighted"`` (by
360
+ true pixel count) or ``None`` (per class). See :mod:`evalsuite.vision.segmentation` for ``aggregate``,
361
+ ``empty`` and the input conventions.
362
+ """
363
+ return _overlap(
364
+ "dice",
365
+ "Dice",
366
+ y_true,
367
+ y_pred,
368
+ num_classes=num_classes,
369
+ labels=labels,
370
+ ignore_index=ignore_index,
371
+ average=average,
372
+ aggregate=aggregate,
373
+ include_background=include_background,
374
+ empty=empty,
375
+ )
376
+
377
+
378
+ @register(
379
+ category=_C,
380
+ task="segmentation",
381
+ name="Intersection over union (Jaccard)",
382
+ definition="Overlap between predicted and true region of a class: intersection over union.",
383
+ formula="IoU = |A ∩ B| / |A ∪ B| = TP / (TP + FP + FN)",
384
+ range="[0, 1]",
385
+ input_requirements=("y_true mask", "y_pred mask"),
386
+ references=(_REF_JACCARD, _REF_VOC),
387
+ )
388
+ def iou(
389
+ y_true: Masks,
390
+ y_pred: Masks,
391
+ *,
392
+ num_classes: Optional[int] = None,
393
+ labels: Optional[Sequence[int]] = None,
394
+ ignore_index: Optional[int] = None,
395
+ average: Average = "macro",
396
+ aggregate: Aggregate = "dataset",
397
+ include_background: bool = True,
398
+ empty: Empty = "ignore",
399
+ ) -> MetricResult:
400
+ """Intersection over union (Jaccard index) per class; same options as :func:`dice`."""
401
+ return _overlap(
402
+ "iou",
403
+ "IoU",
404
+ y_true,
405
+ y_pred,
406
+ num_classes=num_classes,
407
+ labels=labels,
408
+ ignore_index=ignore_index,
409
+ average=average,
410
+ aggregate=aggregate,
411
+ include_background=include_background,
412
+ empty=empty,
413
+ )
414
+
415
+
416
+ @register(
417
+ category=_C,
418
+ task="segmentation",
419
+ name="Mean intersection over union (mIoU)",
420
+ definition="IoU of each class from pixel counts summed over the dataset, averaged over the classes that "
421
+ "occur: the standard semantic segmentation benchmark score.",
422
+ formula="mIoU = (1/K) Σ_k TP_k / (TP_k + FP_k + FN_k)",
423
+ range="[0, 1]",
424
+ input_requirements=("y_true mask", "y_pred mask"),
425
+ references=(_REF_VOC, _REF_LONG),
426
+ )
427
+ def miou(
428
+ y_true: Masks,
429
+ y_pred: Masks,
430
+ *,
431
+ num_classes: Optional[int] = None,
432
+ ignore_index: Optional[int] = None,
433
+ include_background: bool = True,
434
+ ) -> MetricResult:
435
+ """Mean IoU: :func:`iou` with ``average="macro"`` and ``aggregate="dataset"``."""
436
+ r = iou(
437
+ y_true,
438
+ y_pred,
439
+ num_classes=num_classes,
440
+ ignore_index=ignore_index,
441
+ include_background=include_background,
442
+ )
443
+ return MetricResult("miou", "mIoU", float(r), r.params)
444
+
445
+
446
+ @register(
447
+ category=_C,
448
+ task="segmentation",
449
+ name="Pixel accuracy",
450
+ definition="Proportion of (non-ignored) pixels whose class is predicted correctly.",
451
+ formula="Σ_k TP_k / N_pixels",
452
+ range="[0, 1]",
453
+ input_requirements=("y_true mask", "y_pred mask"),
454
+ references=(_REF_LONG,),
455
+ )
456
+ def pixel_accuracy(y_true: Masks, y_pred: Masks, *, ignore_index: Optional[int] = None) -> MetricResult:
457
+ """Overall pixel accuracy, excluding ``ignore_index`` pixels."""
458
+ correct = total = 0
459
+ for a, b in _pairs(y_true, y_pred):
460
+ keep = np.ones(a.shape, bool) if ignore_index is None else a != ignore_index
461
+ correct += int(np.sum((a == b) & keep))
462
+ total += int(keep.sum())
463
+ if total == 0:
464
+ raise InputValidationError("Every pixel is ignored; nothing to evaluate.")
465
+ return MetricResult("pixel_accuracy", "Pixel accuracy", correct / total, {"ignore_index": ignore_index})
466
+
467
+
468
+ @register(
469
+ category=_C,
470
+ task="segmentation",
471
+ name="Mean pixel accuracy",
472
+ definition="Per-class pixel recall (correct pixels of the class over its true pixels), averaged over the "
473
+ "classes that occur in the truth.",
474
+ formula="(1/K) Σ_k TP_k / (TP_k + FN_k)",
475
+ range="[0, 1]",
476
+ input_requirements=("y_true mask", "y_pred mask"),
477
+ references=(_REF_LONG,),
478
+ )
479
+ def mean_pixel_accuracy(
480
+ y_true: Masks,
481
+ y_pred: Masks,
482
+ *,
483
+ num_classes: Optional[int] = None,
484
+ ignore_index: Optional[int] = None,
485
+ ) -> MetricResult:
486
+ """Mean of per-class pixel accuracy over classes present in ``y_true``."""
487
+ pairs = _pairs(y_true, y_pred)
488
+ cls = _classes(pairs, num_classes, None, ignore_index, True)
489
+ tp, _fp, fn = _per_image_counts(pairs, cls, ignore_index)
490
+ t, f = tp.sum(0), fn.sum(0)
491
+ present = (t + f) > 0
492
+ return MetricResult(
493
+ "mean_pixel_accuracy",
494
+ "Mean pixel accuracy",
495
+ float(np.mean(t[present] / (t[present] + f[present]))),
496
+ {"ignore_index": ignore_index},
497
+ )
498
+
499
+
500
+ # ---- boundary and surface metrics ------------------------------------------------------------------
501
+ @functools.lru_cache(maxsize=8)
502
+ def _structure(ndim: int) -> NDArray[np.bool_]:
503
+ out: NDArray[np.bool_] = ndimage.generate_binary_structure(ndim, 1)
504
+ out.setflags(write=False)
505
+ return out
506
+
507
+
508
+ def _surface(mask: NDArray[np.bool_]) -> NDArray[np.bool_]:
509
+ """Foreground pixels with at least one background neighbour (4/6-connectivity)."""
510
+ if not mask.any():
511
+ return mask
512
+ # Erosion with the cross-shaped structure (border = background): a pixel stays interior only if it and its
513
+ # 2·ndim face neighbours are all foreground. Same result as ndimage.binary_erosion, without its overhead.
514
+ interior = mask.copy()
515
+ full = [slice(None)] * mask.ndim
516
+ for ax in range(mask.ndim):
517
+ lo, hi, first, last = list(full), list(full), list(full), list(full)
518
+ lo[ax], hi[ax] = slice(None, -1), slice(1, None)
519
+ first[ax], last[ax] = slice(0, 1), slice(-1, None)
520
+ interior[tuple(hi)] &= mask[tuple(lo)] # neighbour before along this axis
521
+ interior[tuple(lo)] &= mask[tuple(hi)] # neighbour after
522
+ interior[tuple(first)] = False # pixels on the image border touch the background outside
523
+ interior[tuple(last)] = False
524
+ out: NDArray[np.bool_] = mask & ~interior
525
+ return out
526
+
527
+
528
+ def _nearest(src: NDArray[np.float64], dst: NDArray[np.float64]) -> NDArray[np.float64]:
529
+ """Distance from each point of ``src`` to its nearest point of ``dst`` by direct comparison, in chunks of
530
+ rows so memory stays bounded; the square root is taken after the minimum (it is monotonic)."""
531
+ out = np.empty(src.shape[0])
532
+ step = max(1, 262144 // max(dst.shape[0], 1))
533
+ for i in range(0, src.shape[0], step):
534
+ diff = src[i : i + step, None, :] - dst[None, :, :]
535
+ out[i : i + step] = np.einsum("ijk,ijk->ij", diff, diff).min(axis=1)
536
+ return np.sqrt(out)
537
+
538
+
539
+ def _surface_distances(
540
+ a_surface: NDArray[np.bool_], b_surface: NDArray[np.bool_], spacing: Optional[Sequence[float]]
541
+ ) -> tuple[NDArray[np.float64], NDArray[np.float64]]:
542
+ """Nearest-neighbour distances between the two surfaces, both ways (A→B, B→A).
543
+
544
+ Works on the surface points only (never a distance transform of the whole image): small surfaces are
545
+ compared directly, which beats building trees, and large ones use k-d trees. Both give the exact Euclidean
546
+ nearest-surface distance."""
547
+ pa = np.argwhere(a_surface).astype(np.float64)
548
+ pb = np.argwhere(b_surface).astype(np.float64)
549
+ if spacing is not None:
550
+ sc = np.asarray(spacing, dtype=np.float64)
551
+ pa *= sc
552
+ pb *= sc
553
+ if pa.shape[0] * pb.shape[0] <= 4_000_000:
554
+ return _nearest(pa, pb), _nearest(pb, pa)
555
+ from scipy.spatial import cKDTree
556
+
557
+ d_ab = cKDTree(pb).query(pa)[0]
558
+ d_ba = cKDTree(pa).query(pb)[0]
559
+ return np.asarray(d_ab, dtype=np.float64), np.asarray(d_ba, dtype=np.float64)
560
+
561
+
562
+ def _check_spacing(spacing: Optional[Sequence[float]], ndim: int) -> Optional[tuple[float, ...]]:
563
+ if spacing is None:
564
+ return None
565
+ sp = tuple(float(s) for s in spacing)
566
+ if len(sp) != ndim or any(not (s > 0 and math.isfinite(s)) for s in sp):
567
+ raise InputValidationError(f"spacing must have {ndim} positive values (one per image axis).")
568
+ return sp
569
+
570
+
571
+ def _surface_metric(
572
+ which: Literal["hd", "assd"],
573
+ y_true: Masks,
574
+ y_pred: Masks,
575
+ *,
576
+ num_classes: Optional[int],
577
+ labels: Optional[Sequence[int]],
578
+ ignore_index: Optional[int],
579
+ include_background: bool,
580
+ spacing: Optional[Sequence[float]],
581
+ percentile: float,
582
+ average: Optional[Literal["macro"]],
583
+ metric: str,
584
+ name: str,
585
+ ) -> MetricResult:
586
+ if not (0 < percentile <= 100):
587
+ raise InputValidationError("percentile must be in (0, 100].")
588
+ pairs = _pairs(y_true, y_pred)
589
+ cls = _classes(pairs, num_classes, labels, ignore_index, include_background)
590
+ values = np.full((len(pairs), cls.size), np.nan)
591
+ one_empty = 0
592
+ for i, (a, b) in enumerate(pairs):
593
+ sp = _check_spacing(spacing, a.ndim)
594
+ valid = None if ignore_index is None else a != ignore_index
595
+ for j, c in enumerate(cls):
596
+ ta, pb = a == c, b == c
597
+ if valid is not None:
598
+ ta &= valid
599
+ pb &= valid
600
+ has_a, has_b = bool(ta.any()), bool(pb.any())
601
+ if not has_a and not has_b:
602
+ continue
603
+ if not has_a or not has_b:
604
+ values[i, j] = math.inf
605
+ one_empty += 1
606
+ continue
607
+ d_ab, d_ba = _surface_distances(_surface(ta), _surface(pb), sp)
608
+ if which == "hd":
609
+ if percentile == 100:
610
+ values[i, j] = max(float(np.max(d_ab)), float(np.max(d_ba)))
611
+ else:
612
+ values[i, j] = max(np.percentile(d_ab, percentile), np.percentile(d_ba, percentile))
613
+ else:
614
+ values[i, j] = (d_ab.sum() + d_ba.sum()) / (d_ab.size + d_ba.size)
615
+ if one_empty:
616
+ warnings.warn(
617
+ f"{name} is infinite for {one_empty} image/class pair(s) where the class occurs in only one of the "
618
+ "two masks.",
619
+ UndefinedMetricWarning,
620
+ stacklevel=3,
621
+ )
622
+ if not np.isnan(values).any():
623
+ per_class = values.mean(axis=0) # nanmean's NaN bookkeeping is not needed
624
+ else:
625
+ with warnings.catch_warnings():
626
+ warnings.simplefilter("ignore", RuntimeWarning)
627
+ per_class = np.nanmean(values, axis=0)
628
+ params: dict[str, Any] = {
629
+ "spacing": None if spacing is None else tuple(float(s) for s in spacing),
630
+ "ignore_index": ignore_index,
631
+ "include_background": include_background,
632
+ "n_images": len(pairs),
633
+ "aggregate": "image",
634
+ }
635
+ if which == "hd":
636
+ params["percentile"] = percentile
637
+ if average is None:
638
+ return MetricResult(metric, name, per_class, params, labels=tuple(int(c) for c in cls))
639
+ if average != "macro":
640
+ raise InputValidationError("average must be 'macro' or None for surface distances.")
641
+ if np.all(np.isnan(per_class)):
642
+ warnings.warn(f"{name} is undefined: no class occurs in any mask.", UndefinedMetricWarning, stacklevel=3)
643
+ return MetricResult(metric, name, math.nan, params)
644
+ finite = per_class[~np.isnan(per_class)]
645
+ return MetricResult(metric, name, float(finite.mean()), params)
646
+
647
+
648
+ @register(
649
+ category=_C,
650
+ task="segmentation",
651
+ name="Hausdorff distance",
652
+ definition="Largest distance from a point on one boundary to the nearest point on the other (in pixels, "
653
+ "or physical units with spacing); percentile=95 gives the robust HD95.",
654
+ formula="HD = max(max_{a∈∂A} d(a, ∂B), max_{b∈∂B} d(b, ∂A))",
655
+ range="[0, ∞)",
656
+ input_requirements=("y_true mask", "y_pred mask"),
657
+ references=(_REF_HD, _REF_MAIER),
658
+ higher_is_better=False,
659
+ )
660
+ def hausdorff_distance(
661
+ y_true: Masks,
662
+ y_pred: Masks,
663
+ *,
664
+ percentile: float = 100.0,
665
+ spacing: Optional[Sequence[float]] = None,
666
+ num_classes: Optional[int] = None,
667
+ labels: Optional[Sequence[int]] = None,
668
+ ignore_index: Optional[int] = None,
669
+ include_background: bool = False,
670
+ average: Optional[Literal["macro"]] = "macro",
671
+ ) -> MetricResult:
672
+ """Symmetric Hausdorff distance between class boundaries, per image, averaged over images then classes.
673
+
674
+ ``percentile=95`` returns HD95 (the 95th percentile of each directed distance set, then the larger of
675
+ the two, as in MONAI). Boundaries are mask pixels with a background neighbour (face connectivity).
676
+ ``spacing`` gives the physical size of a pixel/voxel along each axis. The background class is excluded
677
+ by default. A class present in only one mask gives ``inf`` (with a warning).
678
+ """
679
+ return _surface_metric(
680
+ "hd",
681
+ y_true,
682
+ y_pred,
683
+ num_classes=num_classes,
684
+ labels=labels,
685
+ ignore_index=ignore_index,
686
+ include_background=include_background,
687
+ spacing=spacing,
688
+ percentile=percentile,
689
+ average=average,
690
+ metric="hausdorff_distance",
691
+ name="HD95" if percentile == 95 else ("Hausdorff distance" if percentile == 100 else f"HD{percentile:g}"),
692
+ )
693
+
694
+
695
+ @register(
696
+ category=_C,
697
+ task="segmentation",
698
+ name="Average symmetric surface distance",
699
+ definition="Mean distance from every boundary point of each mask to the nearest boundary point of the "
700
+ "other, pooled over both directions.",
701
+ formula="ASSD = (Σ_{a∈∂A} d(a, ∂B) + Σ_{b∈∂B} d(b, ∂A)) / (|∂A| + |∂B|)",
702
+ range="[0, ∞)",
703
+ input_requirements=("y_true mask", "y_pred mask"),
704
+ references=(_REF_MAIER,),
705
+ higher_is_better=False,
706
+ )
707
+ def average_surface_distance(
708
+ y_true: Masks,
709
+ y_pred: Masks,
710
+ *,
711
+ spacing: Optional[Sequence[float]] = None,
712
+ num_classes: Optional[int] = None,
713
+ labels: Optional[Sequence[int]] = None,
714
+ ignore_index: Optional[int] = None,
715
+ include_background: bool = False,
716
+ average: Optional[Literal["macro"]] = "macro",
717
+ ) -> MetricResult:
718
+ """Average symmetric surface distance (ASSD), per image, averaged over images then classes."""
719
+ return _surface_metric(
720
+ "assd",
721
+ y_true,
722
+ y_pred,
723
+ num_classes=num_classes,
724
+ labels=labels,
725
+ ignore_index=ignore_index,
726
+ include_background=include_background,
727
+ spacing=spacing,
728
+ percentile=100.0,
729
+ average=average,
730
+ metric="average_surface_distance",
731
+ name="ASSD",
732
+ )
733
+
734
+
735
+ def _boundary_region(mask: NDArray[np.bool_], d: int) -> NDArray[np.bool_]:
736
+ """Pixels of the mask within distance d of its contour (mask minus its d-step erosion), as in Cheng et al."""
737
+ if not mask.any():
738
+ return mask
739
+ eroded = ndimage.binary_erosion(
740
+ mask, structure=ndimage.generate_binary_structure(mask.ndim, mask.ndim), iterations=d, border_value=0
741
+ )
742
+ out: NDArray[np.bool_] = mask & ~eroded
743
+ return out
744
+
745
+
746
+ @register(
747
+ category=_C,
748
+ task="segmentation",
749
+ name="Boundary IoU",
750
+ definition="IoU computed only on the pixels within distance d of each mask's contour, so it is sensitive "
751
+ "to boundary quality and fair across object sizes; d is a fraction of the image diagonal.",
752
+ formula="BIoU = |(G_d ∩ G) ∩ (P_d ∩ P)| / |(G_d ∩ G) ∪ (P_d ∩ P)|",
753
+ range="[0, 1]",
754
+ input_requirements=("y_true mask", "y_pred mask"),
755
+ references=(_REF_BIOU,),
756
+ )
757
+ def boundary_iou(
758
+ y_true: Masks,
759
+ y_pred: Masks,
760
+ *,
761
+ dilation_ratio: float = 0.02,
762
+ num_classes: Optional[int] = None,
763
+ labels: Optional[Sequence[int]] = None,
764
+ ignore_index: Optional[int] = None,
765
+ include_background: bool = False,
766
+ average: Average = "macro",
767
+ empty: Empty = "ignore",
768
+ ) -> MetricResult:
769
+ """Boundary IoU (Cheng et al. 2021) per class, with the boundary band width
770
+ d = max(1, round(dilation_ratio × image diagonal)). Counts are summed over images per class."""
771
+ if not (0 < dilation_ratio < 1):
772
+ raise InputValidationError("dilation_ratio must be between 0 and 1 (0.02 is the paper's default).")
773
+ pairs = _pairs(y_true, y_pred)
774
+ cls = _classes(pairs, num_classes, labels, ignore_index, include_background)
775
+ inter = np.zeros(cls.size)
776
+ union = np.zeros(cls.size)
777
+ for a, b in pairs:
778
+ d = max(1, round(dilation_ratio * math.sqrt(sum(s * s for s in a.shape))))
779
+ valid = np.ones(a.shape, bool) if ignore_index is None else a != ignore_index
780
+ for j, c in enumerate(cls):
781
+ gb = _boundary_region((a == c) & valid, d)
782
+ pb = _boundary_region((b == c) & valid, d)
783
+ inter[j] += np.sum(gb & pb)
784
+ union[j] += np.sum(gb | pb)
785
+ with np.errstate(divide="ignore", invalid="ignore"):
786
+ per_class = np.where(union > 0, inter / np.where(union > 0, union, 1), np.nan)
787
+ params: dict[str, Any] = {
788
+ "dilation_ratio": dilation_ratio,
789
+ "average": average,
790
+ "ignore_index": ignore_index,
791
+ "include_background": include_background,
792
+ "n_images": len(pairs),
793
+ }
794
+ if average == "micro":
795
+ return MetricResult("boundary_iou", "Boundary IoU", float(inter.sum() / union.sum()), params)
796
+ value = _reduce(per_class, union, average, empty, "Boundary IoU")
797
+ if isinstance(value, np.ndarray):
798
+ return MetricResult("boundary_iou", "Boundary IoU", value, params, labels=tuple(int(c) for c in cls))
799
+ return MetricResult("boundary_iou", "Boundary IoU", value, params)
800
+
801
+
802
+ def per_image_scores(
803
+ y_true: Masks,
804
+ y_pred: Masks,
805
+ metric: Literal["dice", "iou"] = "dice",
806
+ *,
807
+ num_classes: Optional[int] = None,
808
+ ignore_index: Optional[int] = None,
809
+ include_background: bool = True,
810
+ ) -> NDArray[np.float64]:
811
+ """Macro Dice or IoU of each image separately (for paired tests between models over the same images)."""
812
+ pairs = _pairs(y_true, y_pred)
813
+ cls = _classes(pairs, num_classes, None, ignore_index, include_background)
814
+ tp, fp, fn = _per_image_counts(pairs, cls, ignore_index)
815
+ with warnings.catch_warnings():
816
+ warnings.simplefilter("ignore", RuntimeWarning)
817
+ return np.asarray(np.nanmean(_score(tp, fp, fn, metric), axis=1), dtype=np.float64)
818
+
819
+
820
+ # ---- report --------------------------------------------------------------------------------------------
821
+ _REPORT_COLUMNS = ("dice", "iou", "boundary_iou", "hd95", "assd")
822
+
823
+
824
+ @dataclass(frozen=True, eq=False)
825
+ class SegmentationReport:
826
+ """Every segmentation measure in one object: dataset-level summary values plus a per-class table
827
+ (Dice, IoU, Boundary IoU, HD95, ASSD and pixel support)."""
828
+
829
+ values: Any
830
+ rows: tuple[Any, ...]
831
+ params: Any = field(default_factory=dict)
832
+
833
+ def __post_init__(self) -> None:
834
+ object.__setattr__(self, "values", MappingProxyType(dict(self.values)))
835
+ object.__setattr__(self, "rows", tuple(MappingProxyType(dict(r)) for r in self.rows))
836
+ object.__setattr__(self, "params", MappingProxyType(dict(self.params)))
837
+
838
+ def __getitem__(self, name: Any) -> Any:
839
+ if name in self.values:
840
+ return float(self.values[name])
841
+ for row in self.rows:
842
+ if row["class"] == name:
843
+ return row
844
+ raise KeyError(f"No value or class {name!r}. Values: {', '.join(self.values)}.")
845
+
846
+ def _table(self, digits: int) -> tuple[list[str], list[list[str]]]:
847
+ header = ["Class", "Dice", "IoU", "Boundary IoU", "HD95", "ASSD", "Pixels"]
848
+ body = [
849
+ [str(r["name"]), *(_fmt(r[c], digits) for c in _REPORT_COLUMNS), f"{int(r['support']):,}"]
850
+ for r in self.rows
851
+ ]
852
+ return header, body
853
+
854
+ def summary(self, *, digits: int = 4) -> str:
855
+ p = self.params
856
+ unit = " (physical units)" if p.get("spacing") else " (pixels)"
857
+ lines = [
858
+ f"EvalSuite segmentation evaluation ({_count(p['n_images'], 'image')}, "
859
+ f"{_count(len(self.rows), 'class')}, "
860
+ f"aggregate={p['aggregate']})",
861
+ f" mIoU {_fmt(self.values['miou'], digits)}",
862
+ f" Mean Dice {_fmt(self.values['dice'], digits)}",
863
+ f" Pixel accuracy {_fmt(self.values['pixel_accuracy'], digits)}",
864
+ f" Mean pixel accuracy {_fmt(self.values['mean_pixel_accuracy'], digits)}",
865
+ f" Boundary IoU {_fmt(self.values['boundary_iou'], digits)}",
866
+ f" {'HD95' + unit:<27} {_fmt(self.values['hd95'], digits)}",
867
+ f" {'ASSD' + unit:<27} {_fmt(self.values['assd'], digits)}",
868
+ "",
869
+ ]
870
+ header, body = self._table(digits)
871
+ widths = [max(len(h), *(len(r[i]) for r in body)) for i, h in enumerate(header)]
872
+ lines.append(" ".join(h.ljust(widths[i]) if i == 0 else h.rjust(widths[i]) for i, h in enumerate(header)))
873
+ lines += [
874
+ " ".join(c.ljust(widths[i]) if i == 0 else c.rjust(widths[i]) for i, c in enumerate(r)) for r in body
875
+ ]
876
+ return "\n".join(lines)
877
+
878
+ def __repr__(self) -> str:
879
+ return self.summary()
880
+
881
+ def to_dict(self) -> dict[str, Any]:
882
+ return cast(
883
+ "dict[str, Any]",
884
+ _json_safe(
885
+ {
886
+ "values": dict(self.values),
887
+ "per_class": [dict(r) for r in self.rows],
888
+ "params": dict(self.params),
889
+ }
890
+ ),
891
+ )
892
+
893
+ def to_json(self, *, indent: Optional[int] = 2) -> str:
894
+ return json.dumps(self.to_dict(), indent=indent, allow_nan=False)
895
+
896
+ def to_dataframe(self) -> pd.DataFrame:
897
+ import pandas as pd
898
+
899
+ frame: pd.DataFrame = pd.DataFrame([dict(r) for r in self.rows]).set_index("class")
900
+ return frame
901
+
902
+ def to_markdown(self, *, digits: int = 4) -> str:
903
+ header, body = self._table(digits)
904
+ lines = ["| " + " | ".join(header) + " |", "| --- |" + " ---: |" * (len(header) - 1)]
905
+ return "\n".join(lines + ["| " + " | ".join(r) + " |" for r in body])
906
+
907
+ def to_latex(self, *, digits: int = 4, caption: Optional[str] = None, label: Optional[str] = None) -> str:
908
+ header, body = self._table(digits)
909
+ return _latex_table(
910
+ [_latex_escape(h) for h in header],
911
+ [[_latex_escape(c) for c in r] for r in body],
912
+ caption or "Segmentation results per class.",
913
+ label,
914
+ )
915
+
916
+ def to_csv(self, path: Optional[PathLike] = None) -> str:
917
+ cols = ["class", "name", *_REPORT_COLUMNS, "support"]
918
+ text = csv_text(cols, [[r[c] for c in cols] for r in self.rows])
919
+ if path is not None:
920
+ with open(path, "w", encoding="utf-8", newline="") as fh:
921
+ fh.write(text)
922
+ return text
923
+
924
+ def to_html(self, *, digits: int = 4, full: bool = True) -> str:
925
+ summary = [
926
+ ["mIoU", _fmt(self.values["miou"], digits)],
927
+ ["Mean Dice", _fmt(self.values["dice"], digits)],
928
+ ["Pixel accuracy", _fmt(self.values["pixel_accuracy"], digits)],
929
+ ["Boundary IoU", _fmt(self.values["boundary_iou"], digits)],
930
+ ["HD95", _fmt(self.values["hd95"], digits)],
931
+ ["ASSD", _fmt(self.values["assd"], digits)],
932
+ ]
933
+ header, body = self._table(digits)
934
+ html = html_table(["Measure", "Value"], summary, caption="Summary")
935
+ html += "\n" + html_table(header, body, caption="Per class")
936
+ return html_document("EvalSuite segmentation evaluation", html) if full else html
937
+
938
+ def save(self, path: PathLike) -> str:
939
+ return save_as(
940
+ path,
941
+ {
942
+ "json": self.to_json,
943
+ "csv": self.to_csv,
944
+ "markdown": self.to_markdown,
945
+ "latex": self.to_latex,
946
+ "html": self.to_html,
947
+ "text": self.summary,
948
+ },
949
+ )
950
+
951
+
952
+ def segmentation_report(
953
+ y_true: Masks,
954
+ y_pred: Masks,
955
+ *,
956
+ num_classes: Optional[int] = None,
957
+ ignore_index: Optional[int] = None,
958
+ class_names: Optional[Mapping[int, str]] = None,
959
+ spacing: Optional[Sequence[float]] = None,
960
+ aggregate: Aggregate = "dataset",
961
+ include_background: bool = True,
962
+ dilation_ratio: float = 0.02,
963
+ ) -> SegmentationReport:
964
+ """Dice, IoU, Boundary IoU, HD95 and ASSD per class plus mIoU, mean Dice, pixel accuracy and mean pixel
965
+ accuracy, in one call. Surface distances are per image (averaged), overlap scores use ``aggregate``."""
966
+ pairs = _pairs(y_true, y_pred)
967
+ cls = _classes(pairs, num_classes, None, ignore_index, include_background)
968
+ common: dict[str, Any] = {"labels": cls.tolist(), "ignore_index": ignore_index, "include_background": True}
969
+ with warnings.catch_warnings():
970
+ warnings.simplefilter("ignore", UndefinedMetricWarning)
971
+ d = np.asarray(dice(y_true, y_pred, average=None, aggregate=aggregate, **common).value, dtype=np.float64)
972
+ j = np.asarray(iou(y_true, y_pred, average=None, aggregate=aggregate, **common).value, dtype=np.float64)
973
+ b = np.asarray(
974
+ boundary_iou(y_true, y_pred, average=None, dilation_ratio=dilation_ratio, **common).value,
975
+ dtype=np.float64,
976
+ )
977
+ hd = np.asarray(
978
+ hausdorff_distance(y_true, y_pred, percentile=95, spacing=spacing, average=None, **common).value,
979
+ dtype=np.float64,
980
+ )
981
+ sd = np.asarray(
982
+ average_surface_distance(y_true, y_pred, spacing=spacing, average=None, **common).value,
983
+ dtype=np.float64,
984
+ )
985
+ tp, _fp, fn = _per_image_counts(pairs, cls, ignore_index)
986
+ support = (tp + fn).sum(0)
987
+
988
+ def mean(x: Any) -> float:
989
+ arr = np.asarray(x, dtype=np.float64)
990
+ arr = arr[~np.isnan(arr)]
991
+ return float(arr.mean()) if arr.size else math.nan
992
+
993
+ rows = [
994
+ {
995
+ "class": int(c),
996
+ "name": class_names.get(int(c), str(int(c))) if class_names else str(int(c)),
997
+ "dice": float(d[i]),
998
+ "iou": float(j[i]),
999
+ "boundary_iou": float(b[i]),
1000
+ "hd95": float(hd[i]),
1001
+ "assd": float(sd[i]),
1002
+ "support": float(support[i]),
1003
+ }
1004
+ for i, c in enumerate(cls)
1005
+ ]
1006
+ values = {
1007
+ "miou": mean(j),
1008
+ "dice": mean(d),
1009
+ "pixel_accuracy": float(pixel_accuracy(y_true, y_pred, ignore_index=ignore_index)),
1010
+ "mean_pixel_accuracy": float(
1011
+ mean_pixel_accuracy(y_true, y_pred, num_classes=num_classes, ignore_index=ignore_index)
1012
+ ),
1013
+ "boundary_iou": mean(b),
1014
+ "hd95": mean(hd),
1015
+ "assd": mean(sd),
1016
+ }
1017
+ return SegmentationReport(
1018
+ values,
1019
+ tuple(rows),
1020
+ {
1021
+ "n_images": len(pairs),
1022
+ "aggregate": aggregate,
1023
+ "ignore_index": ignore_index,
1024
+ "spacing": None if spacing is None else tuple(float(s) for s in spacing),
1025
+ "dilation_ratio": dilation_ratio,
1026
+ "include_background": include_background,
1027
+ },
1028
+ )