Repository navigation
Expand file tree
/
Copy pathTrees_TestM2.py
More file actions
427 lines (291 loc) · 12.3 KB
/
Copy pathTrees_TestM2.py
File metadata and controls
427 lines (291 loc) · 12.3 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
######################################################
#Imports
######################################################
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from sklearn.tree import DecisionTreeClassifier, export_graphviz
from sklearn.ensemble import BaggingClassifier, RandomForestClassifier
from sklearn.metrics import accuracy_score
import pandas as pd
from sklearn.metrics import recall_score, make_scorer, confusion_matrix, roc_curve, auc
######################################################
#Read in Data : Manual Feature Selection
######################################################
'''
#first outcome. manual feature selection. non-duplicated.
Xtrain1 = pd.read_csv('./DataSplit/Xtrain1')
ytrain1 = pd.read_csv('./DataSplit/ytrain1')
ytrain1 = ytrain1['modOneOutcome'].values
ytrain1 = ytrain1.astype('int64')
#second outcome. manual feature selection. non-duplicated.
Xtrain2 = pd.read_csv('./DataSplit/Xtrain2')
ytrain2 = pd.read_csv('./DataSplit/ytrain2')
ytrain2 = ytrain2['modTwoOutcome'].values
ytrain2 = ytrain2.astype('int64')
#first outcome. manual feature selection. duplicated.
XtrainDuplicate1 = pd.read_csv('./DataSplit/XtrainDuplicate1')
ytrainDuplicate1 = pd.read_csv('./DataSplit/ytrainDuplicate1')
ytrainDuplicate1 = ytrainDuplicate1['modOneOutcome'].values
ytrainDuplicate1 = ytrainDuplicate1.astype('int64')
#second outcome. manual feature selection. duplicated
XtrainDuplicate2 = pd.read_csv('./DataSplit/XtrainDuplicate2')
ytrainDuplicate2 = pd.read_csv('./DataSplit/ytrainDuplicate2')
ytrainDuplicate2 = ytrainDuplicate2['modTwoOutcome'].values
ytrainDuplicate2 = ytrainDuplicate2.astype('int64')
#validation data
#outcome 1
Xvalidate1 = pd.read_csv('./DataSplit/Xvalidate1')
yvalidate1 = pd.read_csv('./DataSplit/yvalidate1')
yvalidate1 = yvalidate1['modOneOutcome'].values
yvalidate1 = yvalidate1.astype('int64')
#outcome 2
Xvalidate2 = pd.read_csv('./DataSplit/Xvalidate2')
yvalidate2 = pd.read_csv('./DataSplit/yvalidate2')
yvalidate2 = yvalidate2['modTwoOutcome'].values
yvalidate2 = yvalidate2.astype('int64')
'''
######################################################
#Read in Data : Data-Driven Feature Selection
######################################################
'''
#first outcome. dd feature selection. non-duplicated.
Xtrain1 = pd.read_csv('./DDFSdata/Xtrain1DD')
ytrain1 = pd.read_csv('./DDFSdata/ytrain1DD')
ytrain1 = ytrain1['modOneOutcome'].values
ytrain1 = ytrain1.astype('int64')
'''
#second outcome. dd feature selection. non-duplicated.
Xtrain2 = pd.read_csv('./DDFSdata/Xtrain2DD')
ytrain2 = pd.read_csv('./DDFSdata/ytrain2DD')
ytrain2 = ytrain2['modTwoOutcome'].values
ytrain2 = ytrain2.astype('int64')
'''
#first outcome. dd feature selection. duplicated.
XtrainDuplicate1 = pd.read_csv('./DDFSdata/XtrainDuplicate1DD')
ytrainDuplicate1 = pd.read_csv('./DDFSdata/ytrainDuplicate1DD')
ytrainDuplicate1 = ytrainDuplicate1['modOneOutcome'].values
ytrainDuplicate1 = ytrainDuplicate1.astype('int64')
#second outcome. dd feature selection. duplicated
XtrainDuplicate2 = pd.read_csv('./DDFSdata/XtrainDuplicate2DD')
ytrainDuplicate2 = pd.read_csv('./DDFSdata/ytrainDuplicate2DD')
ytrainDuplicate2 = ytrainDuplicate2['modTwoOutcome'].values
ytrainDuplicate2 = ytrainDuplicate2.astype('int64')
#validation data
#outcome 1
Xvalidate1 = pd.read_csv('./DDFSdata/Xvalidate1DD')
yvalidate1 = pd.read_csv('./DDFSdata/yvalidate1DD')
yvalidate1 = yvalidate1['modOneOutcome'].values
yvalidate1 = yvalidate1.astype('int64')
#outcome 2
Xvalidate2 = pd.read_csv('./DDFSdata/Xvalidate2DD')
yvalidate2 = pd.read_csv('./DDFSdata/yvalidate2DD')
yvalidate2 = yvalidate2['modTwoOutcome'].values
yvalidate2 = yvalidate2.astype('int64')
'''
#second outcome. testing data
#get the testing data. data driven feature selection. non duplicated.
Xtest2 = pd.read_csv('./DDFSdata/Xtest2DD')
ytest2nonArray = pd.read_csv('./DDFSdata/ytest2DD')
print("test data X", Xtest2.shape)
print("test data y", ytest2nonArray.shape)
ytest2 = ytest2nonArray['modTwoOutcome'].values
ytest2 = ytest2.astype('int64')
#want to join for bootstrap CI
toJoin = [Xtest2, ytest2nonArray]
data = pd.concat(toJoin, axis = 1)
######################################################
#Function to get performance
######################################################
# Computing metrics function from Lab 7
def compute_performance(yhat, y, modtype):
print("\n Model Type:", modtype, "\n")
# First, get tp, tn, fp, fn
tp = sum(np.logical_and(yhat == 1, y == 1))
tn = sum(np.logical_and(yhat == 0, y == 0))
fp = sum(np.logical_and(yhat == 1, y == 0))
fn = sum(np.logical_and(yhat == 0, y == 1))
print(f"tp: {tp} tn: {tn} fp: {fp} fn: {fn}")
# Accuracy
trainacc = (tp + tn) / (tp + tn + fp + fn)
# Precision
# "Of the ones I labeled +, how many are actually +?"
precision = tp / (tp + fp)
# Recall
# "Of all the + in the data, how many do I correctly label?"
#do we care abt accid iden.
#waste resources is the ris
recall = tp / (tp + fn)
# Sensitivity
# "Of all the + in the data, how many do I correctly label?"
sensitivity = recall
# Specificity
# "Of all the - in the data, how many do I correctly label?"
specificity = tn / (fp + tn)
# Print results
print("Acc:",trainacc,"Sens:",sensitivity,"Spec:",specificity)
#broken CI method
def confintOutcomeOne(data, model, numboot = 10000):
acc = np.zeros(numboot)
sens = np.zeros(numboot)
spec = np.zeros(numboot)
aucmet = np.zeros(numboot)
for i in range(numboot):
df_bootstrapped = data.sample(data.shape[0], replace = True)
y = df_bootstrapped.modOneOutcome
yhat = model.predict_proba(df_bootstrapped.drop('modOneOutcome', axis = 'columns'))[:,1]
fpr,tpr, _ = roc_curve(y, yhat)
aucmetric = auc(fpr,tpr)
print("auc", aucmetric)
yhat = yhat.astype('int64')
tp = sum(np.logical_and(yhat == 1, y == 1))
tn = sum(np.logical_and(yhat == 0, y == 0))
fp = sum(np.logical_and(yhat == 1, y == 0))
fn = sum(np.logical_and(yhat == 0, y == 1))
print(f"tp: {tp} tn: {tn} fp: {fp} fn: {fn}")
acc[i] = (tp + tn) / (tp + tn + fp + fn)
sens[i] = tp / (tp + fn)
spec[i] = tn / (fp + tn)
aucmet[i] = aucmetric
print("acc:", np.quantile(acc,(0.025,0.975)),
"sens:", np.quantile(sens,(0.025,0.975)),
"spec:", np.quantile(spec,(0.025,0.975)),
"auc:", np.quantile(aucmet,(0.025,0.975)))
######################################################
#Set Up Models
######################################################
#m1 selected
#rf1 = RandomForestClassifier(n_estimators = 400, max_features = 5)
#use these two for model 2 outcome
rf4 = RandomForestClassifier(n_estimators = 400, max_depth = 10, max_features = 10)
######################################################
#Testing
######################################################
#fit models
mod4_M2 = rf4.fit(Xtrain2, ytrain2)
#make predictions
ypred_rf4_M2 = rf4.predict(Xtest2)
#call performance function
compute_performance(ypred_rf4_M2, ytest2, mod4_M2)
#call sklearn functions to get auc
mod4_pred_prob_M2 = mod4_M2.predict_proba(Xtest2)[:,1]
np.save('Preds_Forest_M2_TEST', mod4_pred_prob_M2)
np.save('Truth_Forest_M2_TEST', ytest2)
fpr_mod4_M2, tpr_mod4_M2, _ = roc_curve(ytest2, mod4_pred_prob_M2)
auc_mod4_M2 = auc(fpr_mod4_M2, tpr_mod4_M2)
print("AUC\n", auc_mod4_M2)
#can plot a fitted tree
importances = mod4_M2.feature_importances_
std = np.std([mod4_M2.feature_importances_ for tree in mod4_M2.estimators_],
axis=0)
indices = np.argsort(importances)[::-1]
# Print the feature ranking
print("Feature ranking:")
for f in range(Xtrain2.shape[1]):
print("%d. feature %d (%f)" % (f + 1, indices[f], importances[indices[f]]))
# Plot the feature importances of the forest
plt.figure(figsize = (15, 5))
plt.title("Feature importances")
plt.bar(range(Xtrain2.shape[1]), importances[indices],
color="r", yerr=std[indices], align="center")
plt.xticks(range(Xtrain2.shape[1]), indices)
plt.xlim([-1, Xtrain2.shape[1]])
#plt.show()
plt.savefig('obj2_featureImportance_.png')
######################################################
#Fit and Predict on All Data Types
######################################################
'''
print("OUTCOME 1 NON DUPLICATED DATA\n")
#fit models
mod1_M1 = rf1.fit(Xtrain1, ytrain1)
#mod2_M1 = rf2.fit(Xtrain1, ytrain1)
#make predictions
ypred_rf1_M1 = mod1_M1.predict(Xvalidate1)
#ypred_rf2_M1 = mod2_M1.predict(Xvalidate1)
#first model metrics
#call performance function
compute_performance(ypred_rf1_M1, yvalidate1, mod1_M1)
#call sklearn functions to get auc
mod1_pred_prob_M1 = mod1_M1.predict_proba(Xvalidate1)[:,1]
np.save('Preds_Forest_M1_DD_NoDup', mod1_pred_prob_M1)
np.save('Truth_Forest_M1_DD_NoDup', yvalidate1)
fpr_mod1_M1, tpr_mod1_M1, _ = roc_curve(yvalidate1, mod1_pred_prob_M1)
auc_mod1_M1 = auc(fpr_mod1_M1, tpr_mod1_M1)
print("AUC\n", auc_mod1_M1)
#second model metrics
#compute_performance(ypred_rf2_M1, yvalidate1, mod2_M1)
#mod2_pred_prob_M1 = mod2_M1.predict_proba(Xvalidate1)[:,1]
#fpr_mod2_M1, tpr_mod2_M1, _ = roc_curve(yvalidate1, mod2_pred_prob_M1)
#auc_mod2_M1 = auc(fpr_mod2_M1, tpr_mod2_M1)
#print("AUC\n", auc_mod2_M1)
print("\nOUTCOME 1 DUPLICATED DATA\n")
#print("model 1 only\n")
#fit models
mod1_MD1 = rf1.fit(XtrainDuplicate1, ytrainDuplicate1)
# mod2_MD1 = rf2.fit(XtrainDuplicate1, ytrainDuplicate1)
#make predictions
ypred_rf1_MD1 = mod1_MD1.predict(Xvalidate1)
# ypred_rf2_MD1 = mod2_MD1.predict(Xvalidate1)
#call performance function
compute_performance(ypred_rf1_MD1, yvalidate1, mod1_MD1)
#call sklearn functions to get auc
mod1_pred_prob_MD1 = mod1_MD1.predict_proba(Xvalidate1)[:,1]
np.save('Preds_Forest_M1_DD_YesDup', mod1_pred_prob_MD1)
np.save('Truth_Forest_M1_DD_YesDup', yvalidate1)
fpr_mod1_MD1, tpr_mod1_MD1, _ = roc_curve(yvalidate1, mod1_pred_prob_MD1)
auc_mod1_MD1 = auc(fpr_mod1_MD1, tpr_mod1_MD1)
print("AUC\n", auc_mod1_MD1)
#compute_performance(ypred_rf2_MD1, yvalidate1, mod2_MD1)
#call sklearn functions to get auc
#mod2_pred_prob_MD1 = mod2_MD1.predict_proba(Xvalidate1)[:,1]
#fpr_mod2_MD1, tpr_mod2_MD1, _ = roc_curve(yvalidate1, mod2_pred_prob_MD1)
#auc_mod2_MD1 = auc(fpr_mod2_MD1, tpr_mod2_MD1)
#print("AUC\n", auc_mod2_MD1)
print("\nOUTCOME 2 NON DUPLICATED DATA\n")
#fit models
# mod3_M2 = rf3.fit(Xtrain2, ytrain2)
mod4_M2 = rf4.fit(Xtrain2, ytrain2)
#make predictions
# ypred_rf3_M2 = rf3.predict(Xvalidate2)
ypred_rf4_M2 = rf4.predict(Xvalidate2)
#call performance function
#compute_performance(ypred_rf3_M2, yvalidate2, mod3_M2)
#call sklearn functions to get auc
#mod3_pred_prob_M2 = mod3_M2.predict_proba(Xvalidate2)[:,1]
#fpr_mod3_M2, tpr_mod3_M2, _ = roc_curve(yvalidate2, mod3_pred_prob_M2)
#auc_mod3_M2 = auc(fpr_mod3_M2, tpr_mod3_M2)
#print("AUC\n", auc_mod3_M2)
#call performance function
compute_performance(ypred_rf4_M2, yvalidate2, mod4_M2)
#call sklearn functions to get auc
mod4_pred_prob_M2 = mod4_M2.predict_proba(Xvalidate2)[:,1]
np.save('Preds_Forest_M2_DD_NoDup', mod4_pred_prob_M2)
np.save('Truth_Forest_M2_DD_NoDup', yvalidate2)
fpr_mod4_M2, tpr_mod4_M2, _ = roc_curve(yvalidate2, mod4_pred_prob_M2)
auc_mod4_M2 = auc(fpr_mod4_M2, tpr_mod4_M2)
print("AUC\n", auc_mod4_M2)
print("\nOUTCOME 2 DUPLICATED DATA\n")
#print("model 4 only")
#fit models
# mod3_MD2 = rf3.fit(XtrainDuplicate2, ytrainDuplicate2)
mod4_MD2 = rf4.fit(XtrainDuplicate2, ytrainDuplicate2)
#make predictions
# ypred_rf3_MD2 = mod3_MD2.predict(Xvalidate2)
ypred_rf4_MD2 = mod4_MD2.predict(Xvalidate2)
#call performance function
#compute_performance(ypred_rf3_MD2, yvalidate2, mod3_MD2)
#call sklearn functions to get auc
#mod3_pred_prob_MD2 = mod3_MD2.predict_proba(Xvalidate2)[:,1]
#fpr_mod3_MD2, tpr_mod3_MD2, _ = roc_curve(yvalidate2, mod3_pred_prob_MD2)
#auc_mod3_MD2 = auc(fpr_mod3_MD2, tpr_mod3_MD2)
#print("AUC\n", auc_mod3_MD2)
compute_performance(ypred_rf4_MD2, yvalidate2, mod4_MD2)
#call sklearn functions to get auc
mod4_pred_prob_MD2 = mod4_MD2.predict_proba(Xvalidate2)[:,1]
np.save('Preds_Forest_M2_DD_YesDup', mod4_pred_prob_MD2)
np.save('Truth_Forest_M2_DD_YesDup', yvalidate2)
fpr_mod4_MD2, tpr_mod4_MD2, _ = roc_curve(yvalidate2, mod4_pred_prob_MD2)
auc_mod4_MD2 = auc(fpr_mod4_MD2, tpr_mod4_MD2)
print("AUC\n", auc_mod4_MD2)
'''