-
Notifications
You must be signed in to change notification settings - Fork 0
/
AE-PCA2.py
317 lines (253 loc) · 10.7 KB
/
AE-PCA2.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
import os
import numpy as np
from rdkit import Chem
from rdkit.Chem import Draw, Descriptors
from matplotlib import pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from numpy.random import seed
from tensorflow import set_random_seed
import sklearn
from sklearn import datasets
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn import decomposition
import scipy
import tensorflow as tf
from keras.models import Model, load_model
from keras.layers import Input, Dense, Layer, InputSpec
from keras.callbacks import ModelCheckpoint, TensorBoard
from keras import regularizers, activations, initializers, constraints, Sequential
from keras import backend as K
from keras.constraints import UnitNorm, Constraint
from keras.models import Model
from keras.layers import Input
from keras.layers import LSTM
from keras.layers import Dense
from keras.layers import Concatenate
from keras import regularizers
class WeightsOrthogonalityConstraint (Constraint):
def __init__(self, encoding_dim, weightage = 1.0, axis = 0):
self.encoding_dim = encoding_dim
self.weightage = weightage
self.axis = axis
def weights_orthogonality(self, w):
if(self.axis==1):
w = K.transpose(w)
if(self.encoding_dim > 1):
m = K.dot(K.transpose(w), w) - K.eye(self.encoding_dim)
return self.weightage * K.sqrt(K.sum(K.square(m)))
else:
m = K.sum(w ** 2) - 1.
return m
def __call__(self, w):
return self.weights_orthogonality(w)
smifile = 'Data\chembl_smiles.txt'
data = pd.read_csv(smifile, delimiter="\t", names=["smiles", "No", "Int"])
smiles_train, smiles_test = train_test_split(data["smiles"], random_state=42)
print(smiles_train.shape)
print(smiles_test.shape)
'''data = pd.read_csv('Data\SARS-Cov.csv',names=["PUBCHEM_CID","SMILES","FOLD","PUBCHEM_ACTIVITY_OUTCOME_ASY0","PUBCHEM_ACTIVITY_OUTCOME_ASY1","PUBCHEM_ACTIVITY_OUTCOME_ASY2","PUBCHEM_ACTIVITY_OUTCOME_ASY3"])
print(data["SMILES"])
smiles_train, smiles_test = train_test_split(data["SMILES"], random_state=42)
print(smiles_train.shape)
print(smiles_test.shape)'''
charset = set("".join(list(data.smiles))+"!E")
char_to_int = dict((c,i) for i,c in enumerate(charset))
int_to_char = dict((i,c) for i,c in enumerate(charset))
embed = max([len(smile) for smile in data.smiles]) + 5
charset = set("".join(list(data.smiles))+"!E")
char_to_int = dict((c,i) for i,c in enumerate(charset))
int_to_char = dict((i,c) for i,c in enumerate(charset))
embed = max([len(smile) for smile in data.smiles]) + 5
def vectorize(smiles):
one_hot = np.zeros((smiles.shape[0], embed, len(charset)), dtype=np.int8)
for i, smile in enumerate(smiles):
# encode the startchar
one_hot[i, 0, char_to_int["!"]] = 1
# encode the rest of the chars
for j, c in enumerate(smile):
one_hot[i, j + 1, char_to_int[c]] = 1
# Encode endchar
one_hot[i, len(smile) + 1:, char_to_int["E"]] = 1
# Return two, one for input and the other for output
return one_hot[:, 0:-1, :], one_hot[:, 1:, :]
X_train, Y_train = vectorize(smiles_train.values)
X_test, Y_test = vectorize(smiles_test.values)
print("X",X_train.shape,X_test.shape)
input_shape = X_train.shape[1:]
print(input_shape)
output_dim = Y_train.shape[-1]
latent_dim = 64
lstm_dim = 64
unroll = False
encoder_inputs = Input(shape=input_shape)
encoder = LSTM(lstm_dim, return_state=True,
unroll=unroll)
encoder_outputs, state_h, state_c = encoder(encoder_inputs)
states = Concatenate(axis=-1)([state_h, state_c])
neck = Dense(latent_dim, activation="relu",use_bias = True,
kernel_regularizer=WeightsOrthogonalityConstraint(64,
))
neck_outputs = neck(states)
decode_h = Dense(lstm_dim, activation="relu")
decode_c = Dense(lstm_dim, activation="relu")
state_h_decoded = decode_h(neck_outputs)
state_c_decoded = decode_c(neck_outputs)
encoder_states = [state_h_decoded, state_c_decoded]
decoder_inputs = Input(shape=input_shape)
decoder_lstm = LSTM(lstm_dim,
return_sequences=True,
unroll=unroll
)
decoder_outputs = decoder_lstm(decoder_inputs, initial_state=encoder_states)
decoder_dense = Dense(output_dim, activation='softmax',use_bias = True,
kernel_regularizer=WeightsOrthogonalityConstraint(64,
axis=1))
decoder_outputs = decoder_dense(decoder_outputs)
#Define the model, that inputs the training vector for two places, and predicts one character ahead of the input
model = Model([encoder_inputs, decoder_inputs], decoder_outputs)
#print (model.summary())
from keras.callbacks import History, ReduceLROnPlateau
h = History()
rlr = ReduceLROnPlateau(monitor='val_loss', factor=0.5,patience=10, min_lr=0.000001, verbose=1, min_delta=1e-5)
from keras.optimizers import RMSprop, Adam
opt=Adam(lr=0.005) #Default 0.001
model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])
model.fit([X_train,X_train],Y_train,
epochs=200,
batch_size=256,
shuffle=True,
callbacks=[h, rlr],
validation_data=[[X_test,X_test],Y_test ])
import pickle
file = open('Blog_history','wb')
pickle.dump(h.history, file)
plt.plot(h.history["loss"], label="Loss")
plt.plot(h.history["val_loss"], label="Val_Loss")
plt.yscale("log")
plt.legend()
for i in range(2):
v = model.predict([X_test[i:i+1], X_test[i:i+1]]) #Can't be done as output not necessarely 1
idxs = np.argmax(v, axis=2)
pred= "".join([int_to_char[h] for h in idxs[0]])[:-1]
idxs2 = np.argmax(X_test[i:i+1], axis=2)
true = "".join([int_to_char[k] for k in idxs2[0]])[1:]
if true != pred:
print (true, pred)
smiles_to_latent_model = Model(encoder_inputs, neck_outputs)
smiles_to_latent_model.save("Blog_simple_smi2lat.h5")
latent_input = Input(shape=(latent_dim,))
#reuse_layers
state_h_decoded_2 = decode_h(latent_input)
state_c_decoded_2 = decode_c(latent_input)
latent_to_states_model = Model(latent_input, [state_h_decoded_2, state_c_decoded_2])
latent_to_states_model.save("Blog_simple_lat2state.h5")
inf_decoder_inputs = Input(batch_shape=(1, 1, input_shape[1]))
inf_decoder_lstm = LSTM(lstm_dim,
return_sequences=True,
unroll=unroll,
stateful=True
)
inf_decoder_outputs = inf_decoder_lstm(inf_decoder_inputs)
inf_decoder_dense = Dense(output_dim, activation='softmax')
inf_decoder_outputs = inf_decoder_dense(inf_decoder_outputs)
sample_model = Model(inf_decoder_inputs, inf_decoder_outputs)
for i in range(1,3):
sample_model.layers[i].set_weights(model.layers[i+6].get_weights())
sample_model.save("Blog_simple_samplemodel.h5")
x_latent = smiles_to_latent_model.predict(X_test)
molno = 3
latent_mol = smiles_to_latent_model.predict(X_test[molno:molno+1])
sorti = np.argsort(np.sum(np.abs(x_latent - latent_mol), axis=1))
print (sorti[0:4])
print (smiles_test.iloc[sorti[0:4]])
Draw.MolsToImage(smiles_test.iloc[sorti[1:2]].apply(Chem.MolFromSmiles))
Draw.MolsToImage(smiles_test.iloc[sorti[1:2]].apply(Chem.MolFromSmiles))
log= smiles_test.apply(Chem.MolFromSmiles)
latent_mol = smiles_to_latent_model.predict(X_test[molno:molno+1])
sorti = np.argsort(np.sum(np.abs(x_latent - latent_mol), axis=1))
print (sorti[0:2])
print (smiles_test.iloc[sorti[0:2]])
Draw.MolsToImage(smiles_test.iloc[sorti[0:2]].apply(Chem.MolFromSmiles))
Draw.MolsToImage(smiles_test.iloc[sorti[0:2]].apply(Chem.MolFromSmiles))
#logp = log.apply(Descriptors.MolLogP)
###########################################PCA
logp = smiles_test.apply(Chem.MolFromSmiles).apply(Descriptors.MolLogP)
from sklearn.decomposition import PCA
pca = PCA(n_components = 2)
red = pca.fit_transform(x_latent)
plt.figure()
plt.scatter(red[:,0], red[:,1],marker='.', c= logp)
print(pca.explained_variance_ratio_, np.sum(pca.explained_variance_ratio_))
molwt = smiles_test.apply(Chem.MolFromSmiles).apply(Descriptors.MolMR)
plt.figure()
plt.scatter(red[:,0], red[:,1],marker='.', c= molwt)
############################################################################
x_train_latent = smiles_to_latent_model.predict(X_train)
logp_train = smiles_train.apply(Chem.MolFromSmiles).apply(Descriptors.MolLogP)
from keras.models import Sequential
logp_model = Sequential()
logp_model.add(Dense(128, input_shape=(latent_dim,), activation="relu"))
logp_model.add(Dense(128, activation="relu"))
logp_model.add(Dense(1))
logp_model.compile(optimizer="adam", loss="mse")
rlr = ReduceLROnPlateau(monitor='val_loss', factor=0.5,patience=10, min_lr=0.000001, verbose=1, epsilon=1e-5)
logp_model.fit(x_train_latent, logp_train, batch_size=128, epochs=400, callbacks = [rlr])
logp_pred_train = logp_model.predict(x_train_latent)
logp_pred_test = logp_model.predict(x_latent)
plt.scatter(logp, logp_pred_test, label="Test")
plt.scatter(logp_train, logp_pred_train, label="Train")
plt.legend()
#########################################################################
def latent_to_smiles(latent):
#decode states and set Reset the LSTM cells with them
states = latent_to_states_model.predict(latent)
sample_model.layers[1].reset_states(states=[states[0],states[1]])
#Prepare the input char
startidx = char_to_int["!"]
samplevec = np.zeros((1,1,11))
samplevec[0,0,startidx] = 1
smiles = ""
#Loop and predict next char
for i in range(28):
o = sample_model.predict(samplevec)
sampleidx = np.argmax(o)
samplechar = int_to_char[sampleidx]
if samplechar != "E":
smiles = smiles + int_to_char[sampleidx]
samplevec = np.zeros((1,1,11))
samplevec[0,0,sampleidx] = 1
else:
break
return smiles
smiles = latent_to_smiles(x_latent[0:1])
print (smiles)
print (smiles_test.iloc[0])
wrong = 0
for i in range(985):
smiles = latent_to_smiles(x_latent[i:i+1])
mol = Chem.MolFromSmiles(smiles)
if mol:
pass
else:
print (smiles)
wrong = wrong + 1
print ("%0.1F percent wrongly formatted smiles"%(wrong/float(1000)*100))
#0.5
#Interpolation test in latent_space
i = 0
j= 2
latent1 = x_latent[j:j+1]
latent0 = x_latent[i:i+1]
mols1 = []
ratios = np.linspace(0,1,25)
for r in ratios:
#print r
rlatent = (1.0-r)*latent0 + r*latent1
smiles = latent_to_smiles(rlatent)
mol = Chem.MolFromSmiles(smiles)
if mol:
mols1.append(mol)
else:
print (smiles)
Draw.MolsToGridImage(mols1, molsPerRow=5)