dataeval 0.72.0__py3-none-any.whl → 0.72.2__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 (90) hide show
  1. dataeval/__init__.py +4 -4
  2. dataeval/detectors/__init__.py +4 -3
  3. dataeval/detectors/drift/__init__.py +10 -11
  4. dataeval/{_internal/detectors → detectors}/drift/base.py +51 -102
  5. dataeval/{_internal/detectors → detectors}/drift/cvm.py +9 -8
  6. dataeval/{_internal/detectors → detectors}/drift/ks.py +11 -10
  7. dataeval/{_internal/detectors → detectors}/drift/mmd.py +33 -34
  8. dataeval/{_internal/detectors → detectors}/drift/torch.py +15 -13
  9. dataeval/{_internal/detectors → detectors}/drift/uncertainty.py +12 -9
  10. dataeval/detectors/drift/updates.py +61 -0
  11. dataeval/detectors/linters/__init__.py +3 -3
  12. dataeval/{_internal/detectors → detectors/linters}/clusterer.py +47 -45
  13. dataeval/{_internal/detectors → detectors/linters}/duplicates.py +20 -10
  14. dataeval/{_internal/detectors → detectors/linters}/merged_stats.py +3 -1
  15. dataeval/{_internal/detectors → detectors/linters}/outliers.py +19 -26
  16. dataeval/detectors/ood/__init__.py +8 -16
  17. dataeval/{_internal/detectors → detectors}/ood/ae.py +9 -9
  18. dataeval/{_internal/detectors → detectors}/ood/aegmm.py +10 -30
  19. dataeval/{_internal/detectors → detectors}/ood/base.py +27 -21
  20. dataeval/{_internal/detectors → detectors}/ood/llr.py +27 -23
  21. dataeval/detectors/ood/metadata_ks_compare.py +99 -0
  22. dataeval/detectors/ood/metadata_least_likely.py +119 -0
  23. dataeval/detectors/ood/metadata_ood_mi.py +92 -0
  24. dataeval/{_internal/detectors → detectors}/ood/vae.py +11 -13
  25. dataeval/{_internal/detectors → detectors}/ood/vaegmm.py +10 -32
  26. dataeval/{_internal/interop.py → interop.py} +12 -7
  27. dataeval/metrics/__init__.py +1 -1
  28. dataeval/metrics/bias/__init__.py +4 -4
  29. dataeval/{_internal/metrics → metrics/bias}/balance.py +70 -4
  30. dataeval/{_internal/metrics → metrics/bias}/coverage.py +10 -8
  31. dataeval/{_internal/metrics → metrics/bias}/diversity.py +54 -20
  32. dataeval/metrics/bias/metadata.py +275 -0
  33. dataeval/{_internal/metrics → metrics/bias}/parity.py +21 -17
  34. dataeval/metrics/estimators/__init__.py +3 -3
  35. dataeval/{_internal/metrics → metrics/estimators}/ber.py +31 -28
  36. dataeval/{_internal/metrics → metrics/estimators}/divergence.py +15 -16
  37. dataeval/{_internal/metrics → metrics/estimators}/uap.py +8 -6
  38. dataeval/metrics/stats/__init__.py +7 -7
  39. dataeval/{_internal/metrics → metrics}/stats/base.py +66 -40
  40. dataeval/{_internal/metrics → metrics}/stats/boxratiostats.py +19 -15
  41. dataeval/{_internal/metrics → metrics}/stats/datasetstats.py +19 -17
  42. dataeval/{_internal/metrics → metrics}/stats/dimensionstats.py +12 -10
  43. dataeval/metrics/stats/hashstats.py +156 -0
  44. dataeval/{_internal/metrics → metrics}/stats/labelstats.py +8 -6
  45. dataeval/{_internal/metrics → metrics}/stats/pixelstats.py +12 -11
  46. dataeval/{_internal/metrics → metrics}/stats/visualstats.py +14 -13
  47. dataeval/{_internal/output.py → output.py} +26 -6
  48. dataeval/utils/__init__.py +8 -4
  49. dataeval/utils/image.py +71 -0
  50. dataeval/utils/shared.py +151 -0
  51. dataeval/utils/split_dataset.py +486 -0
  52. dataeval/utils/tensorflow/__init__.py +9 -7
  53. dataeval/{_internal/models/tensorflow → utils/tensorflow/_internal}/autoencoder.py +64 -68
  54. dataeval/{_internal/models/tensorflow/losses.py → utils/tensorflow/_internal/loss.py} +10 -9
  55. dataeval/{_internal/models/tensorflow → utils/tensorflow/_internal}/pixelcnn.py +18 -22
  56. dataeval/{_internal/models/tensorflow → utils/tensorflow/_internal}/trainer.py +3 -1
  57. dataeval/{_internal/models/tensorflow → utils/tensorflow/_internal}/utils.py +18 -18
  58. dataeval/utils/tensorflow/loss/__init__.py +6 -2
  59. dataeval/utils/torch/__init__.py +7 -3
  60. dataeval/{_internal/models/pytorch → utils/torch}/blocks.py +19 -14
  61. dataeval/{_internal → utils/torch}/datasets.py +49 -43
  62. dataeval/utils/torch/models.py +138 -0
  63. dataeval/{_internal/models/pytorch/autoencoder.py → utils/torch/trainer.py} +12 -141
  64. dataeval/{_internal → utils/torch}/utils.py +3 -1
  65. dataeval/workflows/__init__.py +1 -1
  66. dataeval/{_internal/workflows → workflows}/sufficiency.py +42 -37
  67. {dataeval-0.72.0.dist-info → dataeval-0.72.2.dist-info}/METADATA +7 -5
  68. dataeval-0.72.2.dist-info/RECORD +72 -0
  69. dataeval/_internal/detectors/__init__.py +0 -0
  70. dataeval/_internal/detectors/drift/__init__.py +0 -0
  71. dataeval/_internal/detectors/ood/__init__.py +0 -0
  72. dataeval/_internal/metrics/__init__.py +0 -0
  73. dataeval/_internal/metrics/stats/hashstats.py +0 -75
  74. dataeval/_internal/metrics/utils.py +0 -447
  75. dataeval/_internal/models/__init__.py +0 -0
  76. dataeval/_internal/models/pytorch/__init__.py +0 -0
  77. dataeval/_internal/models/pytorch/utils.py +0 -67
  78. dataeval/_internal/models/tensorflow/__init__.py +0 -0
  79. dataeval/_internal/workflows/__init__.py +0 -0
  80. dataeval/detectors/drift/kernels/__init__.py +0 -10
  81. dataeval/detectors/drift/updates/__init__.py +0 -7
  82. dataeval/utils/tensorflow/models/__init__.py +0 -9
  83. dataeval/utils/tensorflow/recon/__init__.py +0 -3
  84. dataeval/utils/torch/datasets/__init__.py +0 -12
  85. dataeval/utils/torch/models/__init__.py +0 -11
  86. dataeval/utils/torch/trainer/__init__.py +0 -7
  87. dataeval-0.72.0.dist-info/RECORD +0 -80
  88. /dataeval/{_internal/models/tensorflow → utils/tensorflow/_internal}/gmm.py +0 -0
  89. {dataeval-0.72.0.dist-info → dataeval-0.72.2.dist-info}/LICENSE.txt +0 -0
  90. {dataeval-0.72.0.dist-info → dataeval-0.72.2.dist-info}/WHEEL +0 -0
