-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNNR.py
328 lines (246 loc) · 10.3 KB
/
NNR.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
#to Get Reproducible Results with Keras #https://machinelearningmastery.com/reproducible-results-neural-networks-keras/
from numpy.random import seed
seed(1)
import tensorflow
tensorflow.random.set_seed(1234)
####################################################
#https://www.dataquest.io/blog/learning-curves-machine-learning/
import pandas as pd
import numpy as np
df = pd.read_csv("dataset.csv")
df = df.dropna() # To drop Null values
print(df.shape)
print("&&&&&&&&")
print(df.head())
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_predict
from sklearn.model_selection import learning_curve
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import MinMaxScaler #For feature normalization
scaler = MinMaxScaler()
features = ['Efficiency','Specificity','BS_Length','Distance_exon_BS (D)'] #'K_Avg_Fold_change', 'K_Median_Fold_change'
target = 'K_Avg_Fold_change'
#target='K_Median_Fold_change'
###########################################
X = df[features]
#insert onehot encoding of reference-kmer
#Onehot=pd.get_dummies(df['sgRNA_sequence'], prefix='sgRNA_sequence')
#X= pd.concat([X,Onehot],axis=1)
y = df[target]
a,b=X.shape
print("#############",X.shape)
print(y.shape)
#print(X.head())
#scale training data
X= scaler.fit_transform(X)
print(",,,,,,,,",X.shape)
#train, test = train_test_split(df, test_size=0.2)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
###################Build NN model
'''
#from keras.models import Sequential
#from keras.layers import Dense
#from keras.optimizers import SGD
from sklearn import metrics #Import scikit-learn metrics module for accuracy calculation
# Evaluate the model: Model Accuracy, how often is the classifier correct
from sklearn import metrics #Import scikit-learn metrics module for accuracy calculation
from sklearn.metrics import classification_report #for classifier evaluation
from sklearn.metrics import roc_curve, auc
from sklearn.metrics import roc_auc_score # for printing AUC
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
'''
############################################
#old stuff
###########
# from https://machinelearningmastery.com/regression-tutorial-keras-deep-learning-library-python/
#model = Sequential()
#model.add(Dense(12, input_dim=b, activation='relu'))
#model.add(Dense(8, activation='relu'))
#####model.add(Dense(1, activation='sigmoid'))
#########################################################################
from pandas import read_csv
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import SGD
from tensorflow.keras.wrappers.scikit_learn import KerasRegressor
#to Get Reproducible Results with Keras #https://machinelearningmastery.com/reproducible-results-neural-networks-keras/
from numpy.random import seed
seed(1)
import tensorflow
tensorflow.random.set_seed(1234)
####################################################
#https://www.dataquest.io/blog/learning-curves-machine-learning/
import pandas as pd
import numpy as np
df = pd.read_csv("dataset.csv")
df = df.dropna() # To drop Null values
print(df.shape)
print("&&&&&&&&")
print(df.head())
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_predict
import matplotlib.pyplot as plt
from sklearn.model_selection import cross_val_predict
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import MinMaxScaler #For feature normalization
scaler = MinMaxScaler()
features = ['Efficiency','Specificity','BS_Length','Distance_exon_BS (D)'] #'K_Avg_Fold_change', 'K_Median_Fold_change'
target = 'K_Avg_Fold_change'
#target='K_Median_Fold_change'
###########################################
X = df[features]
#insert onehot encoding of reference-kmer
#Onehot=pd.get_dummies(df['sgRNA_sequence'], prefix='sgRNA_sequence')
#X= pd.concat([X,Onehot],axis=1)
y = df[target]
a,b=X.shape
print("#############",X.shape)
print(y.shape)
#print(X.head())
#scale training data
X= scaler.fit_transform(X)
print(",,,,,,,,",X.shape)
#train, test = train_test_split(df, test_size=0.2)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
###################Build NN model
#from keras.models import Sequential
#from keras.layers import Dense
#from keras.optimizers import SGD
from sklearn import metrics #Import scikit-learn metrics module for accuracy calculation
# Evaluate the model: Model Accuracy, how often is the classifier correct
from sklearn import metrics #Import scikit-learn metrics module for accuracy calculation
from sklearn.metrics import classification_report #for classifier evaluation
from sklearn.metrics import roc_curve, auc
from sklearn.metrics import roc_auc_score # for printing AUC
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
############################################
#old stuff
###########
# from https://machinelearningmastery.com/regression-tutorial-keras-deep-learning-library-python/
#model = Sequential()
#model.add(Dense(12, input_dim=b, activation='relu'))
#model.add(Dense(8, activation='relu'))
#####model.add(Dense(1, activation='sigmoid'))
#########################################################################
from pandas import read_csv
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import SGD
from tensorflow.keras.wrappers.scikit_learn import KerasRegressor
######################################################
# Initialising the ANN
model = Sequential()
# Adding the input layer and the first hidden layer
model.add(Dense(32, activation = 'relu', input_dim = b))
# Adding the second hidden layer
model.add(Dense(units = 32, activation = 'relu'))
# Adding the third hidden layer
model.add(Dense(units = 32, activation = 'relu'))
# Adding the output layer
model.add(Dense(units = 1))
model.compile(loss='mse', optimizer='adam', metrics=['mse','mae'])
history = model.fit(X_train, y_train, batch_size = 10, epochs = 100,verbose=1, validation_split=0.2)
#history=model.fit(X_train, y_train, epochs=150, batch_size=50, verbose=1, validation_split=0.2)
###########################
y_pred = model.predict(X_test)
plt.plot(y_test, color = 'red', label = 'Real data')
plt.plot(y_pred, color = 'blue', label = 'Predicted data')
plt.title('Prediction')
plt.legend()
plt.show()
####################################################
predicted=y_pred
expected = y_test
#mse = np.mean((predicted-expected)**2)
#print("###",mse)
#print(model.intercept_, model.coef_, mse)
#print(model.score(X_train, y_train))
####################################################
from sklearn.metrics import mean_squared_error
from sklearn import metrics
from math import sqrt
mse=(mean_squared_error(y_test,predicted))
rmse = sqrt(mean_squared_error(y_test,predicted))
print("$$$",mse)
print("@@@",rmse)
#print("The linear regression score is {}".format(model.score(X_train,y_train)))
#print("The linear regression score is {}".format(model.score(X_test,y_test)))
print("The RMSE is {}".format(rmse))
#print("The RMSE of the training set is {}".format(np.sqrt(metrics.mean_squared_error(y_train,X_train))))
#print("The MAE is {}".format(metrics.mean_absolute_error(y_test,predicted)))
print("The MSE is {}".format(metrics.mean_squared_error(y_test,predicted)))
##########################################
print(history.history.keys())
# "Loss"
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss1')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper left')
plt.show()
#############################
plt.plot(history.history['mse'])
plt.plot(history.history['val_mse'])
plt.title('model mse1')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper left')
plt.show()
#######################################################
#needed for plotting learning curve
model.compile(loss='mse', optimizer='adam', metrics=['mse','mae'])
###########################
history = model.fit(X_train, y_train, epochs=150, batch_size=50, verbose=1, validation_split=0.2)
#########################################
####################################################
y_pred = model.predict(X_test)
predicted=y_pred
expected = y_test
#mse = np.mean((predicted-expected)**2)
#print("###",mse)
#print(model.intercept_, model.coef_, mse)
#print(model.score(X_train, y_train))
####################################################
from sklearn.metrics import mean_squared_error
from sklearn import metrics
from math import sqrt
mse=(mean_squared_error(y_test,predicted))
rmse = sqrt(mean_squared_error(y_test,predicted))
print("$$$",mse)
print("@@@",rmse)
#print("The linear regression score is {}".format(model.score(X_train,y_train)))
#print("The linear regression score is {}".format(model.score(X_test,y_test)))
print("The RMSE is {}".format(rmse))
#print("The RMSE of the training set is {}".format(np.sqrt(metrics.mean_squared_error(y_train,X_train))))
#print("The MAE is {}".format(metrics.mean_absolute_error(y_test,predicted)))
print("The MSE is {}".format(metrics.mean_squared_error(y_test,predicted)))
#######################################################
#########################################
print(history.history.keys())
# "Loss"
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss2')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper left')
plt.show()
#############################
plt.plot(history.history['mse'])
plt.plot(history.history['val_mse'])
plt.title('model mse2')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper left')
plt.show()