dataeval 0.76.1__py3-none-any.whl → 0.81.0__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.
Files changed (96) hide show
  1. dataeval/__init__.py +3 -3
  2. dataeval/{output.py → _output.py} +14 -0
  3. dataeval/config.py +77 -0
  4. dataeval/detectors/__init__.py +1 -1
  5. dataeval/detectors/drift/__init__.py +6 -6
  6. dataeval/detectors/drift/{base.py → _base.py} +41 -30
  7. dataeval/detectors/drift/{cvm.py → _cvm.py} +21 -28
  8. dataeval/detectors/drift/{ks.py → _ks.py} +20 -26
  9. dataeval/detectors/drift/{mmd.py → _mmd.py} +33 -19
  10. dataeval/detectors/drift/{torch.py → _torch.py} +2 -1
  11. dataeval/detectors/drift/{uncertainty.py → _uncertainty.py} +23 -7
  12. dataeval/detectors/drift/updates.py +1 -1
  13. dataeval/detectors/linters/__init__.py +0 -3
  14. dataeval/detectors/linters/duplicates.py +17 -8
  15. dataeval/detectors/linters/outliers.py +23 -14
  16. dataeval/detectors/ood/ae.py +29 -8
  17. dataeval/detectors/ood/base.py +5 -4
  18. dataeval/detectors/ood/metadata_ks_compare.py +1 -1
  19. dataeval/detectors/ood/mixin.py +20 -5
  20. dataeval/detectors/ood/output.py +1 -1
  21. dataeval/detectors/ood/vae.py +73 -0
  22. dataeval/metadata/__init__.py +5 -0
  23. dataeval/metadata/_ood.py +238 -0
  24. dataeval/metrics/__init__.py +1 -1
  25. dataeval/metrics/bias/__init__.py +5 -4
  26. dataeval/metrics/bias/{balance.py → _balance.py} +67 -17
  27. dataeval/metrics/bias/{coverage.py → _coverage.py} +41 -35
  28. dataeval/metrics/bias/{diversity.py → _diversity.py} +17 -12
  29. dataeval/metrics/bias/{parity.py → _parity.py} +89 -61
  30. dataeval/metrics/estimators/__init__.py +14 -4
  31. dataeval/metrics/estimators/{ber.py → _ber.py} +42 -11
  32. dataeval/metrics/estimators/_clusterer.py +104 -0
  33. dataeval/metrics/estimators/{divergence.py → _divergence.py} +18 -13
  34. dataeval/metrics/estimators/{uap.py → _uap.py} +4 -4
  35. dataeval/metrics/stats/__init__.py +7 -7
  36. dataeval/metrics/stats/{base.py → _base.py} +52 -16
  37. dataeval/metrics/stats/{boxratiostats.py → _boxratiostats.py} +6 -9
  38. dataeval/metrics/stats/{datasetstats.py → _datasetstats.py} +10 -14
  39. dataeval/metrics/stats/{dimensionstats.py → _dimensionstats.py} +6 -5
  40. dataeval/metrics/stats/{hashstats.py → _hashstats.py} +6 -6
  41. dataeval/metrics/stats/{labelstats.py → _labelstats.py} +4 -4
  42. dataeval/metrics/stats/{pixelstats.py → _pixelstats.py} +5 -4
  43. dataeval/metrics/stats/{visualstats.py → _visualstats.py} +9 -8
  44. dataeval/typing.py +54 -0
  45. dataeval/utils/__init__.py +2 -2
  46. dataeval/utils/_array.py +169 -0
  47. dataeval/utils/_bin.py +199 -0
  48. dataeval/utils/_clusterer.py +144 -0
  49. dataeval/utils/_fast_mst.py +189 -0
  50. dataeval/utils/{image.py → _image.py} +6 -4
  51. dataeval/utils/_method.py +18 -0
  52. dataeval/utils/{shared.py → _mst.py} +3 -65
  53. dataeval/utils/{plot.py → _plot.py} +4 -4
  54. dataeval/utils/data/__init__.py +22 -0
  55. dataeval/utils/data/_embeddings.py +105 -0
  56. dataeval/utils/data/_images.py +65 -0
  57. dataeval/utils/data/_metadata.py +352 -0
  58. dataeval/utils/data/_selection.py +119 -0
  59. dataeval/utils/{dataset/split.py → data/_split.py} +13 -14
  60. dataeval/utils/data/_targets.py +73 -0
  61. dataeval/utils/data/_types.py +58 -0
  62. dataeval/utils/data/collate.py +103 -0
  63. dataeval/utils/data/datasets/__init__.py +17 -0
  64. dataeval/utils/data/datasets/_base.py +254 -0
  65. dataeval/utils/data/datasets/_cifar10.py +134 -0
  66. dataeval/utils/data/datasets/_fileio.py +168 -0
  67. dataeval/utils/data/datasets/_milco.py +153 -0
  68. dataeval/utils/data/datasets/_mixin.py +56 -0
  69. dataeval/utils/data/datasets/_mnist.py +183 -0
  70. dataeval/utils/data/datasets/_ships.py +123 -0
  71. dataeval/utils/data/datasets/_voc.py +352 -0
  72. dataeval/utils/data/selections/__init__.py +15 -0
  73. dataeval/utils/data/selections/_classfilter.py +60 -0
  74. dataeval/utils/data/selections/_indices.py +26 -0
  75. dataeval/utils/data/selections/_limit.py +26 -0
  76. dataeval/utils/data/selections/_reverse.py +18 -0
  77. dataeval/utils/data/selections/_shuffle.py +29 -0
  78. dataeval/utils/metadata.py +51 -376
  79. dataeval/utils/torch/{gmm.py → _gmm.py} +4 -2
  80. dataeval/utils/torch/{internal.py → _internal.py} +21 -51
  81. dataeval/utils/torch/models.py +43 -2
  82. dataeval/workflows/sufficiency.py +10 -9
  83. {dataeval-0.76.1.dist-info → dataeval-0.81.0.dist-info}/METADATA +4 -1
  84. dataeval-0.81.0.dist-info/RECORD +94 -0
  85. dataeval/detectors/linters/clusterer.py +0 -512
  86. dataeval/detectors/linters/merged_stats.py +0 -49
  87. dataeval/detectors/ood/metadata_least_likely.py +0 -119
  88. dataeval/interop.py +0 -69
  89. dataeval/utils/dataset/__init__.py +0 -7
  90. dataeval/utils/dataset/datasets.py +0 -412
  91. dataeval/utils/dataset/read.py +0 -63
  92. dataeval-0.76.1.dist-info/RECORD +0 -67
  93. /dataeval/{log.py → _log.py} +0 -0
  94. /dataeval/utils/torch/{blocks.py → _blocks.py} +0 -0
  95. {dataeval-0.76.1.dist-info → dataeval-0.81.0.dist-info}/LICENSE.txt +0 -0
  96. {dataeval-0.76.1.dist-info → dataeval-0.81.0.dist-info}/WHEEL +0 -0
