forked from deepchem/deepchem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
datasets.py
1606 lines (1358 loc) · 48.3 KB
/
datasets.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
"""
Contains wrapper class for datasets.
"""
import json
import os
import math
import deepchem as dc
import numpy as np
import pandas as pd
import random
from deepchem.utils.save import save_to_disk, save_metadata
from deepchem.utils.save import load_from_disk
from deepchem.utils.save import log
from pandas import read_hdf
import tempfile
import time
import shutil
import json
from multiprocessing.dummy import Pool
import warnings
__author__ = "Bharath Ramsundar"
__copyright__ = "Copyright 2016, Stanford University"
__license__ = "MIT"
def sparsify_features(X):
"""Extracts a sparse feature representation from dense feature array."""
n_samples = len(X)
X_sparse = []
for i in range(n_samples):
nonzero_inds = np.nonzero(X[i])[0]
nonzero_vals = X[i][nonzero_inds]
X_sparse.append((nonzero_inds, nonzero_vals))
X_sparse = np.array(X_sparse, dtype=object)
return X_sparse
def densify_features(X_sparse, num_features):
"""Expands sparse feature representation to dense feature array."""
n_samples = len(X_sparse)
X = np.zeros((n_samples, num_features))
for i in range(n_samples):
nonzero_inds, nonzero_vals = X_sparse[i]
X[i][nonzero_inds.astype(int)] = nonzero_vals
return X
def pad_features(batch_size, X_b):
"""Pads a batch of features to have precisely batch_size elements.
Version of pad_batch for use at prediction time.
"""
num_samples = len(X_b)
if num_samples == batch_size:
return X_b
else:
# By invariant of when this is called, can assume num_samples > 0
# and num_samples < batch_size
if len(X_b.shape) > 1:
feature_shape = X_b.shape[1:]
X_out = np.zeros((batch_size,) + feature_shape, dtype=X_b.dtype)
else:
X_out = np.zeros((batch_size,), dtype=X_b.dtype)
# Fill in batch arrays
start = 0
while start < batch_size:
num_left = batch_size - start
if num_left < num_samples:
increment = num_left
else:
increment = num_samples
X_out[start:start + increment] = X_b[:increment]
start += increment
return X_out
def pad_batch(batch_size, X_b, y_b, w_b, ids_b):
"""Pads batch to have size precisely batch_size elements.
Fills in batch by wrapping around samples till whole batch is filled.
"""
num_samples = len(X_b)
if num_samples == batch_size:
return (X_b, y_b, w_b, ids_b)
# By invariant of when this is called, can assume num_samples > 0
# and num_samples < batch_size
if len(X_b.shape) > 1:
feature_shape = X_b.shape[1:]
X_out = np.zeros((batch_size,) + feature_shape, dtype=X_b.dtype)
else:
X_out = np.zeros((batch_size,), dtype=X_b.dtype)
if y_b is None:
y_out = None
elif len(y_b.shape) < 2:
y_out = np.zeros(batch_size, dtype=y_b.dtype)
else:
y_out = np.zeros((batch_size,) + y_b.shape[1:], dtype=y_b.dtype)
if w_b is None:
w_out = None
elif len(w_b.shape) < 2:
w_out = np.zeros(batch_size, dtype=w_b.dtype)
else:
w_out = np.zeros((batch_size,) + w_b.shape[1:], dtype=w_b.dtype)
ids_out = np.zeros((batch_size,), dtype=ids_b.dtype)
# Fill in batch arrays
start = 0
# Only the first set of copy will be counted in training loss
if w_out is not None:
w_out[start:start + num_samples] = w_b[:]
while start < batch_size:
num_left = batch_size - start
if num_left < num_samples:
increment = num_left
else:
increment = num_samples
X_out[start:start + increment] = X_b[:increment]
if y_out is not None:
y_out[start:start + increment] = y_b[:increment]
ids_out[start:start + increment] = ids_b[:increment]
start += increment
return (X_out, y_out, w_out, ids_out)
class Dataset(object):
"""Abstract base class for datasets defined by X, y, w elements."""
def __init__(self):
raise NotImplementedError()
def __len__(self):
"""
Get the number of elements in the dataset.
"""
raise NotImplementedError()
def get_shape(self):
"""Get the shape of the dataset.
Returns four tuples, giving the shape of the X, y, w, and ids arrays.
"""
raise NotImplementedError()
def get_task_names(self):
"""Get the names of the tasks associated with this dataset."""
raise NotImplementedError()
@property
def X(self):
"""Get the X vector for this dataset as a single numpy array."""
raise NotImplementedError()
@property
def y(self):
"""Get the y vector for this dataset as a single numpy array."""
raise NotImplementedError()
@property
def ids(self):
"""Get the ids vector for this dataset as a single numpy array."""
raise NotImplementedError()
@property
def w(self):
"""Get the weight vector for this dataset as a single numpy array."""
raise NotImplementedError()
def iterbatches(self,
batch_size=None,
epoch=0,
deterministic=False,
pad_batches=False):
"""
Parameters
----------
Returns
-------
"""
"""Get an object that iterates over minibatches from the dataset.
Each minibatch is returned as a tuple of four numpy arrays: (X, y, w, ids).
"""
raise NotImplementedError()
def itersamples(self):
"""Get an object that iterates over the samples in the dataset.
Example:
>>> dataset = NumpyDataset(np.ones((2,2)))
>>> for x, y, w, id in dataset.itersamples():
... print(x.tolist(), y.tolist(), w.tolist(), id)
[1.0, 1.0] [0.0] [0.0] 0
[1.0, 1.0] [0.0] [0.0] 1
"""
raise NotImplementedError()
def transform(self, fn, **args):
"""Construct a new dataset by applying a transformation to every sample in this dataset.
The argument is a function that can be called as follows:
>> newx, newy, neww = fn(x, y, w)
It might be called only once with the whole dataset, or multiple times with
different subsets of the data. Each time it is called, it should transform
the samples and return the transformed data.
Parameters
----------
fn: function
A function to apply to each sample in the dataset
Returns
-------
a newly constructed Dataset object
"""
raise NotImplementedError()
def get_statistics(self, X_stats=True, y_stats=True):
"""Compute and return statistics of this dataset."""
X_means = 0.0
X_m2 = 0.0
y_means = 0.0
y_m2 = 0.0
n = 0
for X, y, _, _ in self.itersamples():
n += 1
if X_stats:
dx = X - X_means
X_means += dx / n
X_m2 += dx * (X - X_means)
if y_stats:
dy = y - y_means
y_means += dy / n
y_m2 += dy * (y - y_means)
if n < 2:
X_stds = 0.0
y_stds = 0
else:
X_stds = np.sqrt(X_m2 / n)
y_stds = np.sqrt(y_m2 / n)
if X_stats and not y_stats:
return X_means, X_stds
elif y_stats and not X_stats:
return y_means, y_stds
elif X_stats and y_stats:
return X_means, X_stds, y_means, y_stds
else:
return None
def make_tf_dataset(self,
batch_size=100,
epochs=1,
deterministic=False,
pad_batches=False):
"""Create a tf.data.Dataset that iterates over the data in this Dataset.
Each value returned by the Dataset's iterator is a tuple of (X, y, w) for
one batch.
Parameters
----------
batch_size: int
the number of samples to include in each batch
epochs: int
the number of times to iterate over the Dataset
deterministic: bool
if True, the data is produced in order. If False, a different random
permutation of the data is used for each epoch.
pad_batches: bool
if True, batches are padded as necessary to make the size of each batch
exactly equal batch_size.
"""
# Retrieve the first sample so we can determine the dtypes.
import tensorflow as tf
X, y, w, ids = next(self.itersamples())
dtypes = (tf.as_dtype(X.dtype), tf.as_dtype(y.dtype), tf.as_dtype(w.dtype))
shapes = (tf.TensorShape([None] + list(X.shape)),
tf.TensorShape([None] + list(y.shape)),
tf.TensorShape([None] + list(w.shape)))
# Create a Tensorflow Dataset.
def gen_data():
for epoch in range(epochs):
for X, y, w, ids in self.iterbatches(batch_size, epoch, deterministic,
pad_batches):
yield (X, y, w)
return tf.data.Dataset.from_generator(gen_data, dtypes, shapes)
class NumpyDataset(Dataset):
"""A Dataset defined by in-memory numpy arrays."""
def __init__(self, X, y=None, w=None, ids=None, n_tasks=1):
n_samples = len(X)
if n_samples > 0:
if y is None:
# Set labels to be zero, with zero weights
y = np.zeros((n_samples, n_tasks), np.float32)
w = np.zeros((n_samples, 1), np.float32)
if ids is None:
ids = np.arange(n_samples)
if not isinstance(X, np.ndarray):
X = np.array(X)
if not isinstance(y, np.ndarray):
y = np.array(y)
if w is None:
if len(y.shape) == 1:
w = np.ones(y.shape[0], np.float32)
else:
w = np.ones((y.shape[0], 1), np.float32)
if not isinstance(w, np.ndarray):
w = np.array(w)
self._X = X
self._y = y
self._w = w
self._ids = np.array(ids, dtype=object)
def __len__(self):
"""
Get the number of elements in the dataset.
"""
return len(self._y)
def get_shape(self):
"""Get the shape of the dataset.
Returns four tuples, giving the shape of the X, y, w, and ids arrays.
"""
return self._X.shape, self._y.shape, self._w.shape, self._ids.shape
def get_task_names(self):
"""Get the names of the tasks associated with this dataset."""
if len(self._y.shape) < 2:
return np.array([0])
return np.arange(self._y.shape[1])
@property
def X(self):
"""Get the X vector for this dataset as a single numpy array."""
return self._X
@property
def y(self):
"""Get the y vector for this dataset as a single numpy array."""
return self._y
@property
def ids(self):
"""Get the ids vector for this dataset as a single numpy array."""
return self._ids
@property
def w(self):
"""Get the weight vector for this dataset as a single numpy array."""
return self._w
def iterbatches(self,
batch_size=None,
epoch=0,
deterministic=False,
pad_batches=False):
"""Get an object that iterates over minibatches from the dataset.
Each minibatch is returned as a tuple of four numpy arrays: (X, y, w, ids).
"""
def iterate(dataset, batch_size, deterministic, pad_batches):
n_samples = dataset._X.shape[0]
if not deterministic:
sample_perm = np.random.permutation(n_samples)
else:
sample_perm = np.arange(n_samples)
if batch_size is None:
batch_size = n_samples
batch_idx = 0
num_batches = np.math.ceil(n_samples / batch_size)
while batch_idx < num_batches:
start = batch_idx * batch_size
end = min(n_samples, (batch_idx + 1) * batch_size)
indices = range(start, end)
perm_indices = sample_perm[indices]
X_batch = dataset._X[perm_indices]
y_batch = dataset._y[perm_indices]
w_batch = dataset._w[perm_indices]
ids_batch = dataset._ids[perm_indices]
if pad_batches:
(X_batch, y_batch, w_batch, ids_batch) = pad_batch(
batch_size, X_batch, y_batch, w_batch, ids_batch)
batch_idx += 1
yield (X_batch, y_batch, w_batch, ids_batch)
return iterate(self, batch_size, deterministic, pad_batches)
def itersamples(self):
"""Get an object that iterates over the samples in the dataset.
Example:
>>> dataset = NumpyDataset(np.ones((2,2)))
>>> for x, y, w, id in dataset.itersamples():
... print(x.tolist(), y.tolist(), w.tolist(), id)
[1.0, 1.0] [0.0] [0.0] 0
[1.0, 1.0] [0.0] [0.0] 1
"""
n_samples = self._X.shape[0]
return ((self._X[i], self._y[i], self._w[i], self._ids[i])
for i in range(n_samples))
def transform(self, fn, **args):
"""Construct a new dataset by applying a transformation to every sample in this dataset.
The argument is a function that can be called as follows:
>> newx, newy, neww = fn(x, y, w)
It might be called only once with the whole dataset, or multiple times with
different subsets of the data. Each time it is called, it should transform
the samples and return the transformed data.
Parameters
----------
fn: function
A function to apply to each sample in the dataset
Returns
-------
a newly constructed Dataset object
"""
newx, newy, neww = fn(self._X, self._y, self._w)
return NumpyDataset(newx, newy, neww, self._ids[:])
def select(self, indices, select_dir=None):
"""Creates a new dataset from a selection of indices from self.
TODO(rbharath): select_dir is here due to dc.splits always passing in
splits.
Parameters
----------
indices: list
List of indices to select.
select_dir: string
Ignored.
"""
X = self.X[indices]
y = self.y[indices]
w = self.w[indices]
ids = self.ids[indices]
return NumpyDataset(X, y, w, ids)
@staticmethod
def from_DiskDataset(ds):
"""
Parameters
----------
ds : DiskDataset
DiskDataset to transorm to NumpyDataset
Returns
-------
NumpyDataset
Data of ds as NumpyDataset
"""
return NumpyDataset(ds.X, ds.y, ds.w, ds.ids)
@staticmethod
def to_json(self, fname):
d = {
'X': self.X.tolist(),
'y': self.y.tolist(),
'w': self.w.tolist(),
'ids': self.ids.tolist()
}
with open(fname, 'w') as fout:
json.dump(d, fout)
@staticmethod
def from_json(fname):
with open(fname) as fin:
d = json.load(fin)
return NumpyDataset(d['X'], d['y'], d['w'], d['ids'])
@staticmethod
def merge(datasets):
"""
Parameters
----------
datasets: list of deepchem.data.NumpyDataset
list of datasets to merge
Returns
-------
Single deepchem.data.NumpyDataset with data concatenated over axis 0
"""
X, y, w, ids = datasets[0].X, datasets[0].y, datasets[0].w, datasets[0].ids
for dataset in datasets[1:]:
X = np.concatenate([X, dataset.X], axis=0)
y = np.concatenate([y, dataset.y], axis=0)
w = np.concatenate([w, dataset.w], axis=0)
ids = np.concatenate(
[ids, dataset.ids],
axis=0,
)
return NumpyDataset(X, y, w, ids, n_tasks=y.shape[1])
class DiskDataset(Dataset):
"""
A Dataset that is stored as a set of files on disk.
"""
def __init__(self, data_dir, verbose=True):
"""
Turns featurized dataframes into numpy files, writes them & metadata to disk.
"""
self.data_dir = data_dir
self.verbose = verbose
log("Loading dataset from disk.", self.verbose)
self.tasks, self.metadata_df = self.load_metadata()
@staticmethod
def create_dataset(shard_generator, data_dir=None, tasks=[], verbose=True):
"""Creates a new DiskDataset
Parameters
----------
shard_generator: Iterable
An iterable (either a list or generator) that provides tuples of data
(X, y, w, ids). Each tuple will be written to a separate shard on disk.
data_dir: str
Filename for data directory. Creates a temp directory if none specified.
tasks: list
List of tasks for this dataset.
"""
if data_dir is None:
data_dir = tempfile.mkdtemp()
elif not os.path.exists(data_dir):
os.makedirs(data_dir)
metadata_rows = []
time1 = time.time()
for shard_num, (X, y, w, ids) in enumerate(shard_generator):
basename = "shard-%d" % shard_num
metadata_rows.append(
DiskDataset.write_data_to_disk(data_dir, basename, tasks, X, y, w,
ids))
metadata_df = DiskDataset._construct_metadata(metadata_rows)
save_metadata(tasks, metadata_df, data_dir)
time2 = time.time()
log("TIMING: dataset construction took %0.3f s" % (time2 - time1), verbose)
return DiskDataset(data_dir, verbose=verbose)
def load_metadata(self):
try:
tasks_filename, metadata_filename = self._get_metadata_filename()
with open(tasks_filename) as fin:
tasks = json.load(fin)
metadata_df = pd.read_csv(metadata_filename, compression='gzip')
metadata_df = metadata_df.where((pd.notnull(metadata_df)), None)
return tasks, metadata_df
except Exception as e:
pass
# Load obsolete format -> save in new format
metadata_filename = os.path.join(self.data_dir, "metadata.joblib")
if os.path.exists(metadata_filename):
tasks, metadata_df = load_from_disk(metadata_filename)
del metadata_df['task_names']
del metadata_df['basename']
save_metadata(tasks, metadata_df, self.data_dir)
return tasks, metadata_df
raise ValueError("No Metadata Found On Disk")
@staticmethod
def _construct_metadata(metadata_entries):
"""Construct a dataframe containing metadata.
metadata_entries should have elements returned by write_data_to_disk
above.
"""
columns = ('ids', 'X', 'y', 'w')
metadata_df = pd.DataFrame(metadata_entries, columns=columns)
return metadata_df
@staticmethod
def write_data_to_disk(data_dir,
basename,
tasks,
X=None,
y=None,
w=None,
ids=None):
if X is not None:
out_X = "%s-X.joblib" % basename
save_to_disk(X, os.path.join(data_dir, out_X))
else:
out_X = None
if y is not None:
out_y = "%s-y.joblib" % basename
save_to_disk(y, os.path.join(data_dir, out_y))
else:
out_y = None
if w is not None:
out_w = "%s-w.joblib" % basename
save_to_disk(w, os.path.join(data_dir, out_w))
else:
out_w = None
if ids is not None:
out_ids = "%s-ids.joblib" % basename
save_to_disk(ids, os.path.join(data_dir, out_ids))
else:
out_ids = None
# note that this corresponds to the _construct_metadata column order
return [out_ids, out_X, out_y, out_w]
def save_to_disk(self):
"""Save dataset to disk."""
save_metadata(self.tasks, self.metadata_df, self.data_dir)
def move(self, new_data_dir):
"""Moves dataset to new directory."""
if os.path.isdir(new_data_dir):
shutil.rmtree(new_data_dir)
shutil.move(self.data_dir, new_data_dir)
self.data_dir = new_data_dir
def get_task_names(self):
"""
Gets learning tasks associated with this dataset.
"""
return self.tasks
# if not len(self.metadata_df):
# raise ValueError("No data in dataset.")
# return next(self.metadata_df.iterrows())[1]['task_names']
def reshard(self, shard_size):
"""Reshards data to have specified shard size."""
# Create temp directory to store resharded version
reshard_dir = tempfile.mkdtemp()
new_metadata = []
# Write data in new shards
def generator():
tasks = self.get_task_names()
X_next = np.zeros((0,) + self.get_data_shape())
y_next = np.zeros((0,) + (len(tasks),))
w_next = np.zeros((0,) + (len(tasks),))
ids_next = np.zeros((0,), dtype=object)
for (X, y, w, ids) in self.itershards():
X_next = np.concatenate([X_next, X], axis=0)
y_next = np.concatenate([y_next, y], axis=0)
w_next = np.concatenate([w_next, w], axis=0)
ids_next = np.concatenate([ids_next, ids])
while len(X_next) > shard_size:
X_batch, X_next = X_next[:shard_size], X_next[shard_size:]
y_batch, y_next = y_next[:shard_size], y_next[shard_size:]
w_batch, w_next = w_next[:shard_size], w_next[shard_size:]
ids_batch, ids_next = ids_next[:shard_size], ids_next[shard_size:]
yield (X_batch, y_batch, w_batch, ids_batch)
# Handle spillover from last shard
yield (X_next, y_next, w_next, ids_next)
resharded_dataset = DiskDataset.create_dataset(
generator(), data_dir=reshard_dir, tasks=self.tasks)
shutil.rmtree(self.data_dir)
shutil.move(reshard_dir, self.data_dir)
self.metadata_df = resharded_dataset.metadata_df
self.save_to_disk()
def get_data_shape(self):
"""
Gets array shape of datapoints in this dataset.
"""
if not len(self.metadata_df):
raise ValueError("No data in dataset.")
sample_X = load_from_disk(
os.path.join(self.data_dir,
next(self.metadata_df.iterrows())[1]['X']))
return np.shape(sample_X)[1:]
def get_shard_size(self):
"""Gets size of shards on disk."""
if not len(self.metadata_df):
raise ValueError("No data in dataset.")
sample_y = load_from_disk(
os.path.join(self.data_dir,
next(self.metadata_df.iterrows())[1]['y']))
return len(sample_y)
def _get_metadata_filename(self):
"""
Get standard location for metadata file.
"""
metadata_filename = os.path.join(self.data_dir, "metadata.csv.gzip")
tasks_filename = os.path.join(self.data_dir, "tasks.json")
return tasks_filename, metadata_filename
def get_number_shards(self):
"""
Returns the number of shards for this dataset.
"""
return self.metadata_df.shape[0]
def itershards(self):
"""
Return an object that iterates over all shards in dataset.
Datasets are stored in sharded fashion on disk. Each call to next() for the
generator defined by this function returns the data from a particular shard.
The order of shards returned is guaranteed to remain fixed.
"""
def iterate(dataset):
for _, row in dataset.metadata_df.iterrows():
X = np.array(load_from_disk(os.path.join(dataset.data_dir, row['X'])))
ids = np.array(
load_from_disk(os.path.join(dataset.data_dir, row['ids'])),
dtype=object)
# These columns may be missing is the dataset is unlabelled.
if row['y'] is not None:
y = np.array(load_from_disk(os.path.join(dataset.data_dir, row['y'])))
else:
y = None
if row['w'] is not None:
w_filename = os.path.join(dataset.data_dir, row['w'])
if os.path.exists(w_filename):
w = np.array(load_from_disk(w_filename))
else:
if len(y.shape) == 1:
w = np.ones(y.shape[0], np.float32)
else:
w = np.ones((y.shape[0], 1), np.float32)
else:
w = None
yield (X, y, w, ids)
return iterate(self)
def iterbatches(self,
batch_size=None,
epoch=0,
deterministic=False,
pad_batches=False):
""" Get an object that iterates over minibatches from the dataset. It is guaranteed
that the number of batches returned is math.ceil(len(dataset)/batch_size).
Each minibatch is returned as a tuple of four numpy arrays: (X, y, w, ids).
Parameters:
-----------
batch_size: int
Number of elements in a batch. If None, then it yields batches with size equal to the size
of each individual shard.
epoch: int
Not used
deterministic: bool
Whether or not we should should shuffle each shard before generating the batches.
Note that this is only local in the sense that it does not ever mix between different
shards.
pad_batches: bool
Whether or not we should pad the last batch, globally, such that it has exactly batch_size
elements.
"""
def iterate(dataset, batch_size):
num_shards = dataset.get_number_shards()
if not deterministic:
shard_perm = np.random.permutation(num_shards)
else:
shard_perm = np.arange(num_shards)
# (ytz): Depending on the application, thread-based pools may be faster
# than process based pools, since process based pools need to pickle/serialize
# objects as an extra overhead. Also, as hideously as un-thread safe this looks,
# we're actually protected by the GIL.
pool = Pool(1) # mp.dummy aliases ThreadPool to Pool
next_shard = pool.apply_async(dataset.get_shard, (shard_perm[0],))
total_yield = 0
if batch_size is None:
num_global_batches = num_shards
else:
num_global_batches = math.ceil(dataset.get_shape()[0][0] / batch_size)
cur_global_batch = 0
cur_shard = 0
carry = None
while cur_global_batch < num_global_batches:
X, y, w, ids = next_shard.get()
if cur_shard < num_shards - 1:
next_shard = pool.apply_async(dataset.get_shard,
(shard_perm[cur_shard + 1],))
else:
pool.close()
if carry is not None:
X = np.concatenate([carry[0], X], axis=0)
if y is not None:
y = np.concatenate([carry[1], y], axis=0)
if w is not None:
w = np.concatenate([carry[2], w], axis=0)
ids = np.concatenate([carry[3], ids], axis=0)
carry = None
n_shard_samples = X.shape[0]
cur_local_batch = 0
if batch_size is None:
shard_batch_size = n_shard_samples
else:
shard_batch_size = batch_size
if n_shard_samples == 0:
cur_shard += 1
if batch_size is None:
cur_global_batch += 1
continue
num_local_batches = math.ceil(n_shard_samples / shard_batch_size)
if not deterministic:
sample_perm = np.random.permutation(n_shard_samples)
else:
sample_perm = np.arange(n_shard_samples)
while cur_local_batch < num_local_batches:
start = cur_local_batch * shard_batch_size
end = min(n_shard_samples, (cur_local_batch + 1) * shard_batch_size)
indices = range(start, end)
perm_indices = sample_perm[indices]
X_b = X[perm_indices]
if y is not None:
y_b = y[perm_indices]
else:
y_b = None
if w is not None:
w_b = w[perm_indices]
else:
w_b = None
ids_b = ids[perm_indices]
assert len(X_b) <= shard_batch_size
if len(X_b) < shard_batch_size and cur_shard != num_shards - 1:
assert carry is None
carry = [X_b, y_b, w_b, ids_b]
else:
# (ytz): this skips everything except possibly the last shard
if pad_batches:
(X_b, y_b, w_b, ids_b) = pad_batch(shard_batch_size, X_b, y_b,
w_b, ids_b)
yield X_b, y_b, w_b, ids_b
cur_global_batch += 1
cur_local_batch += 1
cur_shard += 1
return iterate(self, batch_size)
def itersamples(self):
"""Get an object that iterates over the samples in the dataset.
Example:
>>> dataset = DiskDataset.from_numpy(np.ones((2,2)), np.ones((2,1)), verbose=False)
>>> for x, y, w, id in dataset.itersamples():
... print(x.tolist(), y.tolist(), w.tolist(), id)
[1.0, 1.0] [1.0] [1.0] 0
[1.0, 1.0] [1.0] [1.0] 1
"""
def iterate(dataset):
for (X_shard, y_shard, w_shard, ids_shard) in dataset.itershards():
n_samples = X_shard.shape[0]
for i in range(n_samples):
def sanitize(elem):
if elem is None:
return None
else:
return elem[i]
yield map(sanitize, [X_shard, y_shard, w_shard, ids_shard])
return iterate(self)
def transform(self, fn, **args):
"""Construct a new dataset by applying a transformation to every sample in this dataset.
The argument is a function that can be called as follows:
>> newx, newy, neww = fn(x, y, w)
It might be called only once with the whole dataset, or multiple times with different
subsets of the data. Each time it is called, it should transform the samples and return
the transformed data.
Parameters
----------
fn: function
A function to apply to each sample in the dataset
out_dir: string
The directory to save the new dataset in. If this is omitted, a temporary directory
is created automatically
Returns
-------
a newly constructed Dataset object
"""
if 'out_dir' in args:
out_dir = args['out_dir']
else:
out_dir = tempfile.mkdtemp()
tasks = self.get_task_names()
if 'verbose' in args:
verbose = args['verbose']
else:
verbose = True
def generator():
for shard_num, row in self.metadata_df.iterrows():
X, y, w, ids = self.get_shard(shard_num)
newx, newy, neww = fn(X, y, w)
yield (newx, newy, neww, ids)
return DiskDataset.create_dataset(
generator(), data_dir=out_dir, tasks=tasks, verbose=verbose)
@staticmethod
def from_numpy(X,
y=None,
w=None,
ids=None,
tasks=None,
data_dir=None,
verbose=True):
"""Creates a DiskDataset object from specified Numpy arrays."""
n_samples = len(X)
if ids is None:
ids = np.arange(n_samples)
if y is not None:
if w is None:
if len(y.shape) == 1:
w = np.ones(y.shape[0], np.float32)
else:
w = np.ones((y.shape[0], 1), np.float32)
if tasks is None:
if len(y.shape) > 1:
n_tasks = y.shape[1]
else:
n_tasks = 1
tasks = np.arange(n_tasks)
else:
if w is not None:
warnings.warn('y is None but w is not None. Setting w to None',
UserWarning)
w = None