-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_script_final.py
More file actions
456 lines (390 loc) · 18.1 KB
/
Copy pathmain_script_final.py
File metadata and controls
456 lines (390 loc) · 18.1 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
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
# -*- coding: utf-8 -*-
import itertools
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from collections import Counter
from imblearn.over_sampling import SMOTE
from sklearn import model_selection
from sklearn.utils import shuffle
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import f1_score
from sklearn.metrics import roc_auc_score
from sklearn.metrics import matthews_corrcoef
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import GradientBoostingClassifier
"""
Evaluation of Performance Measures on Classifiers for Amazon Employee Access
We examine different ways to evaluate and manipulate the dataset for classifying
users access needs to a system. Detecting when a user should be given or denied
access to a database or system within their company would remove the need for an
administrator to allocate the permission each time. We will build upon the previous
study and this time evaluate on different measures to decide the best outcome.
We will be using Naive Bayes, k-Nearest Neighbor, Decision Tree, Random Forest
and Gradient Boosting as our classifiers to help produce our measures.
The performance measures we will be evaluating include accuracy, precision,
recall, F-score, Area Under the Curve (AUC), False Positive and False Negative Rate,
and Matthews Correlation Coefficient (MCC). We will also be comparing how an
oversampled dataset, SMOTE performs against an undersampled set.
@author Ian Ferringer
@author Matthew O’Donnell
"""
#Set constants
test_size = 0.20
seed = 7
bar_width = 0.35
opacity = 0.8
offset = 0.5
#Globals
categorical_data = ['ROLE_ROLLUP_1','ROLE_FAMILY']
accuracies = []
precisions = []
recalls = []
f1s = []
rocs = []
mccs = []
fprs = []
fnrs = []
scores = []
def one_hot_encode(dataset, cols):
print "Current # of features:", len(dataset.columns.values)
dataset = pd.get_dummies(dataset, columns = cols)
print "Current # of features:", len(dataset.columns.values)
return dataset
def k_nearest_neighbors_classifier():
return KNeighborsClassifier()
def decision_tree_classifier():
return DecisionTreeClassifier()
def naive_bayes_classifier():
return GaussianNB()
def random_forest_classifier():
return RandomForestClassifier()
def gradient_boosting_classifier():
return GradientBoostingClassifier()
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion Matrix',
cmap=plt.cm.Blues):
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
def raw_dataset(dataset):
# We want to use the 1st attribute to the last attribute
X = dataset.values[:,1:]
# The 0th attribute is the target attribute
Y = dataset.values[:,0]
X_train, X_test, Y_train, Y_test = model_selection.train_test_split(X, Y, test_size=test_size, random_state=seed, stratify=Y)
print('Original training class count {}'.format(Counter(Y_train)))
print('Original test class count {}'.format(Counter(Y_test)))
return X_train, X_test, Y_train, Y_test
def smote_dataset(dataset):
# We want to use the 1st attribute to the last attribute
X = dataset.values[:,1:]
# The 0th attribute is the target attribute
Y = dataset.values[:,0]
X_train, X_test, Y_train, Y_test = model_selection.train_test_split(X, Y, test_size=test_size, random_state=seed, stratify=Y)
print('Original training class count {}'.format(Counter(Y_train)))
# Use Synthetic Minority Over-sampling Technique to even imbalance of classes
sm = SMOTE(random_state=seed)
X_train_resampled, Y_train_resampled = sm.fit_sample(X_train, Y_train)
print('Resampled training class count {}'.format(Counter(Y_train_resampled)))
print('Resampled test class count {}'.format(Counter(Y_test)))
return X_train_resampled, X_test, Y_train_resampled, Y_test
def smote_balanced_dataset(dataset):
print "Current Split by Classification:"
print(dataset.groupby('ACTION').size())
#Seperate out by classification types
denied_set = shuffle(dataset[dataset['ACTION'] == 0])
approved_set = shuffle(dataset[dataset['ACTION'] == 1])
#get minimum number of columns between the two sets
val=np.minimum(denied_set.shape, approved_set.shape)[0]
test_set = denied_set[:val/2].append(approved_set[:val/2], ignore_index=True)
X_test = test_set.values[:,1:]
Y_test = test_set.values[:,0]
train_set = denied_set[val/2:].append(approved_set[val/2:], ignore_index=True)
print "Test Set Split by ACTION:"
print(test_set.groupby('ACTION').size())
print "Train Set Split by ACTION:"
print(train_set.groupby('ACTION').size())
# Use Synthetic Minority Over-sampling Technique to even imbalance of classes
sm = SMOTE(random_state=seed)
X_train_resampled, Y_train_resampled = sm.fit_sample(train_set.values[:,1:], train_set.values[:,0])
print('Resampled training class count {}'.format(Counter(Y_train_resampled)))
print('Resampled test class count {}'.format(Counter(Y_test)))
return X_train_resampled, X_test, Y_train_resampled, Y_test
def undersampled_dataset(dataset):
#Seperate out by classification types
denied_set = dataset[dataset['ACTION'] == 0]
approved_set = dataset[dataset['ACTION'] == 1]
#get minimum number of columns between the two sets
val=np.minimum(denied_set.shape, approved_set.shape)[0]
dataset = denied_set.sample(n=val).append(approved_set.sample(n=val), ignore_index=True)
# We want to use the 1st attribute to the last attribute
X = dataset.values[:,1:]
# The 0th attribute is the target attribute
Y = dataset.values[:,0]
X_train, X_test, Y_train, Y_test = model_selection.train_test_split(X, Y, test_size=test_size, random_state=seed, stratify=Y)
print('unsampled training class count {}'.format(Counter(Y_train)))
print('unsampled test class count {}'.format(Counter(Y_test)))
return X_train, X_test, Y_train, Y_test
def train_test_evaluate(X_train, X_test, Y_train, Y_test, models):
#Arrays to hold evaluation results
accuracy = []
precision = []
recall = []
f1 = []
roc = []
mcc = []
fpr = []
fnr = []
score = []
weight = float(1)/11
idx = 0
for name, model in models:
print "#######################", name,"#######################"
#Fit model and predict
print("training model")
model.fit(X_train, Y_train)
print("testing model")
predictions = model.predict(X_test)
print("evaluating model")
#Compute values for confusion matrix
tn, fp, fn, tp = confusion_matrix(Y_test, predictions).ravel()
#Add each model's results to the corresponding evaluation metric array
accuracy.append(accuracy_score(Y_test, predictions))
precision.append(precision_score(Y_test, predictions, average=None))
print(classification_report(Y_test, predictions))
recall.append(recall_score(Y_test, predictions, average=None))
f1.append(f1_score(Y_test, predictions, average=None))
roc.append(roc_auc_score(Y_test, predictions))
mcc.append(matthews_corrcoef(Y_test, predictions))
fpr.append(float(fp)/(fp+tn))
fnr.append(float(fn)/(fn+tp))
score.append(float(weight)*((accuracy[idx])+(precision[idx][0])+(precision[idx][1])+
(recall[idx])[0]+(recall[idx][1])+
(f1[idx])[0]+(f1[idx][1])+
(roc[idx])+(mcc[idx])+(1-fpr[idx])+(1-fnr[idx])))
print score[idx]
#class names
class_names = ['denied', 'allowed']
np.set_printoptions(precision=2)
cm = confusion_matrix(Y_test, predictions)
print cm
# Plot non-normalized confusion matrix
plt.figure()
plot_confusion_matrix(cm, classes=class_names,
title='Confusion matrix, without normalization')
plt.show()
idx = idx + 1
accuracies.append(accuracy)
precisions.append(precision)
recalls.append(recall)
f1s.append(f1)
rocs.append(roc)
mccs.append(mcc)
fprs.append(fpr)
fnrs.append(fnr)
scores.append(score)
def plot_accuracies(dataset_names, model_names):
num_datasets = np.arange(len(dataset_names))
index = np.arange(len(model_names))
plt.subplots()
for dataset_index in num_datasets:
plt.bar(index + bar_width*dataset_index, accuracies[dataset_index], bar_width, alpha=opacity, label=dataset_names[dataset_index])
plt.xlabel('Models')
plt.ylabel('Accuracy')
plt.title('Accuracy Comparison')
plt.xticks(index + bar_width*offset, model_names)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
def plot_precisions(dataset_names, model_names):
num_datasets = np.arange(len(dataset_names))
index = np.arange(len(model_names))
#Plot for Denied Precision
plt.subplots()
for dataset_index in num_datasets:
plt.bar(index + bar_width*dataset_index, np.array(precisions[dataset_index])[:,0], bar_width, alpha=opacity, label=dataset_names[dataset_index])
plt.xlabel('Models')
plt.ylabel('Precision')
plt.title('Denied Precision Comparison')
plt.xticks(index + bar_width*offset, model_names)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
#Plot for Allowed Precision
plt.subplots()
for dataset_index in num_datasets:
plt.bar(index + bar_width*dataset_index, np.array(precisions[dataset_index])[:,1], bar_width, alpha=opacity, label=dataset_names[dataset_index])
plt.xlabel('Models')
plt.ylabel('Precision')
plt.title('Allowed Precision Comparison')
plt.xticks(index + bar_width*offset, model_names)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
def plot_recall(dataset_names, model_names):
num_datasets = np.arange(len(dataset_names))
index = np.arange(len(model_names))
#Plot for Denied Recall
plt.subplots()
for dataset_index in num_datasets:
plt.bar(index + bar_width*dataset_index, np.array(recalls[dataset_index])[:,0], bar_width, alpha=opacity, label=dataset_names[dataset_index])
plt.xlabel('Models')
plt.ylabel('Recall')
plt.title('Denied Recall Comparison')
plt.xticks(index + bar_width*offset, model_names)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
#Plot for Allowed Recall
plt.subplots()
for dataset_index in num_datasets:
plt.bar(index + bar_width*dataset_index, np.array(recalls[dataset_index])[:,1], bar_width, alpha=opacity, label=dataset_names[dataset_index])
plt.xlabel('Models')
plt.ylabel('Recall')
plt.title('Allowed Recall Comparison')
plt.xticks(index + bar_width*offset, model_names)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
def plot_f1(dataset_names, model_names):
num_datasets = np.arange(len(dataset_names))
index = np.arange(len(model_names))
#Plot for Denied F1-Score
plt.subplots()
for dataset_index in num_datasets:
plt.bar(index + bar_width*dataset_index, np.array(f1s[dataset_index])[:,0], bar_width, alpha=opacity, label=dataset_names[dataset_index])
plt.xlabel('Models')
plt.ylabel('F1-Score')
plt.title('Denied F1-Score Comparison')
plt.xticks(index + bar_width*offset, model_names)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
#Plot for Allowed F1-Score
plt.subplots()
for dataset_index in num_datasets:
plt.bar(index + bar_width*dataset_index, np.array(f1s[dataset_index])[:,1], bar_width, alpha=opacity, label=dataset_names[dataset_index])
plt.xlabel('Models')
plt.ylabel('F1-Score')
plt.title('Allowed F1-Score Comparison')
plt.xticks(index + bar_width*offset, model_names)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
def plot_roc(dataset_names, model_names):
num_datasets = np.arange(len(dataset_names))
index = np.arange(len(model_names))
plt.subplots()
for dataset_index in num_datasets:
plt.bar(index + bar_width*dataset_index, rocs[dataset_index], bar_width, alpha=opacity, label=dataset_names[dataset_index])
plt.xlabel('Models')
plt.ylabel('ROC_AUC Score')
plt.title('Area Under ROC Curve Comparison')
plt.xticks(index + bar_width*offset, model_names)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
def plot_mcc(dataset_names, model_names):
num_datasets = np.arange(len(dataset_names))
index = np.arange(len(model_names))
plt.subplots()
for dataset_index in num_datasets:
plt.bar(index + bar_width*dataset_index, mccs[dataset_index], bar_width, alpha=opacity, label=dataset_names[dataset_index])
plt.xlabel('Models')
plt.ylabel('MCC Score')
plt.title('Matthews Correlation Coefficient Comparison')
plt.xticks(index + bar_width*offset, model_names)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
def plot_fpr(dataset_names, model_names):
num_datasets = np.arange(len(dataset_names))
index = np.arange(len(model_names))
plt.subplots()
for dataset_index in num_datasets:
plt.bar(index + bar_width*dataset_index, fprs[dataset_index], bar_width, alpha=opacity, label=dataset_names[dataset_index])
plt.xlabel('Models')
plt.ylabel('FPR')
plt.title('False Positive (Allow) Rate Comparison')
plt.xticks(index + bar_width*offset, model_names)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
def plot_fnr(dataset_names, model_names):
num_datasets = np.arange(len(dataset_names))
index = np.arange(len(model_names))
plt.subplots()
for dataset_index in num_datasets:
plt.bar(index + bar_width*dataset_index, fnrs[dataset_index], bar_width, alpha=opacity, label=dataset_names[dataset_index])
plt.xlabel('Models')
plt.ylabel('FNR')
plt.title('False Negative (Deny) Rate Comparison')
plt.xticks(index + bar_width*offset, model_names)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
def plot_score(dataset_names, model_names):
num_datasets = np.arange(len(dataset_names))
index = np.arange(len(model_names))
plt.subplots()
for dataset_index in num_datasets:
plt.bar(index + bar_width*dataset_index, scores[dataset_index], bar_width, alpha=opacity, label=dataset_names[dataset_index])
plt.xlabel('Models')
plt.ylabel('Score')
plt.title('Overall Score Evaluation')
plt.xticks(index + bar_width*offset, model_names)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
def main():
#Read in training set
dataset = pd.read_csv("train.csv")
dataset = one_hot_encode(dataset, categorical_data)
#Classification Algorithms
models = []
models.append(('KNN', k_nearest_neighbors_classifier()))
models.append(('DT', decision_tree_classifier()))
models.append(('NB', naive_bayes_classifier()))
models.append(('RFC', random_forest_classifier()))
models.append(('GBC', gradient_boosting_classifier()))
model_names = np.array(models)[:,0]
#Datasets to test
dataset_names = []
dataset_names.append('Raw')
dataset_names.append('SMOTE')
dataset_names.append('SMOTE')
dataset_names.append('UnderSampled')
#Perform training, testing, and evaluation of each dataset over all the models
print "####################### Using Raw Dataset #######################"
X_train, X_test, Y_train, Y_test = raw_dataset(dataset)
train_test_evaluate(X_train, X_test, Y_train, Y_test, models)
print "####################### Using SMOTE Dataset #######################"
X_train, X_test, Y_train, Y_test = smote_dataset(dataset)
train_test_evaluate(X_train, X_test, Y_train, Y_test, models)
print "####################### Using SMOTE Balanced Test Dataset #######################"
X_train, X_test, Y_train, Y_test = smote_balanced_dataset(dataset)
train_test_evaluate(X_train, X_test, Y_train, Y_test, models)
print "####################### Using Undersampled Dataset #######################"
X_train, X_test, Y_train, Y_test = undersampled_dataset(dataset)
train_test_evaluate(X_train, X_test, Y_train, Y_test, models)
#Plot evaluation metrics
plot_accuracies(dataset_names, model_names)
plot_precisions(dataset_names, model_names)
plot_recall(dataset_names, model_names)
plot_f1(dataset_names, model_names)
plot_roc(dataset_names, model_names)
plot_mcc(dataset_names, model_names)
plot_fpr(dataset_names, model_names)
plot_fnr(dataset_names, model_names)
plot_score(dataset_names, model_names)
if __name__ == '__main__':
main()