-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain_functions.py
347 lines (265 loc) · 10.3 KB
/
train_functions.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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 19 08:06:50 2021
@author: mehak
"""
from sklearn import metrics
from sklearn.metrics import confusion_matrix
from sklearn import tree
from sklearn import ensemble
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
import math
def get_metrics(X_test, y_test, model):
probs = model.predict_proba(X_test)
prob_bacteria = probs[:, 0]
prob_fungi = probs[:,1]
tpr_, fpr_, threshold = metrics.roc_curve(y_test, prob_fungi)
precision, recall, thresholds = metrics.precision_recall_curve(y_test, prob_fungi )
auc_roc = metrics.roc_auc_score(y_test, prob_fungi)
cm = confusion_matrix(y_test, (prob_fungi > 0.45) * 1)
TP = cm[1][1]
TN = cm[0][0]
FP = cm[0][1]
FN = cm[1][0]
# Sensitivity, hit rate, recall, or true positive rate
TPR = TP / (TP + FN)
# Specificity or true negative rate
TNR = TN / (TN + FP)
# Precision or positive predictive value
PPV = TP / (TP + FP)
# Negative predictive value
NPV = TN / (TN + FN)
# Fall out or false positive rate
FPR = FP / (FP + TN)
# False negative rate
FNR = FN / (TP + FN)
# False discovery rate
FDR = FP / (TP + FP)
print("Test Sensitivity:", TPR)
print("Test Specificity:", TNR)
print("Test Precision:", PPV)
print("confusion matrix:\n", cm)
acc = model.score(X_test, y_test)
print("Accuracy: ", acc)
if(math.isnan(PPV)):
PPV = 0
if(math.isnan(NPV)):
NPV = 0
result = {
'tpr_roc':tpr_,
'fpr_roc':fpr_,
'precision_prc':precision,
'recall_prc':recall,
'auroc':auc_roc,
'sensitivity':TPR,
'specificity':TNR,
'precision':PPV,
'confusion_matrix':cm,
'accuracy':acc,
'npv': NPV
}
return result
def randomForest(X_up, y_up):
pca = PCA()
clf = ensemble.RandomForestClassifier() # defining decision tree classifier
rv = Pipeline(steps=[("pca", pca), ("clf", clf)])
rv.fit(X_up, y_up) # train data on new data and new target
return rv
def logisticRegression(X_up, y_up):
pca = PCA()
# set the tolerance to a large value to make the example faster
logistic = LogisticRegression(max_iter=10000, tol=0.1)
logistic_model = Pipeline(steps=[("pca", pca), ("logistic", logistic)])
X_digits = X_up
y_digits = y_up
# Parameters of pipelines can be set using ‘__’ separated parameter names:
param_grid = {
"pca__n_components": [5,10, 15, 20, 25, 30, 35, 45, 64],
"logistic__C": np.logspace(-4, 4, 4),
}
search = GridSearchCV(logistic_model, param_grid, n_jobs=-1)
search.fit(X_digits, y_digits)
print("Best parameter (CV score=%0.3f):" % search.best_score_)
print(search.best_params_)
# Plot the PCA spectrum
pca.fit(X_digits)
fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True, figsize=(6, 6))
ax0.plot(
np.arange(1, pca.n_components_ + 1), pca.explained_variance_ratio_, "+", linewidth=2
)
ax0.set_ylabel("PCA explained variance ratio")
ax0.set_xlabel("n_components")
ax0.axvline(
search.best_estimator_.named_steps["pca"].n_components,
linestyle=":",
label="n_components chosen",
)
ax0.legend(prop=dict(size=12))
# For each number of components, find the best classifier results
results = pd.DataFrame(search.cv_results_)
components_col = "param_pca__n_components"
best_clfs = results.groupby(components_col).apply(
lambda g: g.nlargest(1, "mean_test_score")
)
best_clfs.plot(
x=components_col, y="mean_test_score", yerr="std_test_score", legend=False, ax=ax1
)
ax1.set_ylabel("Classification accuracy (val)")
ax1.set_xlabel("n_components")
plt.xlim(-1, 70)
plt.tight_layout()
plt.show()
logistic_model = search.best_estimator_
return logistic_model
def lasso(X_up, y_up):
pca = PCA()
# set the tolerance to a large value to make the example faster
logistic = LogisticRegression(penalty = 'l1', solver = 'saga', max_iter=10000, tol=0.1)
pipe = Pipeline(steps=[("pca", pca), ("logistic", logistic)])
X_digits = X_up
y_digits = y_up
# Parameters of pipelines can be set using ‘__’ separated parameter names:
param_grid = {
"pca__n_components": [5,10, 15, 20, 25, 30, 35, 45, 64],
"logistic__C": [1,2,4,5, 10, 50,100,500,1000],
}
search = GridSearchCV(pipe, param_grid, n_jobs=-1)
search.fit(X_digits, y_digits)
print("Best parameter (CV score=%0.3f):" % search.best_score_)
print(search.best_params_)
# Plot the PCA spectrum
pca.fit(X_digits)
fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True, figsize=(6, 6))
ax0.plot(
np.arange(1, pca.n_components_ + 1), pca.explained_variance_ratio_, "+", linewidth=2
)
ax0.set_ylabel("PCA explained variance ratio")
ax0.set_xlabel("n_components")
ax0.axvline(
search.best_estimator_.named_steps["pca"].n_components,
linestyle=":",
label="n_components chosen",
)
ax0.legend(prop=dict(size=12))
# For each number of components, find the best classifier results
results = pd.DataFrame(search.cv_results_)
components_col = "param_pca__n_components"
best_clfs = results.groupby(components_col).apply(
lambda g: g.nlargest(1, "mean_test_score")
)
best_clfs.plot(
x=components_col, y="mean_test_score", yerr="std_test_score", legend=False, ax=ax1
)
ax1.set_ylabel("Classification accuracy (val)")
ax1.set_xlabel("n_components")
plt.xlim(-1, 70)
plt.tight_layout()
plt.show()
lasso = search.best_estimator_
return lasso
def svm(X_up, y_up):
# Define a pipeline to search for the best combination of PCA truncation
# and classifier regularization.
pca = PCA()
# set the tolerance to a large value to make the example faster
svm = SVC(kernel = 'rbf', probability = True, C = 50, gamma = 0.005)
pipe = Pipeline(steps=[("pca", pca), ("svm", svm)])
X_digits = X_up
y_digits = y_up
# Parameters of pipelines can be set using ‘__’ separated parameter names:
param_grid = {
"pca__n_components": [5,10, 15, 20, 25, 30, 35, 45, 64],
"svm__C": np.logspace(-4, 4, 4),
"svm__gamma": [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1],
"svm__kernel": ['rbf', 'sigmoid', 'poly', 'linear']
}
search = GridSearchCV(pipe, param_grid, n_jobs=-1, scoring = 'f1')
search.fit(X_digits, y_digits)
print("Best parameter (CV score=%0.3f):" % search.best_score_)
print(search.best_params_)
# Plot the PCA spectrum
pca.fit(X_digits)
fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True, figsize=(6, 6))
ax0.plot(
np.arange(1, pca.n_components_ + 1), pca.explained_variance_ratio_, "+", linewidth=2
)
ax0.set_ylabel("PCA explained variance ratio")
ax0.set_xlabel("n_components")
ax0.axvline(
search.best_estimator_.named_steps["pca"].n_components,
linestyle=":",
label="n_components chosen",
)
ax0.legend(prop=dict(size=12))
# For each number of components, find the best classifier results
results = pd.DataFrame(search.cv_results_)
components_col = "param_pca__n_components"
best_clfs = results.groupby(components_col).apply(
lambda g: g.nlargest(1, "mean_test_score")
)
best_clfs.plot(
x=components_col, y="mean_test_score", yerr="std_test_score", legend=False, ax=ax1
)
ax1.set_ylabel("Classification accuracy (val)")
ax1.set_xlabel("n_components")
plt.xlim(-1, 70)
plt.tight_layout()
plt.show()
svm = search.best_estimator_
return svm
def knn(X_up, y_up):
# Define a pipeline to search for the best combination of PCA truncation
# and classifier regularization.
pca = PCA()
# set the tolerance to a large value to make the example faster
knn = KNeighborsClassifier(n_neighbors = 15)
pipe = Pipeline(steps=[("pca", pca), ("knn", knn)])
X_digits = X_up
y_digits = y_up
# Parameters of pipelines can be set using ‘__’ separated parameter names:
param_grid = {
"pca__n_components": [5,10, 15, 20, 25, 30, 35, 45, 64],
"knn__n_neighbors": [5,6,7,8,9,10]
}
search = GridSearchCV(pipe, param_grid, n_jobs=-1)
search.fit(X_digits, y_digits)
print("Best parameter (CV score=%0.3f):" % search.best_score_)
print(search.best_params_)
# Plot the PCA spectrum
pca.fit(X_digits)
fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True, figsize=(6, 6))
ax0.plot(
np.arange(1, pca.n_components_ + 1), pca.explained_variance_ratio_, "+", linewidth=2
)
ax0.set_ylabel("PCA explained variance ratio")
ax0.set_xlabel("n_components")
ax0.axvline(
search.best_estimator_.named_steps["pca"].n_components,
linestyle=":",
label="n_components chosen",
)
ax0.legend(prop=dict(size=12))
# For each number of components, find the best classifier results
results = pd.DataFrame(search.cv_results_)
components_col = "param_pca__n_components"
best_clfs = results.groupby(components_col).apply(
lambda g: g.nlargest(1, "mean_test_score")
)
best_clfs.plot(
x=components_col, y="mean_test_score", yerr="std_test_score", legend=False, ax=ax1
)
ax1.set_ylabel("Classification accuracy (val)")
ax1.set_xlabel("n_components")
plt.xlim(-1, 70)
plt.tight_layout()
plt.show()
knn = search.best_estimator_
return knn