@@ -0,0 +1,352 @@
1
+ from __future__ import annotations
2
+
3
+ __all__ = []
4
+
5
+ import warnings
6
+ from typing import TYPE_CHECKING, Any, Literal, Mapping, Sequence
7
+
8
+ import numpy as np
9
+ from numpy.typing import NDArray
10
+
11
+ from dataeval.typing import Array
12
+ from dataeval.utils._array import as_numpy, to_numpy
13
+ from dataeval.utils._bin import bin_data, digitize_data, is_continuous
14
+ from dataeval.utils.data._types import (
15
+ Dataset,
16
+ ObjectDetectionTarget,
17
+ )
18
+ from dataeval.utils.metadata import merge
19
+
20
+ if TYPE_CHECKING:
21
+ from dataeval.utils.data import Targets
22
+ else:
23
+ from dataeval.utils.data._targets import Targets
24
+
25
+
26
+ class Metadata:
27
+ """
28
+ Class containing binned metadata.
29
+
30
+ Attributes
31
+ ----------
32
+ discrete_factor_names : list[str]
33
+ List containing factor names for the original data that was discrete and
34
+ the binned continuous data
35
+ discrete_data : NDArray[np.int64]
36
+ Array containing values for the original data that was discrete and the
37
+ binned continuous data
38
+ continuous_factor_names : list[str]
39
+ List containing factor names for the original continuous data
40
+ continuous_data : NDArray[np.float64] | None
41
+ Array containing values for the original continuous data or None if there
42
+ was no continuous data
43
+ class_labels : NDArray[np.int]
44
+ Numerical class labels for the images/objects
45
+ class_names : list[str]
46
+ List of unique class names
47
+ total_num_factors : int
48
+ Sum of discrete_factor_names and continuous_factor_names plus 1 for class
49
+ image_indices : NDArray[np.intp]
50
+ Array of the image index that is mapped by the index of the factor
51
+
52
+ Parameters
53
+ ----------
54
+ dataset : ImageClassificationDataset or ObjectDetectionDataset
55
+ Dataset to access original targets and metadata from.
56
+ continuous_factor_bins : Mapping[str, int | Sequence[float]] | None, default None
57
+ Mapping from continuous factor name to the number of bins or bin edges
58
+ auto_bin_method : Literal["uniform_width", "uniform_count", "clusters"], default "uniform_width"
59
+ Method for automatically determining the number of bins for continuous factors
60
+ exclude : Sequence[str] | None, default None
61
+ Filter metadata factors to exclude the specified factors, cannot be set with `include`
62
+ include : Sequence[str] | None, default None
63
+ Filter metadata factors to include the specified factors, cannot be set with `exclude`
64
+ """
65
+
66
+ def __init__(
67
+ self,
68
+ dataset: Dataset[Any, Any],
69
+ *,
70
+ continuous_factor_bins: Mapping[str, int | Sequence[float]] | None = None,
71
+ auto_bin_method: Literal["uniform_width", "uniform_count", "clusters"] = "uniform_width",
72
+ exclude: Sequence[str] | None = None,
73
+ include: Sequence[str] | None = None,
74
+ ) -> None:
75
+ self._collated = False
76
+ self._merged = None
77
+ self._processed = False
78
+
79
+ self._dataset = dataset
80
+ self._continuous_factor_bins = dict(continuous_factor_bins) if continuous_factor_bins else {}
81
+ self._auto_bin_method = auto_bin_method
82
+
83
+ if exclude is not None and include is not None:
84
+ raise ValueError("Filters for `exclude` and `include` are mutually exclusive.")
85
+
86
+ self._exclude = set(exclude or ())
87
+ self._include = set(include or ())
88
+
89
+ @property
90
+ def targets(self) -> Targets:
91
+ self._collate()
92
+ return self._targets
93
+
94
+ @property
95
+ def raw(self) -> list[dict[str, Any]]:
96
+ self._collate()
97
+ return self._raw
98
+
99
+ @property
100
+ def exclude(self) -> set[str]:
101
+ return self._exclude
102
+
103
+ @exclude.setter
104
+ def exclude(self, value: Sequence[str]) -> None:
105
+ exclude = set(value)
106
+ if self._exclude != exclude:
107
+ self._exclude = exclude
108
+ self._include = set()
109
+ self._processed = False
110
+
111
+ @property
112
+ def include(self) -> set[str]:
113
+ return self._include
114
+
115
+ @include.setter
116
+ def include(self, value: Sequence[str]) -> None:
117
+ include = set(value)
118
+ if self._include != include:
119
+ self._include = include
120
+ self._exclude = set()
121
+ self._processed = False
122
+
123
+ @property
124
+ def continuous_factor_bins(self) -> Mapping[str, int | Sequence[float]]:
125
+ return self._continuous_factor_bins
126
+
127
+ @continuous_factor_bins.setter
128
+ def continuous_factor_bins(self, bins: Mapping[str, int | Sequence[float]]) -> None:
129
+ if self._continuous_factor_bins != bins:
130
+ self._continuous_factor_bins = dict(bins)
131
+ self._processed = False
132
+
133
+ @property
134
+ def auto_bin_method(self) -> str:
135
+ return self._auto_bin_method
136
+
137
+ @auto_bin_method.setter
138
+ def auto_bin_method(self, method: Literal["uniform_width", "uniform_count", "clusters"]) -> None:
139
+ if self._auto_bin_method != method:
140
+ self._auto_bin_method = method
141
+ self._processed = False
142
+
143
+ @property
144
+ def merged(self) -> dict[str, Any]:
145
+ self._merge()
146
+ return {} if self._merged is None else self._merged[0]
147
+
148
+ @property
149
+ def dropped_factors(self) -> dict[str, list[str]]:
150
+ self._merge()
151
+ return {} if self._merged is None else self._merged[1]
152
+
153
+ @property
154
+ def discrete_factor_names(self) -> list[str]:
155
+ self._process()
156
+ return self._discrete_factor_names
157
+
158
+ @property
159
+ def discrete_data(self) -> NDArray[np.int64]:
160
+ self._process()
161
+ return self._discrete_data
162
+
163
+ @property
164
+ def continuous_factor_names(self) -> list[str]:
165
+ self._process()
166
+ return self._continuous_factor_names
167
+
168
+ @property
169
+ def continuous_data(self) -> NDArray[np.float64]:
170
+ self._process()
171
+ return self._continuous_data
172
+
173
+ @property
174
+ def class_labels(self) -> NDArray[np.intp]:
175
+ self._collate()
176
+ return self._class_labels
177
+
178
+ @property
179
+ def class_names(self) -> list[str]:
180
+ self._collate()
181
+ return self._class_names
182
+
183
+ @property
184
+ def total_num_factors(self) -> int:
185
+ self._process()
186
+ return self._total_num_factors
187
+
188
+ @property
189
+ def image_indices(self) -> NDArray[np.intp]:
190
+ self._process()
191
+ return self._image_indices
192
+
193
+ def _collate(self, force: bool = False):
194
+ if self._collated and not force:
195
+ return
196
+
197
+ raw: list[dict[str, Any]] = []
198
+
199
+ labels = []
200
+ bboxes = []
201
+ scores = []
202
+ srcidx = []
203
+ is_od = None
204
+ for i in range(len(self._dataset)):
205
+ _, target, metadata = self._dataset[i]
206
+
207
+ raw.append(metadata)
208
+
209
+ if is_od_target := isinstance(target, ObjectDetectionTarget):
210
+ target_len = len(target.labels)
211
+ labels.extend(as_numpy(target.labels).tolist())
212
+ bboxes.extend(as_numpy(target.boxes).tolist())
213
+ scores.extend(as_numpy(target.scores).tolist())
214
+ srcidx.extend([i] * target_len)
215
+ elif isinstance(target, Array):
216
+ target_len = 1
217
+ labels.append(int(np.argmax(as_numpy(target))))
218
+ scores.append(target)
219
+ else:
220
+ raise TypeError("Encountered unsupported target type in dataset")
221
+
222
+ is_od = is_od_target if is_od is None else is_od
223
+ if is_od != is_od_target:
224
+ raise ValueError("Encountered unexpected target type in dataset")
225
+
226
+ labels = as_numpy(labels).astype(np.intp)
227
+ scores = as_numpy(scores).astype(np.float32)
228
+ bboxes = as_numpy(bboxes).astype(np.float32) if is_od else None
229
+ srcidx = as_numpy(srcidx).astype(np.intp) if is_od else None
230
+
231
+ self._targets = Targets(labels, scores, bboxes, srcidx)
232
+ self._raw = raw
233
+
234
+ index2label = self._dataset.metadata.get("index2label", {})
235
+ self._class_labels = self._targets.labels
236
+ self._class_names = [index2label.get(i, str(i)) for i in np.unique(self._class_labels)]
237
+ self._collated = True
238
+
239
+ def _merge(self, force: bool = False):
240
+ if self._merged is not None and not force:
241
+ return
242
+
243
+ targets_per_image = (
244
+ None if self.targets.source is None else np.unique(self.targets.source, return_counts=True)[1].tolist()
245
+ )
246
+ self._merged = merge(self.raw, return_dropped=True, ignore_lists=False, targets_per_image=targets_per_image)
247
+
248
+ def _validate(self) -> None:
249
+ # Check that metadata is a single, flattened dictionary with uniform array lengths
250
+ check_length = None
251
+ if self._targets.labels.ndim > 1:
252
+ raise ValueError(
253
+ f"Got class labels with {self._targets.labels.ndim}-dimensional "
254
+ f"shape {self._targets.labels.shape}, but expected a 1-dimensional array."
255
+ )
256
+ for v in self.merged.values():
257
+ if not isinstance(v, (list, tuple, np.ndarray)):
258
+ raise TypeError(
259
+ "Metadata dictionary needs to be a single dictionary whose values "
260
+ "are arraylike containing the metadata on a per image or per object basis."
261
+ )
262
+ else:
263
+ check_length = len(v) if check_length is None else check_length
264
+ if check_length != len(v):
265
+ raise ValueError(
266
+ "The lists/arrays in the metadata dict have varying lengths. "
267
+ "Metadata requires them to be uniform in length."
268
+ )
269
+ if len(self._class_labels) != check_length:
270
+ raise ValueError(
271
+ f"The length of the label array {len(self._class_labels)} is not the same as "
272
+ f"the length of the metadata arrays {check_length}."
273
+ )
274
+
275
+ def _process(self, force: bool = False) -> None:
276
+ if self._processed and not force:
277
+ return
278
+
279
+ # Validate the metadata dimensions
280
+ self._validate()
281
+
282
+ # Create image indices from targets
283
+ self._image_indices = np.arange(len(self.raw)) if self.targets.source is None else self.targets.source
284
+
285
+ # Include specified metadata keys
286
+ if self.include:
287
+ metadata = {i: self.merged[i] for i in self.include if i in self.merged}
288
+ continuous_factor_bins = (
289
+ {i: self.continuous_factor_bins[i] for i in self.include if i in self.continuous_factor_bins}
290
+ if self.continuous_factor_bins
291
+ else {}
292
+ )
293
+ else:
294
+ metadata = self.merged
295
+ continuous_factor_bins = dict(self.continuous_factor_bins) if self.continuous_factor_bins else {}
296
+ for k in self.exclude:
297
+ metadata.pop(k, None)
298
+ continuous_factor_bins.pop(k, None)
299
+
300
+ # Remove generated "_image_index" if present
301
+ if "_image_index" in metadata:
302
+ metadata.pop("_image_index", None)
303
+
304
+ # Bin according to user supplied bins
305
+ continuous_metadata = {}
306
+ discrete_metadata = {}
307
+ if continuous_factor_bins:
308
+ invalid_keys = set(continuous_factor_bins.keys()) - set(metadata.keys())
309
+ if invalid_keys:
310
+ raise KeyError(
311
+ f"The keys - {invalid_keys} - are present in the `continuous_factor_bins` dictionary "
312
+ "but are not keys in the `metadata` dictionary. Delete these keys from `continuous_factor_bins` "
313
+ "or add corresponding entries to the `metadata` dictionary."
314
+ )
315
+ for factor, bins in continuous_factor_bins.items():
316
+ discrete_metadata[factor] = digitize_data(metadata[factor], bins)
317
+ continuous_metadata[factor] = metadata[factor]
318
+
319
+ # Determine category of the rest of the keys
320
+ remaining_keys = set(metadata.keys()) - set(continuous_metadata.keys())
321
+ for key in remaining_keys:
322
+ data = to_numpy(metadata[key])
323
+ if np.issubdtype(data.dtype, np.number):
324
+ result = is_continuous(data, self._image_indices)
325
+ if result:
326
+ continuous_metadata[key] = data
327
+ unique_samples, ordinal_data = np.unique(data, return_inverse=True)
328
+ if unique_samples.size <= np.max([20, data.size * 0.01]):
329
+ discrete_metadata[key] = ordinal_data
330
+ else:
331
+ warnings.warn(
332
+ f"A user defined binning was not provided for {key}. "
333
+ f"Using the {self.auto_bin_method} method to discretize the data. "
334
+ "It is recommended that the user rerun and supply the desired "
335
+ "bins using the continuous_factor_bins parameter.",
336
+ UserWarning,
337
+ )
338
+ discrete_metadata[key] = bin_data(data, self.auto_bin_method)
339
+ else:
340
+ _, discrete_metadata[key] = np.unique(data, return_inverse=True)
341
+
342
+ # Split out the dictionaries into the keys and values
343
+ self._discrete_factor_names = list(discrete_metadata.keys())
344
+ self._discrete_data = np.stack(list(discrete_metadata.values()), axis=-1, dtype=np.int64)
345
+ self._continuous_factor_names = list(continuous_metadata.keys())
346
+ self._continuous_data = (
347
+ np.stack(list(continuous_metadata.values()), axis=-1, dtype=np.float64)
348
+ if continuous_metadata
349
+ else np.array([], dtype=np.float64)
350
+ )
351
+ self._total_num_factors = len(self._discrete_factor_names + self._continuous_factor_names) + 1
352
+ self._processed = True
@@ -0,0 +1,119 @@
1
+ from __future__ import annotations
2
+
3
+ __all__ = []
4
+
5
+ from enum import IntEnum
6
+ from typing import Any, Generic, Iterator, Sequence, TypeVar
7
+
8
+ from dataeval.utils.data._types import Dataset
9
+
10
+ _TData = TypeVar("_TData")
11
+ _TTarget = TypeVar("_TTarget")
12
+
13
+
14
+ class SelectionStage(IntEnum):
15
+ STATE = 0
16
+ FILTER = 1
17
+ ORDER = 2
18
+
19
+
20
+ class Selection(Generic[_TData, _TTarget]):
21
+ stage: SelectionStage
22
+
23
+ def __call__(self, dataset: Select[_TData, _TTarget]) -> None: ...
24
+
25
+ def __str__(self) -> str:
26
+ return f"{self.__class__.__name__}({', '.join([f'{k}={v}' for k, v in self.__dict__.items()])})"
27
+
28
+
29
+ class Select(Generic[_TData, _TTarget], Dataset[_TData, _TTarget]):
30
+ """
31
+ Wraps a dataset and applies selection criteria to it.
32
+
33
+ Parameters
34
+ ----------
35
+ dataset : Dataset
36
+ The dataset to wrap.
37
+ selections : Selection or list[Selection], optional
38
+ The selection criteria to apply to the dataset.
39
+
40
+ Examples
41
+ --------
42
+ >>> from dataeval.utils.data.selections import ClassFilter, Limit
43
+
44
+ >>> # Construct a sample dataset with size of 100 and class count of 10
45
+ >>> # Elements at index `idx` are returned as tuples:
46
+ >>> # - f"data_{idx}", one_hot_encoded(idx % class_count), {"id": idx}
47
+ >>> dataset = SampleDataset(size=100, class_count=10)
48
+
49
+ >>> # Apply a selection criteria to the dataset
50
+ >>> selections = [Limit(size=5), ClassFilter(classes=[0, 2])]
51
+ >>> selected_dataset = Select(dataset, selections=selections)
52
+
53
+ >>> # Iterate over the selected dataset
54
+ >>> for data, target, meta in selected_dataset:
55
+ ... print(f"({data}, {np.argmax(target)}, {meta})")
56
+ (data_0, 0, {'id': 0})
57
+ (data_2, 2, {'id': 2})
58
+ (data_10, 0, {'id': 10})
59
+ (data_12, 2, {'id': 12})
60
+ (data_20, 0, {'id': 20})
61
+ """
62
+
63
+ _dataset: Dataset[_TData, _TTarget]
64
+ _selection: list[int]
65
+ _selections: Sequence[Selection[_TData, _TTarget]]
66
+ _size_limit: int
67
+
68
+ def __init__(
69
+ self,
70
+ dataset: Dataset[_TData, _TTarget],
71
+ selections: Selection[_TData, _TTarget] | list[Selection[_TData, _TTarget]] | None = None,
72
+ ) -> None:
73
+ self._dataset = dataset
74
+ self._size_limit = len(dataset)
75
+ self._selection = list(range(self._size_limit))
76
+ self._selections = self._sort_selections(selections)
77
+ self.__dict__.update(dataset.__dict__)
78
+
79
+ if self._selections:
80
+ self._apply_selections()
81
+
82
+ def __str__(self) -> str:
83
+ nt = "\n "
84
+ title = f"{self.__class__.__name__} Dataset"
85
+ sep = "-" * len(title)
86
+ selections = f"Selections: [{', '.join([str(s) for s in self._sort_selections(self._selections)])}]"
87
+ return f"{title}\n{sep}{nt}{selections}\n\n{self._dataset}"
88
+
89
+ def _sort_selections(
90
+ self, selections: Selection[_TData, _TTarget] | Sequence[Selection[_TData, _TTarget]] | None
91
+ ) -> list[Selection]:
92
+ if not selections:
93
+ return []
94
+
95
+ selections = [selections] if isinstance(selections, Selection) else selections
96
+ grouped: dict[int, list[Selection]] = {}
97
+ for selection in selections:
98
+ grouped.setdefault(selection.stage, []).append(selection)
99
+ selection_list = [selection for category in sorted(grouped) for selection in grouped[category]]
100
+ return selection_list
101
+
102
+ def _apply_selections(self) -> None:
103
+ for selection in self._selections:
104
+ selection(self)
105
+ self._selection = self._selection[: self._size_limit]
106
+
107
+ def __getattr__(self, name: str, /) -> Any:
108
+ selfattr = getattr(self._dataset, name, None)
109
+ return selfattr if selfattr is not None else getattr(self._dataset, name)
110
+
111
+ def __getitem__(self, index: int) -> tuple[_TData, _TTarget, dict[str, Any]]:
112
+ return self._dataset[self._selection[index]]
113
+
114
+ def __iter__(self) -> Iterator[tuple[_TData, _TTarget, dict[str, Any]]]:
115
+ for i in range(len(self)):
116
+ yield self[i]
117
+
118
+ def __len__(self) -> int:
119
+ return len(self._selection)
@@ -4,7 +4,7 @@ __all__ = []
4
4
 
