-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathCNN.py
More file actions
executable file
·206 lines (166 loc) · 6.72 KB
/
Copy pathCNN.py
File metadata and controls
executable file
·206 lines (166 loc) · 6.72 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
# Import libraries
import os
import numpy as np
from Bio.Alphabet import IUPAC
from keras.optimizers import Adam
from contextlib import redirect_stdout
# Import custom functions
from utils import one_hot_encoder, create_cnn, \
plot_ROC_curve, plot_PR_curve, calc_stat
def CNN_classification(dataset, filename, save_model=False, params=None):
"""
Classification of data with a convolutional neural
network, followed by plotting of ROC and PR curves.
Parameters
---
dataset: the input dataset, containing training and
test split data, and the corresponding labels
for binding- and non-binding sequences.
filename: an identifier to distinguish different
plots from each other.
save_model: optional; if provided, should specify the directory
to save model summary and weights. The classification model
will be returned in this case.
If False, an array containing classification accuracy,
precision and recall will be returned instead.
params: optional; if provided, should specify the optimized
model parameters that were determined in a separate model
tuning step. If None, model parameters are hard-coded.
"""
# Import training/test set
X_train = dataset.train.loc[:, 'AASeq'].values
X_test = dataset.test.loc[:, 'AASeq'].values
X_val = dataset.val.loc[:, 'AASeq'].values
# One hot encode the sequences
X_train = [one_hot_encoder(s=x, alphabet=IUPAC.protein) for x in X_train]
X_train = np.transpose(np.asarray(X_train), (0, 2, 1))
X_test = [one_hot_encoder(s=x, alphabet=IUPAC.protein) for x in X_test]
X_test = np.transpose(np.asarray(X_test), (0, 2, 1))
X_val = [one_hot_encoder(s=x, alphabet=IUPAC.protein) for x in X_val]
X_val = np.transpose(np.asarray(X_val), (0, 2, 1))
# Extract labels of training/test/validation set
y_train = dataset.train.loc[:, 'AgClass'].values
y_test = dataset.test.loc[:, 'AgClass'].values
y_val = dataset.val.loc[:, 'AgClass'].values
# Set parameters for CNN
if not params:
params = [['CONV', 400, 3, 1],
['DROP', 0.5],
['POOL', 2, 1],
['FLAT'],
['DENSE', 50]]
# Create the CNN with above-specified parameters
CNN_classifier = create_cnn(params, (10, 20), 'relu', None)
# Compiling the CNN
opt = Adam(learning_rate=0.000075)
CNN_classifier.compile(optimizer=opt, loss='binary_crossentropy',
metrics=['accuracy'])
# Fit the CNN to the training set
_ = CNN_classifier.fit(
x=X_train, y=y_train, shuffle=True, validation_data=(X_val, y_val),
epochs=20, batch_size=16, verbose=2
)
# Predicting the test set results
y_pred = CNN_classifier.predict(x=X_test)
# ROC curve
title = 'CNN ROC curve (Train={})'.format(filename)
plot_ROC_curve(
y_test, y_pred, plot_title=title,
plot_dir='figures/CNN_ROC_Test_{}.png'.format(filename)
)
# Precision-recall curve
title = 'CNN Precision-Recall curve (Train={})'.format(filename)
plot_PR_curve(
y_test, y_pred, plot_title=title,
plot_dir='figures/CNN_P-R_Test_{}.png'.format(filename)
)
# Save model if specified
if save_model:
# Model summary
with open(os.path.join(save_model, 'CNN_summary.txt'), 'w') as f:
with redirect_stdout(f):
CNN_classifier.summary()
# Model weights
CNN_classifier.save(
os.path.join(save_model, 'CNN_HER2')
)
# Return classification model
return CNN_classifier
else:
# Probabilities larger than 0.5 are significant
y_pred_stand = (y_pred > 0.5)
# Calculate statistics
stats = calc_stat(y_test, y_pred_stand)
# Return statistics
return stats
def CNN_classification_L3(dataset, filename, save_model, params=None):
"""
Classification of data with a convolutional neural
network, followed by plotting of ROC and PR curves.
Parameters
---
dataset: the input dataset, containing training and
test split data, and the corresponding labels
for binding- and non-binding sequences.
filename: an identifier to distinguish different
plots from each other.
save_model: specifies the directory to save model summary
and weights. The classification model will be returned
in this case.
params: optional; if provided, should specify the optimized
model parameters that were determined in a separate model
tuning step. If None, model parameters are hard-coded.
"""
# Import training/test set
X_train = dataset.train.loc[:, 'AASeq'].values
X_test = dataset.test.loc[:, 'AASeq'].values
# One hot encode the sequences
X_train = [one_hot_encoder(s=x, alphabet=IUPAC.protein) for x in X_train]
X_train = np.transpose(np.asarray(X_train), (0, 2, 1))
X_test = [one_hot_encoder(s=x, alphabet=IUPAC.protein) for x in X_test]
X_test = np.transpose(np.asarray(X_test), (0, 2, 1))
# Extract labels of training/test/validation set
y_train = dataset.train.loc[:, 'AgClass'].values
y_test = dataset.test.loc[:, 'AgClass'].values
# Set parameters for CNN
if not params:
params = [['CONV', 400, 3, 1],
['DROP', 0.5],
['POOL', 2, 1],
['FLAT'],
['DENSE', 50]]
# Create the CNN with above-specified parameters
CNN_classifier = create_cnn(params, (9, 20), 'relu', None)
# Compiling the CNN
opt = Adam(learning_rate=0.000075)
CNN_classifier.compile(optimizer=opt, loss='binary_crossentropy',
metrics=['accuracy'])
# Fit the CNN to the training set
_ = CNN_classifier.fit(
x=X_train, y=y_train, shuffle=True, validation_data=(X_test, y_test),
epochs=30, batch_size=16, verbose=2
)
# Predicting the test set results
y_pred = CNN_classifier.predict(x=X_test)
# ROC curve
title = 'CNN ROC curve (Train={})'.format(filename)
plot_ROC_curve(
y_test, y_pred, plot_title=title,
plot_dir='figures/CNN_L3_ROC_Test_{}.png'.format(filename)
)
# Precision-recall curve
title = 'CNN Precision-Recall curve (Train={})'.format(filename)
plot_PR_curve(
y_test, y_pred, plot_title=title,
plot_dir='figures/CNN_L3_P-R_Test_{}.png'.format(filename)
)
# Model summary
with open(os.path.join(save_model, 'CNN_summary_L3.txt'), 'w') as f:
with redirect_stdout(f):
CNN_classifier.summary()
# Model weights
CNN_classifier.save(
os.path.join(save_model, 'CNN_HER2_L3')
)
# Return classification model
return CNN_classifier