/
layers.py
3407 lines (2860 loc) · 113 KB
/
layers.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
# -*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
try:
from collections.abc import Sequence as SequenceCollection
except:
from collections import Sequence as SequenceCollection
from typing import Callable, Dict, List
from tensorflow.keras import activations, initializers, backend
from tensorflow.keras.layers import Dropout, BatchNormalization
class InteratomicL2Distances(tf.keras.layers.Layer):
"""Compute (squared) L2 Distances between atoms given neighbors.
This class computes pairwise distances between its inputs.
Examples
--------
>>> import numpy as np
>>> import deepchem as dc
>>> atoms = 5
>>> neighbors = 2
>>> coords = np.random.rand(atoms, 3)
>>> neighbor_list = np.random.randint(0, atoms, size=(atoms, neighbors))
>>> layer = InteratomicL2Distances(atoms, neighbors, 3)
>>> result = np.array(layer([coords, neighbor_list]))
>>> result.shape
(5, 2)
"""
def __init__(self, N_atoms: int, M_nbrs: int, ndim: int, **kwargs):
"""Constructor for this layer.
Parameters
----------
N_atoms: int
Number of atoms in the system total.
M_nbrs: int
Number of neighbors to consider when computing distances.
n_dim: int
Number of descriptors for each atom.
"""
super(InteratomicL2Distances, self).__init__(**kwargs)
self.N_atoms = N_atoms
self.M_nbrs = M_nbrs
self.ndim = ndim
def get_config(self) -> Dict:
"""Returns config dictionary for this layer."""
config = super(InteratomicL2Distances, self).get_config()
config['N_atoms'] = self.N_atoms
config['M_nbrs'] = self.M_nbrs
config['ndim'] = self.ndim
return config
def call(self, inputs):
"""Invokes this layer.
Parameters
----------
inputs: list
Should be of form `inputs=[coords, nbr_list]` where `coords` is a
tensor of shape `(None, N, 3)` and `nbr_list` is a list.
Returns
-------
Tensor of shape `(N_atoms, M_nbrs)` with interatomic distances.
"""
if len(inputs) != 2:
raise ValueError("InteratomicDistances requires coords,nbr_list")
coords, nbr_list = (inputs[0], inputs[1])
N_atoms, M_nbrs, ndim = self.N_atoms, self.M_nbrs, self.ndim
# Shape (N_atoms, M_nbrs, ndim)
nbr_coords = tf.gather(coords, nbr_list)
# Shape (N_atoms, M_nbrs, ndim)
tiled_coords = tf.tile(
tf.reshape(coords, (N_atoms, 1, ndim)), (1, M_nbrs, 1))
# Shape (N_atoms, M_nbrs)
return tf.reduce_sum((tiled_coords - nbr_coords)**2, axis=2)
class GraphConv(tf.keras.layers.Layer):
"""Graph Convolutional Layers
This layer implements the graph convolution introduced in [1]_. The graph
convolution combines per-node feature vectures in a nonlinear fashion with
the feature vectors for neighboring nodes. This "blends" information in
local neighborhoods of a graph.
References
----------
.. [1] Duvenaud, David K., et al. "Convolutional networks on graphs for learning molecular fingerprints." Advances in neural information processing systems. 2015. https://arxiv.org/abs/1509.09292
"""
def __init__(self,
out_channel: int,
min_deg: int = 0,
max_deg: int = 10,
activation_fn: Callable = None,
**kwargs):
"""Initialize a graph convolutional layer.
Parameters
----------
out_channel: int
The number of output channels per graph node.
min_deg: int, optional (default 0)
The minimum allowed degree for each graph node.
max_deg: int, optional (default 10)
The maximum allowed degree for each graph node. Note that this
is set to 10 to handle complex molecules (some organometallic
compounds have strange structures). If you're using this for
non-molecular applications, you may need to set this much higher
depending on your dataset.
activation_fn: function
A nonlinear activation function to apply. If you're not sure,
`tf.nn.relu` is probably a good default for your application.
"""
super(GraphConv, self).__init__(**kwargs)
self.out_channel = out_channel
self.min_degree = min_deg
self.max_degree = max_deg
self.activation_fn = activation_fn
def build(self, input_shape):
# Generate the nb_affine weights and biases
num_deg = 2 * self.max_degree + (1 - self.min_degree)
self.W_list = [
self.add_weight(
name='kernel' + str(k),
shape=(int(input_shape[0][-1]), self.out_channel),
initializer='glorot_uniform',
trainable=True) for k in range(num_deg)
]
self.b_list = [
self.add_weight(
name='bias' + str(k),
shape=(self.out_channel,),
initializer='zeros',
trainable=True) for k in range(num_deg)
]
self.built = True
def get_config(self):
config = super(GraphConv, self).get_config()
config['out_channel'] = self.out_channel
config['min_deg'] = self.min_degree
config['max_deg'] = self.max_degree
config['activation_fn'] = self.activation_fn
return config
def call(self, inputs):
# Extract atom_features
atom_features = inputs[0]
# Extract graph topology
deg_slice = inputs[1]
deg_adj_lists = inputs[3:]
W = iter(self.W_list)
b = iter(self.b_list)
# Sum all neighbors using adjacency matrix
deg_summed = self.sum_neigh(atom_features, deg_adj_lists)
# Get collection of modified atom features
new_rel_atoms_collection = (self.max_degree + 1 - self.min_degree) * [None]
split_features = tf.split(atom_features, deg_slice[:, 1])
for deg in range(1, self.max_degree + 1):
# Obtain relevant atoms for this degree
rel_atoms = deg_summed[deg - 1]
# Get self atoms
self_atoms = split_features[deg - self.min_degree]
# Apply hidden affine to relevant atoms and append
rel_out = tf.matmul(rel_atoms, next(W)) + next(b)
self_out = tf.matmul(self_atoms, next(W)) + next(b)
out = rel_out + self_out
new_rel_atoms_collection[deg - self.min_degree] = out
# Determine the min_deg=0 case
if self.min_degree == 0:
self_atoms = split_features[0]
# Only use the self layer
out = tf.matmul(self_atoms, next(W)) + next(b)
new_rel_atoms_collection[0] = out
# Combine all atoms back into the list
atom_features = tf.concat(axis=0, values=new_rel_atoms_collection)
if self.activation_fn is not None:
atom_features = self.activation_fn(atom_features)
return atom_features
def sum_neigh(self, atoms, deg_adj_lists):
"""Store the summed atoms by degree"""
deg_summed = self.max_degree * [None]
# Tensorflow correctly processes empty lists when using concat
for deg in range(1, self.max_degree + 1):
gathered_atoms = tf.gather(atoms, deg_adj_lists[deg - 1])
# Sum along neighbors as well as self, and store
summed_atoms = tf.reduce_sum(gathered_atoms, 1)
deg_summed[deg - 1] = summed_atoms
return deg_summed
class GraphPool(tf.keras.layers.Layer):
"""A GraphPool gathers data from local neighborhoods of a graph.
This layer does a max-pooling over the feature vectors of atoms in a
neighborhood. You can think of this layer as analogous to a max-pooling
layer for 2D convolutions but which operates on graphs instead. This
technique is described in [1]_.
References
----------
.. [1] Duvenaud, David K., et al. "Convolutional networks on graphs for
learning molecular fingerprints." Advances in neural information processing
systems. 2015. https://arxiv.org/abs/1509.09292
"""
def __init__(self, min_degree=0, max_degree=10, **kwargs):
"""Initialize this layer
Parameters
----------
min_deg: int, optional (default 0)
The minimum allowed degree for each graph node.
max_deg: int, optional (default 10)
The maximum allowed degree for each graph node. Note that this
is set to 10 to handle complex molecules (some organometallic
compounds have strange structures). If you're using this for
non-molecular applications, you may need to set this much higher
depending on your dataset.
"""
super(GraphPool, self).__init__(**kwargs)
self.min_degree = min_degree
self.max_degree = max_degree
def get_config(self):
config = super(GraphPool, self).get_config()
config['min_degree'] = self.min_degree
config['max_degree'] = self.max_degree
return config
def call(self, inputs):
atom_features = inputs[0]
deg_slice = inputs[1]
deg_adj_lists = inputs[3:]
# Perform the mol gather
# atom_features = graph_pool(atom_features, deg_adj_lists, deg_slice,
# self.max_degree, self.min_degree)
deg_maxed = (self.max_degree + 1 - self.min_degree) * [None]
# Tensorflow correctly processes empty lists when using concat
split_features = tf.split(atom_features, deg_slice[:, 1])
for deg in range(1, self.max_degree + 1):
# Get self atoms
self_atoms = split_features[deg - self.min_degree]
if deg_adj_lists[deg - 1].shape[0] == 0:
# There are no neighbors of this degree, so just create an empty tensor directly.
maxed_atoms = tf.zeros((0, self_atoms.shape[-1]))
else:
# Expand dims
self_atoms = tf.expand_dims(self_atoms, 1)
# always deg-1 for deg_adj_lists
gathered_atoms = tf.gather(atom_features, deg_adj_lists[deg - 1])
gathered_atoms = tf.concat(axis=1, values=[self_atoms, gathered_atoms])
maxed_atoms = tf.reduce_max(gathered_atoms, 1)
deg_maxed[deg - self.min_degree] = maxed_atoms
if self.min_degree == 0:
self_atoms = split_features[0]
deg_maxed[0] = self_atoms
return tf.concat(axis=0, values=deg_maxed)
class GraphGather(tf.keras.layers.Layer):
"""A GraphGather layer pools node-level feature vectors to create a graph feature vector.
Many graph convolutional networks manipulate feature vectors per
graph-node. For a molecule for example, each node might represent an
atom, and the network would manipulate atomic feature vectors that
summarize the local chemistry of the atom. However, at the end of
the application, we will likely want to work with a molecule level
feature representation. The `GraphGather` layer creates a graph level
feature vector by combining all the node-level feature vectors.
One subtlety about this layer is that it depends on the
`batch_size`. This is done for internal implementation reasons. The
`GraphConv`, and `GraphPool` layers pool all nodes from all graphs
in a batch that's being processed. The `GraphGather` reassembles
these jumbled node feature vectors into per-graph feature vectors.
References
----------
.. [1] Duvenaud, David K., et al. "Convolutional networks on graphs for
learning molecular fingerprints." Advances in neural information processing
systems. 2015. https://arxiv.org/abs/1509.09292
"""
def __init__(self, batch_size, activation_fn=None, **kwargs):
"""Initialize this layer.
Parameters
---------
batch_size: int
The batch size for this layer. Note that the layer's behavior
changes depending on the batch size.
activation_fn: function
A nonlinear activation function to apply. If you're not sure,
`tf.nn.relu` is probably a good default for your application.
"""
super(GraphGather, self).__init__(**kwargs)
self.batch_size = batch_size
self.activation_fn = activation_fn
def get_config(self):
config = super(GraphGather, self).get_config()
config['batch_size'] = self.batch_size
config['activation_fn'] = self.activation_fn
return config
def call(self, inputs):
"""Invoking this layer.
Parameters
----------
inputs: list
This list should consist of `inputs = [atom_features, deg_slice,
membership, deg_adj_list placeholders...]`. These are all
tensors that are created/process by `GraphConv` and `GraphPool`
"""
atom_features = inputs[0]
# Extract graph topology
membership = inputs[2]
assert self.batch_size > 1, "graph_gather requires batches larger than 1"
sparse_reps = tf.math.unsorted_segment_sum(atom_features, membership,
self.batch_size)
max_reps = tf.math.unsorted_segment_max(atom_features, membership,
self.batch_size)
mol_features = tf.concat(axis=1, values=[sparse_reps, max_reps])
if self.activation_fn is not None:
mol_features = self.activation_fn(mol_features)
return mol_features
class LSTMStep(tf.keras.layers.Layer):
"""Layer that performs a single step LSTM update.
This layer performs a single step LSTM update. Note that it is *not*
a full LSTM recurrent network. The LSTMStep layer is useful as a
primitive for designing layers such as the AttnLSTMEmbedding or the
IterRefLSTMEmbedding below.
"""
def __init__(self,
output_dim,
input_dim,
init_fn='glorot_uniform',
inner_init_fn='orthogonal',
activation_fn='tanh',
inner_activation_fn='hard_sigmoid',
**kwargs):
"""
Parameters
----------
output_dim: int
Dimensionality of output vectors.
input_dim: int
Dimensionality of input vectors.
init_fn: str
TensorFlow nitialization to use for W.
inner_init_fn: str
TensorFlow initialization to use for U.
activation_fn: str
TensorFlow activation to use for output.
inner_activation_fn: str
TensorFlow activation to use for inner steps.
"""
super(LSTMStep, self).__init__(**kwargs)
self.init = init_fn
self.inner_init = inner_init_fn
self.output_dim = output_dim
# No other forget biases supported right now.
self.activation = activation_fn
self.inner_activation = inner_activation_fn
self.activation_fn = activations.get(activation_fn)
self.inner_activation_fn = activations.get(inner_activation_fn)
self.input_dim = input_dim
def get_config(self):
config = super(LSTMStep, self).get_config()
config['output_dim'] = self.output_dim
config['input_dim'] = self.input_dim
config['init_fn'] = self.init
config['inner_init_fn'] = self.inner_init
config['activation_fn'] = self.activation
config['inner_activation_fn'] = self.inner_activation
return config
def get_initial_states(self, input_shape):
return [backend.zeros(input_shape), backend.zeros(input_shape)]
def build(self, input_shape):
"""Constructs learnable weights for this layer."""
init = initializers.get(self.init)
inner_init = initializers.get(self.inner_init)
self.W = init((self.input_dim, 4 * self.output_dim))
self.U = inner_init((self.output_dim, 4 * self.output_dim))
self.b = tf.Variable(
np.hstack((np.zeros(self.output_dim), np.ones(self.output_dim),
np.zeros(self.output_dim), np.zeros(self.output_dim))),
dtype=tf.float32)
self.built = True
def call(self, inputs):
"""Execute this layer on input tensors.
Parameters
----------
inputs: list
List of three tensors (x, h_tm1, c_tm1). h_tm1 means "h, t-1".
Returns
-------
list
Returns h, [h, c]
"""
x, h_tm1, c_tm1 = inputs
# Taken from Keras code [citation needed]
z = backend.dot(x, self.W) + backend.dot(h_tm1, self.U) + self.b
z0 = z[:, :self.output_dim]
z1 = z[:, self.output_dim:2 * self.output_dim]
z2 = z[:, 2 * self.output_dim:3 * self.output_dim]
z3 = z[:, 3 * self.output_dim:]
i = self.inner_activation_fn(z0)
f = self.inner_activation_fn(z1)
c = f * c_tm1 + i * self.activation_fn(z2)
o = self.inner_activation_fn(z3)
h = o * self.activation_fn(c)
return h, [h, c]
def cosine_dist(x, y):
"""Computes the inner product (cosine similarity) between two tensors.
This assumes that the two input tensors contain rows of vectors where
each column represents a different feature. The output tensor will have
elements that represent the inner product between pairs of normalized vectors
in the rows of `x` and `y`. The two tensors need to have the same number of
columns, because one cannot take the dot product between vectors of different
lengths. For example, in sentence similarity and sentence classification tasks,
the number of columns is the embedding size. In these tasks, the rows of the
input tensors would be different test vectors or sentences. The input tensors
themselves could be different batches. Using vectors or tensors of all 0s
should be avoided.
Methods
-------
The vectors in the input tensors are first l2-normalized such that each vector
has length or magnitude of 1. The inner product (dot product) is then taken
between corresponding pairs of row vectors in the input tensors and returned.
Examples
--------
The cosine similarity between two equivalent vectors will be 1. The cosine
similarity between two equivalent tensors (tensors where all the elements are
the same) will be a tensor of 1s. In this scenario, if the input tensors `x` and
`y` are each of shape `(n,p)`, where each element in `x` and `y` is the same, then
the output tensor would be a tensor of shape `(n,n)` with 1 in every entry.
>>> import tensorflow as tf
>>> import deepchem.models.layers as layers
>>> x = tf.ones((6, 4), dtype=tf.dtypes.float32, name=None)
>>> y_same = tf.ones((6, 4), dtype=tf.dtypes.float32, name=None)
>>> cos_sim_same = layers.cosine_dist(x,y_same)
`x` and `y_same` are the same tensor (equivalent at every element, in this
case 1). As such, the pairwise inner product of the rows in `x` and `y` will
always be 1. The output tensor will be of shape (6,6).
>>> diff = cos_sim_same - tf.ones((6, 6), dtype=tf.dtypes.float32, name=None)
>>> tf.reduce_sum(diff) == 0 # True
<tf.Tensor: shape=(), dtype=bool, numpy=True>
>>> cos_sim_same.shape
TensorShape([6, 6])
The cosine similarity between two orthogonal vectors will be 0 (by definition).
If every row in `x` is orthogonal to every row in `y`, then the output will be a
tensor of 0s. In the following example, each row in the tensor `x1` is orthogonal
to each row in `x2` because they are halves of an identity matrix.
>>> identity_tensor = tf.eye(512, dtype=tf.dtypes.float32)
>>> x1 = identity_tensor[0:256,:]
>>> x2 = identity_tensor[256:512,:]
>>> cos_sim_orth = layers.cosine_dist(x1,x2)
Each row in `x1` is orthogonal to each row in `x2`. As such, the pairwise inner
product of the rows in `x1`and `x2` will always be 0. Furthermore, because the
shape of the input tensors are both of shape `(256,512)`, the output tensor will
be of shape `(256,256)`.
>>> tf.reduce_sum(cos_sim_orth) == 0 # True
<tf.Tensor: shape=(), dtype=bool, numpy=True>
>>> cos_sim_orth.shape
TensorShape([256, 256])
Parameters
----------
x: tf.Tensor
Input Tensor of shape `(n, p)`.
The shape of this input tensor should be `n` rows by `p` columns.
Note that `n` need not equal `m` (the number of rows in `y`).
y: tf.Tensor
Input Tensor of shape `(m, p)`
The shape of this input tensor should be `m` rows by `p` columns.
Note that `m` need not equal `n` (the number of rows in `x`).
Returns
-------
tf.Tensor
Returns a tensor of shape `(n, m)`, that is, `n` rows by `m` columns.
Each `i,j`-th entry of this output tensor is the inner product between
the l2-normalized `i`-th row of the input tensor `x` and the
the l2-normalized `j`-th row of the output tensor `y`.
"""
x_norm = tf.math.l2_normalize(x, axis=1)
y_norm = tf.math.l2_normalize(y, axis=1)
return backend.dot(x_norm, tf.transpose(y_norm))
class AttnLSTMEmbedding(tf.keras.layers.Layer):
"""Implements AttnLSTM as in matching networks paper.
The AttnLSTM embedding adjusts two sets of vectors, the "test" and
"support" sets. The "support" consists of a set of evidence vectors.
Think of these as the small training set for low-data machine
learning. The "test" consists of the queries we wish to answer with
the small amounts of available data. The AttnLSTMEmbdding allows us to
modify the embedding of the "test" set depending on the contents of
the "support". The AttnLSTMEmbedding is thus a type of learnable
metric that allows a network to modify its internal notion of
distance.
See references [1]_ [2]_ for more details.
References
----------
.. [1] Vinyals, Oriol, et al. "Matching networks for one shot learning."
Advances in neural information processing systems. 2016.
.. [2] Vinyals, Oriol, Samy Bengio, and Manjunath Kudlur. "Order matters:
Sequence to sequence for sets." arXiv preprint arXiv:1511.06391 (2015).
"""
def __init__(self, n_test, n_support, n_feat, max_depth, **kwargs):
"""
Parameters
----------
n_support: int
Size of support set.
n_test: int
Size of test set.
n_feat: int
Number of features per atom
max_depth: int
Number of "processing steps" used by sequence-to-sequence for sets model.
"""
super(AttnLSTMEmbedding, self).__init__(**kwargs)
self.max_depth = max_depth
self.n_test = n_test
self.n_support = n_support
self.n_feat = n_feat
def get_config(self):
config = super(AttnLSTMEmbedding, self).get_config()
config['n_test'] = self.n_test
config['n_support'] = self.n_support
config['n_feat'] = self.n_feat
config['max_depth'] = self.max_depth
return config
def build(self, input_shape):
n_feat = self.n_feat
self.lstm = LSTMStep(n_feat, 2 * n_feat)
self.q_init = backend.zeros([self.n_test, n_feat])
self.states_init = self.lstm.get_initial_states([self.n_test, n_feat])
self.built = True
def call(self, inputs):
"""Execute this layer on input tensors.
Parameters
----------
inputs: list
List of two tensors (X, Xp). X should be of shape (n_test,
n_feat) and Xp should be of shape (n_support, n_feat) where
n_test is the size of the test set, n_support that of the support
set, and n_feat is the number of per-atom features.
Returns
-------
list
Returns two tensors of same shape as input. Namely the output
shape will be [(n_test, n_feat), (n_support, n_feat)]
"""
if len(inputs) != 2:
raise ValueError("AttnLSTMEmbedding layer must have exactly two parents")
# x is test set, xp is support set.
x, xp = inputs
# Get initializations
q = self.q_init
states = self.states_init
for d in range(self.max_depth):
# Process using attention
# Eqn (4), appendix A.1 of Matching Networks paper
e = cosine_dist(x + q, xp)
a = tf.nn.softmax(e)
r = backend.dot(a, xp)
# Generate new attention states
y = backend.concatenate([q, r], axis=1)
q, states = self.lstm([y] + states)
return [x + q, xp]
class IterRefLSTMEmbedding(tf.keras.layers.Layer):
"""Implements the Iterative Refinement LSTM.
Much like AttnLSTMEmbedding, the IterRefLSTMEmbedding is another type
of learnable metric which adjusts "test" and "support." Recall that
"support" is the small amount of data available in a low data machine
learning problem, and that "test" is the query. The AttnLSTMEmbedding
only modifies the "test" based on the contents of the support.
However, the IterRefLSTM modifies both the "support" and "test" based
on each other. This allows the learnable metric to be more malleable
than that from AttnLSTMEmbeding.
"""
def __init__(self, n_test, n_support, n_feat, max_depth, **kwargs):
"""
Unlike the AttnLSTM model which only modifies the test vectors
additively, this model allows for an additive update to be
performed to both test and support using information from each
other.
Parameters
----------
n_support: int
Size of support set.
n_test: int
Size of test set.
n_feat: int
Number of input atom features
max_depth: int
Number of LSTM Embedding layers.
"""
super(IterRefLSTMEmbedding, self).__init__(**kwargs)
self.max_depth = max_depth
self.n_test = n_test
self.n_support = n_support
self.n_feat = n_feat
def get_config(self):
config = super(IterRefLSTMEmbedding, self).get_config()
config['n_test'] = self.n_test
config['n_support'] = self.n_support
config['n_feat'] = self.n_feat
config['max_depth'] = self.max_depth
return config
def build(self, input_shape):
n_feat = self.n_feat
# Support set lstm
self.support_lstm = LSTMStep(n_feat, 2 * n_feat)
self.q_init = backend.zeros([self.n_support, n_feat])
self.support_states_init = self.support_lstm.get_initial_states(
[self.n_support, n_feat])
# Test lstm
self.test_lstm = LSTMStep(n_feat, 2 * n_feat)
self.p_init = backend.zeros([self.n_test, n_feat])
self.test_states_init = self.test_lstm.get_initial_states(
[self.n_test, n_feat])
self.built = True
def call(self, inputs):
"""Execute this layer on input tensors.
Parameters
----------
inputs: list
List of two tensors (X, Xp). X should be of shape (n_test,
n_feat) and Xp should be of shape (n_support, n_feat) where
n_test is the size of the test set, n_support that of the
support set, and n_feat is the number of per-atom features.
Returns
-------
Returns two tensors of same shape as input. Namely the output
shape will be [(n_test, n_feat), (n_support, n_feat)]
"""
if len(inputs) != 2:
raise ValueError(
"IterRefLSTMEmbedding layer must have exactly two parents")
x, xp = inputs
# Get initializations
p = self.p_init
q = self.q_init
# Rename support
z = xp
states = self.support_states_init
x_states = self.test_states_init
for d in range(self.max_depth):
# Process support xp using attention
e = cosine_dist(z + q, xp)
a = tf.nn.softmax(e)
# Get linear combination of support set
r = backend.dot(a, xp)
# Process test x using attention
x_e = cosine_dist(x + p, z)
x_a = tf.nn.softmax(x_e)
s = backend.dot(x_a, z)
# Generate new support attention states
qr = backend.concatenate([q, r], axis=1)
q, states = self.support_lstm([qr] + states)
# Generate new test attention states
ps = backend.concatenate([p, s], axis=1)
p, x_states = self.test_lstm([ps] + x_states)
# Redefine
z = r
return [x + p, xp + q]
class SwitchedDropout(tf.keras.layers.Layer):
"""Apply dropout based on an input.
This is required for uncertainty prediction. The standard Keras
Dropout layer only performs dropout during training, but we
sometimes need to do it during prediction. The second input to this
layer should be a scalar equal to 0 or 1, indicating whether to
perform dropout.
"""
def __init__(self, rate, **kwargs):
self.rate = rate
super(SwitchedDropout, self).__init__(**kwargs)
def get_config(self):
config = super(SwitchedDropout, self).get_config()
config['rate'] = self.rate
return config
def call(self, inputs):
rate = self.rate * tf.squeeze(inputs[1])
return tf.nn.dropout(inputs[0], rate=rate)
class WeightedLinearCombo(tf.keras.layers.Layer):
"""Computes a weighted linear combination of input layers, with the weights defined by trainable variables."""
def __init__(self, std=0.3, **kwargs):
"""Initialize this layer.
Parameters
----------
std: float, optional (default 0.3)
The standard deviation to use when randomly initializing weights.
"""
super(WeightedLinearCombo, self).__init__(**kwargs)
self.std = std
def get_config(self):
config = super(WeightedLinearCombo, self).get_config()
config['std'] = self.std
return config
def build(self, input_shape):
init = tf.keras.initializers.RandomNormal(stddev=self.std)
self.input_weights = [
self.add_weight(
'weight_%d' % (i + 1), (1,), initializer=init, trainable=True)
for i in range(len(input_shape))
]
self.built = True
def call(self, inputs):
out_tensor = None
for in_tensor, w in zip(inputs, self.input_weights):
if out_tensor is None:
out_tensor = w * in_tensor
else:
out_tensor += w * in_tensor
return out_tensor
class CombineMeanStd(tf.keras.layers.Layer):
"""Generate Gaussian nose."""
def __init__(self, training_only=False, noise_epsilon=1.0, **kwargs):
"""Create a CombineMeanStd layer.
This layer should have two inputs with the same shape, and its
output also has the same shape. Each element of the output is a
Gaussian distributed random number whose mean is the corresponding
element of the first input, and whose standard deviation is the
corresponding element of the second input.
Parameters
----------
training_only: bool
if True, noise is only generated during training. During
prediction, the output is simply equal to the first input (that
is, the mean of the distribution used during training).
noise_epsilon: float
The noise is scaled by this factor
"""
super(CombineMeanStd, self).__init__(**kwargs)
self.training_only = training_only
self.noise_epsilon = noise_epsilon
def get_config(self):
config = super(CombineMeanStd, self).get_config()
config['training_only'] = self.training_only
config['noise_epsilon'] = self.noise_epsilon
return config
def call(self, inputs, training=True):
if len(inputs) != 2:
raise ValueError("Must have two in_layers")
mean_parent, std_parent = inputs[0], inputs[1]
noise_scale = tf.cast(training or not self.training_only, tf.float32)
from tensorflow.python.ops import array_ops
sample_noise = tf.random.normal(
array_ops.shape(mean_parent), 0, self.noise_epsilon, dtype=tf.float32)
return mean_parent + noise_scale * std_parent * sample_noise
class Stack(tf.keras.layers.Layer):
"""Stack the inputs along a new axis."""
def __init__(self, axis=1, **kwargs):
super(Stack, self).__init__(**kwargs)
self.axis = axis
def get_config(self):
config = super(Stack, self).get_config()
config['axis'] = self.axis
return config
def call(self, inputs):
return tf.stack(inputs, axis=self.axis)
class Variable(tf.keras.layers.Layer):
"""Output a trainable value.
Due to a quirk of Keras, you must pass an input value when invoking
this layer. It doesn't matter what value you pass. Keras assumes
every layer that is not an Input will have at least one parent, and
violating this assumption causes errors during evaluation.
"""
def __init__(self, initial_value, **kwargs):
"""Construct a variable layer.
Parameters
----------
initial_value: array or Tensor
the initial value the layer should output
"""
super(Variable, self).__init__(**kwargs)
self.initial_value = initial_value
def get_config(self):
config = super(Variable, self).get_config()
config['initial_value'] = self.initial_value
return config
def build(self, input_shape):
self.var = tf.Variable(self.initial_value, dtype=self.dtype)
self.built = True
def call(self, inputs):
return self.var
class VinaFreeEnergy(tf.keras.layers.Layer):
"""Computes free-energy as defined by Autodock Vina.
TODO(rbharath): Make this layer support batching.
"""
def __init__(self,
N_atoms,
M_nbrs,
ndim,
nbr_cutoff,
start,
stop,
stddev=.3,
Nrot=1,
**kwargs):
super(VinaFreeEnergy, self).__init__(**kwargs)
self.stddev = stddev
# Number of rotatable bonds
# TODO(rbharath): Vina actually sets this per-molecule. See if makes
# a difference.
self.Nrot = Nrot
self.N_atoms = N_atoms
self.M_nbrs = M_nbrs
self.ndim = ndim
self.nbr_cutoff = nbr_cutoff
self.start = start
self.stop = stop
def get_config(self):
config = super(VinaFreeEnergy, self).get_config()
config['N_atoms'] = self.N_atoms
config['M_nbrs'] = self.M_nbrs
config['ndim'] = self.ndim
config['nbr_cutoff'] = self.nbr_cutoff
config['start'] = self.start
config['stop'] = self.stop
config['stddev'] = self.stddev
config['Nrot'] = self.Nrot
return config
def build(self, input_shape):
self.weighted_combo = WeightedLinearCombo()
self.w = tf.Variable(tf.random.normal((1,), stddev=self.stddev))
self.built = True
def cutoff(self, d, x):
out_tensor = tf.where(d < 8, x, tf.zeros_like(x))
return out_tensor
def nonlinearity(self, c, w):
"""Computes non-linearity used in Vina."""
out_tensor = c / (1 + w * self.Nrot)
return w, out_tensor
def repulsion(self, d):
"""Computes Autodock Vina's repulsion interaction term."""
out_tensor = tf.where(d < 0, d**2, tf.zeros_like(d))
return out_tensor
def hydrophobic(self, d):
"""Computes Autodock Vina's hydrophobic interaction term."""
out_tensor = tf.where(d < 0.5, tf.ones_like(d),
tf.where(d < 1.5, 1.5 - d, tf.zeros_like(d)))
return out_tensor
def hydrogen_bond(self, d):
"""Computes Autodock Vina's hydrogen bond interaction term."""
out_tensor = tf.where(
d < -0.7, tf.ones_like(d),
tf.where(d < 0, (1.0 / 0.7) * (0 - d), tf.zeros_like(d)))