[58db57]: / ddc_pub / ddc_v3.py

Download this file

1462 lines (1201 with data), 53.1 kB

   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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
import os
os.environ[
"TF_CPP_MIN_LOG_LEVEL"
] = "3" # Suppress UserWarning of TensorFlow while loading the model
import shutil
import zipfile
import tempfile
import pickle
import numpy as np
from datetime import datetime
from functools import wraps
from tensorflow.keras.layers import (
Input,
Concatenate,
Dense,
Flatten,
RepeatVector,
TimeDistributed,
Bidirectional,
GaussianNoise,
BatchNormalization,
)
from tensorflow.compat.v1.keras.layers import (
CuDNNLSTM as LSTM,
) # Faster drop-in for LSTM using CuDNN on TF backend on GPU
from tensorflow.keras.models import Model, load_model
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import ReduceLROnPlateau, LearningRateScheduler
from tensorflow.keras.utils import multi_gpu_model, plot_model
from sklearn.preprocessing import StandardScaler # For the descriptors
from sklearn.decomposition import PCA # For the descriptors
# Custom dependencies
from .vectorizers import SmilesVectorizer
from .generators import CodeGenerator as DescriptorGenerator
from .generators import HetSmilesGenerator
from .custom_callbacks import ModelAndHistoryCheckpoint, LearningRateSchedule
def timed(func):
"""Timer decorator to benchmark functions."""
@wraps(func)
def wrapper(*args, **kwargs):
tstart = datetime.now()
result = func(*args, **kwargs)
elapsed = (datetime.now() - tstart).microseconds / 1e6
print("Elapsed time: %.3f seconds." % elapsed)
return result
return wrapper
class DDC:
def __init__(self, **kwargs):
"""Initialize a DDC object from scratch or from a trained configuration. All binary mols are converted to SMILES strings internally, using the vectorizers.
# Examples of __init__ usage
To *train* a blank model with encoder (autoencoder):
model = ddc.DDC(x = mols,
y = mols,
scaling = True,
pca = True,
dataset_info = info,
noise_std = 0.1,
lstm_dim = 256,
dec_layers = 3,
td_dense_dim = 0,
batch_size = 128,
codelayer_dim = 128)
To *train* a blank model without encoder:
model = ddc.DDC(x = descriptors,
y = mols,
scaling = True,
pca = True,
dataset_info = info,
noise_std = 0.1,
lstm_dim = 256,
dec_layers = 3,
td_dense_dim = 0,
batch_size = 128)
To *re-train* a saved model with encoder (autoencoder):
model = ddc.DDC(x = mols,
y = mols,
model_name = saved_model_name)
To *re-train* a saved model without encoder:
model = ddc.DDC(x = descriptors,
y = mols,
model_name = saved_model_name)
To *test* a saved model:
model = ddc.DDC(model_name = saved_model_name)
:param x: Encoder input
:type x: list or numpy.ndarray
:param y: Decoder input for teacher's forcing
:type y: list or numpy.ndarray
:param scaling: Flag to scale descriptor inputs, defaults to `False`
:type scaling: boolean
:param pca: Flag to apply PCA on descriptor inputs, defaults to `False`
:type pca: boolean
:param model_name: Filename of model to load
:type model_name: str
:param dataset_info: Metadata about dataset
:type dataset_info: dict
:param noise_std: Standard deviation of noise in the latent space, defaults to 0.01
:type noise_std: float
:param lstm_dim: Number of LSTM units in the encoder/decoder layers, defaults to 256
:param dec_layers: Number of decoder layers, defaults to 2
:type dec_layers: int
:param td_dense_dim: Number of intermediate Dense units to squeeze LSTM outputs, defaults to 0
:type td_dense_dim: int
:param batch_size: Batch size to train with, defaults to 256
:type batch_size: int
:param codelayer_dim: Dimensionality of latent space
:type codelayer_dim: int
:param bn: Fla to enable batch normalization, defaults to `True`
:type bn: boolean
:param bn_momentum: Momentum value to be used in batch normalization, defaults to 0.9
:type bn_momentum: float
"""
# Identify the mode to start the model in
if "x" in kwargs and "y" in kwargs:
x = kwargs.get("x")
y = kwargs.get("y")
if "model_name" not in kwargs:
self.__mode = "train"
else:
self.__mode = "retrain"
elif "model_name" in kwargs:
self.__mode = "test"
else:
raise NameError("Cannot infer mode from arguments.")
print("Initializing model in %s mode." % self.__mode)
if self.mode == "train":
# Infer input type from type(x)
if type(x[0]) == np.bytes_:
print("Input type is 'binary mols'.")
self.__input_type = "mols" # binary RDKit mols
else:
print("Input type is 'molecular descriptors'.")
self.__input_type = "descriptors" # other molecular descriptors
# If scaling is required
if kwargs.get("scaling", False) is True:
# Normalize the input
print("Applying scaling on input.")
self.__scaler = StandardScaler()
x = self.__scaler.fit_transform(x)
else:
self.__scaler = None
# If PCA is required
if kwargs.get("pca", False) is True:
print("Applying PCA on input.")
self.__pca = PCA(
n_components=x.shape[1]
) # n_components=n_features for now
x = self.__pca.fit_transform(x)
else:
self.__pca = None
self.__maxlen = (
kwargs.get("dataset_info")["maxlen"] + 10
) # Extend maxlen to avoid breaks in training
self.__charset = kwargs.get("dataset_info")["charset"]
self.__dataset_name = kwargs.get("dataset_info")["name"]
self.__lstm_dim = kwargs.get("lstm_dim", 256)
self.__h_activation = kwargs.get("h_activation", "relu")
self.__bn = kwargs.get("bn", True)
self.__bn_momentum = kwargs.get("bn_momentum", 0.9)
self.__noise_std = kwargs.get("noise_std", 0.01)
self.__td_dense_dim = kwargs.get(
"td_dense_dim", 0
) # >0 squeezes RNN connections with Dense sandwiches
self.__batch_size = kwargs.get("batch_size", 256)
self.__dec_layers = kwargs.get("dec_layers", 2)
if self.input_type == "descriptors":
self.__codelayer_dim = x.shape[1] # features
if "codelayer_dim" in kwargs:
print(
"Ignoring requested codelayer_dim because it is inferred from the cardinality of the descriptors."
)
else:
self.__codelayer_dim = kwargs.get("codelayer_dim", 128)
# Create the left/right-padding vectorizers
self.__smilesvec1 = SmilesVectorizer(
canonical=False,
augment=True,
maxlength=self.maxlen,
charset=self.charset,
binary=True,
)
self.__smilesvec2 = SmilesVectorizer(
canonical=False,
augment=True,
maxlength=self.maxlen,
charset=self.charset,
binary=True,
leftpad=False,
)
# self.train_gen.next() #This line is needed to set train_gen.dims (to be fixed in HetSmilesGenerator)
self.__input_shape = self.smilesvec1.dims
self.__dec_dims = list(self.smilesvec1.dims)
self.__dec_dims[0] = self.dec_dims[0] - 1
self.__dec_input_shape = self.dec_dims
self.__output_len = self.smilesvec1.dims[0] - 1
self.__output_dims = self.smilesvec1.dims[-1]
# Build all sub-models as untrained models
if self.input_type == "mols":
self.__build_mol_to_latent_model()
else:
self.__mol_to_latent_model = None
self.__build_latent_to_states_model()
self.__build_batch_model()
# Build data generators
self.__build_generators(x, y)
# Retrain or Test mode
else:
self.__model_name = kwargs.get("model_name")
# Load the model
self.__load(self.model_name)
if self.mode == "retrain":
# If scaling is required
if self.scaler is not None:
print("Applying scaling on input.")
x = self.scaler.transform(x)
# If PCA is required
if self.pca is not None:
print("Applying PCA on input.")
x = self.pca.transform(x)
# Build data generators
self.__build_generators(x, y)
# Build full model out of the sub-models
self.__build_model()
# Show the resulting full model
print(self.model.summary())
"""
Architecture properties.
"""
@property
def lstm_dim(self):
return self.__lstm_dim
@property
def h_activation(self):
return self.__h_activation
@property
def bn(self):
return self.__bn
@property
def bn_momentum(self):
return self.__bn_momentum
@property
def noise_std(self):
return self.__noise_std
@property
def td_dense_dim(self):
return self.__td_dense_dim
@property
def batch_size(self):
return self.__batch_size
@property
def dec_layers(self):
return self.__dec_layers
@property
def codelayer_dim(self):
return self.__codelayer_dim
@property
def steps_per_epoch(self):
return self.__steps_per_epoch
@property
def validation_steps(self):
return self.__validation_steps
@property
def input_shape(self):
return self.__input_shape
@property
def dec_dims(self):
return self.__dec_dims
@property
def dec_input_shape(self):
return self.__dec_input_shape
@property
def output_len(self):
return self.__output_len
@property
def output_dims(self):
return self.__output_dims
@property
def batch_input_length(self):
return self.__batch_input_length
@batch_input_length.setter
def batch_input_length(self, value):
self.__batch_input_length = value
self.__build_sample_model(batch_input_length=value)
"""
Models.
"""
@property
def mol_to_latent_model(self):
return self.__mol_to_latent_model
@property
def latent_to_states_model(self):
return self.__latent_to_states_model
@property
def batch_model(self):
return self.__batch_model
@property
def sample_model(self):
return self.__sample_model
@property
def multi_sample_model(self):
return self.__multi_sample_model
@property
def model(self):
return self.__model
"""
Train properties.
"""
@property
def epochs(self):
return self.__epochs
@property
def clipvalue(self):
return self.__clipvalue
@property
def lr(self):
return self.__lr
@property
def h(self):
return self.__h
@h.setter
def h(self, value):
self.__h = value
"""
Other properties.
"""
@property
def mode(self):
return self.__mode
@property
def dataset_name(self):
return self.__dataset_name
@property
def model_name(self):
return self.__model_name
@property
def input_type(self):
return self.__input_type
@property
def maxlen(self):
return self.__maxlen
@property
def charset(self):
return self.__charset
@property
def smilesvec1(self):
return self.__smilesvec1
@property
def smilesvec2(self):
return self.__smilesvec2
@property
def train_gen(self):
return self.__train_gen
@property
def valid_gen(self):
return self.__valid_gen
@property
def scaler(self):
try:
return self.__scaler
except:
return None
@property
def pca(self):
try:
return self.__pca
except:
return None
"""
Private methods.
"""
def __build_generators(self, x, y, split=0.9):
"""Build data generators to be used for (re)training.
:param x: Encoder input
:type x: list
:param y: Decoder input for teacher's forcing
:type y: list
:param split: Fraction of samples to keep for training (rest for validation), defaults to 0.9
:type split: float, optional
"""
# Sanity check
assert len(x) == len(y)
# Split dataset into train and validation sets
cut = int(split * len(x))
x_train = x[:cut]
x_valid = x[cut:]
y_train = y[:cut]
y_valid = y[cut:]
if self.input_type == "mols":
self.__train_gen = HetSmilesGenerator(
x_train,
None,
self.smilesvec1,
self.smilesvec2,
batch_size=self.batch_size,
shuffle=True,
)
self.__valid_gen = HetSmilesGenerator(
x_valid,
None,
self.smilesvec1,
self.smilesvec2,
batch_size=self.batch_size,
shuffle=True,
)
else:
self.__train_gen = DescriptorGenerator(
x_train,
y_train,
self.smilesvec1,
self.smilesvec2,
batch_size=self.batch_size,
shuffle=True,
)
self.__valid_gen = DescriptorGenerator(
x_valid,
y_valid,
self.smilesvec1,
self.smilesvec2,
batch_size=self.batch_size,
shuffle=True,
)
# Calculate number of batches per training/validation epoch
train_samples = len(x_train)
valid_samples = len(x_valid)
self.__steps_per_epoch = train_samples // self.batch_size
self.__validation_steps = valid_samples // self.batch_size
print(
"Model received %d train samples and %d validation samples."
% (train_samples, valid_samples)
)
def __build_mol_to_latent_model(self):
"""Model that transforms binary molecules to their latent representation.
Only used if input is mols.
"""
# Input tensor (MANDATORY)
encoder_inputs = Input(shape=self.input_shape, name="Encoder_Inputs")
x = encoder_inputs
# The two encoder layers, number of cells are halved as Bidirectional
encoder = Bidirectional(
LSTM(
self.lstm_dim // 2,
return_sequences=True,
return_state=True, # Return the states at end of the batch
name="Encoder_LSTM_1",
)
)
x, state_h, state_c, state_h_reverse, state_c_reverse = encoder(x)
if self.bn:
x = BatchNormalization(momentum=self.bn_momentum, name="BN_1")(x)
encoder2 = Bidirectional(
LSTM(
self.lstm_dim // 2,
return_state=True, # Return the states at end of the batch
name="Encoder_LSTM_2",
)
)
_, state_h2, state_c2, state_h2_reverse, state_c2_reverse = encoder2(x)
# Concatenate all states of the forward and the backward LSTM layers
states = Concatenate(axis=-1, name="Concatenate_1")(
[
state_h,
state_c,
state_h2,
state_c2,
state_h_reverse,
state_c_reverse,
state_h2_reverse,
state_c2_reverse,
]
)
if self.bn:
states = BatchNormalization(momentum=self.bn_momentum, name="BN_2")(states)
# A non-linear recombination
neck_relu = Dense(
self.codelayer_dim, activation=self.h_activation, name="Codelayer_Relu"
)
neck_outputs = neck_relu(states)
if self.bn:
neck_outputs = BatchNormalization(
momentum=self.bn_momentum, name="BN_Codelayer"
)(neck_outputs)
# Add Gaussian noise to "spread" the distribution of the latent variables during training
neck_outputs = GaussianNoise(self.noise_std, name="Gaussian_Noise")(
neck_outputs
)
# Define the model
self.__mol_to_latent_model = Model(encoder_inputs, neck_outputs)
# Name it!
self.mol_to_latent_model._name = "mol_to_latent_model"
def __build_latent_to_states_model(self):
"""Model that constructs the initial states of the decoder from a latent molecular representation.
"""
# Input tensor (MANDATORY)
latent_input = Input(shape=(self.codelayer_dim,), name="Latent_Input")
# Initialize list of state tensors for the decoder
decoder_state_list = []
for dec_layer in range(self.dec_layers):
# The tensors for the initial states of the decoder
name = "Dense_h_" + str(dec_layer)
h_decoder = Dense(self.lstm_dim, activation="relu", name=name)(latent_input)
name = "Dense_c_" + str(dec_layer)
c_decoder = Dense(self.lstm_dim, activation="relu", name=name)(latent_input)
if self.bn:
name = "BN_h_" + str(dec_layer)
h_decoder = BatchNormalization(momentum=self.bn_momentum, name=name)(
h_decoder
)
name = "BN_c_" + str(dec_layer)
c_decoder = BatchNormalization(momentum=self.bn_momentum, name=name)(
c_decoder
)
decoder_state_list.append(h_decoder)
decoder_state_list.append(c_decoder)
# Define the model
self.__latent_to_states_model = Model(latent_input, decoder_state_list)
# Name it!
self.latent_to_states_model._name = "latent_to_states_model"
def __build_batch_model(self):
"""Model that returns a vectorized SMILES string of OHE characters.
"""
# List of input tensors to batch_model
inputs = []
# This is the start character padded OHE smiles for teacher forcing
decoder_inputs = Input(shape=self.dec_input_shape, name="Decoder_Inputs")
inputs.append(decoder_inputs)
# I/O tensor of the LSTM layers
x = decoder_inputs
for dec_layer in range(self.dec_layers):
name = "Decoder_State_h_" + str(dec_layer)
state_h = Input(shape=[self.lstm_dim], name=name)
inputs.append(state_h)
name = "Decoder_State_c_" + str(dec_layer)
state_c = Input(shape=[self.lstm_dim], name=name)
inputs.append(state_c)
# RNN layer
decoder_lstm = LSTM(
self.lstm_dim,
return_sequences=True,
name="Decoder_LSTM_" + str(dec_layer),
)
x = decoder_lstm(x, initial_state=[state_h, state_c])
if self.bn:
x = BatchNormalization(
momentum=self.bn_momentum, name="BN_Decoder_" + str(dec_layer)
)(x)
# Squeeze LSTM interconnections using Dense layers
if self.td_dense_dim > 0:
x = TimeDistributed(
Dense(self.td_dense_dim), name="Time_Distributed_" + str(dec_layer)
)(x)
# Final Dense layer to return soft labels (probabilities)
outputs = Dense(self.output_dims, activation="softmax", name="Dense_Decoder")(x)
# Define the batch_model
self.__batch_model = Model(inputs=inputs, outputs=[outputs])
# Name it!
self.batch_model._name = "batch_model"
def __build_model(self):
"""Full model that constitutes the complete pipeline.
"""
# IFF input is not encoded, stack the encoder (mol_to_latent_model)
if self.input_type == "mols":
# Input tensor (MANDATORY) - Same as the mol_to_latent_model input!
encoder_inputs = Input(shape=self.input_shape, name="Encoder_Inputs")
# Input tensor (MANDATORY) - Same as the batch_model input for teacher's forcing!
decoder_inputs = Input(shape=self.dec_input_shape, name="Decoder_Inputs")
# Stack the three models
# Propagate tensors through 1st model
x = self.mol_to_latent_model(encoder_inputs)
# Propagate tensors through 2nd model
x = self.latent_to_states_model(x)
# Append the first input of the third model to be the one for teacher's forcing
x = [decoder_inputs] + x
# Propagate tensors through 3rd model
x = self.batch_model(x)
# Define full model (SMILES -> SMILES)
self.__model = Model(inputs=[encoder_inputs, decoder_inputs], outputs=[x])
# Input is pre-encoded, no need for encoder
else:
# Input tensor (MANDATORY)
latent_input = Input(shape=(self.codelayer_dim,), name="Latent_Input")
# Input tensor (MANDATORY) - Same as the batch_model input for teacher's forcing!
decoder_inputs = Input(shape=self.dec_input_shape, name="Decoder_Inputs")
# Stack the two models
# Propagate tensors through 1st model
x = self.latent_to_states_model(latent_input)
# Append the first input of the 2nd model to be the one for teacher's forcing
x = [decoder_inputs] + x
# Propagate tensors through 2nd model
x = self.batch_model(x)
# Define full model (latent -> SMILES)
self.__model = Model(inputs=[latent_input, decoder_inputs], outputs=[x])
def __build_sample_model(self, batch_input_length) -> dict:
"""Model that predicts a single OHE character.
This model is generated from the modified config file of the batch_model.
:param batch_input_length: Size of generated batch
:type batch_input_length: int
:return: The dictionary of the configuration
:rtype: dict
"""
self.__batch_input_length = batch_input_length
# Get the configuration of the batch_model
config = self.batch_model.get_config()
# Keep only the "Decoder_Inputs" as single input to the sample_model
config["input_layers"] = [config["input_layers"][0]]
# Find decoder states that are used as inputs in batch_model and remove them
idx_list = []
for idx, layer in enumerate(config["layers"]):
if "Decoder_State_" in layer["name"]:
idx_list.append(idx)
# Pop the layer from the layer list
# Revert indices to avoid re-arranging after deleting elements
for idx in sorted(idx_list, reverse=True):
config["layers"].pop(idx)
# Remove inbound_nodes dependencies of remaining layers on deleted ones
for layer in config["layers"]:
idx_list = []
try:
for idx, inbound_node in enumerate(layer["inbound_nodes"][0]):
if "Decoder_State_" in inbound_node[0]:
idx_list.append(idx)
# Catch the exception for first layer (Decoder_Inputs) that has empty list of inbound_nodes[0]
except:
pass
# Pop the inbound_nodes from the list
# Revert indices to avoid re-arranging
for idx in sorted(idx_list, reverse=True):
layer["inbound_nodes"][0].pop(idx)
# Change the batch_shape of input layer
config["layers"][0]["config"]["batch_input_shape"] = (
batch_input_length,
1,
self.dec_input_shape[-1],
)
# Finally, change the statefulness of the RNN layers
for layer in config["layers"]:
if "Decoder_LSTM_" in layer["name"]:
layer["config"]["stateful"] = True
# layer["config"]["return_sequences"] = True
# Define the sample_model using the modified config file
sample_model = Model.from_config(config)
# Copy the trained weights from the trained batch_model to the untrained sample_model
for layer in sample_model.layers:
# Get weights from the batch_model
weights = self.batch_model.get_layer(layer.name).get_weights()
# Set the weights to the sample_model
sample_model.get_layer(layer.name).set_weights(weights)
if batch_input_length == 1:
self.__sample_model = sample_model
elif batch_input_length > 1:
self.__multi_sample_model = sample_model
return config
def __load(self, model_name):
"""Load a DDC object from a zip file.
:param model_name: Path to model
:type model_name: string
"""
print("Loading model.")
tstart = datetime.now()
# Temporary directory to extract the zipped information
with tempfile.TemporaryDirectory() as dirpath:
# Unzip the directory that contains the saved model(s)
with zipfile.ZipFile(model_name + ".zip", "r") as zip_ref:
zip_ref.extractall(dirpath)
# Load metadata
metadata = pickle.load(open(dirpath + "/metadata.pickle", "rb"))
# Re-load metadata
self.__dict__.update(metadata)
# Load all sub-models
try:
self.__mol_to_latent_model = load_model(
dirpath + "/mol_to_latent_model.h5"
)
except:
print("'mol_to_latent_model' not found, setting to None.")
self.__mol_to_latent_model = None
self.__latent_to_states_model = load_model(
dirpath + "/latent_to_states_model.h5"
)
self.__batch_model = load_model(dirpath + "/batch_model.h5")
# Build sample_model out of the trained batch_model
self.__build_sample_model(batch_input_length=1) # Single-output model
self.__build_sample_model(
batch_input_length=256 # could also be self.batch_size
) # Multi-output model
print("Loading finished in %i seconds." % ((datetime.now() - tstart).seconds))
"""
Public methods.
"""
def fit(
self,
epochs,
lr,
mini_epochs,
patience,
model_name,
gpus=1,
workers=1,
use_multiprocessing=False,
verbose=2,
max_queue_size=10,
clipvalue=0,
save_period=5,
checkpoint_dir="/",
lr_decay=False,
sch_epoch_to_start=500,
sch_last_epoch=999,
sch_lr_init=1e-3,
sch_lr_final=1e-6,
):
"""Fit the full model to the training data.
Supports multi-gpu training if gpus set to >1.
:param epochs: Training iterations over complete training set.
:type epochs: int
:param lr: Initial learning rate
:type lr: float
:param mini_epochs: Subdivisions of a single epoch to trick Keras into applying callbacks
:type mini_epochs: int
:param patience: minimum consecutive mini_epochs of stagnated learning rate to consider before lowering it with ReduceLROnPlateau
:type patience: int
:param model_name: Base name of model checkpoints
:type model_name: str
:param gpus: Number of GPUs to be used for training, defaults to 1
:type gpus: int, optional
:param workers: Keras CPU workers, defaults to 1
:type workers: int, optional
:param use_multiprocessing: Multi-CPU processing, defaults to False
:type use_multiprocessing: bool, optional
:param verbose: Keras training verbosity, defaults to 2
:type verbose: int, optional
:param max_queue_size: Keras generator max number of fetched samples, defaults to 10
:type max_queue_size: int, optional
:param clipvalue: Gradient clipping value, defaults to 0
:type clipvalue: int, optional
:param save_period: Checkpoint period in miniepochs, defaults to 5
:type save_period: int, optional
:param checkpoint_dir: Directory to store checkpoints in, defaults to "/"
:type checkpoint_dir: str, optional
:param lr_decay: Flag to enable exponential learning rate decay, defaults to False
:type lr_decay: bool, optional
:param sch_epoch_to_start: Miniepoch to start exponential learning rate decay, defaults to 500
:type sch_epoch_to_start: int, optional
:param sch_last_epoch: Last miniepoch of exponential learning rate decay, defaults to 999
:type sch_last_epoch: int, optional
:param sch_lr_init: Initial learning rate to start exponential learning rate decay, defaults to 1e-3
:type sch_lr_init: float, optional
:param sch_lr_final: Target learning rate value to stop decaying, defaults to 1e-6
:type sch_lr_final: float, optional
"""
# Get parameter values if specified
self.__epochs = epochs
self.__lr = lr
self.__clipvalue = clipvalue
# Optimizer
if clipvalue > 0:
print("Using gradient clipping %.2f." % clipvalue)
opt = Adam(lr=self.lr, clipvalue=self.clipvalue)
else:
opt = Adam(lr=self.lr)
checkpoint_file = (
checkpoint_dir + "%s--{epoch:02d}--{val_loss:.4f}--{lr:.7f}" % model_name
)
# If model is untrained, history is blank
try:
history = self.h
# Else, append the history
except:
history = {}
# Callback for saving intermediate models during training
mhcp = ModelAndHistoryCheckpoint(
filepath=checkpoint_file,
model_dict=self.__dict__,
monitor="val_loss",
verbose=1,
mode="min",
period=save_period,
history=history,
)
# Training history
self.__h = mhcp.history
if lr_decay:
lr_schedule = LearningRateSchedule(
epoch_to_start=sch_epoch_to_start,
last_epoch=sch_last_epoch,
lr_init=sch_lr_init,
lr_final=sch_lr_final,
)
lr_scheduler = LearningRateScheduler(
schedule=lr_schedule.exp_decay, verbose=1
)
callbacks = [lr_scheduler, mhcp]
else:
rlr = ReduceLROnPlateau(
monitor="val_loss",
factor=0.5,
patience=patience,
min_lr=1e-6,
verbose=1,
min_delta=1e-4,
)
callbacks = [rlr, mhcp]
# Inspect training parameters at the start of the training
self.summary()
# Parallel training on multiple GPUs
if gpus > 1:
parallel_model = multi_gpu_model(self.model, gpus=gpus)
parallel_model.compile(loss="categorical_crossentropy", optimizer=opt)
# This `fit` call will be distributed on all GPUs.
# Each GPU will process (batch_size/gpus) samples per batch.
parallel_model.fit_generator(
self.train_gen,
steps_per_epoch=self.steps_per_epoch / mini_epochs,
epochs=mini_epochs * self.epochs,
validation_data=self.valid_gen,
validation_steps=self.validation_steps / mini_epochs,
callbacks=callbacks,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
verbose=verbose,
) # 1 to show progress bar
elif gpus == 1:
self.model.compile(loss="categorical_crossentropy", optimizer=opt)
self.model.fit_generator(
self.train_gen,
steps_per_epoch=self.steps_per_epoch / mini_epochs,
epochs=mini_epochs * self.epochs,
validation_data=self.valid_gen,
validation_steps=self.validation_steps / mini_epochs,
callbacks=callbacks,
max_queue_size=10,
workers=workers,
use_multiprocessing=use_multiprocessing,
verbose=verbose,
) # 1 to show progress bar
# Build sample_model out of the trained batch_model
self.__build_sample_model(batch_input_length=1) # Single-output model
self.__build_sample_model(
batch_input_length=self.batch_size
) # Multi-output model
def vectorize(self, mols_test, leftpad=True):
"""Perform One-Hot Encoding (OHE) on a binary molecule.
:param mols_test: Molecules to vectorize
:type mols_test: list
:param leftpad: Left zero-padding direction, defaults to True
:type leftpad: bool, optional
:return: One-Hot Encoded molecules
:rtype: list
"""
if leftpad:
return self.smilesvec1.transform(mols_test)
else:
return self.smilesvec2.transform(mols_test)
def transform(self, mols_ohe):
"""Encode a batch of OHE molecules into their latent representations.
Must be called on the output of self.vectorize().
:param mols_ohe: List of One-Hot Encoded molecules
:type mols_ohe: list
:return: Latent representation of input molecules
:rtype: list
"""
latent = self.mol_to_latent_model.predict(mols_ohe)
return latent.reshape((latent.shape[0], 1, latent.shape[1]))
# @timed
def predict(self, latent, temp=1, rng_seed=None):
"""Generate a single SMILES string.
The states of the RNN are set based on the latent input.
Careful, "latent" must be: the output of self.transform()
or
an array of molecular descriptors.
If temp>0, multinomial sampling is used instead of selecting
the single most probable character at each step.
If temp==1, multinomial sampling without temperature scaling is used.
:param latent: 1D Latent vector to steer the generation
:type latent: numpy.ndarray
:param temp: Temperatute of multinomial sampling (argmax if 0), defaults to 1
:type temp: int, optional
:return: The predicted SMILES string and its NLL of being sampled
:rtype: list
"""
# Pass rng_seed for repeatable sampling
if rng_seed is not None:
np.random.seed(rng_seed)
# Scale inputs if model is trained on scaled data
if self.scaler is not None:
latent = self.scaler.transform(
latent.reshape(1, -1)
) # Re-shape because scaler complains
# Apply PCA to input if model is trained accordingly
if self.pca is not None:
latent = self.pca.transform(latent)
states = self.latent_to_states_model.predict(latent)
# Decode states and reset the LSTM cells with them to bias the generation towards the desired properties
for dec_layer in range(self.dec_layers):
self.sample_model.get_layer("Decoder_LSTM_" + str(dec_layer)).reset_states(
states=[states[2 * dec_layer], states[2 * dec_layer + 1]]
)
# Prepare the input char
startidx = self.smilesvec1._char_to_int[self.smilesvec1.startchar]
samplevec = np.zeros((1, 1, self.smilesvec1.dims[-1]))
samplevec[0, 0, startidx] = 1
smiles = ""
# Initialize Negative Log-Likelihood (NLL)
NLL = 0
# Loop and predict next char
for i in range(1000):
o = self.sample_model.predict(samplevec)
# Multinomial sampling with temperature scaling
if temp > 0:
temp = abs(temp) # Handle negative values
nextCharProbs = np.log(o) / temp
nextCharProbs = np.exp(nextCharProbs)
nextCharProbs = (
nextCharProbs / nextCharProbs.sum() - 1e-8
) # Re-normalize for float64 to make exactly 1.0 for np.random.multinomial
sampleidx = np.random.multinomial(
1, nextCharProbs.squeeze(), 1
).argmax()
# Else, select the most probable character
else:
sampleidx = np.argmax(o)
samplechar = self.smilesvec1._int_to_char[sampleidx]
if samplechar != self.smilesvec1.endchar:
# Append the new character
smiles += samplechar
samplevec = np.zeros((1, 1, self.smilesvec1.dims[-1]))
samplevec[0, 0, sampleidx] = 1
# Calculate negative log likelihood for the selected character given the sequence so far
NLL -= np.log(o[0][0][sampleidx])
else:
return smiles, NLL
# @timed
def predict_batch(self, latent, temp=1, rng_seed=None):
"""Generate multiple biased SMILES strings.
Careful, "latent" must be: the output of self.transform()
or
an array of molecular descriptors.
If temp>0, multinomial sampling is used instead of selecting
the single most probable character at each step.
If temp==1, multinomial sampling without temperature scaling is used.
Low temp leads to elimination of characters with low probabilities.
predict_many() generates batch_input_length (default==batch_size) individual SMILES
strings per call. To change that, reset batch_input_length to a new value.
:param latent: List of latent vectors
:type latent: list
:param temp: Temperatute of multinomial sampling (argmax if 0), defaults to 1
:type temp: int, optional
:return: List of predicted SMILES strings and their NLL of being sampled
:rtype: list
"""
# Pass rng_seed for repeatable sampling
if rng_seed is not None:
np.random.seed(rng_seed)
if latent.shape[0] == 1:
# Make a batch prediction by repeating the same latent vector for every neuron
latent = np.ones((self.batch_input_length, self.codelayer_dim)) * latent
else:
# Make sure it is squeezed
latent = latent.squeeze()
# Scale inputs if model is trained on scaled data
if self.scaler is not None:
latent = self.scaler.transform(latent)
# Apply PCA to input if model is trained accordingly
if self.pca is not None:
latent = self.pca.transform(latent)
# Decode states and reset the LSTM cells with them, to bias the generation towards the desired properties
states = self.latent_to_states_model.predict(latent)
for dec_layer in range(self.dec_layers):
self.multi_sample_model.get_layer(
"Decoder_LSTM_" + str(dec_layer)
).reset_states(states=[states[2 * dec_layer], states[2 * dec_layer + 1]])
# Index of input char "^"
startidx = self.smilesvec1._char_to_int[self.smilesvec1.startchar]
# Vectorize the input char for all SMILES
samplevec = np.zeros((self.batch_input_length, 1, self.smilesvec1.dims[-1]))
samplevec[:, 0, startidx] = 1
# Initialize arrays to store SMILES, their NLLs and their status
smiles = np.array([""] * self.batch_input_length, dtype=object)
NLL = np.zeros((self.batch_input_length,))
finished = np.array([False] * self.batch_input_length)
# Loop and predict next char
for i in range(1000):
o = self.multi_sample_model.predict(
samplevec, batch_size=self.batch_input_length
).squeeze()
# Multinomial sampling with temperature scaling
if temp > 0:
temp = abs(temp) # No negative values
nextCharProbs = np.log(o) / temp
nextCharProbs = np.exp(nextCharProbs) # .squeeze()
# Normalize probabilities
nextCharProbs = (nextCharProbs.T / nextCharProbs.sum(axis=1) - 1e-8).T
sampleidc = np.asarray(
[
np.random.multinomial(1, nextCharProb, 1).argmax()
for nextCharProb in nextCharProbs
]
)
else:
sampleidc = np.argmax(o, axis=1)
samplechars = [self.smilesvec1._int_to_char[idx] for idx in sampleidc]
for idx, samplechar in enumerate(samplechars):
if not finished[idx]:
if samplechar != self.smilesvec1.endchar:
# Append the SMILES with the next character
smiles[idx] += self.smilesvec1._int_to_char[sampleidc[idx]]
samplevec = np.zeros(
(self.batch_input_length, 1, self.smilesvec1.dims[-1])
)
# One-Hot Encode the character
# samplevec[:,0,sampleidc] = 1
for count, sampleidx in enumerate(sampleidc):
samplevec[count, 0, sampleidx] = 1
# Calculate negative log likelihood for the selected character given the sequence so far
NLL[idx] -= np.log(o[idx][sampleidc[idx]])
else:
finished[idx] = True
# print("SMILES has finished at %i" %i)
# If all SMILES are finished, i.e. the endchar "$" has been generated, stop the generation
if finished.sum() == len(finished):
return smiles, NLL
@timed
def get_smiles_nll(self, latent, smiles_ref) -> float:
"""Back-calculate the NLL of a given SMILES string if its descriptors are used as RNN states.
:param latent: Descriptors or latent representation of smiles_ref
:type latent: list
:param smiles_ref: Given SMILES to back-calculate its NLL
:type smiles_ref: str
:return: NLL of sampling smiles_ref given its latent representation (or descriptors)
:rtype: float
"""
# Scale inputs if model is trained on scaled data
if self.scaler is not None:
latent = self.scaler.transform(
latent.reshape(1, -1)
) # Re-shape because scaler complains
# Apply PCA to input if model is trained accordingly
if self.pca is not None:
latent = self.pca.transform(latent)
states = self.latent_to_states_model.predict(latent)
# Decode states and reset the LSTM cells with them to bias the generation towards the desired properties
for dec_layer in range(self.dec_layers):
self.sample_model.get_layer("Decoder_LSTM_" + str(dec_layer)).reset_states(
states=[states[2 * dec_layer], states[2 * dec_layer + 1]]
)
# Prepare the input char
startidx = self.smilesvec1._char_to_int[self.smilesvec1.startchar]
samplevec = np.zeros((1, 1, self.smilesvec1.dims[-1]))
samplevec[0, 0, startidx] = 1
# Initialize Negative Log-Likelihood (NLL)
NLL = 0
# Loop and predict next char
for i in range(1000):
o = self.sample_model.predict(samplevec)
samplechar = smiles_ref[i]
sampleidx = self.smilesvec1._char_to_int[samplechar]
if i != len(smiles_ref) - 1:
samplevec = np.zeros((1, 1, self.smilesvec1.dims[-1]))
samplevec[0, 0, sampleidx] = 1
# Calculate negative log likelihood for the selected character given the sequence so far
NLL -= np.log(o[0][0][sampleidx])
else:
return NLL
@timed
def get_smiles_nll_batch(self, latent, smiles_ref) -> list:
"""Back-calculate the individual NLL for a batch of known SMILES strings.
Batch size is equal to self.batch_input_length so reset it if needed.
:param latent: List of latent representations (or descriptors)
:type latent: list
:param smiles_ref: List of given SMILES to back-calculate their NLL
:type smiles_ref: list
:return: List of NLL of sampling smiles_ref given their latent representations (or descriptors)
:rtype: list
"""
assert (
len(latent) <= self.batch_input_length
), "Input length must be less than or equal to batch_input_length."
# Scale inputs if model is trained on scaled data
if self.scaler is not None:
latent = self.scaler.transform(latent)
# Apply PCA to input if model is trained accordingly
if self.pca is not None:
latent = self.pca.transform(latent)
# Decode states and reset the LSTM cells with them, to bias the generation towards the desired properties
states = self.latent_to_states_model.predict(latent)
for dec_layer in range(self.dec_layers):
self.multi_sample_model.get_layer(
"Decoder_LSTM_" + str(dec_layer)
).reset_states(states=[states[2 * dec_layer], states[2 * dec_layer + 1]])
# Index of input char "^"
startidx = self.smilesvec1._char_to_int[self.smilesvec1.startchar]
# Vectorize the input char for all SMILES
samplevec = np.zeros((self.batch_input_length, 1, self.smilesvec1.dims[-1]))
samplevec[:, 0, startidx] = 1
# Initialize arrays to store NLLs and flag if a SMILES is finished
NLL = np.zeros((self.batch_input_length,))
finished = np.array([False] * self.batch_input_length)
# Loop and predict next char
for i in range(1000):
o = self.multi_sample_model.predict(
samplevec, batch_size=self.batch_input_length
).squeeze()
samplechars = []
for smiles in smiles_ref:
try:
samplechars.append(smiles[i])
except:
# This is a finished SMILES, so "i" exceeds dimensions
samplechars.append("$")
sampleidc = np.asarray(
[self.smilesvec1._char_to_int[char] for char in samplechars]
)
for idx, samplechar in enumerate(samplechars):
if not finished[idx]:
if i != len(smiles_ref[idx]) - 1:
samplevec = np.zeros(
(self.batch_input_length, 1, self.smilesvec1.dims[-1])
)
# One-Hot Encode the character
for count, sampleidx in enumerate(sampleidc):
samplevec[count, 0, sampleidx] = 1
# Calculate negative log likelihood for the selected character given the sequence so far
NLL[idx] -= np.log(o[idx][sampleidc[idx]])
else:
finished[idx] = True
# If all SMILES are finished, i.e. the endchar "$" has been generated, stop the generation
if finished.sum() == len(finished):
return NLL
def summary(self):
"""Echo the training configuration for inspection.
"""
print(
"\nModel trained with dataset %s that has maxlen=%d and charset=%s for %d epochs."
% (self.dataset_name, self.maxlen, self.charset, self.epochs)
)
print(
"noise_std: %.6f, lstm_dim: %d, dec_layers: %d, td_dense_dim: %d, batch_size: %d, codelayer_dim: %d, lr: %.6f."
% (
self.noise_std,
self.lstm_dim,
self.dec_layers,
self.td_dense_dim,
self.batch_size,
self.codelayer_dim,
self.lr,
)
)
def get_graphs(self):
"""Export the graphs of the model and its submodels to png files.
Requires "pydot" and "graphviz" to be installed (pip install graphviz && pip install pydot).
"""
try:
from keras.utils import plot_model
from keras.utils.vis_utils import model_to_dot
# from IPython.display import SVG
plot_model(self.model, to_file="model.png")
plot_model(
self.latent_to_states_model, to_file="latent_to_states_model.png"
)
plot_model(self.batch_model, to_file="batch_model.png")
if self.mol_to_latent_model is not None:
plot_model(self.mol_to_latent_model, to_file="mol_to_latent_model.png")
print("Models exported to png files.")
except:
print("Check pydot and graphviz installation.")
@timed
def save(self, model_name):
"""Save model in a zip file.
:param model_name: Path to save model in
:type model_name: str
"""
with tempfile.TemporaryDirectory() as dirpath:
# Save the Keras models
if self.mol_to_latent_model is not None:
self.mol_to_latent_model.save(dirpath + "/mol_to_latent_model.h5")
self.latent_to_states_model.save(dirpath + "/latent_to_states_model.h5")
self.batch_model.save(dirpath + "/batch_model.h5")
# Exclude unpicklable and unwanted attributes
excl_attr = [
"_DDC__mode",
"_DDC__train_gen",
"_DDC__valid_gen",
"_DDC__mol_to_latent_model",
"_DDC__latent_to_states_model",
"_DDC__batch_model",
"_DDC__sample_model",
"_DDC__multi_sample_model",
"_DDC__model",
]
# Cannot deepcopy self.__dict__ because of Keras' thread lock so this is
# bypassed by popping and re-inserting the unpicklable attributes
to_add = {}
# Remove unpicklable attributes
for attr in excl_attr:
to_add[attr] = self.__dict__.pop(attr, None)
# Pickle metadata, i.e. almost everything but the Keras models and generators
pickle.dump(self.__dict__, open(dirpath + "/metadata.pickle", "wb"))
# Zip directory with its contents
shutil.make_archive(model_name, "zip", dirpath)
# Finally, re-load the popped elements for the model to be usable
for attr in excl_attr:
self.__dict__[attr] = to_add[attr]
print("Model saved.")