forked from YifanDengWHU/DDIMDL
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCNN_DDI_tf.py
More file actions
512 lines (447 loc) · 20.6 KB
/
CNN_DDI_tf.py
File metadata and controls
512 lines (447 loc) · 20.6 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
# from NLPProcess import NLPProcess
from numpy.random import seed
seed(1)
from tensorflow import set_random_seed
set_random_seed(1)
import csv
import sqlite3
import time
import numpy as np
import pandas as pd
from pandas import DataFrame
from sklearn.model_selection import KFold
from sklearn.decomposition import PCA
from sklearn.metrics import auc
from sklearn.metrics import roc_auc_score
from sklearn.metrics import accuracy_score
from sklearn.metrics import recall_score
from sklearn.metrics import f1_score
from sklearn.metrics import precision_score
from sklearn.metrics import precision_recall_curve
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import label_binarize
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import GradientBoostingClassifier
import tensorflow as tf
def set_max_gpu_mem(limit=9*1024):
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
try:
# Restrict TensorFlow to only allocate 10GB of memory on the first GPU
tf.config.experimental.set_virtual_device_configuration(
gpus[0],
[tf.config.experimental.VirtualDeviceConfiguration(memory_limit=limit)])
logical_gpus = tf.config.experimental.list_logical_devices('GPU')
print(len(gpus), "Physical GPU,", len(logical_gpus), "Logical GPU(s) with 10GB memory limit")
except RuntimeError as e:
# Virtual devices must be set before GPUs have been initialized
print(e)
set_max_gpu_mem()
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, Dropout, Input, Activation, BatchNormalization
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.callbacks import ModelCheckpoint
from tensorflow.keras.models import load_model
print("TensorFlow version:", tf.__version__)
print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))
MEGA = 10 ** 6
def print_memory_usage():
"""Prints current memory usage stats.
See: https://stackoverflow.com/a/15495136
:return: None
"""
import psutil,os
PROCESS = psutil.Process(os.getpid())
total, available, percent, used, free, *_ = psutil.virtual_memory()
total, available, used, free= total / MEGA, available / MEGA, used / MEGA, free / MEGA
proc = PROCESS.memory_info()[1] / MEGA
print('process = %s total = %s available = %s used = %s free = %s percent = %s'
% (proc, total, available, used, free, percent))
event_num = 65
droprate = 0.3
vector_size = 572
checkpoint_path = "checkpoints/cp.ckpt"
# Create a ModelCheckpoint callback that saves the model's weights
cp_callback = ModelCheckpoint(filepath=checkpoint_path,
save_weights_only=True,
verbose=1)
model_checkpoint_callback = ModelCheckpoint(
filepath='checkpoints/model_{epoch:02d}-{val_loss:.2f}.hdf5',
save_best_only=True,
monitor='val_loss',
mode='min',
verbose=1)
def DNN():
train_input = Input(shape=(vector_size * 2,), name='Inputlayer')
train_in = Dense(512, activation='relu')(train_input)
train_in = BatchNormalization()(train_in)
train_in = Dropout(droprate)(train_in)
train_in = Dense(256, activation='relu')(train_in)
train_in = BatchNormalization()(train_in)
train_in = Dropout(droprate)(train_in)
train_in = Dense(event_num)(train_in)
out = Activation('softmax')(train_in)
model = Model(inputs=train_input, outputs=out)
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
return model
# from keras.models import Model
# from keras.layers import Input, Dense, Conv1D, BatchNormalization, Activation, Flatten, Dropout, Add
from tensorflow.keras.layers import Conv1D, Flatten, Add
from tensorflow.keras.layers import LeakyReLU
def CNN_DDI():
# Define the input layer
inputs = Input(shape=(572, 2), name='InputLayer')
# Convolutional layers as specified in the paper
conv1 = Conv1D(filters=64, kernel_size=3, strides=1, padding='same')(inputs)
conv1 = LeakyReLU(alpha=0.2)(conv1)
conv2 = Conv1D(filters=128, kernel_size=3, strides=1, padding='same')(conv1)
conv2 = LeakyReLU(alpha=0.2)(conv2)
# Residual block starts
conv3_1 = Conv1D(filters=128, kernel_size=3, strides=1, padding='same')(conv2)
conv3_1 = LeakyReLU(alpha=0.2)(conv3_1)
conv3_2 = Conv1D(filters=128, kernel_size=3, strides=1, padding='same')(conv3_1)
conv3_2 = LeakyReLU(alpha=0.2)(conv3_2)
# Add the input of the residual block (conv2) to its output (conv3_2)
res_out = Add()([conv2, conv3_2])
# Residual block ends
conv4 = Conv1D(filters=256, kernel_size=3, strides=1, padding='same')(res_out)
conv4 = LeakyReLU(alpha=0.2)(conv4)
# Flatten the output of the last convolutional layer
flatten = Flatten()(conv4)
# Fully connected layers
fc1 = Dense(267, activation='relu')(flatten)
# fc1 = BatchNormalization()(fc1)
# fc1 = Dropout(droprate)(fc1)
fc2 = Dense(event_num)(fc1) # Assuming 'num_classes' is the number of DDI event types
out = Activation('softmax')(fc2)
# Create the model
model = Model(inputs=inputs, outputs=out)
model.summary()
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
return model
def prepare(df_drug, feature_list, vector_size,mechanism,action,drugA,drugB):
d_label = {}
d_feature = {}
# Transfrom the interaction event to number
# Splice the features
d_event=[]
for i in range(len(mechanism)):
d_event.append(mechanism[i]+" "+action[i])
label_value = 0
count={}
for i in d_event:
if i in count:
count[i]+=1
else:
count[i]=1
list1 = sorted(count.items(), key=lambda x: x[1],reverse=True)
for i in range(len(list1)):
d_label[list1[i][0]]=i
vector = np.zeros((len(np.array(df_drug['name']).tolist()), 0), dtype=float)
for i in feature_list:
vector = np.hstack((vector, feature_vector(i, df_drug, vector_size)))
# Transfrom the drug ID to feature vector
for i in range(len(np.array(df_drug['name']).tolist())):
d_feature[np.array(df_drug['name']).tolist()[i]] = vector[i]
# Use the dictionary to obtain feature vector and label
new_feature = []
new_label = []
name_to_id = {}
for i in range(len(d_event)):
new_feature.append(np.hstack((d_feature[drugA[i]], d_feature[drugB[i]])))
new_label.append(d_label[d_event[i]])
new_feature = np.array(new_feature)
new_label = np.array(new_label)
return (new_feature, new_label, event_num)
def feature_vector(feature_name, df, vector_size):
# df are the 572 kinds of drugs
# Jaccard Similarity
def Jaccard(matrix):
matrix = np.mat(matrix)
numerator = matrix * matrix.T
denominator = np.ones(np.shape(matrix)) * matrix.T + matrix * np.ones(np.shape(matrix.T)) - matrix * matrix.T
return numerator / denominator
all_feature = []
drug_list = np.array(df[feature_name]).tolist()
# Features for each drug, for example, when feature_name is target, drug_list=["P30556|P05412","P28223|P46098|……"]
for i in drug_list:
for each_feature in i.split('|'):
if each_feature not in all_feature:
all_feature.append(each_feature) # obtain all the features
feature_matrix = np.zeros((len(drug_list), len(all_feature)), dtype=float)
df_feature = DataFrame(feature_matrix, columns=all_feature) # Consrtuct feature matrices with key of dataframe
for i in range(len(drug_list)):
for each_feature in df[feature_name].iloc[i].split('|'):
df_feature[each_feature].iloc[i] = 1
sim_matrix = Jaccard(np.array(df_feature))
sim_matrix1 = np.array(sim_matrix)
count = 0
pca = PCA(n_components=vector_size) # PCA dimension
sim_matrix = np.asarray(sim_matrix)
pca.fit(sim_matrix)
sim_matrix = pca.transform(sim_matrix)
return sim_matrix
def get_index(label_matrix, event_num, seed, CV):
index_all_class = np.zeros(len(label_matrix))
for j in range(event_num):
index = np.where(label_matrix == j)
kf = KFold(n_splits=CV, shuffle=True, random_state=seed)
k_num = 0
for train_index, test_index in kf.split(range(len(index[0]))):
index_all_class[index[0][test_index]] = k_num
k_num += 1
return index_all_class
def cross_validation(feature_matrix, label_matrix, clf_type, event_num, seed, CV, set_name):
all_eval_type = 11
result_all = np.zeros((all_eval_type, 1), dtype=float)
each_eval_type = 6
result_eve = np.zeros((event_num, each_eval_type), dtype=float)
y_true = np.array([])
y_pred = np.array([])
y_score = np.zeros((0, event_num), dtype=float)
index_all_class = get_index(label_matrix, event_num, seed, CV)
matrix = []
if type(feature_matrix) != list:
matrix.append(feature_matrix)
# =============================================================================
# elif len(np.shape(feature_matrix))==3:
# for i in range((np.shape(feature_matrix)[-1])):
# matrix.append(feature_matrix[:,:,i])
# =============================================================================
feature_matrix = matrix
for k in range(CV):
train_index = np.where(index_all_class != k)
test_index = np.where(index_all_class == k)
pred = np.zeros((len(test_index[0]), event_num), dtype=float)
# dnn=DNN()
print(len(feature_matrix))
for i in range(len(feature_matrix)):
x_train = feature_matrix[i][train_index]
x_test = feature_matrix[i][test_index]
y_train = label_matrix[train_index]
# one-hot encoding
y_train_one_hot = np.array(y_train)
y_train_one_hot = (np.arange(y_train_one_hot.max() + 1) == y_train[:, None]).astype(dtype='float32')
y_test = label_matrix[test_index]
# one-hot encoding
y_test_one_hot = np.array(y_test)
y_test_one_hot = (np.arange(y_test_one_hot.max() + 1) == y_test[:, None]).astype(dtype='float32')
if clf_type == 'DDIMDL':
dnn = DNN()
early_stopping = EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='auto')
dnn.fit(x_train, y_train_one_hot, batch_size=128, epochs=100, validation_data=(x_test, y_test_one_hot),
callbacks=[early_stopping])
pred += dnn.predict(x_test)
continue
elif clf_type == 'CNN_DDI':
x_train_reshaped = x_train.reshape(-1, 572, 2)
x_test_reshaped = x_test.reshape(-1, 572, 2)
cnn_ddi = CNN_DDI()
print_memory_usage()
# print(x_train_reshaped.shape)
# print(x_test_reshaped.shape)
# print(y_train_one_hot.shape, y_test_one_hot.shape)
early_stopping = EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='auto')
cnn_ddi.fit(x_train_reshaped, y_train_one_hot, batch_size=128, epochs=100, validation_data=(x_test_reshaped, y_test_one_hot),
callbacks=[early_stopping, cp_callback])
pred += cnn_ddi.predict(x_test_reshaped)
continue
elif clf_type == 'RF':
clf = RandomForestClassifier(n_estimators=100)
elif clf_type == 'GBDT':
clf = GradientBoostingClassifier()
elif clf_type == 'SVM':
clf = SVC(probability=True)
elif clf_type == 'FM':
clf = GradientBoostingClassifier()
elif clf_type == 'KNN':
clf = KNeighborsClassifier(n_neighbors=4)
else:
clf = LogisticRegression()
clf.fit(x_train, y_train)
pred += clf.predict_proba(x_test)
pred_score = pred / len(feature_matrix)
pred_type = np.argmax(pred_score, axis=1)
y_true = np.hstack((y_true, y_test))
y_pred = np.hstack((y_pred, pred_type))
y_score = np.row_stack((y_score, pred_score))
result_all, result_eve = evaluate(y_pred, y_score, y_true, event_num, set_name)
# =============================================================================
# a,b=evaluate(pred_type,pred_score,y_test,event_num)
# for i in range(all_eval_type):
# result_all[i]+=a[i]
# for i in range(each_eval_type):
# result_eve[:,i]+=b[:,i]
# result_all=result_all/5
# result_eve=result_eve/5
# =============================================================================
return result_all, result_eve
def evaluate(pred_type, pred_score, y_test, event_num, set_name):
all_eval_type = 11
result_all = np.zeros((all_eval_type, 1), dtype=float)
each_eval_type = 6
result_eve = np.zeros((event_num, each_eval_type), dtype=float)
y_one_hot = label_binarize(y_test, classes=np.arange(event_num))
pred_one_hot = label_binarize(pred_type, classes=np.arange(event_num))
precision, recall, th = multiclass_precision_recall_curve(y_one_hot, pred_score)
result_all[0] = accuracy_score(y_test, pred_type)
result_all[1] = roc_aupr_score(y_one_hot, pred_score, average='micro')
result_all[2] = roc_aupr_score(y_one_hot, pred_score, average='macro')
result_all[3] = roc_auc_score(y_one_hot, pred_score, average='micro')
result_all[4] = roc_auc_score(y_one_hot, pred_score, average='macro')
result_all[5] = f1_score(y_test, pred_type, average='micro')
result_all[6] = f1_score(y_test, pred_type, average='macro')
result_all[7] = precision_score(y_test, pred_type, average='micro')
result_all[8] = precision_score(y_test, pred_type, average='macro')
result_all[9] = recall_score(y_test, pred_type, average='micro')
result_all[10] = recall_score(y_test, pred_type, average='macro')
for i in range(event_num):
result_eve[i, 0] = accuracy_score(y_one_hot.take([i], axis=1).ravel(), pred_one_hot.take([i], axis=1).ravel())
result_eve[i, 1] = roc_aupr_score(y_one_hot.take([i], axis=1).ravel(), pred_one_hot.take([i], axis=1).ravel(),
average=None)
result_eve[i, 2] = roc_auc_score(y_one_hot.take([i], axis=1).ravel(), pred_one_hot.take([i], axis=1).ravel(),
average=None)
result_eve[i, 3] = f1_score(y_one_hot.take([i], axis=1).ravel(), pred_one_hot.take([i], axis=1).ravel(),
average='binary')
result_eve[i, 4] = precision_score(y_one_hot.take([i], axis=1).ravel(), pred_one_hot.take([i], axis=1).ravel(),
average='binary')
result_eve[i, 5] = recall_score(y_one_hot.take([i], axis=1).ravel(), pred_one_hot.take([i], axis=1).ravel(),
average='binary')
return [result_all, result_eve]
def self_metric_calculate(y_true, pred_type):
y_true = y_true.ravel()
y_pred = pred_type.ravel()
if y_true.ndim == 1:
y_true = y_true.reshape((-1, 1))
if y_pred.ndim == 1:
y_pred = y_pred.reshape((-1, 1))
y_true_c = y_true.take([0], axis=1).ravel()
y_pred_c = y_pred.take([0], axis=1).ravel()
TP = 0
TN = 0
FN = 0
FP = 0
for i in range(len(y_true_c)):
if (y_true_c[i] == 1) and (y_pred_c[i] == 1):
TP += 1
if (y_true_c[i] == 1) and (y_pred_c[i] == 0):
FN += 1
if (y_true_c[i] == 0) and (y_pred_c[i] == 1):
FP += 1
if (y_true_c[i] == 0) and (y_pred_c[i] == 0):
TN += 1
print("TP=", TP, "FN=", FN, "FP=", FP, "TN=", TN)
return (TP / (TP + FP), TP / (TP + FN))
def multiclass_precision_recall_curve(y_true, y_score):
y_true = y_true.ravel()
y_score = y_score.ravel()
if y_true.ndim == 1:
y_true = y_true.reshape((-1, 1))
if y_score.ndim == 1:
y_score = y_score.reshape((-1, 1))
y_true_c = y_true.take([0], axis=1).ravel()
y_score_c = y_score.take([0], axis=1).ravel()
precision, recall, pr_thresholds = precision_recall_curve(y_true_c, y_score_c)
return (precision, recall, pr_thresholds)
def roc_aupr_score(y_true, y_score, average="macro"):
def _binary_roc_aupr_score(y_true, y_score):
precision, recall, pr_thresholds = precision_recall_curve(y_true, y_score)
return auc(recall, precision)
def _average_binary_score(binary_metric, y_true, y_score, average): # y_true= y_one_hot
if average == "binary":
return binary_metric(y_true, y_score)
if average == "micro":
y_true = y_true.ravel()
y_score = y_score.ravel()
if y_true.ndim == 1:
y_true = y_true.reshape((-1, 1))
if y_score.ndim == 1:
y_score = y_score.reshape((-1, 1))
n_classes = y_score.shape[1]
score = np.zeros((n_classes,))
for c in range(n_classes):
y_true_c = y_true.take([c], axis=1).ravel()
y_score_c = y_score.take([c], axis=1).ravel()
score[c] = binary_metric(y_true_c, y_score_c)
return np.average(score)
return _average_binary_score(_binary_roc_aupr_score, y_true, y_score, average)
def drawing(d_result, contrast_list, info_list):
column = []
for i in contrast_list:
column.append(i)
df = pd.DataFrame(columns=column)
if info_list[-1] == 'aupr':
for i in contrast_list:
df[i] = d_result[i][:, 1]
else:
for i in contrast_list:
df[i] = d_result[i][:, 2]
df = df.astype('float')
color = dict(boxes='DarkGreen', whiskers='DarkOrange', medians='DarkBlue', caps='Gray')
df.plot.box(ylim=[0, 1.0], grid=True, color=color)
return 0
def save_result(feature_name, result_type, clf_type, result):
with open(feature_name + '_' + result_type + '_' + clf_type+ '.csv', "w", newline='') as csvfile:
writer = csv.writer(csvfile)
for i in result:
writer.writerow(i)
return 0
import os
# Main function adjusted for Jupyter Notebook
def main(args):
seed = 0
CV = 5
interaction_num = 10
print(os.path.curdir)
# Ensure you have the 'event.db' file accessible in your Google Colab environment.
# You might need to upload it or access it from Google Drive.
conn = sqlite3.connect("event.db")
df_drug = pd.read_sql('select * from drug;', conn)
df_event = pd.read_sql('select * from event_number;', conn)
df_interaction = pd.read_sql('select * from event;', conn)
feature_list = args['featureList']
featureName = "+".join(feature_list)
clf_list = args['classifier']
for feature in feature_list:
set_name = feature + '+'
set_name = set_name[:-1]
result_all = {}
result_eve = {}
all_matrix = []
drugList = []
for line in open("DrugList.txt", 'r'):
drugList.append(line.split()[0])
if args['NLPProcess'] == "read":
extraction = pd.read_sql('select * from extraction;', conn)
mechanism = extraction['mechanism']
action = extraction['action']
drugA = extraction['drugA']
drugB = extraction['drugB']
else:
pass
# mechanism, action, drugA, drugB = NLPProcess(drugList, df_interaction)
for feature in feature_list:
print(feature)
new_feature, new_label, event_num = prepare(df_drug, [feature], vector_size, mechanism, action, drugA, drugB)
all_matrix.append(new_feature)
start = time.perf_counter()
for clf in clf_list:
print(clf)
all_result, each_result = cross_validation(all_matrix, new_label, clf, event_num, seed, CV, set_name)
save_result(featureName, 'all', clf, all_result)
save_result(featureName, 'each', clf, each_result)
result_all[clf] = all_result
result_eve[clf] = each_result
print("time used:", time.perf_counter() - start)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("-f","--featureList",default=["smile","target","enzyme", "category"],help="features to use",nargs="+")
parser.add_argument("-c","--classifier",choices=["CNN_DDI","DDIMDL","RF","KNN","LR"],default=["DDIMDL"],help="classifiers to use",nargs="+")
parser.add_argument("-p","--NLPProcess",choices=["read","process"],default="read",help="Read the NLP extraction result directly or process the events again")
args=vars(parser.parse_args())
print(args)
main(args)
print('done')