dataeval 0.76.0__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.
- dataeval/__init__.py +3 -3
- dataeval/{output.py → _output.py} +14 -0
- dataeval/config.py +77 -0
- dataeval/detectors/__init__.py +1 -1
- dataeval/detectors/drift/__init__.py +6 -6
- dataeval/detectors/drift/{base.py → _base.py} +41 -30
- dataeval/detectors/drift/{cvm.py → _cvm.py} +21 -28
- dataeval/detectors/drift/{ks.py → _ks.py} +20 -26
- dataeval/detectors/drift/{mmd.py → _mmd.py} +33 -19
- dataeval/detectors/drift/{torch.py → _torch.py} +2 -1
- dataeval/detectors/drift/{uncertainty.py → _uncertainty.py} +23 -7
- dataeval/detectors/drift/updates.py +1 -1
- dataeval/detectors/linters/__init__.py +0 -3
- dataeval/detectors/linters/duplicates.py +17 -8
- dataeval/detectors/linters/outliers.py +52 -43
- dataeval/detectors/ood/ae.py +29 -8
- dataeval/detectors/ood/base.py +5 -4
- dataeval/detectors/ood/metadata_ks_compare.py +1 -1
- dataeval/detectors/ood/mixin.py +20 -5
- dataeval/detectors/ood/output.py +1 -1
- dataeval/detectors/ood/vae.py +73 -0
- dataeval/metadata/__init__.py +5 -0
- dataeval/metadata/_ood.py +238 -0
- dataeval/metrics/__init__.py +1 -1
- dataeval/metrics/bias/__init__.py +5 -4
- dataeval/metrics/bias/{balance.py → _balance.py} +67 -17
- dataeval/metrics/bias/{coverage.py → _coverage.py} +41 -35
- dataeval/metrics/bias/{diversity.py → _diversity.py} +17 -12
- dataeval/metrics/bias/{parity.py → _parity.py} +89 -63
- dataeval/metrics/estimators/__init__.py +14 -4
- dataeval/metrics/estimators/{ber.py → _ber.py} +42 -11
- dataeval/metrics/estimators/_clusterer.py +104 -0
- dataeval/metrics/estimators/{divergence.py → _divergence.py} +18 -13
- dataeval/metrics/estimators/{uap.py → _uap.py} +4 -4
- dataeval/metrics/stats/__init__.py +7 -7
- dataeval/metrics/stats/{base.py → _base.py} +52 -16
- dataeval/metrics/stats/{boxratiostats.py → _boxratiostats.py} +6 -9
- dataeval/metrics/stats/{datasetstats.py → _datasetstats.py} +10 -14
- dataeval/metrics/stats/{dimensionstats.py → _dimensionstats.py} +6 -5
- dataeval/metrics/stats/{hashstats.py → _hashstats.py} +6 -6
- dataeval/metrics/stats/{labelstats.py → _labelstats.py} +25 -25
- dataeval/metrics/stats/{pixelstats.py → _pixelstats.py} +5 -4
- dataeval/metrics/stats/{visualstats.py → _visualstats.py} +9 -8
- dataeval/typing.py +54 -0
- dataeval/utils/__init__.py +2 -2
- dataeval/utils/_array.py +169 -0
- dataeval/utils/_bin.py +199 -0
- dataeval/utils/_clusterer.py +144 -0
- dataeval/utils/_fast_mst.py +189 -0
- dataeval/utils/{image.py → _image.py} +6 -4
- dataeval/utils/_method.py +18 -0
- dataeval/utils/{shared.py → _mst.py} +3 -65
- dataeval/utils/{plot.py → _plot.py} +4 -4
- dataeval/utils/data/__init__.py +22 -0
- dataeval/utils/data/_embeddings.py +105 -0
- dataeval/utils/data/_images.py +65 -0
- dataeval/utils/data/_metadata.py +352 -0
- dataeval/utils/data/_selection.py +119 -0
- dataeval/utils/{dataset/split.py → data/_split.py} +13 -14
- dataeval/utils/data/_targets.py +73 -0
- dataeval/utils/data/_types.py +58 -0
- dataeval/utils/data/collate.py +103 -0
- dataeval/utils/data/datasets/__init__.py +17 -0
- dataeval/utils/data/datasets/_base.py +254 -0
- dataeval/utils/data/datasets/_cifar10.py +134 -0
- dataeval/utils/data/datasets/_fileio.py +168 -0
- dataeval/utils/data/datasets/_milco.py +153 -0
- dataeval/utils/data/datasets/_mixin.py +56 -0
- dataeval/utils/data/datasets/_mnist.py +183 -0
- dataeval/utils/data/datasets/_ships.py +123 -0
- dataeval/utils/data/datasets/_voc.py +352 -0
- dataeval/utils/data/selections/__init__.py +15 -0
- dataeval/utils/data/selections/_classfilter.py +60 -0
- dataeval/utils/data/selections/_indices.py +26 -0
- dataeval/utils/data/selections/_limit.py +26 -0
- dataeval/utils/data/selections/_reverse.py +18 -0
- dataeval/utils/data/selections/_shuffle.py +29 -0
- dataeval/utils/metadata.py +198 -376
- dataeval/utils/torch/{gmm.py → _gmm.py} +4 -2
- dataeval/utils/torch/{internal.py → _internal.py} +21 -51
- dataeval/utils/torch/models.py +43 -2
- dataeval/workflows/sufficiency.py +10 -9
- {dataeval-0.76.0.dist-info → dataeval-0.81.0.dist-info}/METADATA +44 -15
- dataeval-0.81.0.dist-info/RECORD +94 -0
- dataeval/detectors/linters/clusterer.py +0 -512
- dataeval/detectors/linters/merged_stats.py +0 -49
- dataeval/detectors/ood/metadata_least_likely.py +0 -119
- dataeval/interop.py +0 -69
- dataeval/utils/dataset/__init__.py +0 -7
- dataeval/utils/dataset/datasets.py +0 -412
- dataeval/utils/dataset/read.py +0 -63
- dataeval-0.76.0.dist-info/RECORD +0 -67
- /dataeval/{log.py → _log.py} +0 -0
- /dataeval/utils/torch/{blocks.py → _blocks.py} +0 -0
- {dataeval-0.76.0.dist-info → dataeval-0.81.0.dist-info}/LICENSE.txt +0 -0
- {dataeval-0.76.0.dist-info → dataeval-0.81.0.dist-info}/WHEEL +0 -0
@@ -6,9 +6,9 @@ import contextlib
|
|
6
6
|
from typing import Any
|
7
7
|
|
8
8
|
import numpy as np
|
9
|
-
from numpy.typing import ArrayLike
|
10
9
|
|
11
|
-
from dataeval.
|
10
|
+
from dataeval.typing import ArrayLike
|
11
|
+
from dataeval.utils._array import to_numpy
|
12
12
|
|
13
13
|
with contextlib.suppress(ImportError):
|
14
14
|
from matplotlib.figure import Figure
|
@@ -171,7 +171,7 @@ def histogram_plot(
|
|
171
171
|
data_dict,
|
172
172
|
):
|
173
173
|
# Plot the histogram for the chosen metric
|
174
|
-
ax.hist(data_dict[metric], bins=20, log=log)
|
174
|
+
ax.hist(data_dict[metric].astype(np.float64), bins=20, log=log)
|
175
175
|
|
176
176
|
# Add labels to the histogram
|
177
177
|
ax.set_title(metric)
|
@@ -229,7 +229,7 @@ def channel_histogram_plot(
|
|
229
229
|
# Plot the histogram for the chosen metric
|
230
230
|
data = data_dict[metric][ch_mask].reshape(-1, max_channels)
|
231
231
|
ax.hist(
|
232
|
-
data,
|
232
|
+
data.astype(np.float64),
|
233
233
|
bins=20,
|
234
234
|
density=True,
|
235
235
|
log=log,
|
@@ -0,0 +1,22 @@
|
|
1
|
+
"""Provides utility functions for interacting with Computer Vision datasets."""
|
2
|
+
|
3
|
+
__all__ = [
|
4
|
+
"collate",
|
5
|
+
"datasets",
|
6
|
+
"Embeddings",
|
7
|
+
"Images",
|
8
|
+
"Metadata",
|
9
|
+
"Select",
|
10
|
+
"SplitDatasetOutput",
|
11
|
+
"Targets",
|
12
|
+
"split_dataset",
|
13
|
+
]
|
14
|
+
|
15
|
+
from dataeval.utils.data._embeddings import Embeddings
|
16
|
+
from dataeval.utils.data._images import Images
|
17
|
+
from dataeval.utils.data._metadata import Metadata
|
18
|
+
from dataeval.utils.data._selection import Select
|
19
|
+
from dataeval.utils.data._split import SplitDatasetOutput, split_dataset
|
20
|
+
from dataeval.utils.data._targets import Targets
|
21
|
+
|
22
|
+
from . import collate, datasets
|
@@ -0,0 +1,105 @@
|
|
1
|
+
from __future__ import annotations
|
2
|
+
|
3
|
+
__all__ = []
|
4
|
+
|
5
|
+
import math
|
6
|
+
from typing import Any, Iterator, Sequence
|
7
|
+
|
8
|
+
import torch
|
9
|
+
from torch.utils.data import DataLoader, Subset
|
10
|
+
from tqdm import tqdm
|
11
|
+
|
12
|
+
from dataeval.config import get_device
|
13
|
+
from dataeval.typing import TArray
|
14
|
+
from dataeval.utils.data._types import Dataset
|
15
|
+
from dataeval.utils.torch.models import SupportsEncode
|
16
|
+
|
17
|
+
|
18
|
+
class Embeddings:
|
19
|
+
"""
|
20
|
+
Collection of image embeddings from a dataset.
|
21
|
+
|
22
|
+
Embeddings are accessed by index or slice and are only loaded on-demand.
|
23
|
+
|
24
|
+
Parameters
|
25
|
+
----------
|
26
|
+
dataset : ImageClassificationDataset or ObjectDetectionDataset
|
27
|
+
Dataset to access original images from.
|
28
|
+
batch_size : int, optional
|
29
|
+
Batch size to use when encoding images.
|
30
|
+
model : torch.nn.Module, optional
|
31
|
+
Model to use for encoding images.
|
32
|
+
device : torch.device, optional
|
33
|
+
Device to use for encoding images.
|
34
|
+
verbose : bool, optional
|
35
|
+
Whether to print progress bar when encoding images.
|
36
|
+
"""
|
37
|
+
|
38
|
+
device: torch.device
|
39
|
+
batch_size: int
|
40
|
+
verbose: bool
|
41
|
+
|
42
|
+
def __init__(
|
43
|
+
self,
|
44
|
+
dataset: Dataset[TArray, Any],
|
45
|
+
batch_size: int,
|
46
|
+
indices: Sequence[int] | None = None,
|
47
|
+
model: torch.nn.Module | None = None,
|
48
|
+
device: torch.device | str | None = None,
|
49
|
+
verbose: bool = False,
|
50
|
+
) -> None:
|
51
|
+
self.device = get_device(device)
|
52
|
+
self.batch_size = batch_size
|
53
|
+
self.verbose = verbose
|
54
|
+
|
55
|
+
self._dataset = dataset
|
56
|
+
self._indices = indices if indices is not None else range(len(dataset))
|
57
|
+
model = torch.nn.Flatten() if model is None else model
|
58
|
+
self._model = model.to(self.device).eval()
|
59
|
+
self._encoder = model.encode if isinstance(model, SupportsEncode) else model
|
60
|
+
self._collate_fn = lambda datum: [torch.as_tensor(i) for i, _, _ in datum]
|
61
|
+
|
62
|
+
def to_tensor(self) -> torch.Tensor:
|
63
|
+
"""
|
64
|
+
Converts entire dataset to embeddings.
|
65
|
+
|
66
|
+
Warning
|
67
|
+
-------
|
68
|
+
Will process the entire dataset in batches and return
|
69
|
+
embeddings as a single Tensor in memory.
|
70
|
+
|
71
|
+
Returns
|
72
|
+
-------
|
73
|
+
torch.Tensor
|
74
|
+
"""
|
75
|
+
return self[:]
|
76
|
+
|
77
|
+
# Reduce overhead cost by not tracking tensor gradients
|
78
|
+
@torch.no_grad
|
79
|
+
def _batch(self, indices: Sequence[int]) -> Iterator[torch.Tensor]:
|
80
|
+
# manual batching
|
81
|
+
dataloader = DataLoader(Subset(self._dataset, indices), batch_size=self.batch_size, collate_fn=self._collate_fn)
|
82
|
+
for i, images in (
|
83
|
+
tqdm(enumerate(dataloader), total=math.ceil(len(indices) / self.batch_size), desc="Batch processing")
|
84
|
+
if self.verbose
|
85
|
+
else enumerate(dataloader)
|
86
|
+
):
|
87
|
+
embeddings = self._encoder(torch.stack(images).to(self.device))
|
88
|
+
yield embeddings
|
89
|
+
|
90
|
+
def __getitem__(self, key: int | slice | list[int]) -> torch.Tensor:
|
91
|
+
if isinstance(key, list):
|
92
|
+
return torch.vstack(list(self._batch(key))).to(self.device)
|
93
|
+
if isinstance(key, slice):
|
94
|
+
return torch.vstack(list(self._batch(range(len(self._dataset))[key]))).to(self.device)
|
95
|
+
elif isinstance(key, int):
|
96
|
+
return self._encoder(torch.as_tensor(self._dataset[key][0]).to(self.device))
|
97
|
+
raise TypeError("Invalid argument type.")
|
98
|
+
|
99
|
+
def __iter__(self) -> Iterator[torch.Tensor]:
|
100
|
+
# process in batches while yielding individual embeddings
|
101
|
+
for batch in self._batch(range(len(self._dataset))):
|
102
|
+
yield from batch
|
103
|
+
|
104
|
+
def __len__(self) -> int:
|
105
|
+
return len(self._dataset)
|
@@ -0,0 +1,65 @@
|
|
1
|
+
from __future__ import annotations
|
2
|
+
|
3
|
+
__all__ = []
|
4
|
+
|
5
|
+
from typing import Any, Generic, Iterator, Sequence, overload
|
6
|
+
|
7
|
+
from dataeval.typing import TArray
|
8
|
+
from dataeval.utils.data._types import Dataset
|
9
|
+
|
10
|
+
|
11
|
+
class Images(Generic[TArray]):
|
12
|
+
"""
|
13
|
+
Collection of image data from a dataset.
|
14
|
+
|
15
|
+
Images are accessed by index or slice and are only loaded on-demand.
|
16
|
+
|
17
|
+
Parameters
|
18
|
+
----------
|
19
|
+
dataset : ImageClassificationDataset or ObjectDetectionDataset
|
20
|
+
Dataset to access images from.
|
21
|
+
"""
|
22
|
+
|
23
|
+
def __init__(
|
24
|
+
self,
|
25
|
+
dataset: Dataset[TArray, Any],
|
26
|
+
) -> None:
|
27
|
+
self._dataset = dataset
|
28
|
+
|
29
|
+
def to_list(self) -> Sequence[TArray]:
|
30
|
+
"""
|
31
|
+
Converts entire dataset to a sequence of images.
|
32
|
+
|
33
|
+
Warning
|
34
|
+
-------
|
35
|
+
Will load the entire dataset and return the images as a
|
36
|
+
single sequence of images in memory.
|
37
|
+
|
38
|
+
Returns
|
39
|
+
-------
|
40
|
+
list[TArray]
|
41
|
+
"""
|
42
|
+
return self[:]
|
43
|
+
|
44
|
+
@overload
|
45
|
+
def __getitem__(self, key: slice | list[int]) -> Sequence[TArray]: ...
|
46
|
+
|
47
|
+
@overload
|
48
|
+
def __getitem__(self, key: int) -> TArray: ...
|
49
|
+
|
50
|
+
def __getitem__(self, key: int | slice | list[int]) -> Sequence[TArray] | TArray:
|
51
|
+
if isinstance(key, list):
|
52
|
+
return [self._dataset[i][0] for i in key]
|
53
|
+
if isinstance(key, slice):
|
54
|
+
indices = list(range(len(self._dataset))[key])
|
55
|
+
return [self._dataset[i][0] for i in indices]
|
56
|
+
elif isinstance(key, int):
|
57
|
+
return self._dataset[key][0]
|
58
|
+
raise TypeError("Invalid argument type.")
|
59
|
+
|
60
|
+
def __iter__(self) -> Iterator[TArray]:
|
61
|
+
for i in range(len(self._dataset)):
|
62
|
+
yield self._dataset[i][0]
|
63
|
+
|
64
|
+
def __len__(self) -> int:
|
65
|
+
return len(self._dataset)
|
@@ -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)
|