-
Notifications
You must be signed in to change notification settings - Fork 2
/
RGCVAE_noHist.py
1773 lines (1602 loc) · 99.8 KB
/
RGCVAE_noHist.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
#!/usr/bin/env/python
"""
Usage:
RGCVAE.py [options]
Options:
-h --help Show this screen
--dataset NAME Dataset name: ZINC or QM9
--config-file FILE Hyperparameter configuration file path (in JSON format)
--config CONFIG Hyperparameter configuration dictionary (in JSON format)
--data_dir NAME Data dir name
--restore FILE File to restore weights from.
--restore_n NAME Epoch to restore
--freeze-graph-model Freeze weights of graph model components
--restrict_data NAME [0,1] Load only a subset of the entire dataset
"""
import copy
import sys
import traceback
import pandas as pd
from docopt import docopt
from rdkit.Chem import QED
from model.GGNN_core import *
from model.MLP import *
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '0' # 0, 1, 2, 3
"""
Comments provide the expected tensor shapes where helpful.
Key to symbols in comments:
---------------------------
[...]: a tensor
; ; : a list
b: batch size
e: number of edege types (3)
es: maximum number of BFS transitions in this batch
v: number of vertices per graph in this batch
h: GNN hidden size
"""
class MolGVAE(ChemModel):
def __init__(self, args):
super().__init__(args)
@classmethod
def default_params(cls):
params = dict(super().default_params())
params.update({
# general configuration
'random_seed': 0, # fixed for reproducibility
'suffix': None,
'log_dir': './results',
'train_file': 'data/molecules_train_%s.json' % dataset,
'valid_file': 'data/molecules_valid_%s.json' % dataset,
# 'train_file': 'data/molecules_small_dataset.json',
# 'valid_file': 'data/molecules_test_%s.json' % dataset,
'test_file': 'data/molecules_test_%s.json' % dataset,
"use_gpu": True,
"tensorboard": 3, # frequency if we use tensorboard else None
"use_rec_multi_threads": True,
# general procedure configuration
'task_ids': [0], # id of property prediction
"fix_molecule_validation": True,
'generation': 0, # 0 = do training, 1 = do only gen, 2 = do only rec
'number_of_generation': 20000,
'reconstruction_en': 20, # number of encoding in reconstruction
'reconstruction_dn': 1, # number of decoding in reconstruction
'batch_size': utils.dataset_info(dataset)['batch_size'],
'num_epochs': utils.dataset_info(dataset)['n_epochs'],
'hidden_size_encoder': 70, # encoder hidden size dimension
'latent_space_size': 70, # latent space size
'prior_learning_rate': 0.05, # gradient ascent optimization
'hist_local_search': False,
'use_edge_bias': True, # whether use edge bias in gnn
'optimization_step': 0,
"use_argmax_nodes": False, # use random sampling or argmax during node sampling
"use_argmax_bonds": False, # use random sampling or argmax during bonds generations
'use_mask': True, # true to use node mask
"path_random_order": False, # False: canonical order, True: random order
'tie_fwd_bkwd': True,
"compensate_num": 1, # how many atoms to be added during generation
"gen_hist_sampling": False, # sampling new hist during generation task.
# loss params
"kl_trade_off_lambda": 0.05 if "qm9" in dataset else 0.01,
"kl_trade_off_lambda_factor": 0,
"qed_trade_off_lambda": 10,
'learning_rate': 0.001,
'task_sample_ratios': {}, # weights for properties
'clamp_gradient_norm': 1.0,
# dropout
'graph_state_dropout_keep_prob': 1,
'out_layer_dropout_keep_prob': 1.0,
'edge_weight_dropout_keep_prob': 1,
# GCNN
'num_timesteps': 5, # gnn propagation step
'use_graph': False, # use gnn
'use_gin': True, # use gin as gnn
'gin_epsilon': 0, # gin epsilon
'residual_connection_on': True, # whether residual connection is on
'residual_connections': {
2: [0],
4: [0, 2],
6: [0, 2, 4],
8: [0, 2, 4, 6],
10: [0, 2, 4, 6, 8],
12: [0, 2, 4, 6, 8, 10],
14: [0, 2, 4, 6, 8, 10, 12],
16: [0, 2, 4, 6, 8, 10, 12, 14],
18: [0, 2, 4, 6, 8, 10, 12, 14, 16],
20: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18],
},
})
return params
def prepare_specific_graph_model(self) -> None:
# params
h_dim_en = self.params['hidden_size_encoder']
ls_dim = self.params['latent_space_size']
h_dim_de = ls_dim + 50
expanded_h_dim = h_dim_de + h_dim_en + 1 # 1 for focus bit
hist_dim = self.histograms['hist_dim']
self.placeholders['smiles'] = tf.placeholder_with_default("No smiles as default", [], name='is_training')
self.placeholders['n_epoch'] = tf.placeholder_with_default(0, [], name='n_epoch')
self.placeholders['is_training'] = tf.placeholder_with_default(False, [], name='is_training')
self.placeholders['target_values'] = tf.placeholder(tf.float32, [len(self.params['task_ids']), None],
name='target_values')
self.placeholders['target_mask'] = tf.placeholder(tf.float32, [len(self.params['task_ids']), None],
name='target_mask')
self.placeholders['num_graphs'] = tf.placeholder(tf.int32, [], name='num_graphs')
self.placeholders['out_layer_dropout_keep_prob'] = tf.placeholder(tf.float32, [],
name='out_layer_dropout_keep_prob')
self.placeholders['graph_state_keep_prob'] = tf.placeholder(tf.float32, None, name='graph_state_keep_prob')
self.placeholders['edge_weight_dropout_keep_prob'] = tf.placeholder(tf.float32, None,
name='edge_weight_dropout_keep_prob')
# mask out invalid node
self.placeholders['node_mask'] = tf.placeholder(tf.float32, [None, None], name='node_mask') # [b v]
self.placeholders['num_vertices'] = tf.placeholder(tf.int32, (), name="num_vertices")
# adj for encoder
self.placeholders['adjacency_matrix'] = tf.placeholder(tf.float32, [None, self.num_edge_types, None, None],
name="adjacency_matrix") # [b, e, v, v]
# labels for node symbol prediction
self.placeholders['node_symbols'] = tf.placeholder(tf.float32, [None, None, self.params[
'num_symbols']]) # [b, v, edge_type]
# z_prior sampled from standard normal distribution
self.placeholders['z_prior'] = tf.placeholder(tf.float32, [None, None, ls_dim],
name='z_prior') # the prior of z sampled from normal distribution
# histograms for the first part of the decoder
self.placeholders['histograms'] = tf.placeholder(tf.int32, (None, hist_dim), name="histograms")
self.placeholders['n_histograms'] = tf.placeholder(tf.int32, (None), name="n_histograms")
self.placeholders['hist'] = tf.placeholder(tf.int32, (None, hist_dim), name="hist")
self.placeholders['incr_hist'] = tf.placeholder(tf.float32, (None, None, hist_dim), name="incr_hist")
self.placeholders['incr_diff_hist'] = tf.placeholder(tf.float32, (None, None, hist_dim), name="incr_diff_hist")
self.placeholders['incr_node_mask'] = tf.placeholder(tf.float32, (None, None, self.params['num_symbols']),
name="incr_node_mask")
# weights for encoder and decoder GNN.
with tf.name_scope('graph_convolution_vars'):
if self.params['use_graph']:
if self.params["residual_connection_on"]:
# weights for encoder and decoder GNN. Different weights for each iteration
for scope in ['_encoder', '_decoder']:
if scope == '_encoder':
new_h_dim = h_dim_en
else:
new_h_dim = expanded_h_dim
# For each GNN iteration
for iter_idx in range(self.params['num_timesteps']):
with tf.variable_scope("gru_scope" + scope + str(iter_idx), reuse=False):
self.weights['edge_weights' + scope + str(iter_idx)] = tf.Variable(
utils.glorot_init([self.num_edge_types, new_h_dim, new_h_dim]))
if self.params['use_edge_bias']:
self.weights['edge_biases' + scope + str(iter_idx)] = tf.Variable(
np.zeros([self.num_edge_types, 1, new_h_dim]).astype(np.float32))
cell = tf.contrib.rnn.GRUCell(new_h_dim)
cell = tf.nn.rnn_cell.DropoutWrapper(cell, state_keep_prob=self.placeholders[
'graph_state_keep_prob'])
self.weights['node_gru' + scope + str(iter_idx)] = cell
else:
for scope in ['_encoder', '_decoder']:
if scope == '_encoder':
new_h_dim = h_dim_en
else:
new_h_dim = expanded_h_dim
self.weights['edge_weights' + scope] = tf.Variable(
utils.glorot_init([self.num_edge_types, new_h_dim, new_h_dim]))
if self.params['use_edge_bias']:
self.weights['edge_biases' + scope] = tf.Variable(
np.zeros([self.num_edge_types, 1, new_h_dim]).astype(np.float32))
with tf.variable_scope("gru_scope" + scope):
cell = tf.contrib.rnn.GRUCell(new_h_dim)
cell = tf.nn.rnn_cell.DropoutWrapper(cell,
state_keep_prob=self.placeholders[
'graph_state_keep_prob'])
self.weights['node_gru' + scope] = cell
# GIN VERSION
elif self.params['use_gin']:
self.weights['gin_epsilon'] = tf.constant(self.params['gin_epsilon'], tf.float32)
for scope in ['_encoder']:
if scope == '_encoder':
new_h_dim = h_dim_en
else:
new_h_dim = expanded_h_dim
# For each GNN iteration
for iter_idx in range(self.params['num_timesteps']):
with tf.variable_scope("gin_scope" + scope + str(iter_idx), reuse=False):
for edge_type in range(self.num_edge_types):
self.weights['MLP_edge' + str(edge_type) + scope + str(iter_idx)] = MLP(new_h_dim,
new_h_dim,
[],
self.placeholders[
'out_layer_dropout_keep_prob'],
name='MLP_edge',
activation_function=tf.nn.leaky_relu,
bias=True)
self.weights['MLP' + scope + str(iter_idx)] = MLP_norm(new_h_dim,
new_h_dim,
[new_h_dim],
self.placeholders[
'out_layer_dropout_keep_prob'],
activation_function=tf.nn.leaky_relu)
# ESP1 - base graph convolution layer
# elif self.params['use_gin']:
# self.weights['gin_epsilon'] = tf.constant(self.params['gin_epsilon'], tf.float32)
# for scope in ['_encoder']:
# if scope == '_encoder':
# new_h_dim = h_dim_en
# else:
# new_h_dim = expanded_h_dim
# # For each GNN iteration
# for iter_idx in range(self.params['num_timesteps']):
# with tf.variable_scope("gin_scope" + scope + str(iter_idx), reuse=False):
# self.weights['MLP' + scope + str(iter_idx)] = MLP(new_h_dim,
# new_h_dim,
# [],
# self.placeholders[
# python -u RGCVAE.py --dataset moses --config '{"generation":0, "log_dir":"./results_esp3", "use_mask":false, "num_timesteps":10 "kl_trade_off_lambda":0.05, "hidden_size_encoder":150, "latent_space_size":150, "batch_size":500, "suffix":"kl0.05d150i12"}' | tee output_esp3.txt 'out_layer_dropout_keep_prob'],
# activation_function=tf.nn.leaky_relu)
# ESP2 - link nicolo'
# elif self.params['use_gin']:
# self.weights['gin_epsilon'] = tf.constant(self.params['gin_epsilon'], tf.float32)
# for scope in ['_encoder']:
# if scope == '_encoder':
# new_h_dim = h_dim_en
# else:
# new_h_dim = expanded_h_dim
# # For each GNN iteration
# for iter_idx in range(self.params['num_timesteps']):
# with tf.variable_scope("gin_scope" + scope + str(iter_idx), reuse=False):
# for edge_type in range(self.num_edge_types):
# self.weights['MLP_edge' + str(edge_type) + scope + str(iter_idx)] = MLP(new_h_dim,
# new_h_dim,
# [],
# self.placeholders[
# 'out_layer_dropout_keep_prob'],
# name='MLP_edge',
# activation_function=tf.nn.leaky_relu)
# self.weights['MLP' + scope + str(iter_idx)] = MLP(new_h_dim,
# new_h_dim,
# [],
# self.placeholders[
# 'out_layer_dropout_keep_prob'],
# activation_function=tf.nn.leaky_relu)
# GIN VERSION
with tf.name_scope('distribution_vars'):
# Weights final part encoder. They map all nodes in one point in the latent space
input_size_distribution = h_dim_en * (self.params['num_timesteps'] + 1)
# self.weights['mean_MLP'] = MLP(input_size_distribution, ls_dim,
self.weights['mean_MLP'] = MLP(h_dim_en, ls_dim,
[],
self.placeholders['out_layer_dropout_keep_prob'],
activation_function=tf.nn.leaky_relu,
name='mean_MLP')
# self.weights['logvariance_MLP'] = MLP(input_size_distribution, ls_dim,
self.weights['logvariance_MLP'] = MLP(h_dim_en, ls_dim,
[],
self.placeholders['out_layer_dropout_keep_prob'],
activation_function=tf.nn.leaky_relu,
name='logvariance_MLP')
# ESP1 - base graph convolution layer
# with tf.name_scope('distribution_vars'):
# # Weights final part encoder. They map all nodes in one point in the latent space
# input_size_distribution = h_dim_en * (self.params['num_timesteps'] + 1)
# self.weights['mean_MLP'] = MLP(h_dim_en, ls_dim,
# # [input_size_distribution, input_size_distribution, ls_dim],
# [],
# self.placeholders['out_layer_dropout_keep_prob'],
# activation_function=tf.nn.leaky_relu,
# name='mean_MLP')
# self.weights['logvariance_MLP'] = MLP(h_dim_en, ls_dim,
# [],
# self.placeholders['out_layer_dropout_keep_prob'],
# activation_function=tf.nn.leaky_relu,
# name='logvariance_MLP')
with tf.name_scope('gen_nodes_vars'):
self.weights['histogram_MLP'] = MLP(ls_dim + 2 * hist_dim, 50,
[],
self.placeholders['out_layer_dropout_keep_prob'],
activation_function=tf.nn.leaky_relu,
name='histogram_MLP')
self.weights['node_symbol_MLP'] = MLP(h_dim_de, self.params['num_symbols'],
[h_dim_de],
self.placeholders['out_layer_dropout_keep_prob'],
activation_function=tf.nn.leaky_relu,
name='node_symbol_MLP')
with tf.name_scope('gen_edges_vars'):
# gen edges
# input_size_edge = 4 * (h_dim_en + h_dim_de) # with sum and product as context
input_size_edge = 3 * (h_dim_en + h_dim_de) # remove product as context
self.weights['edge_gen_MLP'] = MLP(input_size_edge, 1,
[input_size_edge, h_dim_de],
self.placeholders['out_layer_dropout_keep_prob'],
activation_function=tf.nn.relu,
name='edge_gen_MLP')
self.weights['edge_type_gen_MLP'] = MLP(input_size_edge, self.num_edge_types,
[input_size_edge, h_dim_de],
self.placeholders['out_layer_dropout_keep_prob'],
activation_function=tf.nn.relu,
name='edge_type_gen_MLP')
with tf.name_scope('qed_vars'):
# weights for linear projection on qed prediction input
input_size_qed = h_dim_en + h_dim_de
self.weights['qed_weights'] = tf.Variable(utils.glorot_init([input_size_qed, input_size_qed]),
name='qed_weights')
self.weights['qed_biases'] = tf.Variable(np.zeros([1, input_size_qed]).astype(np.float32),
name='qed_biases')
self.weights['plogP_weights'] = tf.Variable(utils.glorot_init([input_size_qed, input_size_qed]),
name='plogP_weights')
self.weights['plogP_biases'] = tf.Variable(np.zeros([1, input_size_qed]).astype(np.float32),
name='plogP_biases')
# use node embeddings
self.weights["node_embedding"] = tf.Variable(utils.glorot_init([self.params["num_symbols"], h_dim_en]),
name='node_embedding')
# graph state mask
self.ops['graph_state_mask'] = tf.expand_dims(self.placeholders['node_mask'], 2)
# transform one hot vector to dense embedding vectors
def get_node_embedding_state(self, one_hot_state):
node_nums = tf.argmax(one_hot_state, axis=2)
return tf.nn.embedding_lookup(self.weights["node_embedding"], node_nums) * self.ops['graph_state_mask']
def compute_final_node_representations_with_residual(self, h, adj, scope_name): # scope_name: _encoder or _decoder
# h: initial representation, adj: adjacency matrix, different GNN parameters for encoder and decoder
v = self.placeholders['num_vertices']
# _decoder uses a larger latent space because concat of symbol and latent representation
if scope_name == "_decoder":
h_dim = self.params['hidden_size_encoder'] + self.params['hidden_size_decoder'] + 1
else:
h_dim = self.params['hidden_size_encoder']
h = tf.reshape(h, [-1, h_dim]) # [b*v, h]
# record all hidden states at each iteration
all_hidden_states = [h]
for iter_idx in range(self.params['num_timesteps']):
with tf.variable_scope("gru_scope" + scope_name + str(iter_idx), reuse=None) as g_scope:
for edge_type in range(self.num_edge_types):
# the message passed from this vertice to other vertices
m = tf.matmul(h, self.weights['edge_weights' + scope_name + str(iter_idx)][edge_type]) # [b*v, h]
if self.params['use_edge_bias']:
m += self.weights['edge_biases' + scope_name + str(iter_idx)][edge_type] # [b, v, h]
m = tf.reshape(m, [-1, v, h_dim]) # [b, v, h]
# collect the messages from other vertices to each vertice
if edge_type == 0:
acts = tf.matmul(adj[edge_type], m)
else:
acts += tf.matmul(adj[edge_type], m)
# all messages collected for each node
acts = tf.reshape(acts, [-1, h_dim]) # [b*v, h]
# add residual connection here
layer_residual_connections = self.params['residual_connections'].get(iter_idx)
if layer_residual_connections is None:
layer_residual_states = []
else:
layer_residual_states = [all_hidden_states[residual_layer_idx]
for residual_layer_idx in layer_residual_connections]
# concat current hidden states with residual states
acts = tf.concat([acts] + layer_residual_states, axis=1) # [b, (1+num residual connection)* h]
# feed msg inputs and hidden states to GRU
h = self.weights['node_gru' + scope_name + str(iter_idx)](acts, h)[1] # [b*v, h]
# record the new hidden states
all_hidden_states.append(h)
last_h = tf.reshape(all_hidden_states[-1], [-1, v, h_dim])
return last_h
def compute_final_node_representations_without_residual(self, h, adj, edge_weights, edge_biases, node_gru,
gru_scope_name):
# h: initial representation, adj: adjacency matrix, different GNN parameters for encoder and decoder
v = self.placeholders['num_vertices']
if gru_scope_name == "gru_scope_decoder":
h_dim = self.params['hidden_size_encoder'] + self.params['hidden_size_decoder']
else:
h_dim = self.params['hidden_size_encoder']
h = tf.reshape(h, [-1, h_dim])
with tf.variable_scope(gru_scope_name) as scope:
for i in range(self.params['num_timesteps']):
if i > 0:
tf.get_variable_scope().reuse_variables()
for edge_type in range(self.num_edge_types):
m = tf.matmul(h, tf.nn.dropout(edge_weights[edge_type],
keep_prob=self.placeholders[
'edge_weight_dropout_keep_prob'])) # [b*v, h]
if self.params['use_edge_bias']:
m += edge_biases[edge_type] # [b, v, h]
m = tf.reshape(m, [-1, v, h_dim]) # [b, v, h]
if edge_type == 0:
acts = tf.matmul(adj[edge_type], m) # adj[edge_type]->[b,v,v] m->[b,v,h] res->b[v,h]
else:
acts += tf.matmul(adj[edge_type], m)
acts = tf.reshape(acts, [-1, h_dim]) # [b*v, h]
h = node_gru(acts, h)[1] # [b*v, h]
last_h = tf.reshape(h, [-1, v, h_dim])
return last_h
def compute_final_node_with_GIN(self, h, adj, scope_name): # scope_name: _encoder or _decoder
# h: initial representation, adj: adjacency matrix, different GNN parameters for encoder and decoder
v = self.placeholders['num_vertices']
# _decoder uses a larger latent space because concat of symbol and latent representation
h_dim = self.params['hidden_size_encoder']
h = tf.reshape(h, [-1, h_dim]) # [b*v, h]
weigths_concat = h
for iter_idx in range(self.params['num_timesteps']):
with tf.variable_scope("gin_scope" + scope_name + str(iter_idx), reuse=None) as g_scope:
for edge_type in range(self.num_edge_types):
m = tf.nn.leaky_relu(self.weights['MLP_edge' + str(edge_type) + scope_name + str(iter_idx)](h,
self.placeholders[
'is_training']))
m = tf.reshape(m, [-1, v, h_dim]) # [b, v, h] with softmax
# collect the messages from other vertices to each vertice
if edge_type == 0:
acts = tf.matmul(adj[edge_type], m)
else:
acts += tf.matmul(adj[edge_type], m)
# all messages collected for each node
acts = tf.reshape(acts, [-1, h_dim]) # [b*v, h]
input = tf.multiply((1 + self.weights['gin_epsilon']), h) + acts
h = tf.nn.leaky_relu(
self.weights['MLP' + scope_name + str(iter_idx)](input, self.placeholders['is_training']))
# tensorboard
tf.summary.histogram("gin_scope" + scope_name + str(iter_idx) + "_node_state", h)
weigths_concat = tf.concat([weigths_concat, h], axis=1)
last_h = tf.reshape(h, [-1, v, h_dim])
last_weigths_concat = tf.reshape(weigths_concat, [-1, v, h_dim * (self.params['num_timesteps'] + 1)])
# tensorboard
tf.summary.histogram("last_weigths_concat", last_weigths_concat)
last_h = last_h * self.ops['graph_state_mask']
average_pooling = tf.reduce_mean(last_h, axis=1, keepdims=False)
return last_h, last_weigths_concat, average_pooling
def compute_mean_and_logvariance(self):
v = self.placeholders['num_vertices']
h_dim = self.params['hidden_size_encoder']
ls_dim = self.params['latent_space_size']
# Concatenation
# reshped_last_h = tf.reshape(self.ops['final_node_representations'][1], [-1, h_dim * (self.params['num_timesteps'] + 1)])
# Just last rep.
reshped_last_h = tf.reshape(self.ops['final_node_representations'][0], [-1, h_dim])
mean = self.weights['mean_MLP'](reshped_last_h, self.placeholders['is_training'])
logvariance = tf.minimum(self.weights['logvariance_MLP'](reshped_last_h, self.placeholders['is_training']), 2.5)
# mask everything
mean = tf.reshape(mean, [-1, v, ls_dim]) * self.ops['graph_state_mask']
logvariance = tf.reshape(logvariance, [-1, v, ls_dim]) * self.ops['graph_state_mask']
mean = tf.reshape(mean, [-1, ls_dim])
logvariance = tf.reshape(logvariance, [-1, ls_dim])
self.ops['mean'] = mean
self.ops['logvariance'] = logvariance
tf.summary.histogram("mean", self.ops['mean'])
tf.summary.histogram("logvariance", self.ops['logvariance'])
def sample_with_mean_and_logvariance(self):
v = self.placeholders['num_vertices']
ls_dim = self.params['latent_space_size']
# Sample from normal distribution
z_prior = tf.reshape(self.placeholders['z_prior'], [-1, ls_dim])
# Train: sample from u, Sigma. Generation: sample from 0,1
if self.params['generation'] in [0, 2, 4]: # Training, reconstruction and validation
z_sampled = tf.add(self.ops['mean'], tf.multiply(tf.sqrt(tf.exp(self.ops['logvariance'])), z_prior))
else:
z_sampled = z_prior
# filter
z_sampled = tf.reshape(z_sampled, [-1, v, ls_dim]) * self.ops['graph_state_mask']
self.ops['z_sampled'] = z_sampled
tf.summary.histogram("z_sampled", self.ops['z_sampled'])
"""
Construct the nodes representations
"""
def construct_nodes(self):
h_dim_en = self.params['hidden_size_encoder']
ls_dim = self.params['latent_space_size']
h_dim_de = ls_dim + 50 # check tf.tensorboard value
batch_size = tf.shape(self.ops['z_sampled'])[0]
v = self.placeholders['num_vertices']
if self.params['generation'] in [0, 4]: # Training and test
initial_nodes_decoder, node_symbol_prob, sampled_atoms = self.train_procedure()
elif self.params['generation'] in [1, 2, 3]: # Reconstruction and Generation
initial_nodes_decoder, node_symbol_prob, sampled_atoms = self.gen_rec_procedure()
# batch normalization
initial_nodes_decoder_masked = initial_nodes_decoder * self.ops['graph_state_mask']
initial_nodes_decoder_reshaped = tf.reshape(initial_nodes_decoder_masked, [-1, h_dim_de])
initial_nodes_decoder_bn = tf.layers.batch_normalization(initial_nodes_decoder_reshaped,
training=self.placeholders['is_training'])
initial_nodes_decoder_final = tf.reshape(initial_nodes_decoder_bn, [batch_size, v, h_dim_de])
self.ops['initial_nodes_decoder'] = initial_nodes_decoder_final * self.ops['graph_state_mask']
# uncomment only if we want to remove the bn
# self.ops['initial_nodes_decoder'] = initial_nodes_decoder * self.ops['graph_state_mask']
self.ops['node_symbol_prob'] = node_symbol_prob * self.ops['graph_state_mask']
self.ops['sampled_atoms'] = sampled_atoms * tf.cast(self.placeholders['node_mask'], tf.int32)
# calc one hot repr. for type of atom
self.ops['latent_node_symbols'] = tf.one_hot(self.ops['sampled_atoms'],
self.params['num_symbols'],
name='latent_node_symbols') * self.ops['graph_state_mask']
tf.summary.histogram("hist_embedding", self.ops['initial_nodes_decoder'][:, :, -50:])
tf.summary.histogram("initial_nodes_decoder", self.ops['initial_nodes_decoder'])
tf.summary.histogram("sampled_atoms", self.ops['sampled_atoms'])
def train_procedure(self):
latent_space_dim = self.params['latent_space_size']
h_dim_de = latent_space_dim + 50
hist_dim = self.histograms['hist_dim']
num_symbols = self.params['num_symbols']
batch_size = tf.shape(self.ops['z_sampled'])[0]
v = self.placeholders['num_vertices'] # bucket size dimension, not all time the real one.
# experiment
h_fake = tf.zeros_like(self.placeholders['incr_hist'])
hdiff_fake = tf.zeros_like(self.placeholders['incr_diff_hist'])
# calc emb hist
input_z_hist = tf.concat(
[self.ops['z_sampled'], h_fake, hdiff_fake], -1)
z_input = tf.reshape(input_z_hist, [-1, latent_space_dim + 2 * hist_dim])
hist_emb = tf.nn.tanh(self.weights['histogram_MLP'](z_input, self.placeholders['is_training']))
float_z_sampled = tf.reshape(self.ops['z_sampled'], [-1, latent_space_dim])
conc_z_hist = tf.concat([float_z_sampled, hist_emb], -1)
initial_nodes_decoder = tf.reshape(conc_z_hist, [batch_size, v, h_dim_de])
# calc prob with or without mask
atom_logits = self.weights['node_symbol_MLP'](conc_z_hist, self.placeholders['is_training'])
atom_prob = tf.nn.softmax(atom_logits)
node_symbol_prob = tf.reshape(atom_prob, [batch_size, v, num_symbols])
sampled_atoms = self.placeholders['node_symbols']
sampled_atoms_casted = tf.argmax(sampled_atoms, axis=-1, output_type=tf.int32)
return initial_nodes_decoder, node_symbol_prob, sampled_atoms_casted
def gen_rec_procedure(self):
latent_space_dim = self.params['latent_space_size']
h_dim_de = latent_space_dim + 50
num_symbols = self.params['num_symbols']
batch_size = tf.shape(self.ops['z_sampled'])[0]
# save the new atom [b, v, h]
atoms = tf.TensorArray(dtype=tf.int32, size=batch_size, element_shape=[None, 1])
init_atoms = tf.TensorArray(dtype=tf.float32, size=batch_size, element_shape=[None, h_dim_de])
fx_prob = tf.TensorArray(dtype=tf.float32, size=batch_size, element_shape=[None, num_symbols])
# iteration on all the molecules in the batch size
idx, atoms, init_atoms, fx_prob = tf.while_loop(
lambda idx, atoms, init_atoms, fx_prob: tf.less(idx, batch_size),
# numbers of example sampled
self.for_each_molecula,
(tf.constant(0), atoms, init_atoms, fx_prob),
parallel_iterations=self.params['batch_size']
)
init_h_states = init_atoms.stack()
nodes_type_probs = fx_prob.stack()
atoms = atoms.stack()
return init_h_states, nodes_type_probs, tf.squeeze(atoms, -1)
def for_each_molecula(self, idx_sample, atoms, init_vertices_all, fx_prob_all):
latent_space_dim = self.params['latent_space_size']
h_dim_de = latent_space_dim + 50
num_symbols = self.params['num_symbols']
v = self.placeholders['num_vertices'] # bucket size dimension, not all time the real one.
current_hist = self.placeholders['hist'][idx_sample]
hist_dim = self.histograms['hist_dim']
zero_hist = tf.zeros([hist_dim], tf.int32)
# select the rigth function according to reconstruction or generation
if self.params['generation'] == 1:
funct_to_call = self.generate_nodes
else:
funct_to_call = self.reconstruct_nodes
sampled_atoms = tf.TensorArray(dtype=tf.int32, size=v, element_shape=[1])
vertices = tf.TensorArray(dtype=tf.float32, size=v, element_shape=[h_dim_de])
fx_prob = tf.TensorArray(dtype=tf.float32, size=v, element_shape=[num_symbols])
# iteration on all the atoms in a molecule
idx_atoms, a, v, fx, _, _, _ = tf.while_loop(
lambda idx_atoms, s_atoms, vertices, fx_prob, s_idx, zero_hist, current_hist: tf.less(idx_atoms, v),
funct_to_call,
(tf.constant(0), sampled_atoms, vertices, fx_prob, idx_sample, zero_hist, current_hist)
)
atoms = atoms.write(idx_sample, a.stack())
init_vertices_all = init_vertices_all.write(idx_sample, v.stack())
fx_prob_all = fx_prob_all.write(idx_sample, fx.stack())
return idx_sample + 1, atoms, init_vertices_all, fx_prob_all
def reconstruct_nodes(self, idx_atom, atoms, init_vertices, fx_prob, idx_sample, updated_hist, sampled_hist):
current_sample_z = self.ops['z_sampled'][idx_sample][idx_atom]
current_mask_value = self.placeholders['node_mask'][idx_sample][idx_atom]
current_sample_hist_casted = tf.cast(sampled_hist, dtype=tf.float32)
# concatenation with the histogram embedding
current_hist_casted = tf.cast(updated_hist, dtype=tf.float32)
hist_diff = tf.subtract(current_sample_hist_casted, current_hist_casted)
hist_diff_pos = tf.where(hist_diff > 0, hist_diff, tf.zeros_like(hist_diff))
# experiment
h_fake = tf.zeros_like(current_hist_casted)
hdiff_fake = tf.zeros_like(hist_diff_pos)
conc = tf.concat([current_sample_z, h_fake, hdiff_fake], axis=0)
exp = tf.expand_dims(conc, 0) # [1, z + Hdiff + Hcurrent]
# build a node with NN (K)
hist_emb = tf.nn.tanh(self.weights['histogram_MLP'](exp, self.placeholders['is_training']))
new_z_concat = tf.concat([tf.expand_dims(current_sample_z, 0), hist_emb], -1)
atom_logits = self.weights['node_symbol_MLP'](new_z_concat, self.placeholders['is_training'])
atom_logits = tf.squeeze(atom_logits)
node_probs = tf.nn.softmax(atom_logits)
probs_value = node_probs
s_atom = self.sample_atom(probs_value, True)
new_updated_hist = self.update_hist(updated_hist, s_atom)
# if the node should be masked, we do not update the current_histogram. In this way, it is always the last one
# which represent the molecule.
# new_updated_hist = tf.cond(tf.equal(current_mask_value, 0),
# lambda: updated_hist,
# lambda: self.update_hist(updated_hist, s_atom))
s_atom, init_v, fx = tf.expand_dims(s_atom, 0), tf.squeeze(new_z_concat), probs_value
atoms = atoms.write(idx_atom, s_atom)
init_vertices = init_vertices.write(idx_atom, init_v)
fx_prob = fx_prob.write(idx_atom, fx)
return idx_atom + 1, atoms, init_vertices, fx_prob, idx_sample, new_updated_hist, sampled_hist
"""
For each node (atoms) calculates histograms and new hidden representations
"""
def generate_nodes(self, idx_atom, atoms, init_vertices, fx_prob, idx_sample, updated_hist, sampled_hist):
hist_dim = self.histograms['hist_dim']
current_sample_z = self.ops['z_sampled'][idx_sample][idx_atom]
current_mask_value = self.placeholders['node_mask'][idx_sample][idx_atom]
current_sample_hist_casted = tf.cast(sampled_hist, dtype=tf.float32)
current_hist_casted = tf.cast(updated_hist, dtype=tf.float32)
hist_diff = tf.subtract(current_sample_hist_casted, current_hist_casted)
hist_diff_pos = tf.where(hist_diff > 0, hist_diff, tf.zeros_like(hist_diff))
# experiment
h_fake = tf.zeros_like(current_hist_casted)
hdiff_fake = tf.zeros_like(hist_diff_pos)
conc = tf.concat([current_sample_z, h_fake, hdiff_fake], axis=0)
exp = tf.expand_dims(conc, 0)
# build a node with NN (K)
hist_emb = tf.nn.tanh(self.weights['histogram_MLP'](exp, self.placeholders['is_training']))
new_z_concat = tf.concat([tf.expand_dims(current_sample_z, 0), hist_emb], -1)
atom_logits = self.weights['node_symbol_MLP'](new_z_concat, self.placeholders['is_training'])
atom_logits = tf.squeeze(atom_logits)
node_probs = tf.nn.softmax(atom_logits)
s_atom = self.sample_atom(node_probs, False)
new_updated_hist = self.update_hist(updated_hist, s_atom)
# if the node should be masked, we do not update the current_histogram. In this way, it is always the last one
# which represent the molecule.
# new_updated_hist = tf.cond(tf.equal(current_mask_value, 0),
# lambda: updated_hist,
# lambda: self.update_hist(updated_hist, s_atom))
if self.params['gen_hist_sampling']:
# sampling one compatible histogram with the current new histogram
reshape = tf.reshape(new_updated_hist,
(-1, hist_dim)) # reshape the dimension from [n_valences] to [1, n_valences]
m1 = self.placeholders['histograms'] >= reshape # vector of 0 and 1
m2 = tf.reduce_sum(tf.cast(m1, dtype=tf.int32), axis=1) # [b]
m3 = tf.equal(m2, tf.constant(hist_dim)) # [b]
m4 = tf.cast(m3, dtype=tf.int32) # [b]
m5 = tf.multiply(self.placeholders['n_histograms'], m4) # [b]
mSomma = tf.reduce_sum(m5)
new_sampled_hist = tf.cond(tf.equal(tf.constant(0), mSomma),
lambda: self.case_random_sampling(),
lambda: self.case_sampling(m5, mSomma))
else:
new_sampled_hist = sampled_hist
s_atom, init_v, fx = tf.expand_dims(s_atom, 0), tf.squeeze(new_z_concat), node_probs
atoms = atoms.write(idx_atom, s_atom)
init_vertices = init_vertices.write(idx_atom, init_v)
fx_prob = fx_prob.write(idx_atom, fx)
return idx_atom + 1, atoms, init_vertices, fx_prob, idx_sample, new_updated_hist, new_sampled_hist
def mask_mols(self, logits, hist):
mol_valence_list = []
for key in dataset_info(self.params['dataset'])['maximum_valence'].keys():
mol_valence_list.append(dataset_info(self.params['dataset'])['maximum_valence'][key])
mol_valence = tf.constant(mol_valence_list)
H_b = tf.cast(hist > 0, tf.int32) # obtaining a vector of only 1 and 0
idx = tf.where(tf.less_equal(H_b, 0)) # obtaining al the indexes with 0-values in the hist
valences = tf.cast(idx + 1, tf.int32) # valences to avoid
equals = tf.not_equal(mol_valence, valences) # broadcasting.
mask_bool = tf.reduce_all(equals, 0)
mask = tf.cast(mask_bool, tf.float32)
logits_masked = tf.cond(tf.reduce_any(mask_bool),
lambda: logits + (mask * utils.LARGE_NUMBER - utils.LARGE_NUMBER),
lambda: logits)
return logits_masked, mask_bool
"""
Histograms sampling with probs
"""
def case_sampling(self, m5, mSomma):
prob = m5 / mSomma
m8 = tf.distributions.Categorical(probs=prob).sample()
m9 = self.placeholders['histograms'][m8]
return m9
"""
Histograms uniform sampling
"""
def case_random_sampling(self):
max_n = tf.shape(self.placeholders['histograms'])[0]
idx = tf.random_uniform([], maxval=max_n, dtype=tf.int32)
return self.placeholders['histograms'][idx]
"""
Sample the id of the atom for a value fo probabilities.
In training always apply argmax, while in generation or optimization it is possible to choose among distribution or argmax
"""
def sample_atom(self, fx_prob, training):
if training or self.params['generation'] == 3:
idx = tf.argmax(fx_prob, output_type=tf.int32)
else:
if self.params['use_argmax_nodes']:
idx = tf.argmax(fx_prob, output_type=tf.int32)
else:
idx = tf.distributions.Categorical(probs=fx_prob).sample()
return idx
"""
Update of the histogram according to the new atom.
"""
def update_hist(self, old_hist, id_atom):
hist_dim = self.histograms['hist_dim']
mol_valence_list = []
# this is ok even if the dictionary is not ordered
for key in dataset_info(self.params['dataset'])['maximum_valence'].keys():
mol_valence_list.append(dataset_info(self.params['dataset'])['maximum_valence'][key])
# make the mol-valence array
mol_valence = tf.constant(mol_valence_list)
# take the atom valence
atmo_val = mol_valence[id_atom]
# build an array to be used in add operation
array = tf.one_hot(atmo_val - 1, hist_dim, dtype=tf.int32) # remember that valence start from 1
# summing the two array
new_hist = tf.add(old_hist, array)
return new_hist
def construct_logit_matrices(self):
v = self.placeholders['num_vertices']
batch_size = tf.shape(self.ops['latent_node_symbols'])[0]
# prep valences
mol_valence_list = []
for key in dataset_info(self.params['dataset'])['maximum_valence'].keys():
mol_valence_list.append(dataset_info(self.params['dataset'])['maximum_valence'][key])
mol_valence = tf.constant(mol_valence_list)
indexes = tf.argmax(self.ops['latent_node_symbols'], axis=-1) # [b, v]
valences = tf.nn.embedding_lookup(mol_valence, indexes)
# representation in input to edge decoder
latent_node_state = self.get_node_embedding_state(self.ops['latent_node_symbols'])
filtered_z_sampled = tf.concat([self.ops['initial_nodes_decoder'], latent_node_state], axis=2)
self.ops["initial_repre_for_decoder"] = filtered_z_sampled # [b, v, 2h]
# The tensor array used to collect the cross entropy losses at each step
edges_pred = tf.TensorArray(dtype=tf.float32, size=v)
edges_type_pred = tf.TensorArray(dtype=tf.float32, size=v)
idx_final, edges_pred, edges_type_pred, _ = \
tf.while_loop(
lambda idx, edges_pred, edges_type_pred, valences: idx < v, self.generate_edges,
(tf.constant(0), edges_pred, edges_type_pred, valences)
)
self.ops['edges_pred'] = tf.transpose(edges_pred.stack(), [1, 0, 2]) * self.ops['graph_state_mask']
self.ops['edges_type_pred'] = tf.transpose(edges_type_pred.stack(), [1, 3, 0, 2]) * \
tf.expand_dims(self.ops['graph_state_mask'], 1)
# mask diagonal in order to put all probabilities to 1 in the non existence of the edge
diag_0 = tf.one_hot(tf.range(v), depth=v, on_value=0.0, off_value=1.0, dtype=tf.float32)
self.ops['edges_pred'] = self.ops['edges_pred'] * tf.expand_dims(diag_0, 0)
self.ops['edges_type_pred'] = self.ops['edges_type_pred'] * tf.expand_dims(tf.expand_dims(diag_0, 0), 0)
tf.summary.histogram("edges_pred", self.ops['edges_pred'])
tf.summary.histogram("edges_type_pred", self.ops['edges_type_pred'])
# calc the GT to use
gt_edges_pred = tf.reduce_sum(self.placeholders['adjacency_matrix'], axis=1)
gt_edges_type_pred = self.placeholders['adjacency_matrix']
# binary cross-entropy balanced
n_edges = dataset_info(self.params['dataset'])['n_edges']
n_yes_edges = dataset_info(self.params['dataset'])['loss_yes_edge']
n_no_edges = dataset_info(self.params['dataset'])['loss_no_edge']
edge_loss = - tf.reduce_sum(
(tf.log(self.ops['edges_pred'] + utils.SMALL_NUMBER) * gt_edges_pred) * n_yes_edges +
tf.log((1 - self.ops['edges_pred']) + utils.SMALL_NUMBER) * (1 - gt_edges_pred) * n_no_edges,
axis=[1, 2])
# edge type cross entropy balanced
n_edges = [dataset_info(self.params['dataset'])['loss_edge_weights']] # added a dimension
loss_batchEdge = tf.reduce_sum(tf.log(self.ops['edges_type_pred'] + utils.SMALL_NUMBER) * gt_edges_type_pred,
axis=[2, 3])
edge_type_loss = -tf.reduce_sum(loss_batchEdge * n_edges, axis=-1)
# sum losses
self.ops['cross_entropy_losses'] = edge_loss + edge_type_loss
# self.ops['cross_entropy_losses'] = 2*(2*edge_loss + edge_type_loss)
corr_edge = tf.cast(self.ops['edges_pred'] >= 0.5, tf.float32)
corr_edge = tf.cast(tf.not_equal(corr_edge, gt_edges_pred),
tf.float32)
edges_type_pred_masked = self.ops['edges_type_pred'] * tf.expand_dims(gt_edges_pred, axis=1)
corr_type_edge = tf.cast(tf.not_equal(tf.argmax(edges_type_pred_masked, axis=1),
tf.argmax(gt_edges_type_pred, axis=1)),
tf.float32)
self.ops['edge_pred_error'] = tf.reduce_sum(corr_edge, axis=[1, 2])
self.ops['edge_type_pred_error'] = tf.reduce_sum(corr_type_edge, axis=[1, 2])
def generate_edges(self, idx, edges_pred, edges_type_pred, valences):
v = self.placeholders['num_vertices']
h_dim_en = self.params['hidden_size_encoder']
latent_space_dim = self.params['latent_space_size']
h_dim_de = latent_space_dim + 50
batch_size = tf.shape(self.ops['latent_node_symbols'])[0]
edges_val_req = [i + 1 for i in range(0, self.num_edge_types)]
edges_val_req = tf.expand_dims(edges_val_req, 0)
edges_val_req = tf.expand_dims(edges_val_req, 0)
edges_val_req = tf.tile(edges_val_req, [batch_size, v, 1])
filtered_z_sampled = self.ops["initial_repre_for_decoder"]
# graph features
graph_sum = tf.reduce_mean(filtered_z_sampled, axis=1, keep_dims=True) # [b, 1, 2h]
graph_sum = tf.tile(graph_sum, [1, v, 1])
# graph_prod = tf.reduce_prod(filtered_z_sampled, axis=1, keep_dims=True) # [b, 1, 2h]
# graph_prod = tf.tile(graph_prod, [1, v, 1])
# node in focus feature
node_focus = filtered_z_sampled[:, idx, :]
node_focus = tf.tile(tf.expand_dims(node_focus, axis=1), [1, v, 1])
node_focus_sum = node_focus + filtered_z_sampled
node_focus_prod = node_focus * filtered_z_sampled # [b, v, 2h]
# input_features = tf.concat([node_focus_sum, node_focus_prod, graph_sum, graph_prod], axis=-1)
# dim_input_network = 4 * (h_dim_en + h_dim_de)
input_features = tf.concat([node_focus_sum, node_focus_prod, graph_sum], axis=-1)
dim_input_network = 3 * (h_dim_en + h_dim_de)
# input_features = tf.concat([node_focus, filtered_z_sampled, graph_sum], axis=-1)
# dim_input_network = 3 * (h_dim_en + h_dim_de)
# node in focus valences
node_focus_valences = valences[:, idx]
node_focus_valences = tf.expand_dims(node_focus_valences, axis=1)
node_focus_feature_valences = tf.tile(node_focus_valences, [1, v])
# generate mask
mask_min = tf.stack([node_focus_feature_valences, valences], axis=-1)
mask_min = tf.reduce_min(mask_min, -1)
mask_min = tf.tile(tf.expand_dims(mask_min, 2), [1, 1, self.num_edge_types])
mask = tf.cast(edges_val_req <= mask_min, tf.float32)
mask = tf.reshape(mask, [-1, self.num_edge_types])
# edge prediction
edge_rep = tf.reshape(input_features, [-1, dim_input_network])
edge_pred_tmp = self.weights['edge_gen_MLP'](edge_rep, self.placeholders['is_training'])
edge_pred_tmp = tf.nn.sigmoid(edge_pred_tmp)
edge_pred_tmp = tf.reshape(edge_pred_tmp, [batch_size, v, 1]) * self.ops['graph_state_mask']
edge_pred_tmp = tf.squeeze(edge_pred_tmp, axis=-1)
# edge type prediction
edge_type_pred_tmp = self.weights['edge_type_gen_MLP'](edge_rep, self.placeholders['is_training'])
edge_type_pred_tmp = tf.nn.softmax(edge_type_pred_tmp + (mask * utils.LARGE_NUMBER - utils.LARGE_NUMBER))
edge_type_pred_tmp = tf.reshape(edge_type_pred_tmp, [batch_size, v, self.num_edge_types]) * self.ops[
'graph_state_mask']
edges_pred = edges_pred.write(idx, edge_pred_tmp)
edges_type_pred = edges_type_pred.write(idx, edge_type_pred_tmp)
return idx + 1, edges_pred, edges_type_pred, valences
def fully_connected(self, input, hidden_weight, hidden_bias, output_weight):
output = tf.nn.relu(tf.matmul(input, hidden_weight) + hidden_bias)
output = tf.matmul(output, output_weight)
return output
def construct_loss(self):
v = self.placeholders['num_vertices']
ls_dim = self.params['latent_space_size']
h_dim_de = ls_dim + 50
h_dim_en = self.params['hidden_size_encoder']
kl_trade_off_lambda_start = self.params['kl_trade_off_lambda']
kl_trade_off_lambda_factor = self.params['kl_trade_off_lambda_factor']
n_epoch = self.placeholders['n_epoch']
kl_trade_off_lambda = kl_trade_off_lambda_start + kl_trade_off_lambda_factor * tf.cast(n_epoch, tf.float32)
# Edge loss
self.ops["edge_loss"] = self.ops['cross_entropy_losses']
# KL loss
kl_loss = 1 + self.ops['logvariance'] - tf.square(self.ops['mean']) - tf.exp(self.ops['logvariance'])
kl_loss = tf.reshape(kl_loss, [-1, v, ls_dim]) * self.ops['graph_state_mask']
self.ops['kl_loss'] = -0.5 * tf.reduce_sum(kl_loss, [1, 2])
# Node symbol loss
loss_node_weights = [
[dataset_info(self.params['dataset'])['loss_node_weights']]] # added two dimension [1, 1, t_nodes]
node_symbol_loss = tf.log(self.ops['node_symbol_prob'] + utils.SMALL_NUMBER) * self.placeholders['node_symbols']
self.ops['node_symbol_loss'] = -tf.reduce_sum(node_symbol_loss * loss_node_weights, axis=[1, 2])
# Other statistics
latent_node_symbol = tf.cast(tf.not_equal(tf.argmax(self.ops['node_symbol_prob'], axis=-1),
tf.argmax(self.placeholders['node_symbols'], axis=-1)),
tf.float32)
mols_errors = self.ops['edge_pred_error'] + self.ops['edge_type_pred_error'] + tf.reduce_sum(latent_node_symbol,
axis=-1)
self.ops['reconstruction'] = tf.reduce_sum(tf.cast(tf.equal(mols_errors, 0), tf.float32))
# after because it rewrite the operations
self.ops['node_pred_error'] = tf.reduce_mean(latent_node_symbol)
self.ops['edge_pred_error'] = tf.reduce_mean(self.ops['edge_pred_error'])
self.ops['edge_type_pred_error'] = tf.reduce_mean(self.ops['edge_type_pred_error'])
# Add in the loss for calculating QED
for (internal_id, task_id) in enumerate(self.params['task_ids']):
with tf.variable_scope("out_layer_task%i" % task_id):
input_size_qed = h_dim_de + h_dim_en
with tf.variable_scope("regression_gate"):
self.weights['regression_gate_task%i' % task_id] = MLP(input_size_qed, 1, [],
self.placeholders[
'out_layer_dropout_keep_prob'],
activation_function=tf.nn.leaky_relu)
with tf.variable_scope("regression"):
self.weights['regression_transform_task%i' % task_id] = MLP(input_size_qed, 1, [],
self.placeholders[
'out_layer_dropout_keep_prob'],
activation_function=tf.nn.leaky_relu)
hist_fake = tf.zeros_like(self.placeholders['hist'])
histograms_input = tf.cast(hist_fake, tf.float32)
v = self.placeholders['num_vertices'] # bucket size dimension, not all time the real one.
# histograms = tf.tile(tf.expand_dims(histograms_input, 1), [1, v, 1]) * self.ops['graph_state_mask']
initial_nodes_decoder = self.ops['initial_repre_for_decoder']
if task_id == 0:
computed_values = self.gated_regression_QED(initial_nodes_decoder,
self.weights['regression_gate_task%i' % task_id],
self.weights['regression_transform_task%i' % task_id],
input_size_qed,
self.weights['qed_weights'],
self.weights['qed_biases'],
self.placeholders['num_vertices'],