-
Notifications
You must be signed in to change notification settings - Fork 0
/
Models.py
343 lines (236 loc) · 11.1 KB
/
Models.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
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.dummy import DummyClassifier
from sklearn.metrics import precision_recall_curve, roc_curve, roc_auc_score
from sklearn.model_selection import cross_validate, KFold
def logistic_regrssions_classifier_assessment(X, y):
"""
Logistic Regression comparison for the different datasets
args: X dataset of features
y target set of values for classification
returns:
- a dummy classifier score using "most frequent" value assignment
- the mean of the Logistic Regression Claffifier prediction scores taken from a
5 fold cross validation on the dataset
- graphic as a callable function plotting the ROC/AUC curves
"""
clf_log = LogisticRegression(random_state=0)
def performance_graphics(X=X, y=y, clf=clf_log):
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
clf.fit(X_train, y_train)
proba_ = clf.decision_function(X_test)
precision, recall, thresholds = precision_recall_curve(y_test, proba_)
fp, tp, thresholds_roc = roc_curve(y_test, proba_)
auc_score = np.round(roc_auc_score(y_test, proba_), 4)
close_default = np.argmin(np.abs(thresholds))
close_zero = np.argmin(np.abs(thresholds_roc))
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 4))
ax1.plot(precision, recall, label="Precision Recall Curve")
ax1.plot(precision[close_default],
recall[close_default], 'o',
c='r', markersize=10,
label='threshold 0',
fillstyle="none", mew=2)
ax1.set_title("Logistic Regression performance")
ax1.set_xlabel("Precision")
ax1.set_ylabel("Recall")
ax1.legend(loc='best')
ax2.plot(fp, tp, label="ROC curve")
ax2.plot(fp[close_zero],
tp[close_zero], 'o',
c='r', markersize=10,
label='threshold 0',
fillstyle="none", mew=2)
ax2.set_title(f"ROC performance: AUC Score {auc_score}")
ax2.set_xlabel("False Positive Rate")
ax2.set_ylabel("True Positive (Recall)")
ax2.legend(loc='best')
plt.show();
kfold = KFold(n_splits=5)
cross_val = cross_validate(clf_log, X, y, cv=kfold, return_estimator=True)
mean_score = cross_val['test_score'].mean()
dummy_clf = DummyClassifier(strategy="most_frequent")
dummy_clf.fit(X, y)
d_score = dummy_clf.score(X, y)
graphic = performance_graphics
return d_score, mean_score, graphic
# %%
#------------------------------------------------------------
#-------------------------------------------------------------
def SVM_classifier_assessment(X, y):
"""
SVC comparison for the different datasets
args: X dataset of features
y target set of values for classification
returns:
- a dummy classifier score using "most frequent" value assignment
- the mean of the SVC prediction scores taken from a
5 fold cross validation on the dataset
"""
clf_svc = make_pipeline(StandardScaler(), SVC(gamma='auto', probability=True))
def performance_graphics(X=X, y=y, clf=clf_svc):
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
clf.fit(X_train, y_train)
proba_ = clf.predict_proba(X_test)[:, 1]
precision, recall, thresholds = precision_recall_curve(y_test, proba_)
fp, tp, thresholds_roc = roc_curve(y_test, proba_)
auc_score = np.round(roc_auc_score(y_test, proba_), 4)
close_default = np.argmin(np.abs(thresholds - 0.5))
close_zero = np.argmin(np.abs(thresholds_roc))
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(15, 4))
ax1.plot(precision, recall, label="Precision Recall Curve")
ax1.plot(precision[close_default],
recall[close_default], 'o',
c='r', markersize=10,
label='threshold 0.5',
fillstyle="none", mew=2)
ax1.set_title("RF performance")
ax1.set_xlabel("Precision")
ax1.set_ylabel("Recall")
ax1.legend(loc='best')
ax2.plot(fp, tp, label="ROC curve")
ax2.plot(fp[close_zero],
tp[close_zero], 'o',
c='r', markersize=10,
label='threshold 0',
fillstyle="none", mew=2)
ax2.set_title(f"ROC performance: AUC Score {auc_score}")
ax2.set_xlabel("False Positive Rate")
ax2.set_ylabel("True Positive (Recall)")
ax2.legend(loc='best')
plt.show();
kfold = KFold(n_splits=5)
cross_val = cross_validate(clf_svc, X, y, cv=kfold, return_estimator=True)
mean_score = cross_val['test_score'].mean()
dummy_clf = DummyClassifier(strategy="most_frequent")
dummy_clf.fit(X,y)
d_score = dummy_clf.score(X,y)
graphic = performance_graphics
return d_score, mean_score, graphic
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
def NaiveBayes_classifier_assessment(X, y, priors=None):
"""
GaussianNB comparison for the different datasets
args: X dataset of features
y target set of values for classification
returns:
- a dummy classifier score using "most frequent" value assignment
- the mean of the Gaussian NaiveBayes Claffifier prediction scores taken from a
5 fold cross validation on the dataset
"""
clf_nb = GaussianNB(priors=priors)
print(f"Using prior probability: {priors}")
def performance_graphics(X=X, y=y, clf=clf_nb):
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
clf.fit(X_train, y_train)
proba_ = clf.predict_proba(X_test)[:, 1]
precision, recall, thresholds = precision_recall_curve(y_test, proba_)
fp, tp, thresholds_roc = roc_curve(y_test, proba_)
auc_score = np.round(roc_auc_score(y_test, proba_), 4)
close_default = np.argmin(np.abs(thresholds - 0.5))
close_zero = np.argmin(np.abs(thresholds_roc))
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(15, 4))
ax1.plot(precision, recall, label="Precision Recall Curve")
ax1.plot(precision[close_default],
recall[close_default], 'o',
c='r', markersize=10,
label='threshold 0.5',
fillstyle="none", mew=2)
ax1.set_title("NaiveBayes performance")
ax1.set_xlabel("Precision")
ax1.set_ylabel("Recall")
ax1.legend(loc='best')
ax2.plot(fp, tp, label="ROC curve")
ax2.plot(fp[close_zero],
tp[close_zero], 'o',
c='r', markersize=10,
label='threshold 0.5',
fillstyle="none", mew=2)
ax2.set_title(f"ROC performance: AUC Score {auc_score}")
ax2.set_xlabel("False Positive Rate")
ax2.set_ylabel("True Positive (Recall)")
ax2.legend(loc='best')
plt.show();
kfold = KFold(n_splits=5)
cross_val = cross_validate(clf_nb, X, y, cv=kfold, return_estimator=True)
mean_score = cross_val['test_score'].mean()
dummy_clf = DummyClassifier(strategy="most_frequent")
dummy_clf.fit(X,y)
d_score = dummy_clf.score(X,y)
graphic = performance_graphics
return d_score, mean_score, graphic
#----------------------------------------------------------------------------------
#----------------------------------------------------------------------------------
def RandomForest_classifier_assessment(X, y):
"""
RandomForestClassifier comparison for the different datasets
args: X dataset of features
y target set of values for classification
returns:
- a dummy classifier score using "most frequent" value assignment
- the mean of the RandomForest Claffifier prediction scores taken from a
5 fold cross validation on the dataset
- a dataframe that shows the 10 most important features used by the classifer
"""
clf_rf = RandomForestClassifier(max_depth=4, random_state=0)
def performance_graphics(X=X, y=y, clf_rf=clf_rf):
# type of certainty tied to classifier passed in
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
clf_rf.fit(X_train, y_train)
rf_proba = clf_rf.predict_proba(X_test)[:, 1]
precision, recall, thresholds = precision_recall_curve(y_test, rf_proba)
fp, tp, thresholds_roc = roc_curve(y_test, rf_proba)
auc_score = np.round(roc_auc_score(y_test, rf_proba), 4)
close_default = np.argmin(np.abs(thresholds - 0.5))
close_zero = np.argmin(np.abs(thresholds_roc))
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(15, 4))
ax1.plot(precision, recall, label="Precision Recall Curve")
ax1.plot(precision[close_default],
recall[close_default], 'o',
c='r', markersize=10,
label='threshold 0.5',
fillstyle="none", mew=2)
ax1.set_title("RandomForest performance")
ax1.set_xlabel("Precision")
ax1.set_ylabel("Recall")
ax1.legend(loc='best')
ax2.plot(fp, tp, label="ROC curve")
ax2.plot(fp[close_zero],
tp[close_zero], 'o',
c='r', markersize=10,
label='threshold 0.5',
fillstyle="none", mew=2)
ax2.set_title(f"ROC performance: AUC Score {auc_score}")
ax2.set_xlabel("False Positive Rate")
ax2.set_ylabel("True Positive (Recall)")
ax2.legend(loc='best')
plt.show();
clf_rf = RandomForestClassifier(max_depth=4, random_state=0)
kfold = KFold(n_splits=5)
cross_val = cross_validate(clf_rf, X, y, cv=kfold, return_estimator=True)
mean_score = cross_val['test_score'].mean()
estimator = cross_val['estimator']
ranked_features = {}
for i, clf in enumerate(estimator):
clf_no = i + 1
feat_imp_val = clf.feature_importances_
cols = X.columns
feature_importance = list(zip(cols, feat_imp_val))
feature_importance = sorted(feature_importance, key=lambda x: x[1], reverse=True)
feature_importance = [ f[0] for f in feature_importance]
ranked_features[f"Estimator: {clf_no}"] = feature_importance[:10]
dummy_clf = DummyClassifier(strategy="most_frequent")
dummy_clf.fit(X,y)
d_score = dummy_clf.score(X,y)
df = pd.DataFrame(ranked_features)
graphic = performance_graphics
return d_score, mean_score, df, graphic