@@ -0,0 +1,151 @@
1
+ from __future__ import annotations
2
+
3
+ __all__ = []
4
+
5
+ import sys
6
+ from typing import Any, Callable, Literal, TypeVar
7
+
8
+ import numpy as np
9
+ from numpy.typing import ArrayLike, NDArray
10
+ from scipy.sparse import csr_matrix
11
+ from scipy.sparse.csgraph import minimum_spanning_tree as mst
12
+ from scipy.spatial.distance import pdist, squareform
13
+ from sklearn.neighbors import NearestNeighbors
14
+
15
+ if sys.version_info >= (3, 10):
16
+ from typing import ParamSpec
17
+ else:
18
+ from typing_extensions import ParamSpec
19
+
20
+ from dataeval.interop import as_numpy
21
+
22
+ EPSILON = 1e-5
23
+ HASH_SIZE = 8
24
+ MAX_FACTOR = 4
25
+
26
+
27
+ P = ParamSpec("P")
28
+ R = TypeVar("R")
29
+
30
+
31
+ def get_method(method_map: dict[str, Callable[P, R]], method: str) -> Callable[P, R]:
32
+ if method not in method_map:
33
+ raise ValueError(f"Specified method {method} is not a valid method: {method_map}.")
34
+ return method_map[method]
35
+
36
+
37
+ def flatten(array: ArrayLike) -> NDArray[Any]:
38
+ """
39
+ Flattens input array from (N, ... ) to (N, -1) where all samples N have all data in their last dimension
40
+
41
+ Parameters
42
+ ----------
43
+ X : NDArray, shape - (N, ... )
44
+ Input array
45
+
46
+ Returns
47
+ -------
48
+ NDArray, shape - (N, -1)
49
+ """
50
+ nparr = as_numpy(array)
51
+ return nparr.reshape((nparr.shape[0], -1))
52
+
53
+
54
+ def minimum_spanning_tree(X: NDArray[Any]) -> Any:
55
+ """
56
+ Returns the minimum spanning tree from a :term:`NumPy` image array.
57
+
58
+ Parameters
59
+ ----------
60
+ X : NDArray
61
+ Numpy image array
62
+
63
+ Returns
64
+ -------
65
+ Data representing the minimum spanning tree
66
+ """
67
+ # All features belong on second dimension
68
+ X = flatten(X)
69
+ # We add a small constant to the distance matrix to ensure scipy interprets
70
+ # the input graph as fully-connected.
71
+ dense_eudist = squareform(pdist(X)) + EPSILON
72
+ eudist_csr = csr_matrix(dense_eudist)
73
+ return mst(eudist_csr)
74
+
75
+
76
+ def get_classes_counts(labels: NDArray[np.int_]) -> tuple[int, int]:
77
+ """
78
+ Returns the classes and counts of from an array of labels
79
+
80
+ Parameters
81
+ ----------
82
+ label : NDArray
83
+ Numpy labels array
84
+
85
+ Returns
86
+ -------
87
+ Classes and counts
88
+
89
+ Raises
90
+ ------
91
+ ValueError
92
+ If the number of unique classes is less than 2
93
+ """
94
+ classes, counts = np.unique(labels, return_counts=True)
95
+ M = len(classes)
96
+ if M < 2:
97
+ raise ValueError("Label vector contains less than 2 classes!")
98
+ N = np.sum(counts).astype(int)
99
+ return M, N
100
+
101
+
102
+ def compute_neighbors(
103
+ A: NDArray[Any],
104
+ B: NDArray[Any],
105
+ k: int = 1,
106
+ algorithm: Literal["auto", "ball_tree", "kd_tree"] = "auto",
107
+ ) -> NDArray[Any]:
108
+ """
109
+ For each sample in A, compute the nearest neighbor in B
110
+
111
+ Parameters
112
+ ----------
113
+ A, B : NDArray
114
+ The n_samples and n_features respectively
115
+ k : int
116
+ The number of neighbors to find
117
+ algorithm : Literal
118
+ Tree method for nearest neighbor (auto, ball_tree or kd_tree)
119
+
120
+ Note
121
+ ----
122
+ Do not use kd_tree if n_features > 20
123
+
124
+ Returns
125
+ -------
126
+ List:
127
+ Closest points to each point in A and B
128
+
129
+ Raises
130
+ ------
131
+ ValueError
132
+ If algorithm is not "auto", "ball_tree", or "kd_tree"
133
+
134
+ See Also
135
+ --------
136
+ sklearn.neighbors.NearestNeighbors
137
+ """
138
+
139
+ if k < 1:
140
+ raise ValueError("k must be >= 1")
141
+ if algorithm not in ["auto", "ball_tree", "kd_tree"]:
142
+ raise ValueError("Algorithm must be 'auto', 'ball_tree', or 'kd_tree'")
143
+
144
+ A = flatten(A)
145
+ B = flatten(B)
146
+
147
+ nbrs = NearestNeighbors(n_neighbors=k + 1, algorithm=algorithm).fit(B)
148
+ nns = nbrs.kneighbors(A)[1]
149
+ nns = nns[:, 1:].squeeze()
150
+
151
+ return nns
@@ -0,0 +1,486 @@
1
+ from __future__ import annotations
2
+
3
+ __all__ = ["split_dataset"]
4
+
5
+ import warnings
6
+ from typing import Any
7
+
8
+ import numpy as np
9
+ from numpy.typing import NDArray
10
+ from sklearn.cluster import KMeans
11
+ from sklearn.metrics import silhouette_score
12
+ from sklearn.model_selection import GroupKFold, KFold, StratifiedGroupKFold, StratifiedKFold
13
+ from sklearn.utils.multiclass import type_of_target
14
+
15
+
16
+ def validate_test_val(num_folds: int, test_frac: float | None, val_frac: float | None) -> tuple[float, float]:
17
+ """Check input fractions to ensure unambiguous splitting arguments are passed return calculated
18
+ test and validation fractions.
19
+
20
+
21
+ Parameters
22
+ ----------
23
+ num_folds : int
24
+ number of [train, val] cross-validation folds to generate
25
+ test_frac : float, optional
26
+ If specified, also generate a test set containing (test_frac*100)% of the data
27
+ val_frac : float, optional
28
+ Only specify if requesting a single [train, val] split. The validation split will
29
+ contain (val_frac*100)% of any data not already allocated to the test set
30
+
31
+ Raises
32
+ ------
33
+ UnboundLocalError
34
+ Raised if more than one fold AND the fraction of data to be used for validation are
35
+ both requested. In this case, val_frac is ambiguous, since the validation fraction must be
36
+ by definition 1/num_folds
37
+ ValueError
38
+ Raised if num_folds is 1 (or left blank) AND val_frac is unspecified. When only 1 fold is
39
+ requested, we need to know how much of the data should be allocated for validation.
40
+ ValueError
41
+ Raised if the total fraction of data used for evaluation (val + test) meets or exceeds 1.0
42
+
43
+ Returns
44
+ -------
45
+ tuple[float, float]
46
+ Tuple of the validated and calculated values as appropriate for test and validation fractions
47
+ """
48
+ if (num_folds > 1) and (val_frac is not None):
49
+ raise ValueError("If specifying val_frac, num_folds must be None or 1")
50
+ if (num_folds == 1) and (val_frac is None):
51
+ raise ValueError("If num_folds is None or 1, must assign a value to val_frac")
52
+ t_frac = 0.0 if test_frac is None else test_frac
53
+ v_frac = 1.0 / num_folds * (1.0 - t_frac) if val_frac is None else val_frac * (1.0 - t_frac)
54
+ if (t_frac + v_frac) >= 1.0:
55
+ raise ValueError(f"val_frac + test_frac must be less that 1.0, currently {v_frac+t_frac}")
56
+ return t_frac, v_frac
57
+
58
+
59
+ def check_labels(
60
+ labels: list[int] | NDArray[np.int_], total_partitions: int
61
+ ) -> tuple[NDArray[np.int_], NDArray[np.int_]]:
62
+ """Check to make sure there are more input data than the total number of partitions requested
63
+ Also converts labels to a numpy array, if it isn't already
64
+
65
+ Parameters
66
+ ----------
67
+ labels : list or np.ndarray
68
+ all class labels from the input dataset
69
+ total_partitions : int
70
+ number of train-val splits requested (+1 if a test holdout is specified)
71
+
72
+ Raises
73
+ ------
74
+ IndexError
75
+ Raised if more partitions are requested than number of labels. This is exceedingly rare and
76
+ usually means you've specified some argument incorrectly.
77
+ ValueError
78
+ Raised if the labels are considered continuous by Scikit-Learn. This does not necessarily
79
+ mean that floats are not accepted as a label format. Rather, this exception implies that
80
+ there are too many unique values in the set relative to it's cardinality.
81
+
82
+ Returns
83
+ -------
84
+ index : np.ndarray
85
+ Integer index generated based on the total number of labels
86
+ labels : np.ndarray
87
+ labels, converted to an ndarray if passed as a list.
88
+ """
89
+ if len(labels) <= total_partitions:
90
+ raise IndexError(f"""
91
+ Total number of labels must greater than the number of total partitions.
92
+ Got {len(labels)} labels and {total_partitions} total train/val/test partitions.""")
93
+ if isinstance(labels, list):
94
+ labels = np.array(labels)
95
+ if type_of_target(labels) == "continuous":
96
+ raise ValueError("Detected continuous labels, labels must be discrete for proper stratification")
97
+ index = np.arange(len(labels))
98
+ return index, labels
99
+
100
+
101
+ def check_stratifiable(labels: NDArray[np.int_], total_partitions: int) -> bool:
102
+ """
103
+ Very basic check to see if dataset can be stratified by class label. This is not a
104
+ comprehensive test, as factors such as grouping also affect the ability to stratify by label
105
+
106
+ Parameters
107
+ ----------
108
+ labels : list or np.ndarray
109
+ all class labels from the input dataset
110
+ total_partitions : int
111
+ number of train-val splits requested (+1 if a test holdout is specified)
112
+
113
+ Warns
114
+ -----
115
+ UserWarning
116
+ Warns user if the dataset cannot be stratified due to the number of total (train, val, test)
117
+ partitions exceeding the number of instances of the rarest class label.
118
+
119
+ Returns
120
+ -------
121
+ stratifiable : bool
122
+ True if dataset can be stratified according to the criteria above.
123
+ """
124
+
125
+ stratifiable = True
126
+ _, label_counts = np.unique(labels, return_counts=True)
127
+ rarest_label_count = label_counts.min()
128
+ if rarest_label_count < total_partitions:
129
+ warnings.warn(f"""
130
+ Unable to stratify due to label frequency. The rarest label occurs {rarest_label_count},
131
+ which is fewer than the total number of partitions requested. Setting stratify flag to
132
+ false.""")
133
+ stratifiable = False
134
+ return stratifiable
135
+
136
+
137
+ def check_groups(group_ids: NDArray[np.int_], num_partitions: int) -> bool:
138
+ """
139
+ Warns user if the number of unique group_ids is incompatible with a grouped partition containing
140
+ num_folds folds. If this is the case, returns groups=None, which tells the partitioner not to
141
+ group the input data.
142
+
143
+ Parameters
144
+ ----------
145
+ group_ids : np.ndarray
146
+ Identifies the group to which a sample at the same index belongs.
147
+ num_partitions: int
148
+ How many total (train, val) folds will be generated (+1 if also specifying a test fold).
149
+
150
+ Warns
151
+ -----
152
+ UserWarning
153
+ Warns if there are fewer groups than the minimum required to successfully partition the data
154
+ into num_partitions. The minimum is defined as the number of partitions requested plus one.
155
+
156
+ Returns
157
+ -------
158
+ groupable : bool
159
+ True if dataset can be grouped by the given group ids, given the criteria above.
160
+ """
161
+
162
+ groupable = True
163
+ num_unique_groups = len(np.unique(group_ids))
164
+ min_unique_groups = num_partitions + 1
165
+ if num_unique_groups < min_unique_groups:
166
+ warnings.warn(f"""
167
+ {min_unique_groups} unique groups required for {num_partitions} partitions.
168
+ Found {num_unique_groups} instead. Reverting to ungrouped partitioning""")
169
+ groupable = False
170
+ else:
171
+ groupable = True
172
+ return groupable
173
+
174
+
175
+ def bin_kmeans(array: NDArray[Any]) -> NDArray[np.int_]:
176
+ """
177
+ Find bins of continuous data by iteratively applying k-means clustering, and keeping the
178
+ clustering with the highest silhouette score.
179
+
180
+ Parameters
181
+ ----------
182
+ array : np.ndarray
183
+ continuous data to bin
184
+
185
+ Returns
186
+ -------
187
+ np.ndarray[int]: bin numbers assigned by the kmeans best clusterer.
188
+ """
189
+ array = np.array(array)
190
+ if array.ndim == 1:
191
+ array = array.reshape([-1, 1])
192
+ best_score = 0.60
193
+ else:
194
+ best_score = 0.50
195
+ bin_index = np.zeros(len(array), dtype=np.int_)
196
+ for k in range(2, 20):
197
+ clusterer = KMeans(n_clusters=k)
198
+ cluster_labels = clusterer.fit_predict(array)
199
+ score = silhouette_score(array, cluster_labels, sample_size=25_000)
200
+ if score > best_score:
201
+ best_score = score
202
+ bin_index = cluster_labels.astype(np.int_)
203
+ return bin_index
204
+
205
+
206
+ def angle2xy(angles: NDArray[Any]) -> NDArray[Any]:
207
+ """
208
+ Converts angle measurements to xy coordinates on the unit circle. Needed for binning angle data.
209
+
210
+ Parameters
211
+ ----------
212
+ angles : np.ndarray
213
+ angle data in either radians or degrees
214
+
215
+ Returns
216
+ -------
217
+ xy : np.ndarray
218
+ Nx2 array of xy coordinates for each angle (can be radians or degrees)
219
+ """
220
+ is_radians = ((angles >= -np.pi) & (angles <= 2 * np.pi)).all()
221
+ radians = angles if is_radians else np.pi / 180 * angles
222
+ xy = np.stack([np.cos(radians), np.sin(radians)], axis=1)
223
+ return xy
224
+
225
+
226
+ def get_group_ids(metadata: dict[str, Any], group_names: list[str], num_samples: int) -> NDArray[np.int_]:
227
+ """Returns individual group numbers based on a subset of metadata defined by groupnames
228
+
229
+ Parameters
230
+ ----------
231
+ metadata : dict
232
+ dictionary containing all metadata
233
+ groupnames : list
234
+ which groups from the metadata dictionary to consider for dataset grouping
235
+ num_samples : int
236
+ number of labels. Used to ensure agreement between input data/labels and metadata entries.
237
+
238
+ Raises
239
+ ------
240
+ IndexError
241
+ raised if an entry in the metadata dictionary doesn't have the same length as num_samples
242
+
243
+ Returns
244
+ -------
245
+ group_ids: np.ndarray
246
+ group identifiers from metadata
247
+ """
248
+ features2group = {k: np.array(v) for k, v in metadata.items() if k in group_names}
249
+ if not features2group:
250
+ return np.zeros(num_samples, dtype=int)
251
+ for name, feature in features2group.items():
252
+ if len(feature) != num_samples:
253
+ raise IndexError(f"""Feature length does not match number of labels.
254
+ Got {len(feature)} features and {num_samples} samples""")
255
+ if type_of_target(feature) == "continuous":
256
+ if ("ANGLE" in name.upper()) or ("AZIMUTH" in name.upper()):
257
+ feature = angle2xy(feature)
258
+ features2group[name] = bin_kmeans(feature)
259
+ binned_features = np.stack(list(features2group.values()), axis=1)
260
+ _, group_ids = np.unique(binned_features, axis=0, return_inverse=True)
261
+ return group_ids
262
+
263
+
264
+ def make_splits(
265
+ index: NDArray[np.int_],
266
+ labels: NDArray[np.int_],
267
+ n_folds: int,
268
+ groups: NDArray[np.int_] | None = None,
269
+ stratified: bool = False,
270
+ ) -> list[dict[str, NDArray[np.int_]]]:
271
+ """Split data into n_folds partitions of training and validation data.
272
+
273
+ Parameters
274
+ ----------
275
+ index : np.ndarray
276
+ index corresponding to each label (see below)
277
+ labels : np.ndarray
278
+ classification labels
279
+ n_folds : int
280
+ number or train/val folds
281
+ groups : np.ndarray, Optional
282
+ group index for grouped partitions. Grouped partitions are split such that no group id is
283
+ present in both a training and validation split.
284
+ stratified : bool, default=False
285
+ If True, maintain dataset class balance within each train/val split
286
+
287
+ Returns
288
+ -------
289
+ split_defs : list[dict]
290
+ list of dictionaries, which specifying train index, validation index, and the ratio of
291
+ validation to all data.
292
+ """
293
+ split_defs = []
294
+ index = index.reshape([-1, 1])
295
+ if groups is not None:
296
+ splitter = StratifiedGroupKFold(n_folds) if stratified else GroupKFold(n_folds)
297
+ splits = splitter.split(index, labels, groups)
298
+ else:
299
+ splitter = StratifiedKFold(n_folds) if stratified else KFold(n_folds)
300
+ splits = splitter.split(index, labels)
301
+ for train_idx, eval_idx in splits:
302
+ test_ratio = len(eval_idx) / index.shape[0]
303
+ split_defs.append({"train": train_idx.astype(int), "eval": eval_idx.astype(int), "eval_frac": test_ratio})
304
+ return split_defs
305
+
306
+
307
+ def find_best_split(
308
+ labels: NDArray[np.int_], split_defs: list[dict[str, NDArray[np.int_]]], stratified: bool, eval_frac: float
309
+ ) -> tuple[NDArray[np.int_], NDArray[np.int_]]:
310
+ """Finds the split that most closely satisfies a criterion determined by the arguments passed.
311
+ If stratified is True, returns the split whose class balance most closely resembles the overall
312
+ class balance. If false, returns the split with the size closest to the desired eval_frac
313
+
314
+ Parameters
315
+ ----------
316
+ labels : np.ndarray
317
+ Labels upon which splits are (optionally) stratified
318
+ split_defs : list[dict]
319
+ List of dictionaries, which specifying train index, validation index, and the ratio of
320
+ validation to all data.
321
+ stratified: bool
322
+ If True, maintain dataset class balance within each train/val split
323
+ eval_frac: float
324
+ Desired fraction of the dataset sequestered for evaluation
325
+
326
+ Returns
327
+ -------
328
+ train_index : np.ndarray
329
+ indices of data partitioned for training
330
+ eval_index : np.ndarray
331
+ indices of data partitioned for evaluation
332
+ """
333
+
334
+ def class_freq_diff(split):
335
+ train_labels = labels[split["train"]]
336
+ _, train_counts = np.unique(train_labels, return_counts=True)
337
+ train_freq = train_counts / train_counts.sum()
338
+ return np.square(train_freq - class_freq).sum()
339
+
340
+ if stratified:
341
+ _, class_counts = np.unique(labels, return_counts=True)
342
+ class_freq = class_counts / class_counts.sum()
343
+ best_split = min(split_defs, key=class_freq_diff)
344
+ return best_split["train"], best_split["eval"]
345
+ elif eval_frac <= 2 / 3:
346
+ best_split = min(split_defs, key=lambda x: abs(eval_frac - x["eval_frac"])) # type: ignore
347
+ return best_split["train"], best_split["eval"]
348
+ else:
349
+ best_split = min(split_defs, key=lambda x: abs(eval_frac - (1 - x["eval_frac"]))) # type: ignore
350
+ return best_split["eval"], best_split["train"]
351
+
352
+
353
+ def single_split(
354
+ index: NDArray[np.int_],
355
+ labels: NDArray[np.int_],
356
+ eval_frac: float,
357
+ groups: NDArray[np.int_] | None = None,
358
+ stratified: bool = False,
359
+ ) -> tuple[NDArray[np.int_], NDArray[np.int_]]:
360
+ """Handles the special case where only 1 partition of the data is desired (such as when
361
+ generating the test holdout split). In this case, the desired fraction of the data to be
362
+ partitioned into the test data must be specified, and a single [train, eval] pair are returned.
363
+
364
+ Parameters
365
+ ----------
366
+ index : np.ndarray
367
+ Input Dataset index corresponding to each label
368
+ labels : np.ndarray
369
+ Labels upon which splits are (optionally) stratified
370
+ eval_frac : float
371
+ Fraction of incoming data to be set aside for evaluation
372
+ groups : np.ndarray, Optional
373
+ Group_ids (same shape as labels) for optional group partitioning
374
+ stratified : bool, default=False
375
+ Generates stratified splits if true (recommended)
376
+
377
+ Returns
378
+ -------
379
+ train_index : np.ndarray
380
+ indices of data partitioned for training
381
+ eval_index : np.ndarray
382
+ indices of data partitioned for evaluation
383
+ """
384
+ if groups is not None:
385
+ n_unique_groups = np.unique(groups).shape[0]
386
+ _, label_counts = np.unique(labels, return_counts=True)
387
+ n_folds = min(n_unique_groups, label_counts.min())
388
+ elif eval_frac <= 2 / 3:
389
+ n_folds = max(2, int(round(1 / (eval_frac + 1e-6))))
390
+ else:
391
+ n_folds = max(2, int(round(1 / (1 - eval_frac - 1e-6))))
392
+ split_candidates = make_splits(index, labels, n_folds, groups, stratified)
393
+ best_train, best_eval = find_best_split(labels, split_candidates, stratified, eval_frac)
394
+ return best_train, best_eval
395
+
396
+
397
+ def split_dataset(
398
+ labels: list[int] | NDArray[np.int_],
399
+ num_folds: int = 1,
400
+ stratify: bool = False,
401
+ split_on: list[str] | None = None,
402
+ metadata: dict[str, Any] | None = None,
403
+ test_frac: float | None = None,
404
+ val_frac: float | None = None,
405
+ ) -> dict[str, dict[str, NDArray[np.int_]] | NDArray[np.int_]]:
406
+ """Top level splitting function. Returns a dict with each key-value pair containing
407
+ train and validation indices. Indices for a test holdout may also be optionally included
408
+
409
+ Parameters
410
+ ----------
411
+ labels : Union[list, np.ndarray]
412
+ Classification Labels used to generate splits. Determines the size of the dataset
413
+ num_folds : int, optional
414
+ Number of train/val folds. If None, returns a single train/val split, and val_frac must be
415
+ specified. Defaults to None.
416
+ stratify : bool, default=False
417
+ If true, dataset is split such that the class distribution of the entire dataset is
418
+ preserved within each train/val partition, which is generally recommended.
419
+ split_on : list, optional
420
+ Keys of the metadata dictionary which map to columns upon which to group the dataset.
421
+ A grouped partition is divided such that no group is present within both the training and
422
+ validation set. Split_on groups should be selected to mitigate validation bias. Defaults to
423
+ None, in which groups will not be considered when partitioning the data.
424
+ metadata : dict, optional
425
+ Dict containing data for potential dataset grouping. See split_on above. Defaults to None.
426
+ test_frac : float, optional
427
+ Fraction of data to be optionally held out for test set. Defaults to None, in which no test
428
+ set is created.
429
+ val_frac : float, optional
430
+ Fraction of training data to be set aside for validation in the case where a single
431
+ train/val split is desired. Defaults to None.
432
+
433
+ Raises
434
+ ------
435
+ UnboundLocalError
436
+ Raised if split_on is passed, but metadata is left as None. This is because split_on
437
+ defines the keys in which metadata dict must be indexed to determine the group index of the
438
+ data
439
+
440
+ Returns
441
+ -------
442
+ split_defs : dict
443
+ dictionary of folds, each containing indices of training and validation data.
444
+ ex.
445
+ {
446
+ "Fold_00": {
447
+ "train": [1,2,3,5,6,7,9,10,11],
448
+ "val": [0, 4, 8, 12]
449
+ },
450
+ "test": [13, 14, 15, 16]
451
+ }
452
+ """
453
+
454
+ test_frac, val_frac = validate_test_val(num_folds, test_frac, val_frac)
455
+ total_partitions = num_folds + 1 if test_frac else num_folds
456
+ index, labels = check_labels(labels, total_partitions)
457
+ stratify &= check_stratifiable(labels, total_partitions)
458
+ if split_on:
459
+ if metadata is None:
460
+ raise UnboundLocalError("If split_on is specified, metadata must also be provided")
461
+ groups = get_group_ids(metadata, split_on, len(labels))
462
+ groupable = check_groups(groups, total_partitions)
463
+ if not groupable:
464
+ groups = None
465
+ else:
466
+ groups = None
467
+ split_defs: dict[str, dict[str, NDArray[np.int_]] | NDArray[np.int_]] = {}
468
+ if test_frac:
469
+ tv_idx, test_idx = single_split(index, labels, test_frac, groups, stratify)
470
+ tv_labels = labels[tv_idx]
471
+ tv_groups = groups[tv_idx] if groups is not None else None
472
+ split_defs["test"] = test_idx
473
+ else:
474
+ tv_idx = np.arange(len(labels)).reshape((-1, 1))
475
+ tv_labels = labels
476
+ tv_groups = groups
477
+ if num_folds == 1:
478
+ train_idx, val_idx = single_split(tv_idx, tv_labels, val_frac, tv_groups, stratify)
479
+ split_defs["fold_0"] = {"train": tv_idx[train_idx].squeeze(), "val": tv_idx[val_idx].squeeze()}
480
+ else:
481
+ tv_splits = make_splits(tv_idx, tv_labels, num_folds, tv_groups, stratify)
482
+ for i, split in enumerate(tv_splits):
483
+ train_split = tv_idx[split["train"]]
484
+ val_split = tv_idx[split["eval"]]
485
+ split_defs[f"fold_{i}"] = {"train": train_split.squeeze(), "val": val_split.squeeze()}
486
+ return split_defs
@@ -1,17 +1,19 @@
1
1
  """
2
- Tensorflow models are used in out-of-distribution detectors in the :mod:`dataeval.detectors.ood` module.
2
+ TensorFlow models are used in :term:`out of distribution<Out-of-distribution (OOD)>` detectors in the
3
+ :mod:`dataeval.detectors.ood` module.
3
4
 
4
- DataEval provides both basic default models through the utility :func:`dataeval.utils.tensorflow.models.create_model`
5
- as well as constructors which allow for customization of the encoder, decoder and any other applicable
6
- layers used by the model.
5
+ DataEval provides basic default models through the utility :func:`dataeval.utils.tensorflow.create_model`.
7
6
  """
8
7
 
9
8
  from dataeval import _IS_TENSORFLOW_AVAILABLE
10
9
 
11
- from . import loss, models, recon
12
-
13
10
  __all__ = []
14
11
 
15
12
 
16
13
  if _IS_TENSORFLOW_AVAILABLE:
17
- __all__ = ["loss", "models", "recon"]
14
+ import dataeval.utils.tensorflow.loss as loss
15
+ from dataeval.utils.tensorflow._internal.utils import create_model
16
+
17
+ __all__ = ["create_model", "loss"]
18
+
19
+ del _IS_TENSORFLOW_AVAILABLE