dataeval 0.70.1__tar.gz → 0.71.1__tar.gz

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 (85) hide show
  1. {dataeval-0.70.1 → dataeval-0.71.1}/PKG-INFO +5 -3
  2. {dataeval-0.70.1 → dataeval-0.71.1}/pyproject.toml +10 -5
  3. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/__init__.py +2 -1
  4. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/detectors/ood/ae.py +1 -1
  5. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/detectors/ood/aegmm.py +1 -1
  6. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/detectors/ood/base.py +1 -1
  7. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/detectors/ood/llr.py +3 -3
  8. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/detectors/ood/vae.py +1 -1
  9. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/detectors/ood/vaegmm.py +1 -1
  10. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/detectors/outliers.py +3 -8
  11. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/metrics/stats/base.py +103 -44
  12. dataeval-0.71.1/src/dataeval/_internal/metrics/stats/datasetstats.py +171 -0
  13. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/metrics/stats/dimensionstats.py +20 -20
  14. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/metrics/stats/hashstats.py +9 -9
  15. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/metrics/stats/pixelstats.py +24 -24
  16. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/metrics/stats/visualstats.py +38 -37
  17. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/models/tensorflow/autoencoder.py +2 -2
  18. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/models/tensorflow/losses.py +1 -1
  19. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/models/tensorflow/pixelcnn.py +1 -1
  20. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/models/tensorflow/trainer.py +1 -1
  21. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/models/tensorflow/utils.py +5 -5
  22. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/metrics/stats/__init__.py +8 -1
  23. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/utils/tensorflow/__init__.py +7 -1
  24. dataeval-0.71.1/src/dataeval/utils/tensorflow/loss/__init__.py +7 -0
  25. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/utils/tensorflow/models/__init__.py +5 -1
  26. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/utils/torch/__init__.py +11 -2
  27. dataeval-0.71.1/src/dataeval/utils/torch/datasets/__init__.py +12 -0
  28. dataeval-0.71.1/src/dataeval/utils/torch/models/__init__.py +11 -0
  29. dataeval-0.71.1/src/dataeval/utils/torch/trainer/__init__.py +7 -0
  30. dataeval-0.70.1/src/dataeval/_internal/metrics/stats/datasetstats.py +0 -99
  31. dataeval-0.70.1/src/dataeval/utils/tensorflow/loss/__init__.py +0 -3
  32. dataeval-0.70.1/src/dataeval/utils/torch/datasets/__init__.py +0 -7
  33. dataeval-0.70.1/src/dataeval/utils/torch/models/__init__.py +0 -7
  34. dataeval-0.70.1/src/dataeval/utils/torch/trainer/__init__.py +0 -3
  35. {dataeval-0.70.1 → dataeval-0.71.1}/LICENSE.txt +0 -0
  36. {dataeval-0.70.1 → dataeval-0.71.1}/README.md +0 -0
  37. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/datasets.py +0 -0
  38. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/detectors/__init__.py +0 -0
  39. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/detectors/clusterer.py +0 -0
  40. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/detectors/drift/__init__.py +0 -0
  41. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/detectors/drift/base.py +0 -0
  42. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/detectors/drift/cvm.py +0 -0
  43. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/detectors/drift/ks.py +0 -0
  44. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/detectors/drift/mmd.py +0 -0
  45. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/detectors/drift/torch.py +0 -0
  46. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/detectors/drift/uncertainty.py +0 -0
  47. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/detectors/duplicates.py +0 -0
  48. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/detectors/merged_stats.py +0 -0
  49. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/detectors/ood/__init__.py +0 -0
  50. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/interop.py +0 -0
  51. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/metrics/__init__.py +0 -0
  52. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/metrics/balance.py +0 -0
  53. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/metrics/ber.py +0 -0
  54. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/metrics/coverage.py +0 -0
  55. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/metrics/divergence.py +0 -0
  56. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/metrics/diversity.py +0 -0
  57. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/metrics/parity.py +0 -0
  58. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/metrics/stats/boxratiostats.py +0 -0
  59. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/metrics/stats/labelstats.py +0 -0
  60. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/metrics/uap.py +0 -0
  61. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/metrics/utils.py +0 -0
  62. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/models/__init__.py +0 -0
  63. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/models/pytorch/__init__.py +0 -0
  64. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/models/pytorch/autoencoder.py +0 -0
  65. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/models/pytorch/blocks.py +0 -0
  66. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/models/pytorch/utils.py +0 -0
  67. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/models/tensorflow/__init__.py +0 -0
  68. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/models/tensorflow/gmm.py +0 -0
  69. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/output.py +0 -0
  70. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/utils.py +0 -0
  71. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/workflows/__init__.py +0 -0
  72. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/_internal/workflows/sufficiency.py +0 -0
  73. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/detectors/__init__.py +0 -0
  74. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/detectors/drift/__init__.py +0 -0
  75. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/detectors/drift/kernels/__init__.py +0 -0
  76. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/detectors/drift/updates/__init__.py +0 -0
  77. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/detectors/linters/__init__.py +0 -0
  78. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/detectors/ood/__init__.py +0 -0
  79. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/metrics/__init__.py +0 -0
  80. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/metrics/bias/__init__.py +0 -0
  81. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/metrics/estimators/__init__.py +0 -0
  82. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/py.typed +0 -0
  83. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/utils/__init__.py +0 -0
  84. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/utils/tensorflow/recon/__init__.py +0 -0
  85. {dataeval-0.70.1 → dataeval-0.71.1}/src/dataeval/workflows/__init__.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: dataeval
