/
datablob.py
2088 lines (1785 loc) · 74.5 KB
/
datablob.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Group together and name your training, validation, and test sets.
The classes in this module are used to group together
data into training, validation, and test sets used for
training machine learning models. We also record the
hyperparameters used to process the dataset.
The :py:class:`DataBlob` subclass name and hyperparameters
are used to create a unique content-addressable name
that makes it easy to keep track of many datasets at once.
"""
import errno
import os
from typing import Any, Mapping, Optional, Type, Union, cast
import pandas as pd
import tensorflow as tf
from log_with_context import Logger
import scalarstop.pickle
from scalarstop._constants import (
_DATAFRAME_FILENAME,
_DEFAULT_SAVE_LOAD_VERSION,
_SUBTYPE_TEST,
_SUBTYPE_TRAINING,
_SUBTYPE_VALIDATION,
_SUBTYPES,
)
from scalarstop._filesystem import rmtree
from scalarstop._logging import Timeblock
from scalarstop._naming import temporary_filename
from scalarstop._single_namespace import SingleNamespace
from scalarstop._tfdata import tfdata_load, tfdata_save
from scalarstop.datablob_metadata import DataBlobMetadata
from scalarstop.exceptions import (
DataBlobNotFound,
ElementSpecNotFound,
FileExists,
FileExistsDuringDataBlobCreation,
InconsistentCachingParameters,
IsNotImplemented,
TensorFlowDatasetNotFound,
)
from scalarstop.hyperparams import (
AppendHyperparamsType,
HyperparamsType,
NestedHyperparamsType,
enforce_dict,
)
_LOGGER = Logger(__name__)
class DataBlobBase(SingleNamespace):
"""The abstract base class describing the properties common to all DataBlobs."""
def __init__(
self,
*,
hyperparams: Optional[Union[Mapping[str, Any], HyperparamsType]] = None,
**kwargs,
):
super().__init__(hyperparams=hyperparams, **kwargs)
self._training: Any = None
self._validation: Any = None
self._test: Any = None
def set_training(self) -> Any:
"""Creates and returns a new object representing the training set."""
raise IsNotImplemented("DataBlobBase.set_training()")
@property
def training(self) -> Any:
"""An object representing the training set."""
if self._training is None:
self._training = self.set_training()
return self._training
def set_validation(self) -> Any:
"""Creates and returns a new object representing the validation set."""
raise IsNotImplemented("DataBlobBase.set_validation()")
@property
def validation(self) -> Any:
"""An object representing the validation set."""
if self._validation is None:
self._validation = self.set_validation()
return self._validation
def set_test(self) -> Any:
"""Creates and returns a new object representing the test set."""
raise IsNotImplemented("DataBlobBase.set_test()")
@property
def test(self) -> Any:
"""An object representing the test set."""
if self._test is None:
self._test = self.set_test()
return self._test
class DataBlob(DataBlobBase):
"""
Subclass this to group your training, validation, and test sets for training machine learning models.
Here is how to use :py:class:`DataBlob` to group your training,
validation, and test sets:
1. Subclass :py:class:`DataBlob` with a class name that describes
your dataset in general. In this example, we'll use
``MyDataBlob`` as the class name.
2. Define a dataclass using the ``@sp.dataclass`` decorator at
``MyDataBlob.Hyperparams``. We'll define an *instance* of
this dataclass at ``MyDataBlob.hyperparams``. This describes
the hyperparameters involved in processing your dataset.
3. Override the methods :py:meth:`DataBlob.set_training`,
:py:meth:`DataBlob.set_validation`, and :py:meth:`DataBlob.set_test`
to generate :py:class:`tf.data.Dataset` pipelines
representing your training, validation, and test sets.
Those three steps roughly look like:
>>> import tensorflow as tf
>>> import scalarstop as sp
>>>
>>> class MyDataBlob(sp.DataBlob):
...
... @sp.dataclass
... class Hyperparams(sp.HyperparamsType):
... cols: int
...
... def _data(self):
... x = tf.random.uniform(shape=(10, self.hyperparams.cols))
... y = tf.round(tf.random.uniform(shape=(10,1)))
... return tf.data.Dataset.zip((
... tf.data.Dataset.from_tensor_slices(x),
... tf.data.Dataset.from_tensor_slices(y),
... ))
...
... def set_training(self):
... return self._data()
...
... def set_validation(self):
... return self._data()
...
... def set_test(self):
... return self._data()
>>>
In our above example, our training, validation, and test sets
are created with the exact same code. In practice, you'll
be creating them with different inputs.
Now we create an instance of our subclass so we can start
using it.
>>> datablob = MyDataBlob(hyperparams=dict(cols=3))
>>> datablob
<sp.DataBlob MyDataBlob-bn5hpc7ueo2uz7as1747tetn>
:py:class:`DataBlob` instances are given a unique name
by hashing together the class name with the instance's
hyperparameters.
>>> datablob.name
'MyDataBlob-bn5hpc7ueo2uz7as1747tetn'
>>>
>>> datablob.group_name
'MyDataBlob'
>>>
>>> datablob.hyperparams
MyDataBlob.Hyperparams(cols=3)
>>>
>>> sp.enforce_dict(datablob.hyperparams)
{'cols': 3}
We save exactly one instance of each :py:class:`tf.data.Dataset`
pipeline in the properties :py:attr:`DataBlob.training`,
:py:attr:`DataBlob.validation`, and :py:attr:`DataBlob.test`.
>>> datablob.training
<ZipDataset element_spec=(TensorSpec(shape=(3,), dtype=tf.float32, name=None), TensorSpec(shape=(1,), dtype=tf.float32, name=None))>
>>>
>>> datablob.validation
<ZipDataset element_spec=(TensorSpec(shape=(3,), dtype=tf.float32, name=None), TensorSpec(shape=(1,), dtype=tf.float32, name=None))>
>>>
>>> datablob.test
<ZipDataset element_spec=(TensorSpec(shape=(3,), dtype=tf.float32, name=None), TensorSpec(shape=(1,), dtype=tf.float32, name=None))>
:py:class:`DataBlob` objects have some methods for applying
:py:mod:`tf.data` transformations to the training, validation, and
test sets at the same time:
* **Batching.** :py:meth:`DataBlob.batch` will batch the training, validation,
and test sets at the same time. If you call
:py:meth:`DataBlob.batch` with the keyword argument
``with_tf_distribute=True``, your input batch size will be
multiplied by the number of replicas in your :py:mod:`tf.distribute`
strategy.
* **Caching.** :py:meth:`DataBlob.cache` will cache the training, validation,
and test sets in memory once you iterate over them. This is
useful if your :py:class:`tf.data.Dataset` are doing something
computationally expensive each time you iterate over them.
* **Saving/loading to/from the filesystem.** :py:meth:`DataBlob.save`
saves the training, validation, and test
sets to a path on the filesystem. This can be loaded back with
the classmethod :py:meth:`DataBlob.from_exact_path`.
>>> import os
>>> import tempfile
>>> tempdir = tempfile.TemporaryDirectory()
>>>
>>> datablob = datablob.save(tempdir.name)
>>>
>>> os.listdir(tempdir.name)
['MyDataBlob-bn5hpc7ueo2uz7as1747tetn']
>>> path = os.path.join(tempdir.name, datablob.name)
>>> loaded_datablob = MyDataBlob.from_exact_path(path)
>>> loaded_datablob
<sp.DataBlob MyDataBlob-bn5hpc7ueo2uz7as1747tetn>
Alternatively, if you have the hyperparameters of the
:py:class:`DataBlob` but not the name, you can use the
classmethod :py:meth:`DataBlob.from_filesystem`.
>>> loaded_datablob_2 = MyDataBlob.from_filesystem(
... hyperparams=dict(cols=3),
... datablobs_directory=tempdir.name,
... )
>>> loaded_datablob_2
<sp.DataBlob MyDataBlob-bn5hpc7ueo2uz7as1747tetn>
(and now let's clean up the temporary directory from above)
>>> tempdir.cleanup()
""" # pylint: disable=line-too-long
_training: Optional[tf.data.Dataset] = None
_validation: Optional[tf.data.Dataset] = None
_test: Optional[tf.data.Dataset] = None
@classmethod
def from_filesystem(
cls,
*,
hyperparams: Optional[Union[Mapping[str, Any], HyperparamsType]] = None,
datablobs_directory: str,
shard_offset: Optional[int] = None,
shard_quantity: int = 1,
):
"""
Loads a :py:class:`DataBlob` from the filesystem, calculating the
filename from the hyperparameters.
Args:
hyperparams: The hyperparameters of the model that we want to load.
datablobs_directory: The parent directory of all of your saved
:py:class:`DataBlob` s. The exact filename is calculated
from the class name and hyperparams.
"""
name = cls.calculate_name(hyperparams=hyperparams)
path = os.path.join(datablobs_directory, name)
return cls.from_exact_path(
path, shard_offset=shard_offset, shard_quantity=shard_quantity
)
@classmethod
def from_filesystem_distributed(
cls,
*,
hyperparams: Optional[Union[Mapping[str, Any], HyperparamsType]] = None,
datablobs_directory: str,
cache: bool = False,
repeat: Union[bool, int, None] = True,
per_replica_batch_size: Optional[int] = None,
tf_distribute_strategy: Optional[tf.distribute.Strategy] = None,
) -> "DistributedDataBlob":
"""
Loads a sharded :py:class:`DataBlob` from the filesystem,
automatically splitting the shards amongs the input workers
of a :py:class:`tf.distribute.Strategy`.
Args:
hyperparams: The hyperparameters of the model that we want to load.
datablobs_directory: The parent directory of all of your saved
:py:class:`DataBlob` s. The exact filename is calculated
from the class name and hyperparams.
cache: Whether to cache the :py:class:`DataBlob` in memory.
If ``repeat`` is also enabled, then caching will
happen before repeating.
repeat: Repeats the :py:class:`DataBlob` after loading it.
Set to ``True`` to enable infinite repeating.
Set to a positive integer ``n`` to repeat the
:py:class:`DataBlob` ``n`` times.
Set to ``False`` to disable repeating.
per_replica_batch_size: The batch size for each individual
:py:mod:`tf.distribute` replica. This is the global
batch size divided by :py:attr:`tf.distribute.Strategy.num_replicas_in_sync`.
tf_distribute_strategy: The :py:class:`tf.distribute.Strategy`
subclass to use. Optionally, this method will detect if it
is already inside a `:py:meth:`tf.distribute.Strategy.scope`
context manager.
"""
return _DistributedDataBlobFromFilesystem(
hyperparams=hyperparams,
datablobs_directory=datablobs_directory,
datablob_class=cls,
cache=cache,
repeat=repeat,
per_replica_batch_size=per_replica_batch_size,
tf_distribute_strategy=tf_distribute_strategy,
)
@classmethod
def metadata_from_filesystem(
cls,
*,
hyperparams: Optional[Union[Mapping[str, Any], HyperparamsType]] = None,
datablobs_directory: str,
) -> DataBlobMetadata:
"""
Loads this :py:class:`DataBlob` 's :py:class:`DataBlobMetadata`
from the filesystem, calculating the filename from the hyperparameters.
Args:
hyperparams: The hyperparameters of the model that we want to load.
datablobs_directory: The parent directory of all of your saved
:py:class:`DataBlob` s. The exact filename is calculated
from the class name and hyperparams.
"""
name = cls.calculate_name(hyperparams=hyperparams)
path = os.path.join(datablobs_directory, name)
return cls.metadata_from_exact_path(path)
@classmethod
def from_filesystem_or_new(
cls,
*,
hyperparams: Optional[Union[Mapping[str, Any], HyperparamsType]] = None,
datablobs_directory: str,
shard_offset: Optional[int] = None,
shard_quantity: int = 1,
**kwargs,
):
"""Load a :py:class:`DataBlob` from the filesystem, calculating the
filename from the hyperparameters. Create a new :py:class:`DataBlob`
if we cannot find a saved one on the filesystem.
Args:
hyperparams: The hyperparameters of the model that we want to load.
datablobs_directory: The parent directory of all of your saved
:py:class:`DataBlob` s. The exact filename is calculated
from the class name and hyperparams.
**kwargs: Other keyword arguments that you need to pass to
your ``__init__()``.
"""
try:
return cls.from_filesystem(
hyperparams=hyperparams,
datablobs_directory=datablobs_directory,
shard_offset=shard_offset,
shard_quantity=shard_quantity,
)
except DataBlobNotFound:
return cls(hyperparams=hyperparams, **kwargs)
@staticmethod
def from_exact_path(
path: str, *, shard_offset: Optional[int] = None, shard_quantity: int = 1
) -> "DataBlob":
"""Load a :py:class:`DataBlob` from a directory on the filesystem."""
return _LoadDataBlob.from_exact_path(
path=path, shard_offset=shard_offset, shard_quantity=shard_quantity
)
@classmethod
def from_exact_path_distributed(
cls,
*,
path: str,
cache: bool = False,
repeat: Union[bool, int, None] = True,
per_replica_batch_size: Optional[int] = None,
tf_distribute_strategy: Optional[tf.distribute.get_strategy] = None,
) -> "DistributedDataBlob":
"""
Args:
path: The exact location of the saved :py:class:`DataBlob`
on the filesystem.
cache: Whether to cache the :py:class:`DataBlob` in memory.
If ``repeat`` is also enabled, then caching will
happen before repeating.
repeat: Repeats the :py:class:`DataBlob` after loading it.
Set to ``True`` to enable infinite repeating.
Set to a positive integer ``n`` to repeat the
:py:class:`DataBlob` ``n`` times.
Set to ``False`` to disable repeating.
per_replica_batch_size: The batch size for each individual
:py:mod:`tf.distribute` replica. This is the global
batch size divided by :py:attr:`tf.distribute.Strategy.num_replicas_in_sync`.
tf_distribute_strategy: The :py:class:`tf.distribute.Strategy`
subclass to use. Optionally, this method will detect if it
is already inside a `:py:meth:`tf.distribute.Strategy.scope`
context manager.
"""
return _DistributedDataBlobFromExactPath(
path=path,
datablob_class=cls,
cache=cache,
repeat=repeat,
per_replica_batch_size=per_replica_batch_size,
tf_distribute_strategy=tf_distribute_strategy,
)
@staticmethod
def metadata_from_exact_path(path: str) -> DataBlobMetadata:
"""
Loads this :py:class:`DataBlob` 's :py:class:`DataBlobMetadata`
from a directory on the filesystem.
"""
return DataBlobMetadata.load(path)
def exists_in_datablobs_directory(
self,
datablobs_directory: str,
) -> bool:
"""
Returns ``True`` if this :py:class:`DataBlob` was already saved
within ``datablobs_directory``.
Args:
datablobs_directory: The parent directory of all of your
saved :py:class:`DataBlob` s.
Returns:
Returns ``True`` if we found a py:class:`DataBlob`
metadata file at the expected location.
"""
path = os.path.join(datablobs_directory, self.name)
return os.path.exists(path)
def __repr__(self) -> str:
return f"<sp.DataBlob {self.name}>"
def set_training(self) -> tf.data.Dataset:
"""Create a :py:class:`tf.data.Dataset` for the training set."""
raise IsNotImplemented("DataBlob.set_training()")
@property
def training(self) -> tf.data.Dataset:
"""A :py:class:`tf.data.Dataset` instance representing the training set."""
if self._training is None:
self._training = self.set_training()
return self._training
def set_validation(self) -> tf.data.Dataset:
"""Create a :py:class:`tf.data.Dataset` for the validation set."""
raise IsNotImplemented("DataBlob.set_validation()")
@property
def validation(self) -> tf.data.Dataset:
"""A :py:class:`tf.data.Dataset` instance representing the validation set."""
if self._validation is None:
self._validation = self.set_validation()
return self._validation
def set_test(self) -> tf.data.Dataset:
"""Create a :py:class:`tf.data.Dataset` for the test set."""
raise IsNotImplemented("DataBlob.set_test()")
@property
def test(self) -> tf.data.Dataset:
"""A :py:class:`tf.data.Dataset` instance representing the test set."""
if self._test is None:
self._test = self.set_test()
return self._test
def batch(
self,
batch_size: int,
*,
training: bool = True,
validation: bool = True,
test: bool = True,
with_tf_distribute: bool = False,
) -> "DataBlob":
"""
Batch this :py:class:`DataBlob`.
Args:
batch_size: The number of items to collect into a batch.
training: Whether to batch the training set.
Defaults to ``True``.
validation: Whether to batch the validation set.
Defaults to ``True``.
test: Whether to batch the test set. Defaults to ``True``.
with_tf_distribute: Whether to consider ``tf.distribute``
auto-data sharding when calculating the batch size.
"""
return _BatchDataBlob(
wraps=self,
batch_size=batch_size,
training=training,
validation=validation,
test=test,
with_tf_distribute=with_tf_distribute,
)
def cache(
self,
*,
training: bool = True,
validation: bool = True,
test: bool = True,
precache_training: bool = False,
precache_validation: bool = False,
precache_test: bool = False,
) -> "DataBlob":
"""
Cache this :py:class:`DataBlob` into memory before iterating over it.
By default, this creates a :py:class:`DataBlob` containing a
TensorFlow ``CacheDataset`` for each of the training, validation and test
:py:class:`tf.data.Dataset` s.
But these datasets do not load into memory until the first time you
*completely* iterate over one--from start to end. If you want to
immediately load your training, validation, or test sets, you can
set ``precache_training``, ``precache_validation``, and/or
``precache_test`` to ``True``.
Args:
training: Lazily cache the training set in CPU memory.
Defaults to ``True``.
validation: Lazily cache the validation set in CPU memory.
Defaults to ``True``.
test: Lazily cache the test set in CPU memory.
Defaults to ``True``.
precache_training: Eagerly cache the training set into memory.
Defaults to ``False``.
precache_validation: Eagerly cache the validation set into
memory. Defaults to ``False``.
precache_test: Eagerly cache the test set into memory.
Defaults to ``False``.
"""
return _CacheDataBlob(
wraps=self,
training=training,
validation=validation,
test=test,
precache_training=precache_training,
precache_validation=precache_validation,
precache_test=precache_test,
)
def prefetch(
self,
buffer_size: int,
*,
training: bool = True,
validation: bool = True,
test: bool = True,
) -> "DataBlob":
"""
Creates a :py:class:`DataBlob` that prefetches elements for
performance.
Args:
buffer_size: The maximum number of elements that will
be buffered when prefetching. If the value
:py:meth:`tf.data.experimental.AUTOTUNE` is used,
then the buffer is dynamically tuned.
training: Apply the repeat operator to the training set.
Defaults to ``True``.
validation: Apply the repeat operator to the validation set.
Defaults to ``True``.
test: Apply the repeat operator to the test set.
Defaults to ``True``.
"""
return _PrefetchDataBlob(
wraps=self,
buffer_size=buffer_size,
training=training,
validation=validation,
test=test,
)
def repeat(
self,
count: Optional[int] = None,
*,
training: bool = True,
validation: bool = True,
test: bool = True,
) -> "DataBlob":
"""
Repeats this :py:class:`DataBlob`.
Args:
count: Represents the number of times that the
elements in the :py:class:`tf.data.Dataset` should
be repeated. The default behavior (if ``count`` is
``None`` or ``-1``) is for the dataset be repeated
indefinitely.
training: Apply the repeat operator to the training set.
Defaults to ``True``.
validation: Apply the repeat operator to the validation set.
Defaults to ``True``.
test: Apply the repeat operator to the test set.
Defaults to ``True``.
"""
return _RepeatDataBlob(
wraps=self,
count=count,
training=training,
validation=validation,
test=test,
)
def repeat_interleaved( # pylint: disable=too-many-arguments
self,
count: int,
cycle_length: Optional[int] = None,
block_length: Optional[int] = None,
num_parallel_calls: Optional[int] = None,
deterministic: Optional[bool] = None,
*,
training: bool = True,
validation: bool = True,
test: bool = True,
) -> "DataBlob":
"""
Repeats this :py:class:`DataBlob`, but interleaved order.
Args:
count: Represents the number of times that the
elements in the :py:class:`tf.data.Dataset` should
be repeated. This must be a finite integer
greater than 0. It cannot be a negative number,
``None``, or an infinite value.
training: Apply the repeat operator to the training set.
Defaults to ``True``.
validation: Apply the repeat operator to the validation set.
Defaults to ``True``.
test: Apply the repeat operator to the test set.
Defaults to ``True``.
"""
return _RepeatInterleavedDataBlob(
wraps=self,
count=count,
cycle_length=cycle_length,
block_length=block_length,
num_parallel_calls=num_parallel_calls,
deterministic=deterministic,
training=training,
validation=validation,
test=test,
)
def with_options(
self,
options: tf.data.Options,
*,
training: bool = True,
validation: bool = True,
test: bool = True,
) -> "DataBlob":
"""
Apply a :py:class:`tf.data.Options` object to this :py:class:`DataBlob`.
Args:
options: The :py:class:`tf.data.Options` object to apply.
training: Apply the options to the training set. Defaults to ``True``.
validation: Apply the options to the validation set. Defaults to ``True``.
test: Apply the options to the test set. Defaults to ``True``.
"""
return _WithOptionsDataBlob(
wraps=self,
options=options,
training=training,
validation=validation,
test=test,
)
def save_hook( # pylint: disable=unused-argument
self, *, subtype: str, path: str
) -> None:
"""
Override this method to run additional code when saving this
:py:class:`DataBlob` to disk.
"""
return None
def save(
self,
datablobs_directory: str,
*,
ignore_existing: bool = False,
num_shards: int = 1,
save_load_version: int = _DEFAULT_SAVE_LOAD_VERSION,
) -> "DataBlob":
"""
Save this :py:class:`DataBlob` to disk.
Args:
datablobs_directory: The directory where you plan on storing all of your
DataBlobs. This method will save this :py:class:`DataBlob` in a subdirectory
of ``datablobs_directory`` with same name as :py:attr:`DataBlob.name`.
ignore_existing: Set this to ``True`` to ignore if
there is already a :py:class:`DataBlob` at the given
path.
save_load_version: The ScalarStop version for the ScalarStop protocol.
Returns:
Return ``self``, enabling you to place this call in a chain.
"""
# Begin writing our hyperparameters, dataframes, tfdata, and element spec.
final_datablob_path = os.path.join(datablobs_directory, self.name)
if os.path.exists(final_datablob_path):
if ignore_existing:
return self
raise FileExists(
f"File or directory already exists at path {final_datablob_path}"
)
temp_datablob_path = temporary_filename(final_datablob_path)
os.mkdir(temp_datablob_path)
try:
# Save DataBlob metadata to JSON and Pickle.
DataBlobMetadata.from_datablob(
datablob=self,
save_load_version=save_load_version,
num_shards=num_shards,
).save(temp_datablob_path)
for subtype in _SUBTYPES:
# Create the directory for each subtype.
subtype_path = os.path.join(temp_datablob_path, subtype)
tfdata_dataset = getattr(self, subtype)
tfdata_save(
dataset=tfdata_dataset,
path=subtype_path,
num_shards=num_shards,
save_load_version=save_load_version,
)
# Save additional elements that subclasses want to save.
self.save_hook(subtype=subtype, path=subtype_path)
except BaseException:
# If we run into an error, delete our partially constructed dataset
# from the filesystem.
rmtree(temp_datablob_path)
raise
else:
# Now that we have completed the construction of our dataset,
# we are going to move it from the temporary directory name
# to the permanent directory name.
file_exists_exception = FileExistsDuringDataBlobCreation(
"Failed to rename dataset directory from "
f"{temp_datablob_path} to {final_datablob_path}. "
f"The directory at {final_datablob_path} became occupied "
"during the dataset creation."
)
try:
os.rename(temp_datablob_path, final_datablob_path)
except (FileExistsError, NotADirectoryError) as exc:
raise file_exists_exception from exc
except OSError as exc:
if exc.errno == errno.ENOTEMPTY:
raise file_exists_exception from exc
raise exc
else:
return self
class DataFrameDataBlob(DataBlob):
"""
Subclass this to transform a :py:class:`pandas.DataFrame` into your training, validation, and test sets.
:py:class:`DataBlob` is useful when you want to manually define your
:py:mod:`tf.data` pipelines and their input tensors.
However, if your input tensors are in a fixed-size list or
:py:class:`~pandas.DataFrame` that you want to *slice* into
a training, validation, and test set, then you might find
:py:class:`DataFrameDataBlob` handy.
Here is how to use it:
1. Subclass :py:class:`DataFrameDataBlob` with a class name that
describes your dataset.
2. Override :py:meth:`DataFrameDataBlob.set_dataframe` and have
it return a *single* :py:class:`~pandas.DataFrame` that contains
all of the *inputs* for your training, validation, and
test sets. The :py:class:`~pandas.DataFrame` should have
one column representing training samples and another
column representing training labels.
3. Override :py:meth:`DataFrameDataBlob.transform` and define
a method that transforms an arbitrary :py:class:`~pandas.DataFrame`
of *inputs* into a :py:class:`tf.data.Dataset` pipeline
that represents the actual dataset needed for training
and evaluation.
We define what fraction of the :py:class:`~pandas.DataFrame` to split
with the class attributes :py:attr:`DataFrameDataBlob.training_fraction`
and :py:attr:`DataFrameDataBlob.validation_fraction`. By default,
60 percent of the :py:class:`~pandas.DataFrame` is marked
for the training set, 20 percent for the validation set,
and the remainder of the :py:class:`~pandas.DataFrame` for the test set.
Roughly, this looks like:
>>> import pandas as pd
>>> import tensorflow as tf
>>> import scalarstop as sp
>>>
>>> class MyDataFrameDataBlob(sp.DataFrameDataBlob):
... samples_column: str = "samples"
... labels_column: str = "labels"
... training_fraction: float = 0.6
... validation_fraction: float = 0.2
...
... @sp.dataclass
... class Hyperparams(sp.HyperparamsType):
... length: int = 0
...
... def set_dataframe(self):
... samples = list(range(self.hyperparams.length))
... labels = list(range(self.hyperparams.length))
... return pd.DataFrame({self.samples_column: samples, self.labels_column: labels})
...
... def transform(self, dataframe: pd.DataFrame):
... return tf.data.Dataset.zip((
... tf.data.Dataset.from_tensor_slices(dataframe[self.samples_column]),
... tf.data.Dataset.from_tensor_slices(dataframe[self.labels_column]),
... ))
>>> datablob2 = MyDataFrameDataBlob(hyperparams=dict(length=10))
And you can use the resulting object in all of the same ways as
we've demonstrated with :py:class:`DataBlob` subclass instances above.
""" # pylint: disable=line-too-long
samples_column: str = "samples"
labels_column: str = "labels"
training_fraction: float = 0.6
validation_fraction: float = 0.2
_dataframe: Optional[pd.DataFrame] = None
_training_dataframe: Optional[pd.DataFrame] = None
_validation_dataframe: Optional[pd.DataFrame] = None
_test_dataframe: Optional[pd.DataFrame] = None
@staticmethod
def from_exact_path(
path: str,
*,
shard_offset: Optional[int] = None,
shard_quantity: int = 1,
) -> Union[DataBlob, "DataFrameDataBlob"]:
"""Load a :py:class:`DataFrameDataBlob` from a directory on the filesystem."""
loaded = _LoadDataFrameDataBlob.from_exact_path(
path=path,
shard_offset=shard_offset,
shard_quantity=shard_quantity,
)
return loaded
def __repr__(self) -> str:
return f"<sp.DataFrameDataBlob {self.name}>"
def set_dataframe(self) -> pd.DataFrame:
"""
Create a new :py:class:`pandas.DataFrame` that contains all of the data for
the training, validation, and test sets.
"""
raise IsNotImplemented("DataFrameDataBlob.set_dataframe()")
@property
def dataframe(self) -> pd.DataFrame:
"""
A :py:class:`pandas.DataFrame` that represents the entire
training, validation, and test set.
"""
if self._dataframe is None:
self._dataframe = self.set_dataframe()
return self._dataframe
def set_training_dataframe(self) -> pd.DataFrame:
"""
Sets the :py:class:`pandas.DataFrame` for the training set.
By default, this method slices the :py:class:`pandas.DataFrame` you have supplied to
:py:meth:`set_dataframe`.
Alternatively, you can choose to directly subclass
:py:meth:`set_training_dataframe`, :py:meth:`set_validation_dataframe`,
and :py:meth`set_test_dataframe`.
Returns:
Returns a :py:class:`pandas.DataFrame`.
"""
end = int(len(self.dataframe) * self.training_fraction)
return self.dataframe[:end]
@property
def training_dataframe(self) -> pd.DataFrame:
"""A :py:class:`pandas.DataFrame` representing training set input tensors."""
if self._training_dataframe is None:
self._training_dataframe = self.set_training_dataframe()
return self._training_dataframe
def set_validation_dataframe(self) -> pd.DataFrame:
"""
Sets the :py:class:`pandas.DataFrame` for the validation set.
By default, this method slices the :py:class:`pandas.DataFrame` you have supplied to
:py:meth:`set_dataframe`.
Alternatively, you can choose to directly subclass
:py:meth:`set_training_dataframe`, :py:meth:`set_validation_dataframe`,
and :py:meth`set_test_dataframe`.
Returns:
Returns a :py:class:`pandas.DataFrame`.
"""
start = int(len(self.dataframe) * self.training_fraction)
end = int(
len(self.dataframe) * (self.training_fraction + self.validation_fraction)
)
return self.dataframe[start:end]
@property
def validation_dataframe(self) -> pd.DataFrame:
"""A :py:class:`pandas.DataFrame` representing validation set input tensors."""
if self._validation_dataframe is None:
self._validation_dataframe = self.set_validation_dataframe()
return self._validation_dataframe
def set_test_dataframe(self) -> pd.DataFrame:
"""
Sets the :py:class:`pandas.DataFrame` for the test set.
By default, this method slices the DataFrame you have supplied to
:py:meth:`set_dataframe`.
Alternatively, you can choose to directly subclass
:py:meth:`set_training_dataframe`, :py:meth:`set_validation_dataframe`,
and :py:meth`set_test_dataframe`.
Returns:
Returns a Pandas :py:class:`pandas.DataFrame`.
"""
start = int(