5
5
  import warnings
6
6
  from dataclasses import dataclass
7
- from typing import Any, Iterator, NamedTuple, Protocol
7
+ from typing import Any, Iterator, Protocol
8
8
 
9
9
  import numpy as np
10
10
  from numpy.typing import NDArray
@@ -13,10 +13,11 @@ from sklearn.metrics import silhouette_score
13
13
  from sklearn.model_selection import GroupKFold, KFold, StratifiedGroupKFold, StratifiedKFold
14
14
  from sklearn.utils.multiclass import type_of_target
15
15
 
16
- from dataeval.output import Output, set_metadata
16
+ from dataeval._output import Output, set_metadata
17
17
 
18
18
 
19
- class TrainValSplit(NamedTuple):
19
+ @dataclass
20
+ class TrainValSplit:
20
21
  """Tuple containing train and validation indices"""
21
22
 
22
23
  train: NDArray[np.intp]
@@ -274,8 +275,7 @@ def get_group_ids(metadata: dict[str, Any], group_names: list[str], num_samples:
274
275
  for name, feature in features2group.items():
275
276
  if len(feature) != num_samples:
276
277
  raise ValueError(
277
- f"Feature length does not match number of labels. "
278
- f"Got {len(feature)} features and {num_samples} samples"
278
+ f"Feature length does not match number of labels. Got {len(feature)} features and {num_samples} samples"
279
279
  )
280
280
 
281
281
  if type_of_target(feature) == "continuous":
@@ -505,23 +505,22 @@ def split_dataset(
505
505
  if is_groupable(possible_groups, group_partitions):
506
506
  groups = possible_groups
507
507
 
508
- test_indices: NDArray[np.intp]
509
508
  index = np.arange(label_length)
510
509
 
511
- tv_indices, test_indices = (
510
+ tvs = (
512
511
  single_split(index=index, labels=labels, split_frac=test_frac, groups=groups, stratified=stratify)
513
512
  if test_frac
514
- else (index, np.array([], dtype=np.intp))
513
+ else TrainValSplit(index, np.array([], dtype=np.intp))
515
514
  )
516
515
 
517
- tv_labels = labels[tv_indices]
518
- tv_groups = groups[tv_indices] if groups is not None else None
516
+ tv_labels = labels[tvs.train]
517
+ tv_groups = groups[tvs.train] if groups is not None else None
519
518
 
520
519
  if num_folds == 1:
521
- tv_splits = [single_split(tv_indices, tv_labels, val_frac, tv_groups, stratify)]
520
+ tv_splits = [single_split(tvs.train, tv_labels, val_frac, tv_groups, stratify)]
522
521
  else:
523
- tv_splits = make_splits(tv_indices, tv_labels, num_folds, tv_groups, stratify)
522
+ tv_splits = make_splits(tvs.train, tv_labels, num_folds, tv_groups, stratify)
524
523
 
525
- folds: list[TrainValSplit] = [TrainValSplit(tv_indices[split.train], tv_indices[split.val]) for split in tv_splits]
524
+ folds: list[TrainValSplit] = [TrainValSplit(tvs.train[split.train], tvs.train[split.val]) for split in tv_splits]
526
525
 
527
- return SplitDatasetOutput(test_indices, folds)
526
+ return SplitDatasetOutput(tvs.val, folds)
@@ -0,0 +1,73 @@
1
+ from __future__ import annotations
2
+
3
+ __all__ = []
4
+
5
+ from dataclasses import dataclass
6
+
7
+ import numpy as np
8
+ from numpy.typing import NDArray
9
+
10
+
11
+ def _len(arr: NDArray, dim: int) -> int:
12
+ return 0 if len(arr) == 0 else len(np.atleast_1d(arr) if dim == 1 else np.atleast_2d(arr))
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class Targets:
17
+ """
18
+ Dataclass defining targets for image classification or object detection.
19
+
20
+ Attributes
21
+ ----------
22
+ labels : NDArray[np.intp]
23
+ Labels (N,) for N images or objects
24
+ scores : NDArray[np.float32]
25
+ Probability scores (N,M) for N images of M classes or confidence score (N,) of objects
26
+ bboxes : NDArray[np.float32] | None
27
+ Bounding boxes (N,4) for N objects in (x0,y0,x1,y1) format
28
+ source : NDArray[np.intp] | None
29
+ Source image index (N,) for N objects
30
+ """
31
+
32
+ labels: NDArray[np.intp]
33
+ scores: NDArray[np.float32]
34
+ bboxes: NDArray[np.float32] | None
35
+ source: NDArray[np.intp] | None
36
+
37
+ def __post_init__(self) -> None:
38
+ if (self.bboxes is None) != (self.source is None):
39
+ raise ValueError("Either both bboxes and source must be provided or neither.")
40
+
41
+ labels = _len(self.labels, 1)
42
+ scores = _len(self.scores, 2) if self.bboxes is None else _len(self.scores, 1)
43
+ bboxes = labels if self.bboxes is None else _len(self.bboxes, 2)
44
+ source = labels if self.source is None else _len(self.source, 1)
45
+
46
+ if labels != scores or labels != bboxes or labels != source:
47
+ raise ValueError(
48
+ "Labels, scores, bboxes and source must be the same length (if provided).\n"
49
+ + f" labels: {self.labels.shape}\n"
50
+ + f" scores: {self.scores.shape}\n"
51
+ + f" bboxes: {None if self.bboxes is None else self.bboxes.shape}\n"
52
+ + f" source: {None if self.source is None else self.source.shape}\n"
53
+ )
54
+
55
+ def __len__(self) -> int:
56
+ return len(self.labels)
57
+
58
+ def at(self, idx: int) -> Targets:
59
+ if self.source is None or self.bboxes is None:
60
+ return Targets(
61
+ np.atleast_1d(self.labels[idx]),
62
+ np.atleast_2d(self.scores[idx]),
63
+ None,
64
+ None,
65
+ )
66
+ else:
67
+ mask = np.where(self.source == idx, True, False)
68
+ return Targets(
69
+ np.atleast_1d(self.labels[mask]),
70
+ np.atleast_1d(self.scores[mask]),
71
+ np.atleast_2d(self.bboxes[mask]),
72
+ np.atleast_1d(self.source[mask]),
73
+ )
@@ -0,0 +1,58 @@
1
+ from __future__ import annotations
2
+
3
+ __all__ = []
4
+
5
+ import sys
6
+ from dataclasses import dataclass
7
+ from typing import Any, Generic, Protocol, TypedDict, TypeVar
8
+
9
+ if sys.version_info >= (3, 11):
10
+ from typing import NotRequired, Required
11
+ else:
12
+ from typing_extensions import NotRequired, Required
13
+
14
+ from torch.utils.data import Dataset as _Dataset
15
+
16
+ _TArray = TypeVar("_TArray")
17
+ _TData = TypeVar("_TData", covariant=True)
18
+ _TTarget = TypeVar("_TTarget", covariant=True)
19
+
20
+
21
+ class DatasetMetadata(TypedDict):
22
+ id: Required[str]
23
+ index2label: NotRequired[dict[int, str]]
24
+ split: NotRequired[str]
25
+
26
+
27
+ class Dataset(_Dataset[tuple[_TData, _TTarget, dict[str, Any]]]):
28
+ metadata: DatasetMetadata
29
+
30
+ def __getitem__(self, index: Any) -> tuple[_TData, _TTarget, dict[str, Any]]: ...
31
+ def __len__(self) -> int: ...
32
+
33
+
34
+ class ImageClassificationDataset(Dataset[_TArray, _TArray]): ...
35
+
36
+
37
+ @dataclass
38
+ class ObjectDetectionTarget(Generic[_TArray]):
39
+ boxes: _TArray
40
+ labels: _TArray
41
+ scores: _TArray
42
+
43
+
44
+ class ObjectDetectionDataset(Dataset[_TArray, ObjectDetectionTarget[_TArray]]): ...
45
+
46
+
47
+ @dataclass
48
+ class SegmentationTarget(Generic[_TArray]):
49
+ mask: _TArray
50
+ labels: _TArray
51
+ scores: _TArray
52
+
53
+
54
+ class SegmentationDataset(Dataset[_TArray, SegmentationTarget[_TArray]]): ...
55
+
56
+
57
+ class Transform(Generic[_TArray], Protocol):
58
+ def __call__(self, data: _TArray, /) -> _TArray: ...