3
- Version: 0.70.1
3
+ Version: 0.71.1
4
4
  Summary: DataEval provides a simple interface to characterize image data and its impact on model performance across classification and object-detection tasks
5
5
  Home-page: https://dataeval.ai/
6
6
  License: MIT
@@ -29,10 +29,12 @@ Requires-Dist: nvidia-cudnn-cu11 (>=8.6.0.163) ; extra == "tensorflow" or extra
29
29
  Requires-Dist: pillow (>=10.3.0)
30
30
  Requires-Dist: scikit-learn (>=1.5.0)
31
31
  Requires-Dist: scipy (>=1.10)
32
- Requires-Dist: tensorflow (>=2.14.1,<2.16) ; extra == "tensorflow" or extra == "all"
33
- Requires-Dist: tensorflow_probability (>=0.22.1,<0.24) ; extra == "tensorflow" or extra == "all"
32
+ Requires-Dist: tensorflow (>=2.16) ; extra == "tensorflow" or extra == "all"
33
+ Requires-Dist: tensorflow_probability (>=0.24) ; extra == "tensorflow" or extra == "all"
34
+ Requires-Dist: tf-keras (>2.16) ; extra == "tensorflow" or extra == "all"
34
35
  Requires-Dist: torch (>=2.2.0) ; extra == "torch" or extra == "all"
35
36
  Requires-Dist: torchvision (>=0.17.0) ; extra == "torch" or extra == "all"
37
+ Requires-Dist: tqdm
36
38
  Requires-Dist: xxhash (>=3.3)
37
39
  Project-URL: Documentation, https://dataeval.readthedocs.io/
38
40
  Project-URL: Repository, https://github.com/aria-ml/dataeval/
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "dataeval"
3
- version = "0.70.1" # dynamic
3
+ version = "0.71.1" # dynamic
4
4
  description = "DataEval provides a simple interface to characterize image data and its impact on model performance across classification and object-detection tasks"
5
5
  license = "MIT"
6
6
  readme = "README.md"
@@ -46,20 +46,22 @@ numpy = {version = ">1.24.3"}
46
46
  pillow = {version = ">=10.3.0"}
47
47
  scipy = {version = ">=1.10"}
48
48
  scikit-learn = {version = ">=1.5.0"}
49
+ tqdm = {version = "*"}
49
50
  xxhash = {version = ">=3.3"}
50
51
 
51
52
  # optional
52
53
  matplotlib = {version = "*", optional = true}
53
54
  nvidia-cudnn-cu11 = {version = ">=8.6.0.163", optional = true}
54
- tensorflow = {version = ">=2.14.1, <2.16", optional = true}
55
- tensorflow_probability = {version = ">=0.22.1, <0.24", optional = true}
55
+ tensorflow = {version = ">=2.16", optional = true}
56
+ tensorflow_probability = {version = ">=0.24", optional = true}
57
+ tf-keras = {version = ">2.16", optional = true}
56
58
  torch = {version = ">=2.2.0", source = "pytorch", optional = true}
57
59
  torchvision = {version = ">=0.17.0", source = "pytorch", optional = true}
58
60
 
59
61
  [tool.poetry.extras]
60
- tensorflow = ["tensorflow", "tensorflow_probability", "nvidia-cudnn-cu11"]
62
+ tensorflow = ["tensorflow", "tensorflow_probability", "tf-keras", "nvidia-cudnn-cu11"]
61
63
  torch = ["torch", "torchvision", "matplotlib", "nvidia-cudnn-cu11"]
62
- all = ["matplotlib", "nvidia-cudnn-cu11", "tensorflow", "tensorflow_probability", "torch", "torchvision"]
64
+ all = ["matplotlib", "nvidia-cudnn-cu11", "tensorflow", "tensorflow_probability", "tf-keras", "torch", "torchvision"]
63
65
 
