/
transformers.py
2466 lines (2136 loc) · 74.9 KB
/
transformers.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 data transformations.
"""
import os
import logging
import time
import warnings
from typing import Any, List, Optional, Tuple, Union
import numpy as np
import scipy
import scipy.ndimage
import tensorflow as tf
import deepchem as dc
from deepchem.data import Dataset, NumpyDataset, DiskDataset
from deepchem.feat import Featurizer
from deepchem.feat.mol_graphs import ConvMol
logger = logging.getLogger(__name__)
def undo_grad_transforms(grad, tasks, transformers):
"""DEPRECATED. DO NOT USE."""
logger.warning(
"undo_grad_transforms is DEPRECATED and will be removed in a future version of DeepChem. "
"Manually implement transforms to perform force calculations.")
for transformer in reversed(transformers):
if transformer.transform_y:
grad = transformer.untransform_grad(grad, tasks)
return grad
def get_grad_statistics(dataset):
"""Computes and returns statistics of a dataset
DEPRECATED DO NOT USE.
This function assumes that the first task of a dataset holds the
energy for an input system, and that the remaining tasks holds the
gradient for the system.
"""
logger.warning(
"get_grad_statistics is DEPRECATED and will be removed in a future version of DeepChem. Manually compute force/energy statistics."
)
if len(dataset) == 0:
return None, None, None, None
y = dataset.y
energy = y[:, 0]
grad = y[:, 1:]
for i in range(energy.size):
grad[i] *= energy[i]
ydely_means = np.sum(grad, axis=0) / len(energy)
return grad, ydely_means
class Transformer(object):
"""Abstract base class for different data transformation techniques.
A transformer is an object that applies a transformation to a given
dataset. Think of a transformation as a mathematical operation which
makes the source dataset more amenable to learning. For example, one
transformer could normalize the features for a dataset (ensuring
they have zero mean and unit standard deviation). Another
transformer could for example threshold values in a dataset so that
values outside a given range are truncated. Yet another transformer
could act as a data augmentation routine, generating multiple
different images from each source datapoint (a transformation need
not necessarily be one to one).
Transformers are designed to be chained, since data pipelines often
chain multiple different transformations to a dataset. Transformers
are also designed to be scalable and can be applied to
large `dc.data.Dataset` objects. Not that Transformers are not
usually thread-safe so you will have to be careful in processing
very large datasets.
This class is an abstract superclass that isn't meant to be directly
instantiated. Instead, you will want to instantiate one of the
subclasses of this class inorder to perform concrete
transformations.
"""
# Hack to allow for easy unpickling:
# http://stefaanlippens.net/pickleproblem
__module__ = os.path.splitext(os.path.basename(__file__))[0]
def __init__(self,
transform_X: bool = False,
transform_y: bool = False,
transform_w: bool = False,
transform_ids: bool = False,
dataset: Optional[Dataset] = None):
"""Initializes transformation based on dataset statistics.
Parameters
----------
transform_X: bool, optional (default False)
Whether to transform X
transform_y: bool, optional (default False)
Whether to transform y
transform_w: bool, optional (default False)
Whether to transform w
transform_ids: bool, optional (default False)
Whether to transform ids
dataset: dc.data.Dataset object, optional (default None)
Dataset to be transformed
"""
if self.__class__.__name__ == "Transformer":
raise ValueError(
"Transformer is an abstract superclass and cannot be directly instantiated. You probably want to instantiate a concrete subclass instead."
)
self.transform_X = transform_X
self.transform_y = transform_y
self.transform_w = transform_w
self.transform_ids = transform_ids
# Some transformation must happen
assert transform_X or transform_y or transform_w or transform_ids
def transform_array(
self, X: np.ndarray, y: np.ndarray, w: np.ndarray,
ids: np.ndarray) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
"""Transform the data in a set of (X, y, w, ids) arrays.
Parameters
----------
X: np.ndarray
Array of features
y: np.ndarray
Array of labels
w: np.ndarray
Array of weights.
ids: np.ndarray
Array of identifiers.
Returns
-------
Xtrans: np.ndarray
Transformed array of features
ytrans: np.ndarray
Transformed array of labels
wtrans: np.ndarray
Transformed array of weights
idstrans: np.ndarray
Transformed array of ids
"""
raise NotImplementedError(
"Each Transformer is responsible for its own transform_array method.")
def untransform(self, transformed):
"""Reverses stored transformation on provided data.
Depending on whether `transform_X` or `transform_y` or `transform_w` was
set, this will perform different un-transformations. Note that this method
may not always be defined since some transformations aren't 1-1.
Parameters
----------
transformed: np.ndarray
Array which was previously transformed by this class.
"""
raise NotImplementedError(
"Each Transformer is responsible for its own untransform method.")
def transform(self,
dataset: Dataset,
parallel: bool = False,
out_dir: Optional[str] = None,
**kwargs) -> Dataset:
"""Transforms all internally stored data in dataset.
This method transforms all internal data in the provided dataset by using
the `Dataset.transform` method. Note that this method adds X-transform,
y-transform columns to metadata. Specified keyword arguments are passed on
to `Dataset.transform`.
Parameters
----------
dataset: dc.data.Dataset
Dataset object to be transformed.
parallel: bool, optional (default False)
if True, use multiple processes to transform the dataset in parallel.
For large datasets, this might be faster.
out_dir: str, optional
If `out_dir` is specified in `kwargs` and `dataset` is a `DiskDataset`,
the output dataset will be written to the specified directory.
Returns
-------
Dataset
A newly transformed Dataset object
"""
# Add this case in to handle non-DiskDataset that should be written to disk
if out_dir is not None:
if not isinstance(dataset, dc.data.DiskDataset):
dataset = dc.data.DiskDataset.from_numpy(dataset.X, dataset.y,
dataset.w, dataset.ids)
_, y_shape, w_shape, _ = dataset.get_shape()
if y_shape == tuple() and self.transform_y:
raise ValueError("Cannot transform y when y_values are not present")
if w_shape == tuple() and self.transform_w:
raise ValueError("Cannot transform w when w_values are not present")
return dataset.transform(self, out_dir=out_dir, parallel=parallel)
def transform_on_array(
self, X: np.ndarray, y: np.ndarray, w: np.ndarray,
ids: np.ndarray) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
"""Transforms numpy arrays X, y, and w
DEPRECATED. Use `transform_array` instead.
Parameters
----------
X: np.ndarray
Array of features
y: np.ndarray
Array of labels
w: np.ndarray
Array of weights.
ids: np.ndarray
Array of identifiers.
Returns
-------
Xtrans: np.ndarray
Transformed array of features
ytrans: np.ndarray
Transformed array of labels
wtrans: np.ndarray
Transformed array of weights
idstrans: np.ndarray
Transformed array of ids
"""
warnings.warn(
"transform_on_array() is deprecated and has been renamed to transform_array()."
"transform_on_array() will be removed in DeepChem 3.0", FutureWarning)
X, y, w, ids = self.transform_array(X, y, w, ids)
return X, y, w, ids
def undo_transforms(y: np.ndarray,
transformers: List[Transformer]) -> np.ndarray:
"""Undoes all transformations applied.
Transformations are reversed using `transformer.untransform`.
Transformations will be assumed to have been applied in the order specified,
so transformations will be reversed in the opposite order. That is if
`transformers = [t1, t2]`, then this method will do `t2.untransform`
followed by `t1.untransform`.
Parameters
----------
y: np.ndarray
Array of values for which transformations have to be undone.
transformers: list[dc.trans.Transformer]
List of transformations which have already been applied to `y` in the
order specifed.
Returns
-------
y_out: np.ndarray
The array with all transformations reversed.
"""
# Note that transformers have to be undone in reversed order
for transformer in reversed(transformers):
if transformer.transform_y:
y = transformer.untransform(y)
return y
class MinMaxTransformer(Transformer):
"""Ensure each value rests between 0 and 1 by using the min and max.
`MinMaxTransformer` transforms the dataset by shifting each axis of X or y
(depending on whether transform_X or transform_y is True), except the first
one by the minimum value along the axis and dividing the result by the range
(maximum value - minimum value) along the axis. This ensures each axis is
between 0 and 1. In case of multi-task learning, it ensures each task is
given equal importance.
Given original array A, the transformed array can be written as:
>>> import numpy as np
>>> A = np.random.rand(10, 10)
>>> A_min = np.min(A, axis=0)
>>> A_max = np.max(A, axis=0)
>>> A_t = np.nan_to_num((A - A_min)/(A_max - A_min))
Examples
--------
>>> n_samples = 10
>>> n_features = 3
>>> n_tasks = 1
>>> ids = np.arange(n_samples)
>>> X = np.random.rand(n_samples, n_features)
>>> y = np.random.rand(n_samples, n_tasks)
>>> w = np.ones((n_samples, n_tasks))
>>> dataset = dc.data.NumpyDataset(X, y, w, ids)
>>> transformer = dc.trans.MinMaxTransformer(transform_y=True, dataset=dataset)
>>> dataset = transformer.transform(dataset)
Note
----
This class can only transform `X` or `y` and not `w`. So only one of
`transform_X` or `transform_y` can be set.
Raises
------
ValueError
if `transform_X` and `transform_y` are both set.
"""
def __init__(self,
transform_X: bool = False,
transform_y: bool = False,
dataset: Optional[Dataset] = None):
"""Initialization of MinMax transformer.
Parameters
----------
transform_X: bool, optional (default False)
Whether to transform X
transform_y: bool, optional (default False)
Whether to transform y
dataset: dc.data.Dataset object, optional (default None)
Dataset to be transformed
"""
if transform_X and transform_y:
raise ValueError("Can only transform only one of X and y")
if dataset is not None and transform_X:
self.X_min = np.min(dataset.X, axis=0)
self.X_max = np.max(dataset.X, axis=0)
elif dataset is not None and transform_y:
self.y_min = np.min(dataset.y, axis=0)
self.y_max = np.max(dataset.y, axis=0)
if len(dataset.y.shape) > 1:
assert len(self.y_min) == dataset.y.shape[1]
super(MinMaxTransformer, self).__init__(
transform_X=transform_X, transform_y=transform_y, dataset=dataset)
def transform_array(
self, X: np.ndarray, y: np.ndarray, w: np.ndarray,
ids: np.ndarray) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
"""Transform the data in a set of (X, y, w, ids) arrays.
Parameters
----------
X: np.ndarray
Array of features
y: np.ndarray
Array of labels
w: np.ndarray
Array of weights.
ids: np.ndarray
Array of ids.
Returns
-------
Xtrans: np.ndarray
Transformed array of features
ytrans: np.ndarray
Transformed array of labels
wtrans: np.ndarray
Transformed array of weights
idstrans: np.ndarray
Transformed array of ids
"""
if self.transform_X:
# Handle division by zero
denominator = np.where((self.X_max - self.X_min) > 0,
(self.X_max - self.X_min),
np.ones_like(self.X_max - self.X_min))
X = np.nan_to_num((X - self.X_min) / denominator)
elif self.transform_y:
# Handle division by zero
denominator = np.where((self.y_max - self.y_min) > 0,
(self.y_max - self.y_min),
np.ones_like(self.y_max - self.y_min))
y = np.nan_to_num((y - self.y_min) / denominator)
return (X, y, w, ids)
def untransform(self, z: np.ndarray) -> np.ndarray:
"""
Undo transformation on provided data.
Parameters
----------
z: np.ndarray
Transformed X or y array
Returns
-------
np.ndarray
Array with min-max scaling undone.
"""
if self.transform_X:
X_max = self.X_max
X_min = self.X_min
return z * (X_max - X_min) + X_min
elif self.transform_y:
y_min = self.y_min
y_max = self.y_max
n_tasks = len(y_min)
z_shape = list(z.shape)
z_shape.reverse()
for dim in z_shape:
if dim != n_tasks and dim == 1:
y_min = np.expand_dims(y_min, -1)
y_max = np.expand_dims(y_max, -1)
y = z * (y_max - y_min) + y_min
return y
else:
return z
class NormalizationTransformer(Transformer):
"""Normalizes dataset to have zero mean and unit standard deviation
This transformer transforms datasets to have zero mean and unit standard
deviation.
Examples
--------
>>> n_samples = 10
>>> n_features = 3
>>> n_tasks = 1
>>> ids = np.arange(n_samples)
>>> X = np.random.rand(n_samples, n_features)
>>> y = np.random.rand(n_samples, n_tasks)
>>> w = np.ones((n_samples, n_tasks))
>>> dataset = dc.data.NumpyDataset(X, y, w, ids)
>>> transformer = dc.trans.NormalizationTransformer(transform_y=True, dataset=dataset)
>>> dataset = transformer.transform(dataset)
Note
----
This class can only transform `X` or `y` and not `w`. So only one of
`transform_X` or `transform_y` can be set.
Raises
------
ValueError
if `transform_X` and `transform_y` are both set.
"""
def __init__(self,
transform_X: bool = False,
transform_y: bool = False,
transform_w: bool = False,
dataset: Optional[Dataset] = None,
transform_gradients: bool = False,
move_mean: bool = True):
"""Initialize normalization transformation.
Parameters
----------
transform_X: bool, optional (default False)
Whether to transform X
transform_y: bool, optional (default False)
Whether to transform y
transform_w: bool, optional (default False)
Whether to transform w
dataset: dc.data.Dataset object, optional (default None)
Dataset to be transformed
"""
if transform_X and transform_y:
raise ValueError("Can only transform only one of X and y")
if transform_w:
raise ValueError("MinMaxTransformer doesn't support w transformation.")
if dataset is not None and transform_X:
X_means, X_stds = dataset.get_statistics(X_stats=True, y_stats=False)
self.X_means = X_means
self.X_stds = X_stds
elif dataset is not None and transform_y:
y_means, y_stds = dataset.get_statistics(X_stats=False, y_stats=True)
self.y_means = y_means
# Control for pathological case with no variance.
y_stds_np = np.array(y_stds)
y_stds_np[y_stds_np == 0] = 1.
self.y_stds = y_stds_np
self.transform_gradients = transform_gradients
self.move_mean = move_mean
if self.transform_gradients:
true_grad, ydely_means = get_grad_statistics(dataset)
self.grad = np.reshape(true_grad, (true_grad.shape[0], -1, 3))
self.ydely_means = ydely_means
super(NormalizationTransformer, self).__init__(
transform_X=transform_X,
transform_y=transform_y,
transform_w=transform_w,
dataset=dataset)
def transform_array(
self, X: np.ndarray, y: np.ndarray, w: np.ndarray,
ids: np.ndarray) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
"""Transform the data in a set of (X, y, w) arrays.
Parameters
----------
X: np.ndarray
Array of features
y: np.ndarray
Array of labels
w: np.ndarray
Array of weights.
ids: np.ndarray
Array of ids.
Returns
-------
Xtrans: np.ndarray
Transformed array of features
ytrans: np.ndarray
Transformed array of labels
wtrans: np.ndarray
Transformed array of weights
idstrans: np.ndarray
Transformed array of ids
"""
if self.transform_X:
if not hasattr(self, 'move_mean') or self.move_mean:
X = np.nan_to_num((X - self.X_means) / self.X_stds)
else:
X = np.nan_to_num(X / self.X_stds)
if self.transform_y:
if not hasattr(self, 'move_mean') or self.move_mean:
y = np.nan_to_num((y - self.y_means) / self.y_stds)
else:
y = np.nan_to_num(y / self.y_stds)
return (X, y, w, ids)
def untransform(self, z: np.ndarray) -> np.ndarray:
"""
Undo transformation on provided data.
Parameters
----------
z: np.ndarray
Array to transform back
Returns
-------
z_out: np.ndarray
Array with normalization undone.
"""
if self.transform_X:
if not hasattr(self, 'move_mean') or self.move_mean:
return z * self.X_stds + self.X_means
else:
return z * self.X_stds
elif self.transform_y:
y_stds = self.y_stds
y_means = self.y_means
# Handle case with 1 task correctly
if len(self.y_stds.shape) == 0:
n_tasks = 1
else:
n_tasks = self.y_stds.shape[0]
z_shape = list(z.shape)
# Get the reversed shape of z: (..., n_tasks, batch_size)
z_shape.reverse()
# Find the task dimension of z
for dim in z_shape:
if dim != n_tasks and dim == 1:
# Prevent broadcasting on wrong dimension
y_stds = np.expand_dims(y_stds, -1)
y_means = np.expand_dims(y_means, -1)
if not hasattr(self, 'move_mean') or self.move_mean:
return z * y_stds + y_means
else:
return z * y_stds
else:
return z
def untransform_grad(self, grad, tasks):
"""DEPRECATED. DO NOT USE."""
logger.warning(
"NormalizationTransformer.untransform_grad is DEPRECATED and will be removed in a future version of DeepChem. "
"Manually implement transforms to perform force calculations.")
if self.transform_y:
grad_means = self.y_means[1:]
energy_var = self.y_stds[0]
grad_var = 1 / energy_var * (
self.ydely_means - self.y_means[0] * self.y_means[1:])
energy = tasks[:, 0]
transformed_grad = []
for i in range(energy.size):
Etf = energy[i]
grad_Etf = grad[i].flatten()
grad_E = Etf * grad_var + energy_var * grad_Etf + grad_means
grad_E = np.reshape(grad_E, (-1, 3))
transformed_grad.append(grad_E)
transformed_grad = np.asarray(transformed_grad)
return transformed_grad
class ClippingTransformer(Transformer):
"""Clip large values in datasets.
Examples
--------
Let's clip values from a synthetic dataset
>>> n_samples = 10
>>> n_features = 3
>>> n_tasks = 1
>>> ids = np.arange(n_samples)
>>> X = np.random.rand(n_samples, n_features)
>>> y = np.zeros((n_samples, n_tasks))
>>> w = np.ones((n_samples, n_tasks))
>>> dataset = dc.data.NumpyDataset(X, y, w, ids)
>>> transformer = dc.trans.ClippingTransformer(transform_X=True)
>>> dataset = transformer.transform(dataset)
"""
def __init__(self,
transform_X: bool = False,
transform_y: bool = False,
dataset: Optional[Dataset] = None,
x_max: float = 5.,
y_max: float = 500.):
"""Initialize clipping transformation.
Parameters
----------
transform_X: bool, optional (default False)
Whether to transform X
transform_y: bool, optional (default False)
Whether to transform y
dataset: dc.data.Dataset object, optional
Dataset to be transformed
x_max: float, optional
Maximum absolute value for X
y_max: float, optional
Maximum absolute value for y
Note
----
This transformer can transform `X` and `y` jointly, but does not transform
`w`.
Raises
------
ValueError
if `transform_w` is set.
"""
super(ClippingTransformer, self).__init__(
transform_X=transform_X, transform_y=transform_y, dataset=dataset)
self.x_max = x_max
self.y_max = y_max
def transform_array(
self, X: np.ndarray, y: np.ndarray, w: np.ndarray,
ids: np.ndarray) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
"""Transform the data in a set of (X, y, w) arrays.
Parameters
----------
X: np.ndarray
Array of Features
y: np.ndarray
Array of labels
w: np.ndarray
Array of weights
ids: np.ndarray
Array of ids.
Returns
-------
X: np.ndarray
Transformed features
y: np.ndarray
Transformed tasks
w: np.ndarray
Transformed weights
idstrans: np.ndarray
Transformed array of ids
"""
if self.transform_X:
X[X > self.x_max] = self.x_max
X[X < (-1.0 * self.x_max)] = -1.0 * self.x_max
if self.transform_y:
y[y > self.y_max] = self.y_max
y[y < (-1.0 * self.y_max)] = -1.0 * self.y_max
return (X, y, w, ids)
def untransform(self, z):
"""Not implemented."""
raise NotImplementedError(
"Cannot untransform datasets with ClippingTransformer.")
class LogTransformer(Transformer):
"""Computes a logarithmic transformation
This transformer computes the transformation given by
>>> import numpy as np
>>> A = np.random.rand(10, 10)
>>> A = np.log(A + 1)
Assuming that tasks/features are not specified. If specified, then
transformations are only performed on specified tasks/features.
Examples
--------
>>> n_samples = 10
>>> n_features = 3
>>> n_tasks = 1
>>> ids = np.arange(n_samples)
>>> X = np.random.rand(n_samples, n_features)
>>> y = np.zeros((n_samples, n_tasks))
>>> w = np.ones((n_samples, n_tasks))
>>> dataset = dc.data.NumpyDataset(X, y, w, ids)
>>> transformer = dc.trans.LogTransformer(transform_X=True)
>>> dataset = transformer.transform(dataset)
Note
----
This class can only transform `X` or `y` and not `w`. So only one of
`transform_X` or `transform_y` can be set.
Raises
------
ValueError
if `transform_w` is set or `transform_X` and `transform_y` are both set.
"""
def __init__(self,
transform_X: bool = False,
transform_y: bool = False,
features: Optional[List[int]] = None,
tasks: Optional[List[str]] = None,
dataset: Optional[Dataset] = None):
"""Initialize log transformer.
Parameters
----------
transform_X: bool, optional (default False)
Whether to transform X
transform_y: bool, optional (default False)
Whether to transform y
features: list[Int]
List of features indices to transform
tasks: list[str]
List of task names to transform.
dataset: dc.data.Dataset object, optional (default None)
Dataset to be transformed
"""
if transform_X and transform_y:
raise ValueError("Can only transform only one of X and y")
self.features = features
self.tasks = tasks
super(LogTransformer, self).__init__(
transform_X=transform_X, transform_y=transform_y, dataset=dataset)
def transform_array(
self, X: np.ndarray, y: np.ndarray, w: np.ndarray,
ids: np.ndarray) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
"""Transform the data in a set of (X, y, w) arrays.
Parameters
----------
X: np.ndarray
Array of features
y: np.ndarray
Array of labels
w: np.ndarray
Array of weights.
ids: np.ndarray
Array of weights.
Returns
-------
Xtrans: np.ndarray
Transformed array of features
ytrans: np.ndarray
Transformed array of labels
wtrans: np.ndarray
Transformed array of weights
idstrans: np.ndarray
Transformed array of ids
"""
if self.transform_X:
num_features = len(X[0])
if self.features is None:
X = np.log(X + 1)
else:
for j in range(num_features):
if j in self.features:
X[:, j] = np.log(X[:, j] + 1)
else:
X[:, j] = X[:, j]
if self.transform_y:
num_tasks = len(y[0])
if self.tasks is None:
y = np.log(y + 1)
else:
for j in range(num_tasks):
if j in self.tasks:
y[:, j] = np.log(y[:, j] + 1)
else:
y[:, j] = y[:, j]
return (X, y, w, ids)
def untransform(self, z: np.ndarray) -> np.ndarray:
"""
Undo transformation on provided data.
Parameters
----------
z: np.ndarray,
Transformed X or y array
Returns
-------
np.ndarray
Array with a logarithmic transformation undone.
"""
if self.transform_X:
num_features = len(z[0])
if self.features is None:
return np.exp(z) - 1
else:
for j in range(num_features):
if j in self.features:
z[:, j] = np.exp(z[:, j]) - 1
else:
z[:, j] = z[:, j]
return z
elif self.transform_y:
num_tasks = len(z[0])
if self.tasks is None:
return np.exp(z) - 1
else:
for j in range(num_tasks):
if j in self.tasks:
z[:, j] = np.exp(z[:, j]) - 1
else:
z[:, j] = z[:, j]
return z
else:
return z
class BalancingTransformer(Transformer):
"""Balance positive and negative (or multiclass) example weights.
This class balances the sample weights so that the sum of all example
weights from all classes is the same. This can be useful when you're
working on an imbalanced dataset where there are far fewer examples of some
classes than others.
Examples
--------
Here's an example for a binary dataset.
>>> n_samples = 10
>>> n_features = 3
>>> n_tasks = 1
>>> n_classes = 2
>>> ids = np.arange(n_samples)
>>> X = np.random.rand(n_samples, n_features)
>>> y = np.random.randint(n_classes, size=(n_samples, n_tasks))
>>> w = np.ones((n_samples, n_tasks))
>>> dataset = dc.data.NumpyDataset(X, y, w, ids)
>>> transformer = dc.trans.BalancingTransformer(dataset=dataset)
>>> dataset = transformer.transform(dataset)
And here's a multiclass dataset example.
>>> n_samples = 50
>>> n_features = 3
>>> n_tasks = 1
>>> n_classes = 5
>>> ids = np.arange(n_samples)
>>> X = np.random.rand(n_samples, n_features)
>>> y = np.random.randint(n_classes, size=(n_samples, n_tasks))
>>> w = np.ones((n_samples, n_tasks))
>>> dataset = dc.data.NumpyDataset(X, y, w, ids)
>>> transformer = dc.trans.BalancingTransformer(dataset=dataset)
>>> dataset = transformer.transform(dataset)
See Also
--------
deepchem.trans.DuplicateBalancingTransformer: Balance by duplicating samples.
Note
----
This transformer is only meaningful for classification datasets where `y`
takes on a limited set of values. This class can only transform `w` and does
not transform `X` or `y`.
Raises
------
ValueError
if `transform_X` or `transform_y` are set. Also raises or if `y` or `w` aren't of shape `(N,)` or `(N, n_tasks)`.
"""
def __init__(self, dataset: Dataset):
# BalancingTransformer can only transform weights.
super(BalancingTransformer, self).__init__(
transform_w=True, dataset=dataset)
# Compute weighting factors from dataset.
y = dataset.y
w = dataset.w
# Handle 1-D case
if len(y.shape) == 1:
y = np.reshape(y, (len(y), 1))
if len(w.shape) == 1:
w = np.reshape(w, (len(w), 1))
if len(y.shape) != 2:
raise ValueError("y must be of shape (N,) or (N, n_tasks)")
if len(w.shape) != 2:
raise ValueError("w must be of shape (N,) or (N, n_tasks)")
self.classes = sorted(np.unique(y))
weights = []
for ind, task in enumerate(dataset.get_task_names()):
task_w = w[:, ind]
task_y = y[:, ind]
# Remove labels with zero weights
task_y = task_y[task_w != 0]
N_task = len(task_y)
class_counts = []
# Note that we may have 0 elements of a given class since we remove those
# labels with zero weight. This typically happens in multitask datasets
# where some datapoints only have labels for some tasks.
for c in self.classes:
# this works because task_y is 1D
num_c = len(np.where(task_y == c)[0])
class_counts.append(num_c)
# This is the right ratio since N_task/num_c * num_c = N_task
# for all classes
class_weights = [
N_task / float(num_c) if num_c > 0 else 0 for num_c in class_counts
]
weights.append(class_weights)
self.weights = weights
def transform_array(
self, X: np.ndarray, y: np.ndarray, w: np.ndarray,
ids: np.ndarray) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
"""Transform the data in a set of (X, y, w) arrays.
Parameters
----------
X: np.ndarray
Array of features
y: np.ndarray
Array of labels
w: np.ndarray
Array of weights.
ids: np.ndarray
Array of weights.
Returns
-------
Xtrans: np.ndarray
Transformed array of features
ytrans: np.ndarray
Transformed array of labels
wtrans: np.ndarray
Transformed array of weights
idstrans: np.ndarray
Transformed array of ids
"""
w_balanced = np.zeros_like(w)
if len(y.shape) == 1 and len(w.shape) == 2 and w.shape[1] == 1:
y = np.expand_dims(y, 1)
if len(y.shape) == 1:
n_tasks = 1
elif len(y.shape) == 2:
n_tasks = y.shape[1]
else:
raise ValueError("y must be of shape (N,) or (N, n_tasks)")
for ind in range(n_tasks):
if n_tasks == 1:
task_y = y
task_w = w
else:
task_y = y[:, ind]
task_w = w[:, ind]
for i, c in enumerate(self.classes):