-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsrcode
378 lines (313 loc) · 14 KB
/
srcode
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
# edited by Tianran Zhang at 2016-06-05
#import necessary packages
import numpy as np
import matplotlib as plt
import random
from sklearn.ensemble import AdaBoostClassifier
from sklearn.ensemble import BaggingClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import GradientBoostingClassifier
from mlxtend.classifier import EnsembleVoteClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn import cross_validation
from scipy.stats import randint as sp_randint
from sklearn.metrics import confusion_matrix
from sklearn.metrics import roc_auc_score
from sklearn.metrics import accuracy_score
from sklearn.svm import SVC
# # # # # # # # # # # # # # # # # # # # # # # # # # # #
# load training data
print "Loading training data..."
x_train = np.genfromtxt('BinaryTrain_data.csv', delimiter=',')
train_labels_raw = np.genfromtxt('BinaryTrain_sbj_list.csv', delimiter=',', skip_header=1)
y_train = train_labels_raw[:, 1]
# divide data into training and testing sets
Size_percentage = 0.20 # size of test set as a percentage in [0., 1.]
seed = random.randint(0, 2 ** 30) # pseudo-random seed for split
x_train1, x_test1, y_train1, y_test1 = cross_validation.train_test_split(x_train, y_train, test_size=Size_percentage,
random_state=seed)
# load testing data
print "Loading the given test data..."
x_test = np.genfromtxt('BinaryTest_data.csv', delimiter=',')
#feature selection
print "feature selection..."
from sklearn import metrics
from sklearn.ensemble import ExtraTreesClassifier
model = ExtraTreesClassifier()
model.fit(x_train, y_train)
# display the relative importance of each attribute
print(model.feature_importances_)
# adaboost classifier
# initialize the (defaults to using shallow decision trees
# as the weak learner to boost) and optimize parameters using random search
print "Training adaboost DT..."
bdt = AdaBoostClassifier(DecisionTreeClassifier(max_depth=1),
n_estimators=300)
bdt1 = AdaBoostClassifier(DecisionTreeClassifier(max_depth=1),
n_estimators=300)
bdt.fit(x_train, y_train)
bdt1.fit(x_train1, y_train1)
print "Generating CV scores for Adaboost sampled training data..."
scores = cross_validation.cross_val_score(bdt1, x_train1, y_train1, cv=5)
print("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2))
print "Generating CV scores for Adaboost all train data "
scores = cross_validation.cross_val_score(bdt, x_train, y_train, cv=5)
print("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2))
AUC_Ada = []
for train_index, test_index in cross_validation.KFold(n=150, n_folds=5, shuffle=True,
random_state=None):
x_train_cv, x_test_cv = x_train[train_index], x_train[test_index]
y_train_cv, y_test_cv = y_train[train_index], y_train[test_index]
bdt_cv = AdaBoostClassifier(DecisionTreeClassifier(max_depth=1),
n_estimators=300)
bdt_cv.fit(x_train_cv, y_train_cv)
predictionAda = bdt_cv.predict(x_test_cv)
AUC_Ada.append(roc_auc_score(y_test_cv, predictionAda))
print np.mean(AUC_Ada)
# set up bagging around each AdaBoost set
print "Training bagged DT..."
bagged = BaggingClassifier(n_estimators=201,
max_samples=0.1)
bagged1 = BaggingClassifier(n_estimators=201,
max_samples=0.1)
bagged.fit(x_train, y_train)
bagged1.fit(x_train1, y_train1)
print "Generating CV scores of bagged decision tree for sampled train data"
scores = cross_validation.cross_val_score(bagged1, x_train1, y_train1, cv=5)
print("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2))
print "Generating CV scores of bagged decision tree for all train data "
scores = cross_validation.cross_val_score(bagged, x_train, y_train, cv=5)
print("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2))
AUC_Bag=[]
for train_index, test_index in cross_validation.KFold(n=150, n_folds=5, shuffle=False,
random_state = None):
x_train_cv, x_test_cv = x_train[train_index], x_train[test_index]
y_train_cv, y_test_cv = y_train[train_index], y_train[test_index]
bagged_cv = BaggingClassifier(n_estimators=201,
max_samples=0.14)
bagged_cv.fit(x_train_cv, y_train_cv)
predictionBag = bagged_cv.predict(x_test_cv)
# print predictionBag, y_test_cv
# print roc_auc_score(y_test_cv, predictionBag)
AUC_Bag.append(roc_auc_score(y_test_cv, predictionBag))
print np.mean(AUC_Bag)
# initialize a random forest classifier
print 'Training random forest...'
rfc = RandomForestClassifier(n_estimators=400,
max_features=40,
min_samples_split=2,
min_samples_leaf=1)
rfc1 = RandomForestClassifier(n_estimators=400,
max_features=40,
min_samples_split=2,
min_samples_leaf=1)
rfc.fit(x_train, y_train)
rfc1.fit(x_train1, y_train1)
print "Generating CV scores for random forest sampled training data..."
scores = cross_validation.cross_val_score(rfc1, x_train1, y_train1, cv=5)
print("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2))
print "Generating CV scores for random forest all train data "
scores = cross_validation.cross_val_score(rfc, x_train, y_train, cv=5)
print("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2))
AUC_RF=[]
for train_index, test_index in cross_validation.KFold(n=150, n_folds=5, shuffle=False,
random_state=None):
x_train_cv, x_test_cv = x_train[train_index], x_train[test_index]
y_train_cv, y_test_cv = y_train[train_index], y_train[test_index]
rfc_cv = RandomForestClassifier(n_estimators=400,
max_features=40,
min_samples_split=2,
min_samples_leaf=1)
rfc_cv.fit(x_train_cv, y_train_cv)
predictionRF = rfc_cv.predict(x_test_cv)
# print predictionBag, y_test_cv
# print roc_auc_score(y_test_cv, predictionBag)
AUC_RF.append(roc_auc_score(y_test_cv, predictionRF))
print np.mean(AUC_RF)
print 'Training SVM...'
clf = SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
decision_function_shape=None, degree=3, gamma='auto', kernel='rbf',
max_iter=-1, probability=False, random_state=None, shrinking=True,
tol=0.010, verbose=False)
clf1 = SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
decision_function_shape=None, degree=3, gamma='auto', kernel='rbf',
max_iter=-1, probability=False, random_state=None, shrinking=True,
tol=0.010, verbose=False)
clf.fit(x_train, y_train)
clf1.fit(x_train1, y_train1)
print "Generating CV scores for SVC sampled training data..."
scores = cross_validation.cross_val_score(clf1, x_train1, y_train1, cv=5)
print("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2))
print "Generating CV scores for SVC all train data "
scores = cross_validation.cross_val_score(clf, x_train, y_train, cv=5)
print("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2))
eclf = EnsembleVoteClassifier(clfs=[bdt, bagged, rfc], weights=[1, 1, 1], voting='soft')
eclf1 = EnsembleVoteClassifier(clfs=[bdt1, bagged1, rfc1], weights=[1, 1, 1], voting='soft')
print "Generating CV scores for ensemble model sampled training data..."
scores = cross_validation.cross_val_score(eclf1, x_train1, y_train1, cv=5)
print("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2))
print "Generating CV scores for ensemble model all train data "
scores = cross_validation.cross_val_score(eclf, x_train, y_train, cv=5)
print("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2))
#==============================================================================
AUC_Ensem=[]
for train_index, test_index in cross_validation.KFold(n=150, n_folds=5, shuffle=False,
random_state=None):
x_train_cv, x_test_cv = x_train[train_index], x_train[test_index]
y_train_cv, y_test_cv = y_train[train_index], y_train[test_index]
bagged2 = BaggingClassifier(n_estimators=201,
max_samples=0.14)
bagged2.fit(x_train_cv, y_train_cv)
bdt2 = AdaBoostClassifier(DecisionTreeClassifier(max_depth=1),
n_estimators=300)
bdt2.fit(x_train_cv, y_train_cv)
rfc2 = RandomForestClassifier(n_estimators=400,
max_features=40,
min_samples_split=2,
min_samples_leaf=1)
rfc2.fit(x_train_cv, y_train_cv)
#eclf2 = EnsembleVoteClassifier(clfs=[bdt2, bagged2, rfc2],
# weights=[1, 1, 1],
#voting='soft')
predictionAda = bdt2.predict(x_test_cv)
predictionBag = bagged2.predict(x_test_cv)
predictionRF = rfc2.predict(x_test_cv)
predictionEnsemble= []
for i in range (30):
if 1.4*predictionAda[i] + 0.8*predictionBag[i] + 0.8*predictionRF[i] > 1:
predictionEnsemble.append(1)
else:
predictionEnsemble.append(0)
#predictionEnsemble = eclf2.predict(x_test_cv)
AUC_Ensem.append(roc_auc_score(y_test_cv, predictionEnsemble))
print np.mean(AUC_Ensem)
#==========================================================================
#'External' validation using the 20% sampled test set
print "for all train data..."
print "generate predictive result for each model"
print "Adaboost DT:"
predictions1 = bdt.predict(x_test)
print "Bagged DT:"
predictions2 = bagged.predict(x_test)
print "Random Forest:"
predictions3 = rfc.predict(x_test)
print "for sampled training data..."
print "predictive performance for each model on subset testing data"
print "---------------"
print "Adaboost DT:"
predictions4 = bdt1.predict(x_test1)
print confusion_matrix(y_test1,predictions4)
print " AUC:"
print roc_auc_score(y_test1,predictions4)
print "accuracy:"
print accuracy_score(y_test1,predictions4)
print "Bagged DT:"
predictions5 = bagged1.predict(x_test1)
print confusion_matrix(y_test1,predictions5)
print " AUC:"
print roc_auc_score(y_test1,predictions5)
print "accuracy:"
print accuracy_score(y_test1,predictions5)
print "Random Forest:"
predictions6 = rfc1.predict(x_test1)
print confusion_matrix(y_test1,predictions6)
print " AUC:"
print roc_auc_score(y_test1,predictions6)
print "accuracy:"
print accuracy_score(y_test1,predictions6)
#Generating predicted labels for all training data using results from all 3 models
predictions = []
for i in range(100):
if predictions1[i] + predictions2[i] + predictions3[i] > 1:
predictions.append(1)
else:
predictions.append(0)
#save predicted labels for all training data into .csv file 'predictions'
f = open('/Users/zhangtianran/Downloads/MICCAI_2014_MLC-master/predictions.csv', 'w')
#f.write('Label\n')
for i in range(100):
f.write(str(int(predictions[i])) + '\n')
predictions = []
for i in range(30):
if predictions4[i]+ predictions5[i] +predictions6[i] > 1: #
predictions.append(1)
else:
predictions.append(0)
f = open('/Users/zhangtianran/Downloads/MICCAI_2014_MLC-master/validate_pre.csv', 'w')
#f.write('Label\n')
for i in range(30):
f.write(str(int(predictions[i])) + '\n')
#f = open('/Users/zhangtianran/Downloads/MICCAI_2014_MLC-master/test_truth.csv', 'w')
#f.write('Label\n')
#for i in range(30):
# f.write(str(int(y_test1[i])) + '\n')
#print y_test1
#print predictions
print "for ensembled model..."
print confusion_matrix(y_test1,predictions)
print " AUC:"
print roc_auc_score(y_test1,predictions)
print "Accuracy:"
print accuracy_score(y_test1,predictions)
################################################################################
# RESULTS:
################################################################################
# with original training data:
# training with 80%, testing on 20% yields score = 0.662213740458
# with transformed tf-idf data (not sure if this is working yet
# because this seems signifigantly worse than with the original data):
# training with 75%, testing on 25% yields score = 0.644083969466
# submission using all training data yields about 0.53 on the leaderboard
################################################################################
# RANDOM DISORGANIZED CODE BELOW:
################################################################################
####
# FOR PRINTING CROSS VALIDATION SCORES:
####
# print "Generating CV scores..."
# scores = cross_validation.cross_val_score(random_search, x_train, y_train, cv=5)
# print("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2))
####
# FOR PLOTTING:
####
# perform the plot
# plt.plot(estimators, validation_means, label='Train')
# plt.errorbar(estimators, validation_means, validation_std_devs)
# plt.legend(loc='best')
# plt.title('n_estimators vs. validation mean score')
# plt.xlabel('number of estimators')
# plt.ylabel('mean validation score')
# plt.show()
####
# FOR PLOTTING ESTIMATORS VS VALIDATION MEANS:
####
# estimator_range = [i for i in range(1, 600 + 1)]
# estimators = estimator_range[::100]
# validation_means = []
# validation_std_devs = []
# print estimators
# for n in estimators:
# print "Training with n_estimators = " + str(n)
# bdt = AdaBoostClassifier(DecisionTreeClassifier(max_depth=2),
# n_estimators=n,
# learning_rate=1.)
# print "Computing validation mean..."
# scores = cross_validation.cross_val_score(bdt, x_train, y_train, cv=5)
# validation_means.append(scores.mean())
# validation_std_devs.append(scores.std() * 2)
#==========
# training scores
#print "Training scores..."
#print bdt.score(x_train, y_train)
#print bagged.score(x_train, y_train)
#print rfc.score(x_train, y_train)
#print bdt1.score(x_train1, y_train1)
#print bagged1.score(x_train1, y_train1)
#print rfc1.score(x_train1, y_train1)
# score the classfier on the test set
# print "Scoring..."
# print bdt.score(x_test, y_test)
# print bagged.score(x_test, y_test)
# print rfc.score(x_test, y_test)
# In[ ]:
# In[ ]: