/
data_loader.py
1166 lines (1000 loc) · 39.4 KB
/
data_loader.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
"""
Process an input dataset into a format suitable for machine learning.
"""
import os
import tempfile
import zipfile
import time
import logging
import warnings
from typing import List, Optional, Tuple, Any, Sequence, Union, Iterator
import pandas as pd
import numpy as np
from deepchem.utils.typing import OneOrMany
from deepchem.utils.data_utils import load_image_files, load_csv_files, load_json_files, load_sdf_files
from deepchem.utils.genomics_utils import encode_bio_sequence
from deepchem.feat import UserDefinedFeaturizer, Featurizer
from deepchem.data import Dataset, DiskDataset, NumpyDataset, ImageDataset
logger = logging.getLogger(__name__)
def _convert_df_to_numpy(df: pd.DataFrame,
tasks: List[str]) -> Tuple[np.ndarray, np.ndarray]:
"""Transforms a dataframe containing deepchem input into numpy arrays
This is a private helper method intended to help parse labels and
weights arrays from a pandas dataframe. Here `df` is a dataframe
which has columns for each task in `tasks`. These labels are
extracted into a labels array `y`. Weights `w` are initialized to
all ones, but weights for any missing labels are set to 0.
Parameters
----------
df: pd.DataFrame
Pandas dataframe with columns for all tasks
tasks: List[str]
List of tasks
Returns
-------
Tuple[np.ndarray, np.ndarray]
The tuple is `(w, y)`.
"""
n_samples = df.shape[0]
n_tasks = len(tasks)
y = np.hstack(
[np.reshape(np.array(df[task].values), (n_samples, 1)) for task in tasks])
w = np.ones((n_samples, n_tasks))
if y.dtype.kind in ['O', 'U']:
missing = (y == '')
y[missing] = 0
w[missing] = 0
return y.astype(float), w.astype(float)
class DataLoader(object):
"""Handles loading/featurizing of data from disk.
The main use of `DataLoader` and its child classes is to make it
easier to load large datasets into `Dataset` objects.`
`DataLoader` is an abstract superclass that provides a
general framework for loading data into DeepChem. This class should
never be instantiated directly. To load your own type of data, make
a subclass of `DataLoader` and provide your own implementation for
the `create_dataset()` method.
To construct a `Dataset` from input data, first instantiate a
concrete data loader (that is, an object which is an instance of a
subclass of `DataLoader`) with a given `Featurizer` object. Then
call the data loader's `create_dataset()` method on a list of input
files that hold the source data to process. Note that each subclass
of `DataLoader` is specialized to handle one type of input data so
you will have to pick the loader class suitable for your input data
type.
Note that it isn't necessary to use a data loader to process input
data. You can directly use `Featurizer` objects to featurize
provided input into numpy arrays, but note that this calculation
will be performed in memory, so you will have to write generators
that walk the source files and write featurized data to disk
yourself. `DataLoader` and its subclasses make this process easier
for you by performing this work under the hood.
"""
def __init__(self,
tasks: List[str],
featurizer: Featurizer,
id_field: Optional[str] = None,
log_every_n: int = 1000):
"""Construct a DataLoader object.
This constructor is provided as a template mainly. You
shouldn't ever call this constructor directly as a user.
Parameters
----------
tasks: List[str]
List of task names
featurizer: Featurizer
Featurizer to use to process data.
id_field: str, optional (default None)
Name of field that holds sample identifier. Note that the
meaning of "field" depends on the input data type and can have a
different meaning in different subclasses. For example, a CSV
file could have a field as a column, and an SDF file could have
a field as molecular property.
log_every_n: int, optional (default 1000)
Writes a logging statement this often.
"""
if self.__class__ is DataLoader:
raise ValueError(
"DataLoader should never be instantiated directly. Use a subclass instead."
)
if not isinstance(tasks, list):
raise ValueError("tasks must be a list.")
self.tasks = tasks
self.id_field = id_field
self.user_specified_features = None
if isinstance(featurizer, UserDefinedFeaturizer):
self.user_specified_features = featurizer.feature_fields
self.featurizer = featurizer
self.log_every_n = log_every_n
def featurize(self,
inputs: OneOrMany[Any],
data_dir: Optional[str] = None,
shard_size: Optional[int] = 8192) -> Dataset:
"""Featurize provided files and write to specified location.
DEPRECATED: This method is now a wrapper for `create_dataset()`
and calls that method under the hood.
For large datasets, automatically shards into smaller chunks
for convenience. This implementation assumes that the helper
methods `_get_shards` and `_featurize_shard` are implemented and
that each shard returned by `_get_shards` is a pandas dataframe.
You may choose to reuse or override this method in your subclass
implementations.
Parameters
----------
inputs: List
List of inputs to process. Entries can be filenames or arbitrary objects.
data_dir: str, default None
Directory to store featurized dataset.
shard_size: int, optional (default 8192)
Number of examples stored in each shard.
Returns
-------
Dataset
A `Dataset` object containing a featurized representation of data
from `inputs`.
"""
warnings.warn(
"featurize() is deprecated and has been renamed to create_dataset()."
"featurize() will be removed in DeepChem 3.0", FutureWarning)
return self.create_dataset(inputs, data_dir, shard_size)
def create_dataset(self,
inputs: OneOrMany[Any],
data_dir: Optional[str] = None,
shard_size: Optional[int] = 8192) -> Dataset:
"""Creates and returns a `Dataset` object by featurizing provided files.
Reads in `inputs` and uses `self.featurizer` to featurize the
data in these inputs. For large files, automatically shards
into smaller chunks of `shard_size` datapoints for convenience.
Returns a `Dataset` object that contains the featurized dataset.
This implementation assumes that the helper methods `_get_shards`
and `_featurize_shard` are implemented and that each shard
returned by `_get_shards` is a pandas dataframe. You may choose
to reuse or override this method in your subclass implementations.
Parameters
----------
inputs: List
List of inputs to process. Entries can be filenames or arbitrary objects.
data_dir: str, optional (default None)
Directory to store featurized dataset.
shard_size: int, optional (default 8192)
Number of examples stored in each shard.
Returns
-------
DiskDataset
A `DiskDataset` object containing a featurized representation of data
from `inputs`.
"""
logger.info("Loading raw samples now.")
logger.info("shard_size: %s" % str(shard_size))
# Special case handling of single input
if not isinstance(inputs, list):
inputs = [inputs]
def shard_generator():
for shard_num, shard in enumerate(self._get_shards(inputs, shard_size)):
time1 = time.time()
X, valid_inds = self._featurize_shard(shard)
ids = shard[self.id_field].values
ids = ids[valid_inds]
if len(self.tasks) > 0:
# Featurize task results iff they exist.
y, w = _convert_df_to_numpy(shard, self.tasks)
# Filter out examples where featurization failed.
y, w = (y[valid_inds], w[valid_inds])
assert len(X) == len(ids) == len(y) == len(w)
else:
# For prospective data where results are unknown, it
# makes no sense to have y values or weights.
y, w = (None, None)
assert len(X) == len(ids)
time2 = time.time()
logger.info("TIMING: featurizing shard %d took %0.3f s" %
(shard_num, time2 - time1))
yield X, y, w, ids
return DiskDataset.create_dataset(shard_generator(), data_dir, self.tasks)
def _get_shards(self, inputs: List, shard_size: Optional[int]) -> Iterator:
"""Stub for children classes.
Should implement a generator that walks over the source data in
`inputs` and returns a "shard" at a time. Here a shard is a
chunk of input data that can reasonably be handled in memory. For
example, this may be a set of rows from a CSV file or a set of
molecules from a SDF file. To re-use the
`DataLoader.create_dataset()` method, each shard must be a pandas
dataframe.
If you chose to override `create_dataset()` directly you don't
need to override this helper method.
Parameters
----------
inputs: list
List of inputs to process. Entries can be filenames or arbitrary objects.
shard_size: int, optional
Number of examples stored in each shard.
"""
raise NotImplementedError
def _featurize_shard(self, shard: Any):
"""Featurizes a shard of input data.
Recall a shard is a chunk of input data that can reasonably be
handled in memory. For example, this may be a set of rows from a
CSV file or a set of molecules from a SDF file. Featurize this
shard in memory and return the results.
Parameters
----------
shard: Any
A chunk of input data
"""
raise NotImplementedError
class CSVLoader(DataLoader):
"""
Creates `Dataset` objects from input CSV files.
This class provides conveniences to load data from CSV files.
It's possible to directly featurize data from CSV files using
pandas, but this class may prove useful if you're processing
large CSV files that you don't want to manipulate directly in
memory.
Examples
--------
Let's suppose we have some smiles and labels
>>> smiles = ["C", "CCC"]
>>> labels = [1.5, 2.3]
Let's put these in a dataframe.
>>> import pandas as pd
>>> df = pd.DataFrame(list(zip(smiles, labels)), columns=["smiles", "task1"])
Let's now write this to disk somewhere. We can now use `CSVLoader` to
process this CSV dataset.
>>> import tempfile
>>> import deepchem as dc
>>> with dc.utils.UniversalNamedTemporaryFile(mode='w') as tmpfile:
... df.to_csv(tmpfile.name)
... loader = dc.data.CSVLoader(["task1"], feature_field="smiles",
... featurizer=dc.feat.CircularFingerprint())
... dataset = loader.create_dataset(tmpfile.name)
>>> len(dataset)
2
Of course in practice you should already have your data in a CSV file if
you're using `CSVLoader`. If your data is already in memory, use
`InMemoryLoader` instead.
"""
def __init__(self,
tasks: List[str],
featurizer: Featurizer,
feature_field: Optional[str] = None,
id_field: Optional[str] = None,
smiles_field: Optional[str] = None,
log_every_n: int = 1000):
"""Initializes CSVLoader.
Parameters
----------
tasks: List[str]
List of task names
featurizer: Featurizer
Featurizer to use to process data.
feature_field: str, optional (default None)
Field with data to be featurized.
id_field: str, optional, (default None)
CSV column that holds sample identifier
smiles_field: str, optional (default None) (DEPRECATED)
Name of field that holds smiles string.
log_every_n: int, optional (default 1000)
Writes a logging statement this often.
"""
if not isinstance(tasks, list):
raise ValueError("tasks must be a list.")
if smiles_field is not None:
logger.warning(
"smiles_field is deprecated and will be removed in a future version of DeepChem."
"Use feature_field instead.")
if feature_field is not None and smiles_field != feature_field:
raise ValueError(
"smiles_field and feature_field if both set must have the same value."
)
elif feature_field is None:
feature_field = smiles_field
self.tasks = tasks
self.feature_field = feature_field
self.id_field = id_field
if id_field is None:
self.id_field = feature_field # Use features as unique ids if necessary
else:
self.id_field = id_field
self.user_specified_features = None
if isinstance(featurizer, UserDefinedFeaturizer):
self.user_specified_features = featurizer.feature_fields
self.featurizer = featurizer
self.log_every_n = log_every_n
def _get_shards(self, input_files: List[str],
shard_size: Optional[int]) -> Iterator[pd.DataFrame]:
"""Defines a generator which returns data for each shard
Parameters
----------
input_files: List[str]
List of filenames to process
shard_size: int, optional
The size of a shard of data to process at a time.
Returns
-------
Iterator[pd.DataFrame]
Iterator over shards
"""
return load_csv_files(input_files, shard_size)
def _featurize_shard(self,
shard: pd.DataFrame) -> Tuple[np.ndarray, np.ndarray]:
"""Featurizes a shard of an input dataframe.
Parameters
----------
shard: pd.DataFrame
DataFrame that holds a shard of the input CSV file
Returns
-------
features: np.ndarray
Features computed from CSV file.
valid_inds: np.ndarray
Indices of rows in source CSV with valid data.
"""
logger.info("About to featurize shard.")
if self.featurizer is None:
raise ValueError(
"featurizer must be specified in constructor to featurizer data/")
features = [elt for elt in self.featurizer(shard[self.feature_field])]
valid_inds = np.array(
[1 if np.array(elt).size > 0 else 0 for elt in features], dtype=bool)
features = [
elt for (is_valid, elt) in zip(valid_inds, features) if is_valid
]
return np.array(features), valid_inds
class UserCSVLoader(CSVLoader):
"""
Handles loading of CSV files with user-defined features.
This is a convenience class that allows for descriptors already present in a
CSV file to be extracted without any featurization necessary.
Examples
--------
Let's suppose we have some descriptors and labels. (Imagine that these
descriptors have been computed by an external program.)
>>> desc1 = [1, 43]
>>> desc2 = [-2, -22]
>>> labels = [1.5, 2.3]
>>> ids = ["cp1", "cp2"]
Let's put these in a dataframe.
>>> import pandas as pd
>>> df = pd.DataFrame(list(zip(ids, desc1, desc2, labels)), columns=["id", "desc1", "desc2", "task1"])
Let's now write this to disk somewhere. We can now use `UserCSVLoader` to
process this CSV dataset.
>>> import tempfile
>>> import deepchem as dc
>>> featurizer = dc.feat.UserDefinedFeaturizer(["desc1", "desc2"])
>>> with dc.utils.UniversalNamedTemporaryFile(mode='w') as tmpfile:
... df.to_csv(tmpfile.name)
... loader = dc.data.UserCSVLoader(["task1"], id_field="id",
... featurizer=featurizer)
... dataset = loader.create_dataset(tmpfile.name)
>>> len(dataset)
2
>>> dataset.X[0, 0]
1
The difference between `UserCSVLoader` and `CSVLoader` is that our
descriptors (our features) have already been computed for us, but are spread
across multiple columns of the CSV file.
Of course in practice you should already have your data in a CSV file if
you're using `UserCSVLoader`. If your data is already in memory, use
`InMemoryLoader` instead.
"""
def _get_shards(self, input_files: List[str],
shard_size: Optional[int]) -> Iterator[pd.DataFrame]:
"""Defines a generator which returns data for each shard
Parameters
----------
input_files: List[str]
List of filenames to process
shard_size: int, optional
The size of a shard of data to process at a time.
Returns
-------
Iterator[pd.DataFrame]
Iterator over shards
"""
return load_csv_files(input_files, shard_size)
def _featurize_shard(self,
shard: pd.DataFrame) -> Tuple[np.ndarray, np.ndarray]:
"""Featurizes a shard of an input dataframe.
Parameters
----------
shard: pd.DataFrame
DataFrame that holds a shard of the input CSV file
Returns
-------
features: np.ndarray
Features extracted from CSV file.
valid_inds: np.ndarray
Indices of rows in source CSV with valid data.
"""
assert isinstance(self.featurizer, UserDefinedFeaturizer)
time1 = time.time()
feature_fields = self.featurizer.feature_fields
shard[feature_fields] = shard[feature_fields].apply(pd.to_numeric)
X_shard = shard[feature_fields].to_numpy()
time2 = time.time()
logger.info(
"TIMING: user specified processing took %0.3f s" % (time2 - time1))
return (X_shard, np.ones(len(X_shard), dtype=bool))
class JsonLoader(DataLoader):
"""
Creates `Dataset` objects from input json files.
This class provides conveniences to load data from json files.
It's possible to directly featurize data from json files using
pandas, but this class may prove useful if you're processing
large json files that you don't want to manipulate directly in
memory.
It is meant to load JSON files formatted as "records" in line
delimited format, which allows for sharding.
``list like [{column -> value}, ... , {column -> value}]``.
Examples
--------
Let's create the sample dataframe.
>>> composition = ["LiCoO2", "MnO2"]
>>> labels = [1.5, 2.3]
>>> import pandas as pd
>>> df = pd.DataFrame(list(zip(composition, labels)), columns=["composition", "task"])
Dump the dataframe to the JSON file formatted as "records" in line delimited format and
load the json file by JsonLoader.
>>> import tempfile
>>> import deepchem as dc
>>> with dc.utils.UniversalNamedTemporaryFile(mode='w') as tmpfile:
... df.to_json(tmpfile.name, orient='records', lines=True)
... featurizer = dc.feat.ElementPropertyFingerprint()
... loader = dc.data.JsonLoader(["task"], feature_field="composition", featurizer=featurizer)
... dataset = loader.create_dataset(tmpfile.name)
>>> len(dataset)
2
"""
def __init__(self,
tasks: List[str],
feature_field: str,
featurizer: Featurizer,
label_field: Optional[str] = None,
weight_field: Optional[str] = None,
id_field: Optional[str] = None,
log_every_n: int = 1000):
"""Initializes JsonLoader.
Parameters
----------
tasks: List[str]
List of task names
feature_field: str
JSON field with data to be featurized.
featurizer: Featurizer
Featurizer to use to process data
label_field: str, optional (default None)
Field with target variables.
weight_field: str, optional (default None)
Field with weights.
id_field: str, optional (default None)
Field for identifying samples.
log_every_n: int, optional (default 1000)
Writes a logging statement this often.
"""
if not isinstance(tasks, list):
raise ValueError("Tasks must be a list.")
self.tasks = tasks
self.feature_field = feature_field
self.label_field = label_field
self.weight_field = weight_field
self.id_field = id_field
self.user_specified_features = None
if isinstance(featurizer, UserDefinedFeaturizer):
self.user_specified_features = featurizer.feature_fields
self.featurizer = featurizer
self.log_every_n = log_every_n
def create_dataset(self,
input_files: OneOrMany[str],
data_dir: Optional[str] = None,
shard_size: Optional[int] = 8192) -> DiskDataset:
"""Creates a `Dataset` from input JSON files.
Parameters
----------
input_files: OneOrMany[str]
List of JSON filenames.
data_dir: Optional[str], default None
Name of directory where featurized data is stored.
shard_size: int, optional (default 8192)
Shard size when loading data.
Returns
-------
DiskDataset
A `DiskDataset` object containing a featurized representation of data
from `input_files`.
"""
if not isinstance(input_files, list):
try:
if isinstance(input_files, str):
input_files = [input_files]
else:
input_files = list(input_files)
except TypeError:
raise ValueError(
"input_files is of an unrecognized form. Must be one filename or a list of filenames."
)
def shard_generator():
"""Yield X, y, w, and ids for shards."""
for shard_num, shard in enumerate(
self._get_shards(input_files, shard_size)):
time1 = time.time()
X, valid_inds = self._featurize_shard(shard)
if self.id_field:
ids = shard[self.id_field].values
else:
ids = np.ones(len(valid_inds))
ids = ids[valid_inds]
if len(self.tasks) > 0:
# Featurize task results if they exist.
y, w = _convert_df_to_numpy(shard, self.tasks)
if self.label_field:
y = shard[self.label_field]
if self.weight_field:
w = shard[self.weight_field]
# Filter out examples where featurization failed.
y, w = (y[valid_inds], w[valid_inds])
assert len(X) == len(ids) == len(y) == len(w)
else:
# For prospective data where results are unknown, it
# makes no sense to have y values or weights.
y, w = (None, None)
assert len(X) == len(ids)
time2 = time.time()
logger.info("TIMING: featurizing shard %d took %0.3f s" %
(shard_num, time2 - time1))
yield X, y, w, ids
return DiskDataset.create_dataset(shard_generator(), data_dir, self.tasks)
def _get_shards(self, input_files: List[str],
shard_size: Optional[int]) -> Iterator[pd.DataFrame]:
"""Defines a generator which returns data for each shard
Parameters
----------
input_files: List[str]
List of filenames to process
shard_size: int, optional
The size of a shard of data to process at a time.
Returns
-------
Iterator[pd.DataFrame]
Iterator over shards
"""
return load_json_files(input_files, shard_size)
def _featurize_shard(self,
shard: pd.DataFrame) -> Tuple[np.ndarray, np.ndarray]:
"""Featurizes a shard of an input dataframe.
Helper that computes features for the given shard of data.
Parameters
----------
shard: pd.DataFrame
DataFrame that holds data to be featurized.
Returns
-------
features: np.ndarray
Array of feature vectors. Note that samples for which featurization has
failed will be filtered out.
valid_inds: np.ndarray
Boolean values indicating successful featurization for corresponding
sample in the source.
"""
logger.info("About to featurize shard.")
if self.featurizer is None:
raise ValueError(
"featurizer must be specified in constructor to featurizer data/")
features = [elt for elt in self.featurizer(shard[self.feature_field])]
valid_inds = np.array(
[1 if np.array(elt).size > 0 else 0 for elt in features], dtype=bool)
features = [
elt for (is_valid, elt) in zip(valid_inds, features) if is_valid
]
return np.array(features), valid_inds
class SDFLoader(DataLoader):
"""Creates a `Dataset` object from SDF input files.
This class provides conveniences to load and featurize data from
Structure Data Files (SDFs). SDF is a standard format for structural
information (3D coordinates of atoms and bonds) of molecular compounds.
Examples
--------
>>> import deepchem as dc
>>> import os
>>> current_dir = os.path.dirname(os.path.realpath(__file__))
>>> featurizer = dc.feat.CircularFingerprint(size=16)
>>> loader = dc.data.SDFLoader(["LogP(RRCK)"], featurizer=featurizer, sanitize=True)
>>> dataset = loader.create_dataset(os.path.join(current_dir, "tests", "membrane_permeability.sdf")) # doctest:+ELLIPSIS
>>> len(dataset)
2
"""
def __init__(self,
tasks: List[str],
featurizer: Featurizer,
sanitize: bool = False,
log_every_n: int = 1000):
"""Initialize SDF Loader
Parameters
----------
tasks: list[str]
List of tasknames. These will be loaded from the SDF file.
featurizer: Featurizer
Featurizer to use to process data
sanitize: bool, optional (default False)
Whether to sanitize molecules.
log_every_n: int, optional (default 1000)
Writes a logging statement this often.
"""
self.featurizer = featurizer
self.sanitize = sanitize
self.tasks = tasks
# The field in which dc.utils.save.load_sdf_files stores RDKit mol objects
self.mol_field = "mol"
# The field in which load_sdf_files return value stores smiles
self.id_field = "smiles"
self.log_every_n = log_every_n
def _get_shards(self, input_files: List[str],
shard_size: Optional[int]) -> Iterator[pd.DataFrame]:
"""Defines a generator which returns data for each shard
Parameters
----------
input_files: List[str]
List of filenames to process
shard_size: int, optional
The size of a shard of data to process at a time.
Returns
-------
Iterator[pd.DataFrame]
Iterator over shards
"""
return load_sdf_files(
input_files=input_files,
clean_mols=self.sanitize,
tasks=self.tasks,
shard_size=shard_size)
def _featurize_shard(self,
shard: pd.DataFrame) -> Tuple[np.ndarray, np.ndarray]:
"""Featurizes a shard of an input dataframe.
Helper that computes features for the given shard of data.
Parameters
----------
shard: pd.DataFrame
DataFrame that holds data to be featurized.
Returns
-------
features: np.ndarray
Array of feature vectors. Note that samples for which featurization has
failed will be filtered out.
valid_inds: np.ndarray
Boolean values indicating successful featurization for corresponding
sample in the source.
"""
features = [elt for elt in self.featurizer(shard[self.mol_field])]
valid_inds = np.array(
[1 if np.array(elt).size > 0 else 0 for elt in features], dtype=bool)
features = [
elt for (is_valid, elt) in zip(valid_inds, features) if is_valid
]
return np.array(features), valid_inds
class FASTALoader(DataLoader):
"""Handles loading of FASTA files.
FASTA files are commonly used to hold sequence data. This
class provides convenience files to lead FASTA data and
one-hot encode the genomic sequences for use in downstream
learning tasks.
"""
def __init__(self):
"""Initialize loader."""
pass
def create_dataset(self,
input_files: OneOrMany[str],
data_dir: Optional[str] = None,
shard_size: Optional[int] = None) -> DiskDataset:
"""Creates a `Dataset` from input FASTA files.
At present, FASTA support is limited and only allows for one-hot
featurization, and doesn't allow for sharding.
Parameters
----------
input_files: List[str]
List of fasta files.
data_dir: str, optional (default None)
Name of directory where featurized data is stored.
shard_size: int, optional (default None)
For now, this argument is ignored and each FASTA file gets its
own shard.
Returns
-------
DiskDataset
A `DiskDataset` object containing a featurized representation of data
from `input_files`.
"""
if isinstance(input_files, str):
input_files = [input_files]
def shard_generator():
for input_file in input_files:
X = encode_bio_sequence(input_file)
ids = np.ones(len(X))
# (X, y, w, ids)
yield X, None, None, ids
return DiskDataset.create_dataset(shard_generator(), data_dir)
class ImageLoader(DataLoader):
"""Handles loading of image files.
This class allows for loading of images in various formats.
For user convenience, also accepts zip-files and directories
of images and uses some limited intelligence to attempt to
traverse subdirectories which contain images.
"""
def __init__(self, tasks: Optional[List[str]] = None):
"""Initialize image loader.
At present, custom image featurizers aren't supported by this
loader class.
Parameters
----------
tasks: List[str], optional (default None)
List of task names for image labels.
"""
if tasks is None:
tasks = []
self.tasks = tasks
def create_dataset(self,
inputs: Union[OneOrMany[str], Tuple[Any]],
data_dir: Optional[str] = None,
shard_size: Optional[int] = 8192,
in_memory: bool = False) -> Dataset:
"""Creates and returns a `Dataset` object by featurizing provided image files and labels/weights.
Parameters
----------
inputs: `Union[OneOrMany[str], Tuple[Any]]`
The inputs provided should be one of the following
- filename
- list of filenames
- Tuple (list of filenames, labels)
- Tuple (list of filenames, labels, weights)
Each file in a given list of filenames should either be of a supported
image format (.png, .tif only for now) or of a compressed folder of
image files (only .zip for now). If `labels` or `weights` are provided,
they must correspond to the sorted order of all filenames provided, with
one label/weight per file.
data_dir: str, optional (default None)
Directory to store featurized dataset.
shard_size: int, optional (default 8192)
Shard size when loading data.
in_memory: bool, optioanl (default False)
If true, return in-memory NumpyDataset. Else return ImageDataset.
Returns
-------
ImageDataset or NumpyDataset or DiskDataset
- if `in_memory == False`, the return value is ImageDataset.
- if `in_memory == True` and `data_dir is None`, the return value is NumpyDataset.
- if `in_memory == True` and `data_dir is not None`, the return value is DiskDataset.
"""
labels, weights = None, None
if isinstance(inputs, tuple):
if len(inputs) == 1:
input_files = inputs[0]
if isinstance(inputs, str):
input_files = [inputs]
elif len(inputs) == 2:
input_files, labels = inputs
elif len(inputs) == 3:
input_files, labels, weights = inputs
else:
raise ValueError("Input must be a tuple of length 1, 2, or 3")
else:
input_files = inputs
if isinstance(input_files, str):
input_files = [input_files]
image_files = []
# Sometimes zip files contain directories within. Traverse directories
while len(input_files) > 0:
remainder = []
for input_file in input_files:
filename, extension = os.path.splitext(input_file)
extension = extension.lower()
# TODO(rbharath): Add support for more extensions
if os.path.isdir(input_file):
dirfiles = [
os.path.join(input_file, subfile)
for subfile in os.listdir(input_file)
]
remainder += dirfiles
elif extension == ".zip":
zip_dir = tempfile.mkdtemp()
zip_ref = zipfile.ZipFile(input_file, 'r')
zip_ref.extractall(path=zip_dir)
zip_ref.close()
zip_files = [
os.path.join(zip_dir, name) for name in zip_ref.namelist()
]
for zip_file in zip_files:
_, extension = os.path.splitext(zip_file)
extension = extension.lower()
if extension in [".png", ".tif"]:
image_files.append(zip_file)
elif extension in [".png", ".tif"]:
image_files.append(input_file)
else:
raise ValueError("Unsupported file format")
input_files = remainder
# Sort image files
image_files = sorted(image_files)
if in_memory:
if data_dir is None:
return NumpyDataset(
load_image_files(image_files), y=labels, w=weights, ids=image_files)
else:
dataset = DiskDataset.from_numpy(
load_image_files(image_files),
y=labels,
w=weights,
ids=image_files,
tasks=self.tasks,
data_dir=data_dir)
if shard_size is not None:
dataset.reshard(shard_size)
return dataset
else:
return ImageDataset(image_files, y=labels, w=weights, ids=image_files)
class InMemoryLoader(DataLoader):
"""Facilitate Featurization of In-memory objects.
When featurizing a dataset, it's often the case that the initial set of
data (pre-featurization) fits handily within memory. (For example, perhaps
it fits within a column of a pandas DataFrame.) In this case, it would be
convenient to directly be able to featurize this column of data. However,
the process of featurization often generates large arrays which quickly eat
up available memory. This class provides convenient capabilities to process
such in-memory data by checkpointing generated features periodically to
disk.
Example
-------
Here's an example with only datapoints and no labels or weights.
>>> import deepchem as dc
>>> smiles = ["C", "CC", "CCC", "CCCC"]
>>> featurizer = dc.feat.CircularFingerprint()
>>> loader = dc.data.InMemoryLoader(tasks=["task1"], featurizer=featurizer)
>>> dataset = loader.create_dataset(smiles, shard_size=2)
>>> len(dataset)
4
Here's an example with both datapoints and labels