/
datasets.py
3000 lines (2612 loc) · 99.2 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 random
import logging
import tempfile
import time
import shutil
import multiprocessing
from multiprocessing.dummy import Pool
from ast import literal_eval as make_tuple
from typing import Any, Dict, Iterable, Iterator, List, Optional, Sequence, Tuple, Union
import numpy as np
from numpy.typing import ArrayLike
import pandas as pd
import deepchem as dc
from deepchem.utils.typing import OneOrMany, Shape
from deepchem.utils.data_utils import save_to_disk, load_from_disk, load_image_files
Batch = Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]
logger = logging.getLogger(__name__)
def sparsify_features(X: np.ndarray) -> np.ndarray:
"""Extracts a sparse feature representation from dense feature array.
Parameters
----------
X: np.ndarray
A numpy array of shape `(n_samples, ...)`.
Returns
-------
X_sparse: np.ndarray
A numpy array with `dtype=object` where `X_sparse[i]` is a
typle of `(nonzero_inds, nonzero_vals)` with nonzero indices and
values in the i-th sample of `X`.
"""
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))
return np.array(X_sparse, dtype=object)
def densify_features(X_sparse: np.ndarray, num_features: int) -> np.ndarray:
"""Expands sparse feature representation to dense feature array.
Assumes that the sparse representation was constructed from an array
which had original shape `(n_samples, num_features)` so doesn't
support reconstructing multidimensional dense arrays.
Parameters
----------
X_sparse: np.ndarray
Must have `dtype=object`. `X_sparse[i]` must be a tuple of nonzero
indices and values.
num_features: int
Number of features in dense array.
Returns
-------
X: np.ndarray
A numpy array of shape `(n_samples, num_features)`.
"""
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: int, X_b: np.ndarray) -> np.ndarray:
"""Pads a batch of features to have precisely batch_size elements.
Given an array of features with length less than or equal to
batch-size, pads it to `batch_size` length. It does this by
repeating the original features in tiled fashion. For illustration,
suppose that `len(X_b) == 3` and `batch_size == 10`.
>>> X_b = np.arange(3)
>>> X_b
array([0, 1, 2])
>>> batch_size = 10
>>> X_manual = np.array([0, 1, 2, 0, 1, 2, 0, 1, 2, 0])
>>> X_out = pad_features(batch_size, X_b)
>>> assert (X_manual == X_out).all()
This function is similar to `pad_batch` but doesn't handle labels
`y` or weights `w` and is intended to be used for inference-time
query processing.
Parameters
----------
batch_size: int
The number of datapoints in a batch
X_b: np.ndarray
Must be such that `len(X_b) <= batch_size`
Returns
-------
X_out: np.ndarray
A numpy array with `len(X_out) == batch_size`.
"""
num_samples = len(X_b)
if num_samples > batch_size:
raise ValueError("Cannot pad an array longer than `batch_size`")
elif 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: int, X_b: np.ndarray, y_b: np.ndarray,
w_b: np.ndarray, ids_b: np.ndarray) -> Batch:
"""Pads batch to have size precisely batch_size elements.
Given arrays of features `X_b`, labels `y_b`, weights `w_b`, and
identifiers `ids_b` all with length less than or equal to
batch-size, pads them to `batch_size` length. It does this by
repeating the original entries in tiled fashion. Note that `X_b,
y_b, w_b, ids_b` must all have the same length.
Parameters
----------
batch_size: int
The number of datapoints in a batch
X_b: np.ndarray
Must be such that `len(X_b) <= batch_size`
y_b: np.ndarray
Must be such that `len(y_b) <= batch_size`
w_b: np.ndarray
Must be such that `len(w_b) <= batch_size`
ids_b: np.ndarray
Must be such that `len(ids_b) <= batch_size`
Returns
-------
Batch
The batch is a tuple of `(X_out, y_out, w_out, ids_out)`,
all numpy arrays with length `batch_size`.
"""
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.
`Dataset` objects are used to store representations of a dataset as
used in a machine learning task. Datasets contain features `X`,
labels `y`, weights `w` and identifiers `ids`. Different subclasses
of `Dataset` may choose to hold `X, y, w, ids` in memory or on disk.
The `Dataset` class attempts to provide for strong interoperability
with other machine learning representations for datasets.
Interconversion methods allow for `Dataset` objects to be converted
to and from numpy arrays, pandas dataframes, tensorflow datasets,
and pytorch datasets (only to and not from for pytorch at present).
Note that you can never instantiate a `Dataset` object directly.
Instead you will need to instantiate one of the concrete subclasses.
"""
def __init__(self) -> None:
raise NotImplementedError()
def __len__(self) -> int:
"""Get the number of elements in the dataset.
Returns
-------
int
The number of elements in the dataset.
"""
raise NotImplementedError()
def get_shape(self) -> Tuple[Shape, Shape, Shape, Shape]:
"""Get the shape of the dataset.
Returns four tuples, giving the shape of the X, y, w, and ids
arrays.
Returns
-------
Tuple
The tuple contains four elements, which are the shapes of
the X, y, w, and ids arrays.
"""
raise NotImplementedError()
def get_task_names(self) -> np.ndarray:
"""Get the names of the tasks associated with this dataset."""
raise NotImplementedError()
@property
def X(self) -> np.ndarray:
"""Get the X vector for this dataset as a single numpy array.
Returns
-------
np.ndarray
A numpy array of identifiers `X`.
Note
----
If data is stored on disk, accessing this field may involve loading
data from disk and could potentially be slow. Using
`iterbatches()` or `itersamples()` may be more efficient for
larger datasets.
"""
raise NotImplementedError()
@property
def y(self) -> np.ndarray:
"""Get the y vector for this dataset as a single numpy array.
Returns
-------
np.ndarray
A numpy array of identifiers `y`.
Note
----
If data is stored on disk, accessing this field may involve loading
data from disk and could potentially be slow. Using
`iterbatches()` or `itersamples()` may be more efficient for
larger datasets.
"""
raise NotImplementedError()
@property
def ids(self) -> np.ndarray:
"""Get the ids vector for this dataset as a single numpy array.
Returns
-------
np.ndarray
A numpy array of identifiers `ids`.
Note
----
If data is stored on disk, accessing this field may involve loading
data from disk and could potentially be slow. Using
`iterbatches()` or `itersamples()` may be more efficient for
larger datasets.
"""
raise NotImplementedError()
@property
def w(self) -> np.ndarray:
"""Get the weight vector for this dataset as a single numpy array.
Returns
-------
np.ndarray
A numpy array of weights `w`.
Note
----
If data is stored on disk, accessing this field may involve loading
data from disk and could potentially be slow. Using
`iterbatches()` or `itersamples()` may be more efficient for
larger datasets.
"""
raise NotImplementedError()
def __repr__(self) -> str:
"""Convert self to REPL print representation."""
threshold = dc.utils.get_print_threshold()
task_str = np.array2string(
np.array(self.get_task_names()), threshold=threshold)
X_shape, y_shape, w_shape, _ = self.get_shape()
if self.__len__() < dc.utils.get_max_print_size():
id_str = np.array2string(self.ids, threshold=threshold)
return "<%s X.shape: %s, y.shape: %s, w.shape: %s, ids: %s, task_names: %s>" % (
self.__class__.__name__, str(X_shape), str(y_shape), str(w_shape),
id_str, task_str)
else:
return "<%s X.shape: %s, y.shape: %s, w.shape: %s, task_names: %s>" % (
self.__class__.__name__, str(X_shape), str(y_shape), str(w_shape),
task_str)
def __str__(self) -> str:
"""Convert self to str representation."""
return self.__repr__()
def iterbatches(self,
batch_size: Optional[int] = None,
epochs: int = 1,
deterministic: bool = False,
pad_batches: bool = False) -> Iterator[Batch]:
"""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)`.
Parameters
----------
batch_size: int, optional (default None)
Number of elements in each batch.
epochs: int, optional (default 1)
Number of epochs to walk over dataset.
deterministic: bool, optional (default False)
If True, follow deterministic order.
pad_batches: bool, optional (default False)
If True, pad each batch to `batch_size`.
Returns
-------
Iterator[Batch]
Generator which yields tuples of four numpy arrays `(X, y, w, ids)`.
"""
raise NotImplementedError()
def itersamples(self) -> Iterator[Batch]:
"""Get an object that iterates over the samples in the dataset.
Examples
--------
>>> 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, transformer: "dc.trans.Transformer", **args) -> "Dataset":
"""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
----------
transformer: dc.trans.Transformer
The transformation to apply to each sample in the dataset.
Returns
-------
Dataset
A newly constructed Dataset object.
"""
raise NotImplementedError()
def select(self,
indices: Union[Sequence[int], np.ndarray],
select_dir: Optional[str] = None) -> "Dataset":
"""Creates a new dataset from a selection of indices from self.
Parameters
----------
indices: Sequence
List of indices to select.
select_dir: str, optional (default None)
Path to new directory that the selected indices will be copied to.
"""
raise NotImplementedError()
def get_statistics(self, X_stats: bool = True,
y_stats: bool = True) -> Tuple[np.ndarray, ...]:
"""Compute and return statistics of this dataset.
Uses `self.itersamples()` to compute means and standard deviations
of the dataset. Can compute on large datasets that don't fit in
memory.
Parameters
----------
X_stats: bool, optional (default True)
If True, compute feature-level mean and standard deviations.
y_stats: bool, optional (default True)
If True, compute label-level mean and standard deviations.
Returns
-------
Tuple
- If `X_stats == True`, returns `(X_means, X_stds)`.
- If `y_stats == True`, returns `(y_means, y_stds)`.
- If both are true, returns `(X_means, X_stds, y_means, y_stds)`.
"""
x_shape, y_shape, w_shape, ids_shape = self.get_shape()
X_means = np.zeros(x_shape[1:])
X_m2 = np.zeros(x_shape[1:])
y_means = np.zeros(y_shape[1:])
y_m2 = np.zeros(y_shape[1:])
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 = np.zeros(x_shape[1:])
y_stds = np.zeros(y_shape[1:])
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 tuple()
def make_tf_dataset(self,
batch_size: int = 100,
epochs: int = 1,
deterministic: bool = False,
pad_batches: bool = 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, default 100
The number of samples to include in each batch.
epochs: int, default 1
The number of times to iterate over the Dataset.
deterministic: bool, default False
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, default False
If True, batches are padded as necessary to make the size of
each batch exactly equal batch_size.
Returns
-------
tf.data.Dataset
TensorFlow Dataset that iterates over the same data.
Note
----
This class requires TensorFlow to be installed.
"""
try:
import tensorflow as tf
except:
raise ImportError("This method requires TensorFlow to be installed.")
# Retrieve the first sample so we can determine the dtypes.
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)), # type: ignore
tf.TensorShape([None] + list(y.shape)), # type: ignore
tf.TensorShape([None] + list(w.shape))) # type: ignore
# Create a Tensorflow Dataset.
def gen_data():
for X, y, w, ids in self.iterbatches(batch_size, epochs, deterministic,
pad_batches):
yield (X, y, w)
return tf.data.Dataset.from_generator(gen_data, dtypes, shapes)
def make_pytorch_dataset(self,
epochs: int = 1,
deterministic: bool = False,
batch_size: Optional[int] = None):
"""Create a torch.utils.data.IterableDataset that iterates over the data in this Dataset.
Each value returned by the Dataset's iterator is a tuple of (X, y, w, id)
containing the data for one batch, or for a single sample if batch_size is None.
Parameters
----------
epochs: int, default 1
The number of times to iterate over the Dataset.
deterministic: bool, default False
If True, the data is produced in order. If False, a different
random permutation of the data is used for each epoch.
batch_size: int, optional (default None)
The number of samples to return in each batch. If None, each returned
value is a single sample.
Returns
-------
torch.utils.data.IterableDataset
`torch.utils.data.IterableDataset` that iterates over the data in
this dataset.
Note
----
This class requires PyTorch to be installed.
"""
raise NotImplementedError()
def to_dataframe(self) -> pd.DataFrame:
"""Construct a pandas DataFrame containing the data from this Dataset.
Returns
-------
pd.DataFrame
Pandas dataframe. If there is only a single feature per datapoint,
will have column "X" else will have columns "X1,X2,..." for
features. If there is only a single label per datapoint, will
have column "y" else will have columns "y1,y2,..." for labels. If
there is only a single weight per datapoint will have column "w"
else will have columns "w1,w2,...". Will have column "ids" for
identifiers.
"""
X = self.X
y = self.y
w = self.w
ids = self.ids
if len(X.shape) == 1 or X.shape[1] == 1:
columns = ['X']
else:
columns = [f'X{i+1}' for i in range(X.shape[1])]
X_df = pd.DataFrame(X, columns=columns)
if len(y.shape) == 1 or y.shape[1] == 1:
columns = ['y']
else:
columns = [f'y{i+1}' for i in range(y.shape[1])]
y_df = pd.DataFrame(y, columns=columns)
if len(w.shape) == 1 or w.shape[1] == 1:
columns = ['w']
else:
columns = [f'w{i+1}' for i in range(w.shape[1])]
w_df = pd.DataFrame(w, columns=columns)
ids_df = pd.DataFrame(ids, columns=['ids'])
return pd.concat([X_df, y_df, w_df, ids_df], axis=1, sort=False)
@staticmethod
def from_dataframe(df: pd.DataFrame,
X: Optional[OneOrMany[str]] = None,
y: Optional[OneOrMany[str]] = None,
w: Optional[OneOrMany[str]] = None,
ids: Optional[str] = None):
"""Construct a Dataset from the contents of a pandas DataFrame.
Parameters
----------
df: pd.DataFrame
The pandas DataFrame
X: str or List[str], optional (default None)
The name of the column or columns containing the X array. If
this is None, it will look for default column names that match
those produced by to_dataframe().
y: str or List[str], optional (default None)
The name of the column or columns containing the y array. If
this is None, it will look for default column names that match
those produced by to_dataframe().
w: str or List[str], optional (default None)
The name of the column or columns containing the w array. If
this is None, it will look for default column names that match
those produced by to_dataframe().
ids: str, optional (default None)
The name of the column containing the ids. If this is None, it
will look for default column names that match those produced by
to_dataframe().
"""
# Find the X values.
if X is not None:
X_val = df[X]
elif 'X' in df.columns:
X_val = df['X']
else:
columns = []
i = 1
while f'X{i}' in df.columns:
columns.append(f'X{i}')
i += 1
X_val = df[columns]
if len(X_val.shape) == 1:
X_val = np.expand_dims(X_val, 1)
# Find the y values.
if y is not None:
y_val = df[y]
elif 'y' in df.columns:
y_val = df['y']
else:
columns = []
i = 1
while f'y{i}' in df.columns:
columns.append(f'y{i}')
i += 1
y_val = df[columns]
if len(y_val.shape) == 1:
y_val = np.expand_dims(y_val, 1)
# Find the w values.
if w is not None:
w_val = df[w]
elif 'w' in df.columns:
w_val = df['w']
else:
columns = []
i = 1
while f'w{i}' in df.columns:
columns.append(f'w{i}')
i += 1
w_val = df[columns]
if len(w_val.shape) == 1:
w_val = np.expand_dims(w_val, 1)
# Find the ids.
if ids is not None:
ids_val = df[ids]
elif 'ids' in df.columns:
ids_val = df['ids']
else:
ids_val = None
return NumpyDataset(X_val, y_val, w_val, ids_val)
class NumpyDataset(Dataset):
"""A Dataset defined by in-memory numpy arrays.
This subclass of `Dataset` stores arrays `X,y,w,ids` in memory as
numpy arrays. This makes it very easy to construct `NumpyDataset`
objects.
Examples
--------
>>> import numpy as np
>>> dataset = NumpyDataset(X=np.random.rand(5, 3), y=np.random.rand(5,), ids=np.arange(5))
"""
def __init__(self,
X: ArrayLike,
y: Optional[ArrayLike] = None,
w: Optional[ArrayLike] = None,
ids: Optional[ArrayLike] = None,
n_tasks: int = 1) -> None:
"""Initialize this object.
Parameters
----------
X: np.ndarray
Input features. A numpy array of shape `(n_samples,...)`.
y: np.ndarray, optional (default None)
Labels. A numpy array of shape `(n_samples, ...)`. Note that each label can
have an arbitrary shape.
w: np.ndarray, optional (default None)
Weights. Should either be 1D array of shape `(n_samples,)` or if
there's more than one task, of shape `(n_samples, n_tasks)`.
ids: np.ndarray, optional (default None)
Identifiers. A numpy array of shape `(n_samples,)`
n_tasks: int, default 1
Number of learning tasks.
"""
n_samples = np.shape(X)[0]
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) -> int:
"""Get the number of elements in the dataset."""
return len(self._y)
def get_shape(self) -> Tuple[Shape, Shape, Shape, Shape]:
"""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) -> np.ndarray:
"""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) -> np.ndarray:
"""Get the X vector for this dataset as a single numpy array."""
return self._X
@property
def y(self) -> np.ndarray:
"""Get the y vector for this dataset as a single numpy array."""
return self._y
@property
def ids(self) -> np.ndarray:
"""Get the ids vector for this dataset as a single numpy array."""
return self._ids
@property
def w(self) -> np.ndarray:
"""Get the weight vector for this dataset as a single numpy array."""
return self._w
def iterbatches(self,
batch_size: Optional[int] = None,
epochs: int = 1,
deterministic: bool = False,
pad_batches: bool = False) -> Iterator[Batch]:
"""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)`.
Parameters
----------
batch_size: int, optional (default None)
Number of elements in each batch.
epochs: int, default 1
Number of epochs to walk over dataset.
deterministic: bool, optional (default False)
If True, follow deterministic order.
pad_batches: bool, optional (default False)
If True, pad each batch to `batch_size`.
Returns
-------
Iterator[Batch]
Generator which yields tuples of four numpy arrays `(X, y, w, ids)`.
"""
def iterate(dataset: NumpyDataset, batch_size: Optional[int], epochs: int,
deterministic: bool, pad_batches: bool):
n_samples = dataset._X.shape[0]
if deterministic:
sample_perm = np.arange(n_samples)
if batch_size is None:
batch_size = n_samples
for epoch in range(epochs):
if not deterministic:
sample_perm = np.random.permutation(n_samples)
batch_idx = 0
num_batches = 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, epochs, deterministic, pad_batches)
def itersamples(self) -> Iterator[Batch]:
"""Get an object that iterates over the samples in the dataset.
Returns
-------
Iterator[Batch]
Iterator which yields tuples of four numpy arrays `(X, y, w, ids)`.
Examples
--------
>>> 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, transformer: "dc.trans.Transformer",
**args) -> "NumpyDataset":
"""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
----------
transformer: dc.trans.Transformer
The transformation to apply to each sample in the dataset
Returns
-------
NumpyDataset
A newly constructed NumpyDataset object
"""
newx, newy, neww, newids = transformer.transform_array(
self._X, self._y, self._w, self._ids)
return NumpyDataset(newx, newy, neww, newids)
def select(self,
indices: Union[Sequence[int], np.ndarray],
select_dir: Optional[str] = None) -> "NumpyDataset":
"""Creates a new dataset from a selection of indices from self.
Parameters
----------
indices: List[int]
List of indices to select.
select_dir: str, optional (default None)
Used to provide same API as `DiskDataset`. Ignored since
`NumpyDataset` is purely in-memory.
Returns
-------
NumpyDataset
A selected NumpyDataset object
"""
X = self.X[indices]
y = self.y[indices]
w = self.w[indices]
ids = self.ids[indices]
return NumpyDataset(X, y, w, ids)
def make_pytorch_dataset(self,
epochs: int = 1,
deterministic: bool = False,
batch_size: Optional[int] = None):
"""Create a torch.utils.data.IterableDataset that iterates over the data in this Dataset.
Each value returned by the Dataset's iterator is a tuple of (X, y, w, id)
containing the data for one batch, or for a single sample if batch_size is None.
Parameters
----------
epochs: int, default 1
The number of times to iterate over the Dataset
deterministic: bool, default False
If True, the data is produced in order. If False, a different
random permutation of the data is used for each epoch.
batch_size: int, optional (default None)
The number of samples to return in each batch. If None, each returned
value is a single sample.
Returns
-------
torch.utils.data.IterableDataset
`torch.utils.data.IterableDataset` that iterates over the data in
this dataset.
Note
----
This method requires PyTorch to be installed.
"""
try:
from deepchem.data.pytorch_datasets import _TorchNumpyDataset
except:
raise ImportError("This method requires PyTorch to be installed.")
pytorch_ds = _TorchNumpyDataset(
numpy_dataset=self,
epochs=epochs,
deterministic=deterministic,
batch_size=batch_size)
return pytorch_ds
@staticmethod
def from_DiskDataset(ds: "DiskDataset") -> "NumpyDataset":
"""Convert DiskDataset to NumpyDataset.
Parameters
----------
ds: DiskDataset
DiskDataset to transform to NumpyDataset.
Returns
-------
NumpyDataset
A new NumpyDataset created from DiskDataset.
"""
return NumpyDataset(ds.X, ds.y, ds.w, ds.ids)
def to_json(self, fname: str) -> None:
"""Dump NumpyDataset to the json file .
Parameters
----------
fname: str
The name of the json file.
"""
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: str) -> "NumpyDataset":
"""Create NumpyDataset from the json file.
Parameters
----------
fname: str
The name of the json file.