-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevaluating.py
193 lines (137 loc) · 5.03 KB
/
evaluating.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
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.tree import DecisionTreeClassifier
from sklearn.cross_validation import cross_val_score
from sklearn.cross_validation import train_test_split
import preprocessing as prep
from sklearn.preprocessing import label_binarize
#ROC
import matplotlib.pyplot as plt
from itertools import cycle
from sklearn.metrics import roc_curve, auc
from scipy import interp
from sklearn.model_selection import cross_val_predict
import numpy as np
from sklearn.model_selection import StratifiedKFold
def evaluate_all_metrics_on_all_models(data):
print("dataset: ", data.data_set_name)
print("threshold: ", data.rare_value_threshold)
# firstly print accuracy with crossvalidation
crossvalidation_accuracy_with_model('knn', data)
crossvalidation_accuracy_with_model('bayes', data)
crossvalidation_accuracy_with_model('tree', data)
# secondly print AUC for all models
auc_for_model('knn', data)
auc_for_model('bayes', data)
auc_for_model('tree', data)
print("======================================")
#model = 'knn' or 'bayes' or 'decision_tree'
def crossvalidation_accuracy_with_model(model, data):
if model == 'knn':
#knn in sklearn requires numbers -> gotta do preprocessing
dataPrep = prep.replaceStringsWithNumbers(data)
knn = KNeighborsClassifier(n_neighbors = 5)
score = accuracy_for_model(knn, data)
elif model == 'bayes':
gnb = GaussianNB()
score = accuracy_for_model(gnb, data)
else: #decision_tree
clf = DecisionTreeClassifier(random_state=0)
score = accuracy_for_model(clf, data)
print (model, ' accuracy: ', score)
return 0
# data should be of type DataSet
def accuracy_for_model(model, data):
y = data.y().values
X = data.X().values
scores = cross_val_score(model, X, y, cv=10)
return scores.mean(), scores.std()
def auc_for_model(model, data):
if model == 'knn':
#knn in sklearn requires numbers -> gotta do preprocessing
dataPrep = prep.replaceStringsWithNumbers(data)
knn = KNeighborsClassifier(n_neighbors = 5)
score = auc_value_for_model(knn, data)
elif model == 'bayes':
dataPrep = prep.replaceStringsWithNumbers(data)
gnb = GaussianNB()
score = auc_value_for_model(gnb, dataPrep)
else: #decision_tree
dataPrep = prep.replaceStringsWithNumbers(data)
clf = DecisionTreeClassifier(random_state=0)
score = auc_value_for_model(clf, dataPrep)
print (model, ' auc: ', score)
return 0
def auc_value_for_model(model, data):
cv = StratifiedKFold(n_splits=10)
X = data.X().values
y = data.y().values
classifier = model
mean_tpr = 0.0
mean_fpr = np.linspace(0, 1, 100)
mean_tpr = 0.0
mean_fpr = np.linspace(0, 1, 100)
colors = cycle(['cyan', 'indigo', 'seagreen', 'yellow', 'blue', 'darkorange', 'red', 'red', 'red', 'red'])
lw = 2
i = 0
for (train, test), color in zip(cv.split(X, y), colors):
probas_ = classifier.fit(X[train], y[train]).predict_proba(X[test])
# Compute ROC curve and area the curve
fpr, tpr, thresholds = roc_curve(y[test], probas_[:, 1])
mean_tpr += interp(mean_fpr, fpr, tpr)
mean_tpr[0] = 0.0
roc_auc = auc(fpr, tpr)
i += 1
mean_tpr /= cv.get_n_splits(X, y)
mean_tpr[-1] = 1.0
mean_auc = auc(mean_fpr, mean_tpr)
return mean_auc
def multiclass_auc_value_for_model(model, data):
X = data.X().values
y = data.y().values
# Binarize the output
y = label_binarize(y, classes=['B', 'R', 'L'])
n_classes = y.shape[1]
# shuffle and split training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.5,
random_state=0)
y_pred = model.fit(X_train, y_train).predict(X_test)
roc_auc_score(y_pred, y_test)
print(roc_auc)
def draw_roc_for_model(model, data):
# Run classifier with cross-validation and plot ROC curves
cv = StratifiedKFold(n_splits=6)
# classifier = svm.SVC(kernel='linear', probability=True,
# random_state=random_state)
X = data.X().values
y = data.y().values
# print(X.shape)
classifier = model
mean_tpr = 0.0
mean_fpr = np.linspace(0, 1, 100)
colors = cycle(['cyan', 'indigo', 'seagreen', 'yellow', 'blue', 'darkorange'])
lw = 2
i = 0
for (train, test), color in zip(cv.split(X, y), colors):
probas_ = classifier.fit(X[train], y[train]).predict_proba(X[test])
# Compute ROC curve and area the curve
fpr, tpr, thresholds = roc_curve(y[test], probas_[:, 1])
mean_tpr += interp(mean_fpr, fpr, tpr)
mean_tpr[0] = 0.0
roc_auc = auc(fpr, tpr)
plt.plot(fpr, tpr, lw=lw, color=color, label='ROC fold %d (area = %0.2f)' % (i, roc_auc))
i += 1
plt.plot([0, 1], [0, 1], linestyle='--', lw=lw, color='k',
label='Luck')
mean_tpr /= cv.get_n_splits(X, y)
mean_tpr[-1] = 1.0
mean_auc = auc(mean_fpr, mean_tpr)
print("auc: ", mean_auc)
plt.plot(mean_fpr, mean_tpr, color='g', label='Mean ROC (area = %0.2f)' % mean_auc, lw=lw)
plt.xlim([-0.05, 1.05])
plt.ylim([-0.05, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic example')
plt.legend(loc="lower right")
plt.show()