64
66
  [tool.poetry.group.dev]
65
67
  optional = true
@@ -130,11 +132,14 @@ reportMissingImports = false
130
132
 
131
133
  [tool.pytest.ini_options]
132
134
  norecursedirs = ["prototype"]
135
+ testpaths = ["tests"]
133
136
  addopts = ["--pythonwarnings=ignore::DeprecationWarning", "--verbose", "--durations=20", "--durations-min=1.0"]
134
137
 
135
138
  [tool.coverage.run]
136
139
  source = ["src/dataeval", "src/dataeval/_internal"]
137
140
  branch = true
141
+ concurrency = ["multiprocessing"]
142
+ parallel = true
138
143
 
139
144
  [tool.coverage.report]
140
145
  exclude_also = ["raise NotImplementedError"]
@@ -1,8 +1,9 @@
1
- __version__ = "0.70.1"
1
+ __version__ = "0.71.1"
2
2
 
3
3
  from importlib.util import find_spec
4
4
 
5
5
  _IS_TORCH_AVAILABLE = find_spec("torch") is not None
6
+ _IS_TORCHVISION_AVAILABLE = find_spec("torchvision") is not None
6
7
  _IS_TENSORFLOW_AVAILABLE = find_spec("tensorflow") is not None and find_spec("tensorflow_probability") is not None
7
8
 
8
9
  del find_spec
@@ -10,9 +10,9 @@ from __future__ import annotations
10
10
 
11
11
  from typing import Callable
12
12
 
13
- import keras
14
13
  import numpy as np
15
14
  import tensorflow as tf
15
+ import tf_keras as keras
16
16
  from numpy.typing import ArrayLike
17
17
 
18
18
  from dataeval._internal.detectors.ood.base import OODBase, OODScoreOutput
@@ -10,8 +10,8 @@ from __future__ import annotations
10
10
 
11
11
  from typing import Callable
12
12
 
13
- import keras
14
13
  import tensorflow as tf
14
+ import tf_keras as keras
15
15
  from numpy.typing import ArrayLike
16
16
 
17
17
  from dataeval._internal.detectors.ood.base import OODGMMBase, OODScoreOutput
@@ -12,9 +12,9 @@ from abc import ABC, abstractmethod
12
12
  from dataclasses import dataclass
13
13
  from typing import Callable, Literal, cast
14
14
 
15
- import keras
16
15
  import numpy as np
17
16
  import tensorflow as tf
17
+ import tf_keras as keras
18
18
  from numpy.typing import ArrayLike, NDArray
19
19
 
20
20
  from dataeval._internal.interop import to_numpy
@@ -11,12 +11,12 @@ from __future__ import annotations
11
11
  from functools import partial
12
12
  from typing import Callable
13
13
 
14
- import keras
15
14
  import numpy as np
16
15
  import tensorflow as tf
17
- from keras.layers import Input
18
- from keras.models import Model
16
+ import tf_keras as keras
19
17
  from numpy.typing import ArrayLike, NDArray
18
+ from tf_keras.layers import Input
19
+ from tf_keras.models import Model
20
20
 
21
21
  from dataeval._internal.detectors.ood.base import OODBase, OODScoreOutput
22
22
  from dataeval._internal.interop import to_numpy
@@ -10,9 +10,9 @@ from __future__ import annotations
10
10
 
11
11
  from typing import Callable
12
12
 
13
- import keras
14
13
  import numpy as np
15
14
  import tensorflow as tf
15
+ import tf_keras as keras
16
16
  from numpy.typing import ArrayLike
17
17
 
18
18
  from dataeval._internal.detectors.ood.base import OODBase, OODScoreOutput
@@ -10,9 +10,9 @@ from __future__ import annotations
10
10
 
11
11
  from typing import Callable
12
12
 
13
- import keras
14
13
  import numpy as np
15
14
  import tensorflow as tf
15
+ import tf_keras as keras
16
16
  from numpy.typing import ArrayLike
17
17
 
18
18
  from dataeval._internal.detectors.ood.base import OODGMMBase, OODScoreOutput
@@ -147,7 +147,7 @@ class Outliers:
147
147
  mask = _get_outlier_mask(values.astype(np.float64), self.outlier_method, self.outlier_threshold)
148
148
  indices = np.flatnonzero(mask)
149
149
  for i, value in zip(indices, values[mask]):
150
- flagged_images.setdefault(i, {}).update({stat: value})
150
+ flagged_images.setdefault(int(i), {}).update({stat: value})
151
151
 
