/
splitters.py
1534 lines (1319 loc) · 52.2 KB
/
splitters.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 an abstract base class that supports chemically aware data splits.
"""
import inspect
import os
import random
import tempfile
import itertools
import logging
from typing import Any, Dict, List, Iterator, Optional, Sequence, Tuple
import numpy as np
import pandas as pd
import deepchem as dc
from deepchem.data import Dataset, DiskDataset
from deepchem.utils import get_print_threshold
logger = logging.getLogger(__name__)
def randomize_arrays(array_list):
# assumes that every array is of the same dimension
num_rows = array_list[0].shape[0]
perm = np.random.permutation(num_rows)
permuted_arrays = []
for array in array_list:
permuted_arrays.append(array[perm])
return permuted_arrays
class Splitter(object):
"""Splitters split up Datasets into pieces for training/validation/testing.
In machine learning applications, it's often necessary to split up a dataset
into training/validation/test sets. Or to k-fold split a dataset (that is,
divide into k equal subsets) for cross-validation. The `Splitter` class is
an abstract superclass for all splitters that captures the common API across
splitter classes.
Note that `Splitter` is an abstract superclass. You won't want to
instantiate this class directly. Rather you will want to use a concrete
subclass for your application.
"""
def k_fold_split(self,
dataset: Dataset,
k: int,
directories: Optional[List[str]] = None,
**kwargs) -> List[Tuple[Dataset, Dataset]]:
"""
Parameters
----------
dataset: Dataset
Dataset to do a k-fold split
k: int
Number of folds to split `dataset` into.
directories: List[str], optional (default None)
List of length 2*k filepaths to save the result disk-datasets.
Returns
-------
List[Tuple[Dataset, Dataset]]
List of length k tuples of (train, cv) where `train` and `cv` are both `Dataset`.
"""
logger.info("Computing K-fold split")
if directories is None:
directories = [tempfile.mkdtemp() for _ in range(2 * k)]
else:
assert len(directories) == 2 * k
cv_datasets = []
train_ds_base = None
train_datasets = []
# rem_dataset is remaining portion of dataset
if isinstance(dataset, DiskDataset):
rem_dataset = dataset
else:
rem_dataset = DiskDataset.from_numpy(dataset.X, dataset.y, dataset.w,
dataset.ids)
for fold in range(k):
# Note starts as 1/k since fold starts at 0. Ends at 1 since fold goes up
# to k-1.
frac_fold = 1. / (k - fold)
train_dir, cv_dir = directories[2 * fold], directories[2 * fold + 1]
fold_inds, rem_inds, _ = self.split(
rem_dataset,
frac_train=frac_fold,
frac_valid=1 - frac_fold,
frac_test=0,
**kwargs)
cv_dataset = rem_dataset.select(fold_inds, select_dir=cv_dir)
cv_datasets.append(cv_dataset)
# FIXME: Incompatible types in assignment (expression has type "Dataset", variable has type "DiskDataset")
rem_dataset = rem_dataset.select(rem_inds) # type: ignore
train_ds_to_merge: Iterator[Dataset] = filter(
None, [train_ds_base, rem_dataset])
train_ds_to_merge = filter(lambda x: len(x) > 0, train_ds_to_merge)
train_dataset = DiskDataset.merge(train_ds_to_merge, merge_dir=train_dir)
train_datasets.append(train_dataset)
update_train_base_merge: Iterator[Dataset] = filter(
None, [train_ds_base, cv_dataset])
train_ds_base = DiskDataset.merge(update_train_base_merge)
return list(zip(train_datasets, cv_datasets))
def train_valid_test_split(self,
dataset: Dataset,
train_dir: Optional[str] = None,
valid_dir: Optional[str] = None,
test_dir: Optional[str] = None,
frac_train: float = 0.8,
frac_valid: float = 0.1,
frac_test: float = 0.1,
seed: Optional[int] = None,
log_every_n: int = 1000,
**kwargs) -> Tuple[Dataset, Dataset, Dataset]:
""" Splits self into train/validation/test sets.
Returns Dataset objects for train, valid, test.
Parameters
----------
dataset: Dataset
Dataset to be split.
train_dir: str, optional (default None)
If specified, the directory in which the generated
training dataset should be stored. This is only
considered if `isinstance(dataset, dc.data.DiskDataset)`
valid_dir: str, optional (default None)
If specified, the directory in which the generated
valid dataset should be stored. This is only
considered if `isinstance(dataset, dc.data.DiskDataset)`
is True.
test_dir: str, optional (default None)
If specified, the directory in which the generated
test dataset should be stored. This is only
considered if `isinstance(dataset, dc.data.DiskDataset)`
is True.
frac_train: float, optional (default 0.8)
The fraction of data to be used for the training split.
frac_valid: float, optional (default 0.1)
The fraction of data to be used for the validation split.
frac_test: float, optional (default 0.1)
The fraction of data to be used for the test split.
seed: int, optional (default None)
Random seed to use.
log_every_n: int, optional (default 1000)
Controls the logger by dictating how often logger outputs
will be produced.
Returns
-------
Tuple[Dataset, Optional[Dataset], Dataset]
A tuple of train, valid and test datasets as dc.data.Dataset objects.
"""
logger.info("Computing train/valid/test indices")
train_inds, valid_inds, test_inds = self.split(
dataset,
frac_train=frac_train,
frac_test=frac_test,
frac_valid=frac_valid,
seed=seed,
log_every_n=log_every_n)
if train_dir is None:
train_dir = tempfile.mkdtemp()
if valid_dir is None:
valid_dir = tempfile.mkdtemp()
if test_dir is None:
test_dir = tempfile.mkdtemp()
train_dataset = dataset.select(train_inds, train_dir)
valid_dataset = dataset.select(valid_inds, valid_dir)
test_dataset = dataset.select(test_inds, test_dir)
if isinstance(train_dataset, DiskDataset):
train_dataset.memory_cache_size = 40 * (1 << 20) # 40 MB
return train_dataset, valid_dataset, test_dataset
def train_test_split(self,
dataset: Dataset,
train_dir: Optional[str] = None,
test_dir: Optional[str] = None,
frac_train: float = 0.8,
seed: Optional[int] = None,
**kwargs) -> Tuple[Dataset, Dataset]:
"""Splits self into train/test sets.
Returns Dataset objects for train/test.
Parameters
----------
dataset: data like object
Dataset to be split.
train_dir: str, optional (default None)
If specified, the directory in which the generated
training dataset should be stored. This is only
considered if `isinstance(dataset, dc.data.DiskDataset)`
is True.
test_dir: str, optional (default None)
If specified, the directory in which the generated
test dataset should be stored. This is only
considered if `isinstance(dataset, dc.data.DiskDataset)`
is True.
frac_train: float, optional (default 0.8)
The fraction of data to be used for the training split.
seed: int, optional (default None)
Random seed to use.
Returns
-------
Tuple[Dataset, Dataset]
A tuple of train and test datasets as dc.data.Dataset objects.
"""
valid_dir = tempfile.mkdtemp()
train_dataset, _, test_dataset = self.train_valid_test_split(
dataset,
train_dir,
valid_dir,
test_dir,
frac_train=frac_train,
frac_test=1 - frac_train,
frac_valid=0.,
seed=seed,
**kwargs)
return train_dataset, test_dataset
def split(self,
dataset: Dataset,
frac_train: float = 0.8,
frac_valid: float = 0.1,
frac_test: float = 0.1,
seed: Optional[int] = None,
log_every_n: Optional[int] = None) -> Tuple:
"""Return indices for specified split
Parameters
----------
dataset: dc.data.Dataset
Dataset to be split.
seed: int, optional (default None)
Random seed to use.
frac_train: float, optional (default 0.8)
The fraction of data to be used for the training split.
frac_valid: float, optional (default 0.1)
The fraction of data to be used for the validation split.
frac_test: float, optional (default 0.1)
The fraction of data to be used for the test split.
log_every_n: int, optional (default None)
Controls the logger by dictating how often logger outputs
will be produced.
Returns
-------
Tuple
A tuple `(train_inds, valid_inds, test_inds)` of the indices (integers) for
the various splits.
"""
raise NotImplementedError
def __str__(self) -> str:
"""Convert self to str representation.
Returns
-------
str
The string represents the class.
Examples
--------
>>> import deepchem as dc
>>> str(dc.splits.RandomSplitter())
'RandomSplitter'
"""
args_spec = inspect.getfullargspec(self.__init__) # type: ignore
args_names = [arg for arg in args_spec.args if arg != 'self']
args_num = len(args_names)
args_default_values = [None for _ in range(args_num)]
if args_spec.defaults is not None:
defaults = list(args_spec.defaults)
args_default_values[-len(defaults):] = defaults
override_args_info = ''
for arg_name, default in zip(args_names, args_default_values):
if arg_name in self.__dict__:
arg_value = self.__dict__[arg_name]
# validation
# skip list
if isinstance(arg_value, list):
continue
if isinstance(arg_value, str):
# skip path string
if "\\/." in arg_value or "/" in arg_value or '.' in arg_value:
continue
# main logic
if default != arg_value:
override_args_info += '_' + arg_name + '_' + str(arg_value)
return self.__class__.__name__ + override_args_info
def __repr__(self) -> str:
"""Convert self to repr representation.
Returns
-------
str
The string represents the class.
Examples
--------
>>> import deepchem as dc
>>> dc.splits.RandomSplitter()
RandomSplitter[]
"""
args_spec = inspect.getfullargspec(self.__init__) # type: ignore
args_names = [arg for arg in args_spec.args if arg != 'self']
args_info = ''
for arg_name in args_names:
value = self.__dict__[arg_name]
# for str
if isinstance(value, str):
value = "'" + value + "'"
# for list
if isinstance(value, list):
threshold = get_print_threshold()
value = np.array2string(np.array(value), threshold=threshold)
args_info += arg_name + '=' + str(value) + ', '
return self.__class__.__name__ + '[' + args_info[:-2] + ']'
class RandomSplitter(Splitter):
"""Class for doing random data splits.
Examples
--------
>>> import numpy as np
>>> import deepchem as dc
>>> # Creating a dummy NumPy dataset
>>> X, y = np.random.randn(5), np.random.randn(5)
>>> dataset = dc.data.NumpyDataset(X, y)
>>> # Creating a RandomSplitter object
>>> splitter = dc.splits.RandomSplitter()
>>> # Splitting dataset into train and test datasets
>>> train_dataset, test_dataset = splitter.train_test_split(dataset)
"""
def split(self,
dataset: Dataset,
frac_train: float = 0.8,
frac_valid: float = 0.1,
frac_test: float = 0.1,
seed: Optional[int] = None,
log_every_n: Optional[int] = None
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""
Splits internal compounds randomly into train/validation/test.
Parameters
----------
dataset: Dataset
Dataset to be split.
seed: int, optional (default None)
Random seed to use.
frac_train: float, optional (default 0.8)
The fraction of data to be used for the training split.
frac_valid: float, optional (default 0.1)
The fraction of data to be used for the validation split.
frac_test: float, optional (default 0.1)
The fraction of data to be used for the test split.
seed: int, optional (default None)
Random seed to use.
log_every_n: int, optional (default None)
Log every n examples (not currently used).
Returns
-------
Tuple[np.ndarray, np.ndarray, np.ndarray]
A tuple of train indices, valid indices, and test indices.
Each indices is a numpy array.
"""
np.testing.assert_almost_equal(frac_train + frac_valid + frac_test, 1.)
if seed is not None:
np.random.seed(seed)
num_datapoints = len(dataset)
train_cutoff = int(frac_train * num_datapoints)
valid_cutoff = int((frac_train + frac_valid) * num_datapoints)
shuffled = np.random.permutation(range(num_datapoints))
return (shuffled[:train_cutoff], shuffled[train_cutoff:valid_cutoff],
shuffled[valid_cutoff:])
class RandomGroupSplitter(Splitter):
"""Random split based on groupings.
A splitter class that splits on groupings. An example use case is when
there are multiple conformations of the same molecule that share the same
topology. This splitter subsequently guarantees that resulting splits
preserve groupings.
Note that it doesn't do any dynamic programming or something fancy to try
to maximize the choice such that frac_train, frac_valid, or frac_test is
maximized. It simply permutes the groups themselves. As such, use with
caution if the number of elements per group varies significantly.
"""
def __init__(self, groups: Sequence):
"""Initialize this object.
Parameters
----------
groups: Sequence
An array indicating the group of each item.
The length is equals to `len(dataset.X)`
Note
----
The examples of groups is the following.
| groups : 3 2 2 0 1 1 2 4 3
| dataset.X : 0 1 2 3 4 5 6 7 8
| groups : a b b e q x a a r
| dataset.X : 0 1 2 3 4 5 6 7 8
"""
self.groups = groups
def split(self,
dataset: Dataset,
frac_train: float = 0.8,
frac_valid: float = 0.1,
frac_test: float = 0.1,
seed: Optional[int] = None,
log_every_n: Optional[int] = None
) -> Tuple[List[int], List[int], List[int]]:
"""Return indices for specified split
Parameters
----------
dataset: Dataset
Dataset to be split.
frac_train: float, optional (default 0.8)
The fraction of data to be used for the training split.
frac_valid: float, optional (default 0.1)
The fraction of data to be used for the validation split.
frac_test: float, optional (default 0.1)
The fraction of data to be used for the test split.
seed: int, optional (default None)
Random seed to use.
log_every_n: int, optional (default None)
Log every n examples (not currently used).
Returns
-------
Tuple[List[int], List[int], List[int]]
A tuple `(train_inds, valid_inds, test_inds` of the indices (integers) for
the various splits.
"""
assert len(self.groups) == dataset.X.shape[0]
np.testing.assert_almost_equal(frac_train + frac_valid + frac_test, 1.)
if seed is not None:
np.random.seed(seed)
# dict is needed in case groups aren't strictly flattened or
# hashed by something non-integer like
group_dict: Dict[Any, List[int]] = {}
for idx, g in enumerate(self.groups):
if g not in group_dict:
group_dict[g] = []
group_dict[g].append(idx)
group_idxs = np.array([g for g in group_dict.values()])
num_groups = len(group_idxs)
train_cutoff = int(frac_train * num_groups)
valid_cutoff = int((frac_train + frac_valid) * num_groups)
shuffled_group_idxs = np.random.permutation(range(num_groups))
train_groups = shuffled_group_idxs[:train_cutoff]
valid_groups = shuffled_group_idxs[train_cutoff:valid_cutoff]
test_groups = shuffled_group_idxs[valid_cutoff:]
train_idxs = list(itertools.chain(*group_idxs[train_groups]))
valid_idxs = list(itertools.chain(*group_idxs[valid_groups]))
test_idxs = list(itertools.chain(*group_idxs[test_groups]))
return train_idxs, valid_idxs, test_idxs
class RandomStratifiedSplitter(Splitter):
"""RandomStratified Splitter class.
For sparse multitask datasets, a standard split offers no guarantees
that the splits will have any active compounds. This class tries to
arrange that each split has a proportional number of the actives for each
task. This is strictly guaranteed only for single-task datasets, but for
sparse multitask datasets it usually manages to produces a fairly accurate
division of the actives for each task.
Note
----
This splitter is primarily designed for boolean labeled data. It considers
only whether a label is zero or non-zero. When labels can take on multiple
non-zero values, it does not try to give each split a proportional fraction
of the samples with each value.
"""
def split(self,
dataset: Dataset,
frac_train: float = 0.8,
frac_valid: float = 0.1,
frac_test: float = 0.1,
seed: Optional[int] = None,
log_every_n: Optional[int] = None) -> Tuple:
"""Return indices for specified split
Parameters
----------
dataset: dc.data.Dataset
Dataset to be split.
seed: int, optional (default None)
Random seed to use.
frac_train: float, optional (default 0.8)
The fraction of data to be used for the training split.
frac_valid: float, optional (default 0.1)
The fraction of data to be used for the validation split.
frac_test: float, optional (default 0.1)
The fraction of data to be used for the test split.
log_every_n: int, optional (default None)
Controls the logger by dictating how often logger outputs
will be produced.
Returns
-------
Tuple
A tuple `(train_inds, valid_inds, test_inds)` of the indices (integers) for
the various splits.
"""
y_present = (dataset.y != 0) * (dataset.w != 0)
if len(y_present.shape) == 1:
y_present = np.expand_dims(y_present, 1)
elif len(y_present.shape) > 2:
raise ValueError(
'RandomStratifiedSplitter cannot be applied when y has more than two dimensions'
)
if seed is not None:
np.random.seed(seed)
# Figure out how many positive samples we want for each task in each dataset.
n_tasks = y_present.shape[1]
indices_for_task = [
np.random.permutation(np.nonzero(y_present[:, i])[0])
for i in range(n_tasks)
]
count_for_task = np.array([len(x) for x in indices_for_task])
train_target = np.round(frac_train * count_for_task).astype(int)
valid_target = np.round(frac_valid * count_for_task).astype(int)
test_target = np.round(frac_test * count_for_task).astype(int)
# Assign the positive samples to datasets. Since a sample may be positive
# on more than one task, we need to keep track of the effect of each added
# sample on each task. To try to keep everything balanced, we cycle through
# tasks, assigning one positive sample for each one.
train_counts = np.zeros(n_tasks, int)
valid_counts = np.zeros(n_tasks, int)
test_counts = np.zeros(n_tasks, int)
set_target = [train_target, valid_target, test_target]
set_counts = [train_counts, valid_counts, test_counts]
set_inds: List[List[int]] = [[], [], []]
assigned = set()
max_count = np.max(count_for_task)
for i in range(max_count):
for task in range(n_tasks):
indices = indices_for_task[task]
if i < len(indices) and indices[i] not in assigned:
# We have a sample that hasn't been assigned yet. Assign it to
# whichever set currently has the lowest fraction of its target for
# this task.
index = indices[i]
set_frac = [
1 if set_target[i][task] == 0 else
set_counts[i][task] / set_target[i][task] for i in range(3)
]
set_index = np.argmin(set_frac)
set_inds[set_index].append(index)
assigned.add(index)
set_counts[set_index] += y_present[index]
# The remaining samples are negative for all tasks. Add them to fill out
# each set to the correct total number.
n_samples = y_present.shape[0]
set_size = [
int(np.round(n_samples * f))
for f in (frac_train, frac_valid, frac_test)
]
s = 0
for i in np.random.permutation(range(n_samples)):
if i not in assigned:
while s < 2 and len(set_inds[s]) >= set_size[s]:
s += 1
set_inds[s].append(i)
return tuple(sorted(x) for x in set_inds)
class SingletaskStratifiedSplitter(Splitter):
"""Class for doing data splits by stratification on a single task.
Examples
--------
>>> n_samples = 100
>>> n_features = 10
>>> n_tasks = 10
>>> X = np.random.rand(n_samples, n_features)
>>> y = np.random.rand(n_samples, n_tasks)
>>> w = np.ones_like(y)
>>> dataset = DiskDataset.from_numpy(np.ones((100,n_tasks)), np.ones((100,n_tasks)))
>>> splitter = SingletaskStratifiedSplitter(task_number=5)
>>> train_dataset, test_dataset = splitter.train_test_split(dataset)
"""
def __init__(self, task_number: int = 0):
"""
Creates splitter object.
Parameters
----------
task_number: int, optional (default 0)
Task number for stratification.
"""
self.task_number = task_number
# FIXME: Signature of "k_fold_split" incompatible with supertype "Splitter"
def k_fold_split( # type: ignore [override]
self,
dataset: Dataset,
k: int,
directories: Optional[List[str]] = None,
seed: Optional[int] = None,
log_every_n: Optional[int] = None,
**kwargs) -> List[Dataset]:
"""
Splits compounds into k-folds using stratified sampling.
Overriding base class k_fold_split.
Parameters
----------
dataset: Dataset
Dataset to be split.
k: int
Number of folds to split `dataset` into.
directories: List[str], optional (default None)
List of length k filepaths to save the result disk-datasets.
seed: int, optional (default None)
Random seed to use.
log_every_n: int, optional (default None)
Log every n examples (not currently used).
Returns
-------
fold_datasets: List[Dataset]
List of dc.data.Dataset objects
"""
logger.info("Computing K-fold split")
if directories is None:
directories = [tempfile.mkdtemp() for _ in range(k)]
else:
assert len(directories) == k
y_s = dataset.y[:, self.task_number]
sortidx = np.argsort(y_s)
sortidx_list = np.array_split(sortidx, k)
fold_datasets = []
for fold in range(k):
fold_dir = directories[fold]
fold_ind = sortidx_list[fold]
fold_dataset = dataset.select(fold_ind, fold_dir)
fold_datasets.append(fold_dataset)
return fold_datasets
def split(self,
dataset: Dataset,
frac_train: float = 0.8,
frac_valid: float = 0.1,
frac_test: float = 0.1,
seed: Optional[int] = None,
log_every_n: Optional[int] = None
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""
Splits compounds into train/validation/test using stratified sampling.
Parameters
----------
dataset: Dataset
Dataset to be split.
frac_train: float, optional (default 0.8)
Fraction of dataset put into training data.
frac_valid: float, optional (default 0.1)
Fraction of dataset put into validation data.
frac_test: float, optional (default 0.1)
Fraction of dataset put into test data.
seed: int, optional (default None)
Random seed to use.
log_every_n: int, optional (default None)
Log every n examples (not currently used).
Returns
-------
Tuple[np.ndarray, np.ndarray, np.ndarray]
A tuple of train indices, valid indices, and test indices.
Each indices is a numpy array.
"""
# JSG Assert that split fractions can be written as proper fractions over 10.
# This can be generalized in the future with some common demoninator determination.
# This will work for 80/20 train/test or 80/10/10 train/valid/test (most use cases).
np.testing.assert_equal(frac_train + frac_valid + frac_test, 1.)
np.testing.assert_equal(10 * frac_train + 10 * frac_valid + 10 * frac_test,
10.)
if seed is not None:
np.random.seed(seed)
y_s = dataset.y[:, self.task_number]
sortidx = np.argsort(y_s)
split_cd = 10
train_cutoff = int(np.round(frac_train * split_cd))
valid_cutoff = int(np.round(frac_valid * split_cd)) + train_cutoff
train_idx: np.ndarray = np.array([])
valid_idx: np.ndarray = np.array([])
test_idx: np.ndarray = np.array([])
while sortidx.shape[0] >= split_cd:
sortidx_split, sortidx = np.split(sortidx, [split_cd])
shuffled = np.random.permutation(range(split_cd))
train_idx = np.hstack([train_idx, sortidx_split[shuffled[:train_cutoff]]])
valid_idx = np.hstack(
[valid_idx, sortidx_split[shuffled[train_cutoff:valid_cutoff]]])
test_idx = np.hstack([test_idx, sortidx_split[shuffled[valid_cutoff:]]])
# Append remaining examples to train
if sortidx.shape[0] > 0:
np.hstack([train_idx, sortidx])
return (train_idx, valid_idx, test_idx)
class IndexSplitter(Splitter):
"""Class for simple order based splits.
Use this class when the `Dataset` you have is already ordered sa you would
like it to be processed. Then the first `frac_train` proportion is used for
training, the next `frac_valid` for validation, and the final `frac_test` for
testing. This class may make sense to use your `Dataset` is already time
ordered (for example).
"""
def split(self,
dataset: Dataset,
frac_train: float = 0.8,
frac_valid: float = 0.1,
frac_test: float = 0.1,
seed: Optional[int] = None,
log_every_n: Optional[int] = None
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Splits internal compounds into train/validation/test in provided order.
Parameters
----------
dataset: Dataset
Dataset to be split.
frac_train: float, optional (default 0.8)
The fraction of data to be used for the training split.
frac_valid: float, optional (default 0.1)
The fraction of data to be used for the validation split.
frac_test: float, optional (default 0.1)
The fraction of data to be used for the test split.
seed: int, optional (default None)
Random seed to use.
log_every_n: int, optional
Log every n examples (not currently used).
Returns
-------
Tuple[np.ndarray, np.ndarray, np.ndarray]
A tuple of train indices, valid indices, and test indices.
Each indices is a numpy array.
"""
np.testing.assert_almost_equal(frac_train + frac_valid + frac_test, 1.)
num_datapoints = len(dataset)
train_cutoff = int(frac_train * num_datapoints)
valid_cutoff = int((frac_train + frac_valid) * num_datapoints)
indices = np.arange(num_datapoints)
return (indices[:train_cutoff], indices[train_cutoff:valid_cutoff],
indices[valid_cutoff:])
class SpecifiedSplitter(Splitter):
"""Split data in the fashion specified by user.
For some applications, you will already know how you'd like to split the
dataset. In this splitter, you simplify specify `valid_indices` and
`test_indices` and the datapoints at those indices are pulled out of the
dataset. Note that this is different from `IndexSplitter` which only splits
based on the existing dataset ordering, while this `SpecifiedSplitter` can
split on any specified ordering.
"""
def __init__(self,
valid_indices: Optional[List[int]] = None,
test_indices: Optional[List[int]] = None):
"""
Parameters
-----------
valid_indices: List[int]
List of indices of samples in the valid set
test_indices: List[int]
List of indices of samples in the test set
"""
self.valid_indices = valid_indices
self.test_indices = test_indices
def split(self,
dataset: Dataset,
frac_train: float = 0.8,
frac_valid: float = 0.1,
frac_test: float = 0.1,
seed: Optional[int] = None,
log_every_n: Optional[int] = None
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""
Splits internal compounds into train/validation/test in designated order.
Parameters
----------
dataset: Dataset
Dataset to be split.
frac_train: float, optional (default 0.8)
Fraction of dataset put into training data.
frac_valid: float, optional (default 0.1)
Fraction of dataset put into validation data.
frac_test: float, optional (default 0.1)
Fraction of dataset put into test data.
seed: int, optional (default None)
Random seed to use.
log_every_n: int, optional (default None)
Log every n examples (not currently used).
Returns
-------
Tuple[np.ndarray, np.ndarray, np.ndarray]
A tuple of train indices, valid indices, and test indices.
Each indices is a numpy array.
"""
num_datapoints = len(dataset)
indices = np.arange(num_datapoints).tolist()
train_indices = []
if self.valid_indices is None:
self.valid_indices = []
if self.test_indices is None:
self.test_indices = []
valid_test = list(self.valid_indices)
valid_test.extend(self.test_indices)
for indice in indices:
if indice not in valid_test:
train_indices.append(indice)
return (np.array(train_indices), np.array(self.valid_indices),
np.array(self.test_indices))
#################################################################
# Splitter for molecule datasets
#################################################################
class MolecularWeightSplitter(Splitter):
"""
Class for doing data splits by molecular weight.
Note
----
This class requires RDKit to be installed.
"""
def split(self,
dataset: Dataset,
frac_train: float = 0.8,
frac_valid: float = 0.1,
frac_test: float = 0.1,
seed: Optional[int] = None,
log_every_n: Optional[int] = None
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Splits on molecular weight.
Splits internal compounds into train/validation/test using the MW
calculated by SMILES string.
Parameters
----------
dataset: Dataset
Dataset to be split.
frac_train: float, optional (default 0.8)
The fraction of data to be used for the training split.
frac_valid: float, optional (default 0.1)
The fraction of data to be used for the validation split.
frac_test: float, optional (default 0.1)
The fraction of data to be used for the test split.
seed: int, optional (default None)
Random seed to use.
log_every_n: int, optional (default None)
Log every n examples (not currently used).
Returns
-------
Tuple[np.ndarray, np.ndarray, np.ndarray]
A tuple of train indices, valid indices, and test indices.
Each indices is a numpy array.
"""
try:
from rdkit import Chem
except ModuleNotFoundError:
raise ImportError("This function requires RDKit to be installed.")
np.testing.assert_almost_equal(frac_train + frac_valid + frac_test, 1.)
if seed is not None:
np.random.seed(seed)
mws = []
for smiles in dataset.ids:
mol = Chem.MolFromSmiles(smiles)
mw = Chem.rdMolDescriptors.CalcExactMolWt(mol)
mws.append(mw)
# Sort by increasing MW
sortidx = np.argsort(mws)
train_cutoff = int(frac_train * len(sortidx))
valid_cutoff = int((frac_train + frac_valid) * len(sortidx))
return (sortidx[:train_cutoff], sortidx[train_cutoff:valid_cutoff],
sortidx[valid_cutoff:])
class MaxMinSplitter(Splitter):
"""Chemical diversity splitter.
Class for doing splits based on the MaxMin diversity algorithm. Intuitively,
the test set is comprised of the most diverse compounds of the entire dataset.
Furthermore, the validation set is comprised of diverse compounds under
the test set.
Note
----
This class requires RDKit to be installed.
"""
def split(self,
dataset: Dataset,
frac_train: float = 0.8,
frac_valid: float = 0.1,
frac_test: float = 0.1,
seed: Optional[int] = None,
log_every_n: Optional[int] = None
) -> Tuple[List[int], List[int], List[int]]:
"""
Splits internal compounds into train/validation/test using the MaxMin diversity algorithm.
Parameters
----------
dataset: Dataset
Dataset to be split.
frac_train: float, optional (default 0.8)
The fraction of data to be used for the training split.
frac_valid: float, optional (default 0.1)
The fraction of data to be used for the validation split.
frac_test: float, optional (default 0.1)
The fraction of data to be used for the test split.
seed: int, optional (default None)
Random seed to use.
log_every_n: int, optional (default None)
Log every n examples (not currently used).
Returns
-------
Tuple[List[int], List[int], List[int]]
A tuple of train indices, valid indices, and test indices.
Each indices is a list of integers.
"""
try:
from rdkit import Chem, DataStructs
from rdkit.Chem import AllChem
from rdkit.SimDivFilters.rdSimDivPickers import MaxMinPicker
except ModuleNotFoundError: