-
Notifications
You must be signed in to change notification settings - Fork 0
/
poi_id.py
284 lines (208 loc) · 8.94 KB
/
poi_id.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
#!/usr/bin/python
import sys
import pickle
sys.path.append("../tools/")
from feature_format import featureFormat, targetFeatureSplit
from tester import dump_classifier_and_data
import fraudfunctions
import tester
from sklearn.feature_selection import SelectKBest
from sklearn.pipeline import Pipeline
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import AdaBoostClassifier
### Task 1: Select what features you'll use.
# These are the features in the enron dataset.
# I will create new features later and
# select best features according to algorithm
# using SelectKBest().
features_list = ['poi',
'bonus',
'deferral_payments',
'deferred_income',
'director_fees',
'exercised_stock_options',
'expenses',
'loan_advances',
'long_term_incentive',
'other',
'restricted_stock',
'restricted_stock_deferred',
'salary',
'total_payments',
'total_stock_value',
'from_messages',
'from_poi_to_this_person',
'from_this_person_to_poi',
'shared_receipt_with_poi',
'to_messages']
### Load the dictionary containing the dataset
data_dict = pickle.load(open("final_project_dataset.pkl", "r") )
### Task 2: Remove outliers
outliers = ['TOTAL', 'LOCKHART EUGENE E', 'THE TRAVEL AGENCY IN THE PARK']
fraudfunctions.remove_outliers(data_dict, outliers)
### Task 3: Create new feature(s)
fraudfunctions.fraction_poi_communication(data_dict)
fraudfunctions.total_wealth(data_dict)
features_list += ['fraction_poi_communication', 'total_wealth']
### Store to my_dataset for easy export below.
my_dataset = data_dict
# Top 10 best features using SelectKBest().
best_features_list = ['poi',
'exercised_stock_options',
'total_stock_value',
'bonus',
'salary',
'total_wealth',
'deferred_income',
'long_term_incentive',
'restricted_stock',
'total_payments',
]
### Extract features and labels from dataset for local testing
data = featureFormat(my_dataset, features_list, sort_keys=True)
labels, features = targetFeatureSplit(data)
### Task 4: Tune and try a variety of classifiers
def tune_logistic_regression():
skb = SelectKBest()
pca = PCA()
lr_clf = LogisticRegression()
pipe_lr = Pipeline(steps=[("SKB", skb), ("PCA", pca), ("LogisticRegression", lr_clf)])
lr_k = {"SKB__k": range(9, 10)}
lr_params = {'LogisticRegression__C': [1e-08, 1e-07, 1e-06],
'LogisticRegression__tol': [1e-2, 1e-3, 1e-4],
'LogisticRegression__penalty': ['l1', 'l2'],
'LogisticRegression__random_state': [42, 46, 60]}
lr_pca = {"PCA__n_components": range(3, 8), "PCA__whiten": [True, False]}
lr_k.update(lr_params)
lr_k.update(lr_pca)
fraudfunctions.get_best_parameters_reports(pipe_lr, lr_k, features, labels)
def tune_svc():
skb = SelectKBest()
pca = PCA()
svc_clf = SVC()
pipe_svc = Pipeline(steps=[("SKB", skb), ("PCA", pca), ("SVC", svc_clf)])
svc_k = {"SKB__k": range(8, 10)}
svc_params = {'SVC__C': [1000], 'SVC__gamma': [0.001], 'SVC__kernel': ['rbf']}
svc_pca = {"PCA__n_components": range(3, 8), "PCA__whiten": [True, False]}
svc_k.update(svc_params)
svc_k.update(svc_pca)
fraudfunctions.get_best_parameters_reports(pipe_svc, svc_k, features, labels)
def tune_decision_tree():
skb = SelectKBest()
pca = PCA()
dt_clf = DecisionTreeClassifier()
pipe = Pipeline(steps=[("SKB", skb), ("PCA", pca), ("DecisionTreeClassifier", dt_clf)])
dt_k = {"SKB__k": range(8, 10)}
dt_params = {"DecisionTreeClassifier__min_samples_leaf": [2, 6, 10, 12],
"DecisionTreeClassifier__min_samples_split": [2, 6, 10, 12],
"DecisionTreeClassifier__criterion": ["entropy", "gini"],
"DecisionTreeClassifier__max_depth": [None, 5],
"DecisionTreeClassifier__random_state": [42, 46, 60]}
dt_pca = {"PCA__n_components": range(4, 7), "PCA__whiten": [True, False]}
dt_k.update(dt_params)
dt_k.update(dt_pca)
fraudfunctions.get_best_parameters_reports(pipe, dt_k, features, labels)
def tune_random_forest():
skb = SelectKBest()
rf_clf = RandomForestClassifier()
pipe_rf = Pipeline(steps=[("SKB", skb), ("RandomForestClassifier", rf_clf)])
rf_k = {"SKB__k": range(8, 11)}
rf_params = {'RandomForestClassifier__max_depth': [None, 5, 10],
'RandomForestClassifier__n_estimators': [10, 15, 20, 25],
'RandomForestClassifier__random_state': [42, 46, 60]}
rf_k.update(rf_params)
fraudfunctions.get_best_parameters_reports(pipe_rf, rf_k, features, labels)
def tune_ada_boost():
skb = SelectKBest()
ab_clf = AdaBoostClassifier()
pipe_ab = Pipeline(steps=[("SKB", skb), ("AdaBoostClassifier", ab_clf)])
ab_k = {"SKB__k": range(8, 11)}
ab_params = {'AdaBoostClassifier__n_estimators': [10, 20, 30, 40],
'AdaBoostClassifier__algorithm': ['SAMME', 'SAMME.R'],
'AdaBoostClassifier__learning_rate': [.8, 1, 1.2, 1.5]}
ab_k.update(ab_params)
fraudfunctions.get_best_parameters_reports(pipe_ab, ab_k, features, labels)
if __name__ == '__main__':
''' GAUSSIAN NAIVE BAYES '''
# clf = GaussianNB()
# print "Gaussian Naive Bayes : \n", tester.test_classifier(clf, my_dataset, best_features_list)
''' LOGISTIC REGRESSION '''
#tune_logistic_regression()
best_features_list_lr = fraudfunctions.get_k_best(my_dataset, features_list, 9)
clf_lr = Pipeline(steps=[
('scaler', StandardScaler()),
('pca', PCA(n_components=4, whiten=False)),
('classifier', LogisticRegression(tol=0.01, C=1e-08, penalty='l2', random_state=42))])
print "Logistic Regression : \n", tester.test_classifier(clf_lr, my_dataset, best_features_list_lr)
# ''' SUPPORT VECTOR CLASSIFIER '''
#
# #tune_svc()
#
# best_features_list_svc = fraudfunctions.get_k_best(my_dataset, features_list, 8)
#
# clf_svc = Pipeline(steps=[
# ('scaler', StandardScaler()),
# ('pca', PCA(n_components=6, whiten=True)),
# ('classifier', SVC(C=1000, gamma=.001, kernel='rbf'))])
#
# print "Support Vector Classifier : \n", tester.test_classifier(clf_svc, my_dataset, best_features_list_svc)
#
#
# ''' DECISION TREE CLASSIFIER '''
#
# #tune_decision_tree()
#
# best_features_list_dt = fraudfunctions.get_k_best(my_dataset, features_list, 8)
#
# clf_dt = Pipeline(steps=[
# ('scaler', StandardScaler()),
# ('pca', PCA(n_components=5, whiten=True)),
# ('classifier', DecisionTreeClassifier(criterion='entropy',
# min_samples_leaf=2,
# min_samples_split=2,
# random_state=46,
# class_weight = 'balanced',
# max_depth=None))
# ])
#
# print "Decision Tree Classifier : \n",tester.test_classifier(clf_dt, my_dataset, best_features_list_dt)
#
#
# ''' RANDOM FOREST CLASSIFIER '''
#
# #tune_random_forest()
#
# best_features_list_rf = fraudfunctions.get_k_best(my_dataset, features_list, 9)
#
# clf_rf = Pipeline(steps=[
# ('scaler', StandardScaler()),
# ('classifier', RandomForestClassifier(max_depth=5,
# n_estimators=25,
# random_state=42))
# ])
#
# print "Random Forest Classifier : \n", tester.test_classifier(clf_rf, my_dataset, best_features_list_rf)
#
#
# ''' ADA BOOST CLASSIFIER '''
#
# #tune_ada_boost()
#
# best_features_list_ab = fraudfunctions.get_k_best(my_dataset, features_list, 9)
#
# clf_ab = Pipeline(steps=[
# ('scaler', StandardScaler()),
# ('classifier', AdaBoostClassifier(learning_rate=1.5,
# n_estimators=30,
# algorithm='SAMME.R'))
# ])
#
# print "Ada Boost Classifier : \n", tester.test_classifier(clf_ab, my_dataset, best_features_list_ab)
''' dump final algorithm classifier, dataset and features in the data directory '''
dump_classifier_and_data(clf_lr, my_dataset, best_features_list_lr)