152
152
  return dict(sorted(flagged_images.items()))
153
153
 
@@ -261,11 +261,6 @@ class Outliers:
261
261
  >>> results.issues[10]
262
262
  {'skew': -3.906, 'kurtosis': 13.266, 'entropy': 0.2128, 'contrast': 1.25, 'zeros': 0.05493}
263
263
  """
264
- self.stats = datasetstats(
265
- images=data,
266
- use_dimension=self.use_dimension,
267
- use_pixel=self.use_pixel,
268
- use_visual=self.use_visual,
269
- )
270
- outliers = self._get_outliers({k: v for o in self.stats.outputs() for k, v in o.dict().items()})
264
+ self.stats = datasetstats(images=data)
265
+ outliers = self._get_outliers(self.stats.dict())
271
266
  return OutliersOutput(outliers)
@@ -3,9 +3,13 @@ from __future__ import annotations
3
3
  import re
4
4
  import warnings
5
5
  from dataclasses import dataclass
6
- from typing import Any, Callable, Iterable, NamedTuple, Optional, Union
6
+ from functools import partial
7
+ from itertools import repeat
8
+ from multiprocessing import Pool
9
+ from typing import Any, Callable, Generic, Iterable, NamedTuple, Optional, TypeVar, Union
7
10
 
8
11
  import numpy as np
12
+ import tqdm
9
13
  from numpy.typing import ArrayLike, NDArray
10
14
 
11
15
  from dataeval._internal.interop import to_numpy_iter
@@ -91,7 +95,11 @@ class BaseStatsOutput(OutputMetadata):
91
95
  return len(self.source_index)
92
96
 
93
97
 
94
- class StatsProcessor:
98
+ TStatsOutput = TypeVar("TStatsOutput", bound=BaseStatsOutput, covariant=True)
99
+
100
+
101
+ class StatsProcessor(Generic[TStatsOutput]):
102
+ output_class: type[TStatsOutput]
95
103
  cache_keys: list[str] = []
96
104
  image_function_map: dict[str, Callable[[StatsProcessor], Any]] = {}
97
105
  channel_function_map: dict[str, Callable[[StatsProcessor], Any]] = {}
@@ -119,6 +127,9 @@ class StatsProcessor:
119
127
  else:
120
128
  return self.fn_map[fn_key](self)
121
129
 
130
+ def process(self) -> dict:
131
+ return {k: self.fn_map[k](self) for k in self.fn_map}
132
+
122
133
  @property
123
134
  def image(self) -> NDArray:
124
135
  if self._image is None:
@@ -143,14 +154,66 @@ class StatsProcessor:
143
154
  self._scaled = self._scaled.reshape(self.image.shape[0], -1)
144
155
  return self._scaled
145
156
 
157
+ @classmethod
158
+ def convert_output(
159
+ cls, source: dict[str, Any], source_index: list[SourceIndex], box_count: list[int]
160
+ ) -> TStatsOutput:
161
+ output = {}
162
+ for key in source:
163
+ if key not in cls.output_class.__annotations__:
164
+ continue
165
+ stat_type: str = cls.output_class.__annotations__[key]
166
+ dtype_match = re.match(DTYPE_REGEX, stat_type)
167
+ if dtype_match is not None:
168
+ output[key] = np.asarray(source[key], dtype=np.dtype(dtype_match.group(1)))
169
+ else:
170
+ output[key] = source[key]
171
+ return cls.output_class(**output, source_index=source_index, box_count=np.asarray(box_count, dtype=np.uint16))
172
+
173
+
174
+ class StatsProcessorOutput(NamedTuple):
175
+ results: list[dict[str, Any]]
176
+ source_indices: list[SourceIndex]
177
+ box_counts: list[int]
178
+ warnings_list: list[tuple[int, int, NDArray, tuple[int, ...]]]
179
+
180
+
181
+ def process_stats(
182
+ i: int,
183
+ image_boxes: tuple[NDArray, NDArray | None],
184
+ per_channel: bool,
185
+ stats_processor_cls: Iterable[type[StatsProcessor]],
186
+ ) -> StatsProcessorOutput:
187
+ image, boxes = image_boxes
188
+ results_list: list[dict[str, Any]] = []
189
+ source_indices: list[SourceIndex] = []
190
+ box_counts: list[int] = []
191
+ warnings_list: list[tuple[int, int, NDArray, tuple[int, ...]]] = []
192
+ nboxes = [None] if boxes is None else normalize_box_shape(boxes)
193
+ for i_b, box in enumerate(nboxes):
194
+ i_b = None if box is None else i_b
195
+ processor_list = [p(image, box, per_channel) for p in stats_processor_cls]
196
+ if any(not p.is_valid_slice for p in processor_list) and i_b is not None and box is not None:
197
+ warnings_list.append((i, i_b, box, image.shape))
198
+ results_list.append({k: v for p in processor_list for k, v in p.process().items()})
199
+ if per_channel:
200
+ source_indices.extend([SourceIndex(i, i_b, c) for c in range(image_boxes[0].shape[-3])])
201
+ else:
202
+ source_indices.append(SourceIndex(i, i_b, None))
203
+ box_counts.append(0 if boxes is None else len(boxes))
204
+ return StatsProcessorOutput(results_list, source_indices, box_counts, warnings_list)
205
+
206
+
207
+ def process_stats_unpack(args, per_channel: bool, stats_processor_cls: Iterable[type[StatsProcessor]]):
208
+ return process_stats(*args, per_channel=per_channel, stats_processor_cls=stats_processor_cls)
209
+
146
210
 
147
211
  def run_stats(
148
212
  images: Iterable[ArrayLike],
149
213
  bboxes: Iterable[ArrayLike] | None,
150
214
  per_channel: bool,
151
- stats_processor_cls: type,
152
- output_cls: type,
153
- ) -> dict:
215
+ stats_processor_cls: Iterable[type[StatsProcessor[TStatsOutput]]],
216
+ ) -> list[TStatsOutput]:
154
217
  """
155
218
  Compute specified statistics on a set of images.
156
219
 
@@ -169,15 +232,13 @@ def run_stats(
169
232
  iterable should match the length of the input images.
170
233
  per_channel : bool
171
234
  A flag which determines if the states should be evaluated on a per-channel basis or not.
172
- output_cls : type
173
- The output class for which stats values will be calculated.
235
+ stats_processor_cls : Iterable[type[StatsProcessor]]
236
+ An iterable of stats processor classes that calculate stats and return output classes.
174
237
 
175
238
  Returns
176
239
  -------
177
- dict[str, NDArray]]
178
- A dictionary containing the computed statistics for each image.
179
- The dictionary keys correspond to the names of the statistics, and the values are NumPy arrays
180
- with the results of the computations.
240
+ list[TStatsOutput]
241
+ A list of output classes corresponding to the input processor types.
181
242
 
182
243
  Note
183
244
  ----
@@ -189,43 +250,41 @@ def run_stats(
189
250
  be reused to avoid redundant computation.
190
251
  """
191
252
  results_list: list[dict[str, NDArray]] = []
192
- output_list = list(output_cls.__annotations__)
193
253
  source_index = []
194
254
  box_count = []
195
- bbox_iter = (None for _ in images) if bboxes is None else to_numpy_iter(bboxes)
196
-
197
- for i, (boxes, image) in enumerate(zip(bbox_iter, to_numpy_iter(images))):
198
- nboxes = [None] if boxes is None else normalize_box_shape(boxes)
199
- for i_b, box in enumerate(nboxes):
200
- i_b = None if box is None else i_b
201
- processor: StatsProcessor = stats_processor_cls(image, box, per_channel)
202
- if not processor.is_valid_slice:
203
- warnings.warn(f"Bounding box {i_b}: {box} is out of bounds of image {i}: {image.shape}.")
204
- results_list.append({stat: processor.get(stat) for stat in output_list})
205
- if per_channel:
206
- source_index.extend([SourceIndex(i, i_b, c) for c in range(image.shape[-3])])
207
- else:
208
- source_index.append(SourceIndex(i, i_b, None))
209
- box_count.append(0 if boxes is None else len(boxes))
255
+ bbox_iter = repeat(None) if bboxes is None else to_numpy_iter(bboxes)
256
+
257
+ warning_list = []
258
+ total_for_status = getattr(images, "__len__")() if hasattr(images, "__len__") else None
259
+ stats_processor_cls = stats_processor_cls if isinstance(stats_processor_cls, Iterable) else [stats_processor_cls]
260
+
261
+ # TODO: Introduce global controls for CPU job parallelism and GPU configurations
262
+ with Pool(16) as p:
263
+ for r in tqdm.tqdm(
264
+ p.imap(
265
+ partial(process_stats_unpack, per_channel=per_channel, stats_processor_cls=stats_processor_cls),
266
+ enumerate(zip(to_numpy_iter(images), bbox_iter)),
267
+ ),
268
+ total=total_for_status,
269
+ ):
270
+ results_list.extend(r.results)
271
+ source_index.extend(r.source_indices)
272
+ box_count.extend(r.box_counts)
273
+ warning_list.extend(r.warnings_list)
274
+ p.close()
275
+ p.join()
276
+
277
+ # warnings are not emitted while in multiprocessing pools so we emit after gathering all warnings
278
+ for w in warning_list:
279
+ warnings.warn(f"Bounding box [{w[0]}][{w[1]}]: {w[2]} is out of bounds of {w[3]}.", UserWarning)
210
280
 
211
281
  output = {}
212
- if per_channel:
213
- for i, results in enumerate(results_list):
214
- for stat, result in results.items():
282
+ for results in results_list:
283
+ for stat, result in results.items():
284
+ if per_channel:
215
285
  output.setdefault(stat, []).extend(result.tolist())
216
- else:
217
- for results in results_list:
218
- for stat, result in results.items():
286
+ else:
219
287
  output.setdefault(stat, []).append(result.tolist() if isinstance(result, np.ndarray) else result)
220
288
 
221
- for stat in output:
222
- stat_type: str = output_cls.__annotations__[stat]
223
-
224
- dtype_match = re.match(DTYPE_REGEX, stat_type)
225
- if dtype_match is not None:
226
- output[stat] = np.asarray(output[stat], dtype=np.dtype(dtype_match.group(1)))
227
-
228
- output[SOURCE_INDEX] = source_index
229
- output[BOX_COUNT] = np.asarray(box_count, dtype=np.uint16)
230
-
231
- return output
289
+ outputs = [s.convert_output(output, source_index, box_count) for s in stats_processor_cls]
290
+ return outputs
@@ -0,0 +1,171 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Any, Iterable
5
+
6
+ from numpy.typing import ArrayLike
7
+
8
+ from dataeval._internal.metrics.stats.base import BaseStatsOutput, run_stats
9
+ from dataeval._internal.metrics.stats.dimensionstats import (
10
+ DimensionStatsOutput,
11
+ DimensionStatsProcessor,
12
+ )
13
+ from dataeval._internal.metrics.stats.labelstats import LabelStatsOutput, labelstats
14
+ from dataeval._internal.metrics.stats.pixelstats import PixelStatsOutput, PixelStatsProcessor
15
+ from dataeval._internal.metrics.stats.visualstats import VisualStatsOutput, VisualStatsProcessor
16
+ from dataeval._internal.output import OutputMetadata, set_metadata
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class DatasetStatsOutput(OutputMetadata):
21
+ """
22
+ Output class for :func:`datasetstats` stats metric
23
+
24
+ This class represents the outputs of various stats functions against a single
25
+ dataset, such that each index across all stat outputs are representative of
26
+ the same source image. Modifying or mixing outputs will result in inaccurate
27
+ outlier calculations if not created correctly.
28
+
29
+ Attributes
30
+ ----------
31
+ dimensionstats : DimensionStatsOutput
32
+ pixelstats: PixelStatsOutput
33
+ visualstats: VisualStatsOutput
34
+ labelstats: LabelStatsOutput or None
35
+ """
36
+
37
+ dimensionstats: DimensionStatsOutput
38
+ pixelstats: PixelStatsOutput
39
+ visualstats: VisualStatsOutput
40
+ labelstats: LabelStatsOutput | None = None
41
+
42
+ def outputs(self) -> list[OutputMetadata]:
43
+ return [s for s in (self.dimensionstats, self.pixelstats, self.visualstats, self.labelstats) if s is not None]
44
+
45
+ def dict(self) -> dict[str, Any]:
46
+ return {k: v for o in self.outputs() for k, v in o.dict().items()}
47
+
48
+ def __post_init__(self):
49
+ lengths = [len(s) for s in self.outputs() if isinstance(s, BaseStatsOutput)]
50
+ if not all(length == lengths[0] for length in lengths):
51
+ raise ValueError("All StatsOutput classes must contain the same number of image sources.")
52
+
53
+
54
+ @dataclass(frozen=True)
55
+ class ChannelStatsOutput(OutputMetadata):
56
+ """
57
+ Output class for :func:`channelstats` stats metric
58
+
59
+ This class represents the outputs of various per-channel stats functions against
60
+ a single dataset, such that each index across all stat outputs are representative
61
+ of the same source image. Modifying or mixing outputs will result in inaccurate
62
+ outlier calculations if not created correctly.
63
+
64
+ Attributes
65
+ ----------
66
+ pixelstats: PixelStatsOutput
67
+ visualstats: VisualStatsOutput
68
+ """
69
+
70
+ pixelstats: PixelStatsOutput
71
+ visualstats: VisualStatsOutput
72
+
73
+ def outputs(self) -> list[BaseStatsOutput]:
74
+ return [self.pixelstats, self.visualstats]
75
+
76
+ def dict(self) -> dict[str, Any]:
77
+ return {**self.pixelstats.dict(), **self.visualstats.dict()}
78
+
79
+ def __post_init__(self):
80
+ lengths = [len(s) for s in self.outputs()]
81
+ if not all(length == lengths[0] for length in lengths):
82
+ raise ValueError("All StatsOutput classes must contain the same number of image sources.")
83
+
84
+
85
+ @set_metadata("dataeval.metrics")
86
+ def datasetstats(
87
+ images: Iterable[ArrayLike],
88
+ bboxes: Iterable[ArrayLike] | None = None,
89
+ labels: Iterable[ArrayLike] | None = None,
90
+ ) -> DatasetStatsOutput:
91
+ """
92
+ Calculates various statistics for each image
93
+
94
+ This function computes dimension, pixel and visual metrics
95
+ on the images or individual bounding boxes for each image as
96
+ well as label statistics if provided.
97
+
98
+ Parameters
99
+ ----------
100
+ images : Iterable[ArrayLike]
101
+ Images to perform calculations on
102
+ bboxes : Iterable[ArrayLike] or None
103
+ Bounding boxes in `xyxy` format for each image to perform calculations on
104
+ labels : Iterable[ArrayLike] or None
105
+ Labels of images or boxes to perform calculations on
106
+
107
+ Returns
108
+ -------
109
+ DatasetStatsOutput
110
+ Output class containing the outputs of various stats functions
111
+
112
+ See Also
113
+ --------
114
+ dimensionstats, labelstats, pixelstats, visualstats, Outliers
115
+
116
+ Examples
117
+ --------
118
+ Calculating the dimension, pixel and visual stats for a dataset with bounding boxes
119
+
120
+ >>> stats = datasetstats(images, bboxes)
121
+ >>> print(stats.dimensionstats.aspect_ratio)
122
+ [ 0.864 0.5884 16. 1.143 1.692 0.5835 0.6665 2.555 1.3
123
+ 0.8335 1. 0.6 0.522 15. 3.834 1.75 0.75 0.7 ]
124
+ >>> print(stats.visualstats.contrast)
125
+ [1.744 1.946 0.1164 0.0635 0.0633 0.06274 0.0429 0.0317 0.0317
126
+ 0.02576 0.02081 0.02171 0.01915 0.01767 0.01799 0.01595 0.01433 0.01478]
127
+ """
128
+ outputs = run_stats(images, bboxes, False, [DimensionStatsProcessor, PixelStatsProcessor, VisualStatsProcessor])
129
+ return DatasetStatsOutput(*outputs, labelstats=labelstats(labels) if labels else None) # type: ignore
130
+
131
+
132
+ @set_metadata("dataeval.metrics")
133
+ def channelstats(
134
+ images: Iterable[ArrayLike],
135
+ bboxes: Iterable[ArrayLike] | None = None,
136
+ ) -> ChannelStatsOutput:
137
+ """
138
+ Calculates various per-channel statistics for each image
139
+
140
+ This function computes pixel and visual metrics on the images
141
+ or individual bounding boxes for each image.
142
+
143
+ Parameters
144
+ ----------
145
+ images : Iterable[ArrayLike]
146
+ Images to perform calculations on
147
+ bboxes : Iterable[ArrayLike] or None
148
+ Bounding boxes in `xyxy` format for each image to perform calculations on
149
+
150
+ Returns
151
+ -------
152
+ ChannelStatsOutput
153
+ Output class containing the per-channel outputs of various stats functions
154
+
155
+ See Also
156
+ --------
157
+ pixelstats, visualstats
158
+
159
+ Examples
160
+ --------
161
+ Calculating the per-channel pixel and visual stats for a dataset
162
+
163
+ >>> stats = channelstats(images)
164
+ >>> print(stats.visualstats.darkness)
165
+ [0.07495 0.1748 0.275 0.1047 0.11096 0.1172 0.2047 0.2109 0.2172
166
+ 0.3047 0.311 0.3171 0.4048 0.411 0.4172 0.505 0.5107 0.517
167
+ 0.6045 0.611 0.617 0.7046 0.711 0.7173 0.8047 0.811 0.8174
168
+ 0.905 0.911 0.917 ]
169
+ """
170
+ outputs = run_stats(images, bboxes, True, [PixelStatsProcessor, VisualStatsProcessor])
171
+ return ChannelStatsOutput(*outputs) # type: ignore
@@ -11,24 +11,6 @@ from dataeval._internal.metrics.utils import get_bitdepth
11
11
  from dataeval._internal.output import set_metadata
12
12
 
13
13
 
14
- class DimensionStatsProcessor(StatsProcessor):
15
- image_function_map = {
16
- "left": lambda x: x.box[0],
17
- "top": lambda x: x.box[1],
18
- "width": lambda x: x.shape[-1],
19
- "height": lambda x: x.shape[-2],
20
- "channels": lambda x: x.shape[-3],
21
- "size": lambda x: np.prod(x.shape[-2:]),
22
- "aspect_ratio": lambda x: x.shape[-1] / x.shape[-2],
23
- "depth": lambda x: get_bitdepth(x.image).depth,
24
- "center": lambda x: np.asarray([(x.box[0] + x.box[2]) / 2, (x.box[1] + x.box[3]) / 2]),
25
- "distance": lambda x: np.sqrt(
26
- np.square(((x.box[0] + x.box[2]) / 2) - (x.width / 2))
27
- + np.square(((x.box[1] + x.box[3]) / 2) - (x.height / 2))
28
- ),
29
- }
30
-
31
-
32
14
  @dataclass(frozen=True)
33
15
  class DimensionStatsOutput(BaseStatsOutput):
34
16
  """
@@ -70,6 +52,25 @@ class DimensionStatsOutput(BaseStatsOutput):
70
52
  distance: NDArray[np.float16]
71
53
 
72
54
 
55
+ class DimensionStatsProcessor(StatsProcessor[DimensionStatsOutput]):
56
+ output_class = DimensionStatsOutput
57
+ image_function_map = {
58
+ "left": lambda x: x.box[0],
59
+ "top": lambda x: x.box[1],
60
+ "width": lambda x: x.box[2] - x.box[0],
61
+ "height": lambda x: x.box[3] - x.box[1],
62
+ "channels": lambda x: x.shape[-3],
63
+ "size": lambda x: (x.box[2] - x.box[0]) * (x.box[3] - x.box[1]),
64
+ "aspect_ratio": lambda x: (x.box[2] - x.box[0]) / (x.box[3] - x.box[1]),
65
+ "depth": lambda x: get_bitdepth(x.image).depth,
66
+ "center": lambda x: np.asarray([(x.box[0] + x.box[2]) / 2, (x.box[1] + x.box[3]) / 2]),
67
+ "distance": lambda x: np.sqrt(
68
+ np.square(((x.box[0] + x.box[2]) / 2) - (x.shape[-1] / 2))
69
+ + np.square(((x.box[1] + x.box[3]) / 2) - (x.shape[-2] / 2))
70
+ ),
71
+ }
72
+
73
+
73
74
  @set_metadata("dataeval.metrics")
74
75
  def dimensionstats(
75
76
  images: Iterable[ArrayLike],
@@ -109,5 +110,4 @@ def dimensionstats(
109
110
  >>> print(results.channels)
110
111
  [1 1 1 1 1 1 3 1 1 3]
111
112
  """
112
- output = run_stats(images, bboxes, False, DimensionStatsProcessor, DimensionStatsOutput)
113
- return DimensionStatsOutput(**output)
113
+ return run_stats(images, bboxes, False, [DimensionStatsProcessor])[0]
@@ -10,13 +10,6 @@ from dataeval._internal.metrics.utils import pchash, xxhash
10
10
  from dataeval._internal.output import set_metadata
11
11
 
12
12
 
13
- class HashStatsProcessor(StatsProcessor):
14
- image_function_map = {
15
- "xxhash": lambda x: xxhash(x.image),
16
- "pchash": lambda x: pchash(x.image),
17
- }
18
-
19
-
20
13
  @dataclass(frozen=True)
21
14
  class HashStatsOutput(BaseStatsOutput):
22
15
  """
@@ -34,6 +27,14 @@ class HashStatsOutput(BaseStatsOutput):
34
27
  pchash: list[str]
35
28
 
36
29
 
30
+ class HashStatsProcessor(StatsProcessor[HashStatsOutput]):
31
+ output_class = HashStatsOutput
32
+ image_function_map = {
33
+ "xxhash": lambda x: xxhash(x.image),
34
+ "pchash": lambda x: pchash(x.image),
35
+ }
36
+
37
+
37
38
  @set_metadata("dataeval.metrics")
38
39
  def hashstats(
39
40
  images: Iterable[ArrayLike],
@@ -71,5 +72,4 @@ def hashstats(
71
72
  >>> print(results.pchash)
72
73
  ['8f25506af46a7c6a', '8000808000008080', '8e71f18e0ef18e0e', 'a956d6a956d6a928']
73
74
  """
74
- output = run_stats(images, bboxes, False, HashStatsProcessor, HashStatsOutput)
75
- return HashStatsOutput(**output)
75
+ return run_stats(images, bboxes, False, [HashStatsProcessor])[0]