-
Notifications
You must be signed in to change notification settings - Fork 19
/
models_classification.py
executable file
·1330 lines (1053 loc) · 62.9 KB
/
models_classification.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
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#######################################################################################################################
##### IMPORT STANDARD MODULES
#######################################################################################################################
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import pydot
import os
from scipy.stats.mstats import chisquare, mode
from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import KFold
from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier,AdaBoostClassifier, GradientBoostingClassifier
from sklearn.tree import DecisionTreeClassifier, export_graphviz
from sklearn.grid_search import GridSearchCV
from sklearn import metrics, cross_validation
from sklearn.feature_selection import RFE, RFECV
from StringIO import StringIO
import xgboost as xgb
from xgboost.sklearn import XGBClassifier
#######################################################################################################################
##### GENERIC MODEL CLASS
#######################################################################################################################
#This class contains the generic classification functions and variable definitions applicable across all models
class GenericModelClass(object):
def __init__(self, alg, data_train, data_test, target, predictors=[],cv_folds=5,scoring_metric='accuracy'):
self.alg = alg #an instance of particular model class
self.data_train = data_train #training data
self.data_test = data_test #testing data
self.target = target
self.cv_folds = cv_folds
self.predictors = predictors
self.train_predictions = []
self.train_pred_prob = []
self.test_predictions = []
self.test_pred_prob = []
self.num_target_class = len(data_train[target].unique())
#define scoring metric:
self.scoring_metric = scoring_metric
#grid-search objects:
self.gridsearch_class = None
self.gridsearch_result = None
#Define a Series object to store generic classification model outcomes;
self.classification_output=pd.Series(index=['ModelID','Accuracy','CVScore_mean','CVScore_std','AUC',
'ActualScore (manual entry)','CVMethod','ConfusionMatrix','Predictors'])
#not to be used for all but most
self.feature_imp = None
#Modify and get predictors for the model:
def set_predictors(self, predictors):
self.predictors=predictors
def get_predictors(self):
return self.predictors
def get_test_predictions(self, getprob=False):
if getprob:
return self.test_pred_prob
else:
return self.test_predictions
def get_feature_importance(self):
return self.feature_imp
def set_scoring_metric(scoring_metric):
self.scoring_metric = scoring_metric
#Implement K-Fold cross-validation
def KFold_CrossValidation(self, scoring_metric):
# Generate cross validation folds for the training dataset.
error = cross_validation.cross_val_score(self.alg, self.data_train[self.predictors], self.data_train[self.target],
cv=self.cv_folds, scoring=scoring_metric, n_jobs=4)
#Old Method:
# kf = KFold(self.data_train.shape[0], n_folds=self.cv_folds)
# error = []
# for train, test in kf:
# # Filter training data
# train_predictors = (self.data_train[self.predictors].iloc[train,:])
# # The target we're using to train the algorithm.
# train_target = self.data_train[self.target].iloc[train]
# # Training the algorithm using the predictors and target.
# self.alg.fit(train_predictors, train_target)
# #Record error from each cross-validation run
# error.append(self.alg.score(self.data_train[self.predictors].iloc[test,:], self.data_train[self.target].iloc[test]))
return {'mean_error': np.mean(error),
'std_error': np.std(error),
'all_error': error }
#Implement recursive feature elimination
# Inputs:
# nfeat - the num of top features to select
# step - the number of features to remove at each step
# inplace - True: modiy the data of the class with the data after RFE
# Returns:
# selected - a series object containing the selected features
def RecursiveFeatureElimination(self, nfeat=None, step=1, inplace=False):
rfe = RFE(self.alg, n_features_to_select=nfeat, step=step)
rfe.fit(self.data_train[self.predictors], self.data_train[self.target])
ranks = pd.Series(rfe.ranking_, index=self.predictors)
selected = ranks.loc[rfe.support_]
if inplace:
self.set_predictors(selected.index.tolist())
return selected
#Performs similar function as RFE but with CV. It removed features similar to RFE but the importance of the group of features is based on the cross-validation score. The set of features with highest cross validation scores is then chosen. The difference from RFE is that the #features is not an input but selected by algo
def RecursiveFeatureEliminationCV(self, step=1, inplace=False):
rfecv = RFECV(self.alg, step=step,cv=self.cv_folds,scoring=self.scoring_metric)
rfecv.fit(self.data_train[self.predictors], self.data_train[self.target])
min_nfeat = len(self.predictors) - step*(len(rfecv.grid_scores_)-1) # n - step*(number of iter - 1)
plt.xlabel("Number of features selected")
plt.ylabel("Cross validation score (nb of correct classifications)")
plt.plot(range(min_nfeat, len(self.predictors) + 1,step), rfecv.grid_scores_)
plt.show(block=False)
ranks = pd.Series(rfecv.ranking_, index=self.predictors)
selected = ranks.loc[rfecv.support_]
if inplace:
self.set_predictors(selected.index.tolist())
return ranks
#Perform Grid-Search with CV:
def GridSearch(self, param_grid, n_jobs=1,iid=True, cv=None):
self.gridsearch_class = GridSearchCV(self.alg, param_grid=param_grid, scoring=self.scoring_metric, n_jobs=n_jobs, iid=iid, cv=cv)
self.gridsearch_class.fit(self.data_train[self.predictors], self.data_train[self.target])
print 'Grid Search Results:'
self.gridsearch_result = pd.DataFrame()
for key in param_grid.keys():
self.gridsearch_result[key] = [ x[0][key] for x in self.gridsearch_class.grid_scores_]
self.gridsearch_result['meanCV'] = [x[1] for x in self.gridsearch_class.grid_scores_]
self.gridsearch_result['stdCV'] = [np.std(x[2]) for x in self.gridsearch_class.grid_scores_]
print self.gridsearch_result
print '\nBest Parameters: ', self.gridsearch_class.best_params_
print '\nBest Score: ', self.gridsearch_class.best_score_
# return self.gridsearch_class
# Determine key metrics to analyze the classification model. These are stored in the classification_output series object belonginf to this class.
def calc_model_characteristics(self, performCV=True):
self.classification_output['Accuracy'] = metrics.accuracy_score(self.data_train[self.target],self.train_predictions)
#define scoring metric:
if self.scoring_metric == 'roc_auc':
self.classification_output['ScoringMetric'] = metrics.roc_auc_score(self.data_train[self.target],self.train_pred_prob[:,1])
elif self.scoring_metric == 'log_loss':
self.classification_output['ScoringMetric'] = metrics.log_loss(self.data_train[self.target],self.train_pred_prob)
if performCV:
cv_score= self.KFold_CrossValidation(scoring_metric=self.scoring_metric)
else:
cv_score={'mean_error': 0.0, 'std_error': 0.0}
self.classification_output['CVMethod'] = 'KFold - ' + str(self.cv_folds)
self.classification_output['CVScore_mean'] = cv_score['mean_error']
self.classification_output['CVScore_std'] = cv_score['std_error']
if self.num_target_class < 3:
# print self.data_train[self.target].shape
# print self.train_pred_prob.shape
self.classification_output['AUC'] = metrics.roc_auc_score(self.data_train[self.target],self.train_pred_prob[:,1])
else:
self.classification_output['AUC'] = np.nan
self.classification_output['ConfusionMatrix'] = pd.crosstab(self.data_train[self.target], self.train_predictions).to_string()
self.classification_output['Predictors'] = str(self.predictors)
# Print the metric determined in the previous function.
def printReport(self):
print "\nModel Report"
print "Confusion Matrix:"
print pd.crosstab(self.data_train[self.target], self.train_predictions)
print 'Note: rows - actual; col - predicted'
# print "\nClassification Report:"
# print metrics.classification_report(y_true=self.data_train[self.target], y_pred=self.train_predictions)
print "Train (Accuracy) : %s" % "{0:.3%}".format(self.classification_output['Accuracy'])
if self.scoring_metric!='accuracy':
print "Train (%s) : %f" % (self.scoring_metric,self.classification_output['ScoringMetric'])
print "AUC : %s" % "{0:.3%}".format(self.classification_output['AUC'])
print "CV Score (Specified Metric) : Mean - %f | Std - %f" % (self.classification_output['CVScore_mean'],self.classification_output['CVScore_std'])
# create submission file with the absolute prediction
def submission(self, IDcol, filename="Submission.csv"):
submission = pd.DataFrame({ x: self.data_test[x] for x in list(IDcol)})
submission[self.target] = self.test_predictions.astype(int)
submission.to_csv(filename, index=False)
# create submission file with the predicted probabilities
def submission_proba(self, IDcol, proba_colnames,filename="Submission.csv"):
submission = pd.DataFrame({ x: self.data_test[x] for x in list(IDcol)})
if len(list(proba_colnames))>1:
for i in range(len(proba_colnames)):
submission[proba_colnames[i]] = self.test_pred_prob[:,i]
else:
submission[list(proba_colnames)[0]] = self.test_pred_prob[:,1]
submission.to_csv(filename, index=False)
#checks whether the ensemble directory exists and creates one if it doesn't
def create_ensemble_dir(self):
ensdir = os.path.join(os.getcwd(), 'ensemble')
if not os.path.isdir(ensdir):
os.mkdir(ensdir)
#######################################################################################################################
##### LOGISTIC REGRESSION
#######################################################################################################################
class Logistic_Regression(GenericModelClass):
def __init__(self,data_train, data_test, target, predictors=[],cv_folds=10,scoring_metric='accuracy'):
GenericModelClass.__init__(self, alg=LogisticRegression(), data_train=data_train, data_test=data_test, target=target, predictors=predictors,cv_folds=cv_folds,scoring_metric=scoring_metric)
self.default_parameters = {'C':1.0, 'tol':0.0001, 'solver':'liblinear','multi_class':'ovr','class_weight':'balanced'}
self.model_output=pd.Series(self.default_parameters)
self.model_output['Coefficients'] = "-"
#Set parameters to default values:
self.set_parameters(set_default=True)
# Set the parameters of the model.
# Note:
# > only the parameters to be updated are required to be passed
# > if set_default is True, the passed parameters are ignored and default parameters are set which are defined in scikit learn module
def set_parameters(self, param=None, set_default=False):
if set_default:
param = self.default_parameters
if 'C' in param:
self.alg.set_params(C=param['C'])
self.model_output['C'] = param['C']
if 'tol' in param:
self.alg.set_params(tol=param['tol'])
self.model_output['tol'] = param['tol']
if 'solver' in param:
self.alg.set_params(solver=param['solver'])
self.model_output['solver'] = param['solver']
if 'multi_class' in param:
self.alg.set_params(multi_class=param['multi_class'])
self.model_output['multi_class'] = param['multi_class']
if 'class_weight' in param:
self.alg.set_params(class_weight=param['class_weight'])
self.model_output['class_weight'] = param['class_weight']
if 'cv_folds' in param:
self.cv_folds = param['cv_folds']
#Fit the model using predictors and parameters specified before.
# Inputs:
# printCV - if True, CV is performed
def modelfit(self, performCV=True):
#Outpute the parameters for the model for cross-checking:
print 'Model being built with the following parameters:'
print self.alg.get_params()
self.alg.fit(self.data_train[self.predictors], self.data_train[self.target])
if self.num_target_class==2:
coeff = pd.Series(np.concatenate((self.alg.intercept_,self.alg.coef_)), index=["Intercept"]+self.predictors)
else:
cols = ['coef_class_%d'%i for i in range(0,self.num_target_class)]
coeff = pd.DataFrame(self.alg.coef_.T, columns=cols,index=self.predictors)
print 'Coefficients: '
print coeff
self.model_output['Coefficients'] = coeff.to_string()
#Get train predictions:
self.train_predictions = self.alg.predict(self.data_train[self.predictors])
self.train_pred_prob = self.alg.predict_proba(self.data_train[self.predictors])
#Get test predictions:
self.test_predictions = self.alg.predict(self.data_test[self.predictors])
self.test_pred_prob = self.alg.predict_proba(self.data_test[self.predictors])
self.calc_model_characteristics(performCV)
self.printReport()
#Export the model into the model file as well as create a submission with model index. This will be used for creating an ensemble.
def export_model(self, IDcol):
self.create_ensemble_dir()
filename = os.path.join(os.getcwd(),'ensemble/logreg_models.csv')
comb_series = self.classification_output.append(self.model_output, verify_integrity=True)
if os.path.exists(filename):
models = pd.read_csv(filename)
mID = int(max(models['ModelID'])+1)
else:
mID = 1
models = pd.DataFrame(columns=comb_series.index)
comb_series['ModelID'] = mID
models = models.append(comb_series, ignore_index=True)
models.to_csv(filename, index=False, float_format="%.5f")
model_filename = os.path.join(os.getcwd(),'ensemble/logreg_'+str(mID)+'.csv')
self.submission(IDcol, model_filename)
#######################################################################################################################
##### DECISION TREE
#######################################################################################################################
class Decision_Tree_Class(GenericModelClass):
def __init__(self,data_train, data_test, target, predictors=[],cv_folds=10,scoring_metric='accuracy'):
GenericModelClass.__init__(self, alg=DecisionTreeClassifier(), data_train=data_train,
data_test=data_test, target=target, predictors=predictors,cv_folds=cv_folds,scoring_metric=scoring_metric)
self.default_parameters = {'criterion':'gini', 'max_depth':None,
'min_samples_split':2, 'min_samples_leaf':1,
'max_features':None, 'random_state':None, 'max_leaf_nodes':None, 'class_weight':'balanced'}
self.model_output = pd.Series(self.default_parameters)
self.model_output['Feature_Importance'] = "-"
#Set parameters to default values:
self.set_parameters(set_default=True)
# Set the parameters of the model.
# Note:
# > only the parameters to be updated are required to be passed
# > if set_default is True, the passed parameters are ignored and default parameters are set which are defined in scikit learn module
def set_parameters(self, param=None, set_default=False):
#Set param to default values if default set
if set_default:
param = self.default_parameters
if 'criterion' in param:
self.alg.set_params(criterion=param['criterion'])
self.model_output['criterion'] = param['criterion']
if 'max_depth' in param:
self.alg.set_params(max_depth=param['max_depth'])
self.model_output['max_depth'] = param['max_depth']
if 'min_samples_split' in param:
self.alg.set_params(min_samples_split=param['min_samples_split'])
self.model_output['min_samples_split'] = param['min_samples_split']
if 'min_samples_leaf' in param:
self.alg.set_params(min_samples_leaf=param['min_samples_leaf'])
self.model_output['min_samples_leaf'] = param['min_samples_leaf']
if 'max_features' in param:
self.alg.set_params(max_features=param['max_features'])
self.model_output['max_features'] = param['max_features']
if 'random_state' in param:
self.alg.set_params(random_state=param['random_state'])
self.model_output['random_state'] = param['random_state']
if 'max_leaf_nodes' in param:
self.alg.set_params(max_leaf_nodes=param['max_leaf_nodes'])
self.model_output['max_leaf_nodes'] = param['max_leaf_nodes']
if 'class_weight' in param:
self.alg.set_params(class_weight=param['class_weight'])
self.model_output['class_weight'] = param['class_weight']
if 'cv_folds' in param:
self.cv_folds = param['cv_folds']
#Fit the model using predictors and parameters specified before.
# Inputs:
# printCV - if True, CV is performed
def modelfit(self, performCV=True):
#Outpute the parameters for the model for cross-checking:
print 'Model being built with the following parameters:'
print self.alg.get_params()
self.alg.fit(self.data_train[self.predictors], self.data_train[self.target])
# print Feature Importance Scores table
self.feature_imp = pd.Series(self.alg.feature_importances_, index=self.predictors).sort_values(ascending=False)
self.feature_imp.plot(kind='bar', title='Feature Importances')
plt.ylabel('Feature Importance Score')
plt.show(block=False)
self.model_output['Feature_Importance'] = self.feature_imp.to_string()
#Get train predictions:
self.train_predictions = self.alg.predict(self.data_train[self.predictors])
self.train_pred_prob = self.alg.predict_proba(self.data_train[self.predictors])
#Get test predictions:
self.test_predictions = self.alg.predict(self.data_test[self.predictors])
self.test_pred_prob = self.alg.predict_proba(self.data_test[self.predictors])
self.calc_model_characteristics(performCV)
self.printReport()
#Print the tree in visual format
# Inputs:
# export_pdf - if True, a pdf will be exported with the filename as specified in pdf_name argument
# pdf_name - name of the pdf file if export_pdf is True
def printTree(self, export_pdf=True, file_name="Decision_Tree.pdf"):
dot_data = StringIO()
export_graphviz(self.alg, out_file=dot_data, feature_names=self.predictors,
filled=True, rounded=True, special_characters=True)
export_graphviz(self.alg, out_file='data.dot', feature_names=self.predictors,
filled=True, rounded=True, special_characters=True)
graph = pydot.graph_from_dot_data(dot_data.getvalue())
if export_pdf:
graph.write_pdf(file_name)
return graph
#Export the model into the model file as well as create a submission with model index. This will be used for creating an ensemble.
def export_model(self, IDcol):
self.create_ensemble_dir()
filename = os.path.join(os.getcwd(),'ensemble/dectree_models.csv')
comb_series = self.classification_output.append(self.model_output, verify_integrity=True)
if os.path.exists(filename):
models = pd.read_csv(filename)
mID = int(max(models['ModelID'])+1)
else:
mID = 1
models = pd.DataFrame(columns=comb_series.index)
comb_series['ModelID'] = mID
models = models.append(comb_series, ignore_index=True)
models.to_csv(filename, index=False, float_format="%.5f")
model_filename = os.path.join(os.getcwd(),'ensemble/dectree_'+str(mID)+'.csv')
self.submission(IDcol, model_filename)
#######################################################################################################################
##### RANDOM FOREST
#######################################################################################################################
class Random_Forest_Class(GenericModelClass):
def __init__(self,data_train, data_test, target, predictors=[],cv_folds=10,scoring_metric='accuracy'):
GenericModelClass.__init__(self, alg=RandomForestClassifier(), data_train=data_train,
data_test=data_test, target=target, predictors=predictors,cv_folds=cv_folds,scoring_metric=scoring_metric)
self.default_parameters = {
'n_estimators':10, 'criterion':'gini', 'max_depth':None,' min_samples_split':2,
'min_samples_leaf':1, 'max_features':'auto', 'max_leaf_nodes':None,
'oob_score':False, 'random_state':None, 'class_weight':'balanced', 'n_jobs':1
}
self.model_output = pd.Series(self.default_parameters)
self.model_output['Feature_Importance'] = "-"
self.model_output['OOB_Score'] = "-"
#Set parameters to default values:
self.set_parameters(set_default=True)
# Set the parameters of the model.
# Note:
# > only the parameters to be updated are required to be passed
# > if set_default is True, the passed parameters are ignored and default parameters are set which are defined in scikit learn module
def set_parameters(self, param=None, set_default=False):
#Set param to default values if default set
if set_default:
param = self.default_parameters
#trees in forest:
if 'n_estimators' in param:
self.alg.set_params(n_estimators=param['n_estimators'])
self.model_output['n_estimators'] = param['n_estimators']
#decision tree split criteria
if 'criterion' in param:
self.alg.set_params(criterion=param['criterion'])
self.model_output['criterion'] = param['criterion']
#maximum depth of each tree (ignored if max_leaf_nodes is not None)
if 'max_depth' in param:
self.alg.set_params(max_depth=param['max_depth'])
self.model_output['max_depth'] = param['max_depth']
#min #samples required to split an internal node; typically around 20-50
if 'min_samples_split' in param:
self.alg.set_params(min_samples_split=param['min_samples_split'])
self.model_output['min_samples_split'] = param['min_samples_split']
#The minimum number of samples in newly created leaves.
if 'min_samples_leaf' in param:
self.alg.set_params(min_samples_leaf=param['min_samples_leaf'])
self.model_output['min_samples_leaf'] = param['min_samples_leaf']
#max features to be considered for each split
if 'max_features' in param:
self.alg.set_params(max_features=param['max_features'])
self.model_output['max_features'] = param['max_features']
#for replication of results
if 'random_state' in param:
self.alg.set_params(random_state=param['random_state'])
self.model_output['random_state'] = param['random_state']
#to research
if 'max_leaf_nodes' in param:
self.alg.set_params(max_leaf_nodes=param['max_leaf_nodes'])
self.model_output['max_leaf_nodes'] = param['max_leaf_nodes']
#whether to use Out of Bag samples for calculate generalization error
if 'oob_score' in param:
self.alg.set_params(oob_score=param['oob_score'])
self.model_output['oob_score'] = param['oob_score']
if 'class_weight' in param:
self.alg.set_params(class_weight=param['class_weight'])
self.model_output['class_weight'] = param['class_weight']
if 'n_jobs' in param:
self.alg.set_params(n_jobs=param['n_jobs'])
self.model_output['n_jobs'] = param['n_jobs']
#cross validation folds
if 'cv_folds' in param:
self.cv_folds = param['cv_folds']
#Fit the model using predictors and parameters specified before.
# Inputs:
# printCV - if True, CV is performed
def modelfit(self, performCV=True, printTopN='all'):
#Outpute the parameters for the model for cross-checking:
print 'Model being built with the following parameters:'
print self.alg.get_params()
self.alg.fit(self.data_train[self.predictors], self.data_train[self.target])
# print Feature Importance Scores table
self.feature_imp = pd.Series(self.alg.feature_importances_, index=self.predictors).sort_values(ascending=False)
num_print = len(self.feature_imp)
if printTopN != 'all':
num_print = min(printTopN,len(self.feature_imp))
self.feature_imp.iloc[:num_print-1].plot(kind='bar', title='Feature Importances')
plt.ylabel('Feature Importance Score')
plt.show(block=False)
self.model_output['Feature_Importance'] = self.feature_imp.to_string()
if self.model_output['oob_score']:
print 'OOB Score : %f' % self.alg.oob_score_
self.model_output['OOB_Score'] = self.alg.oob_score_
#Get train predictions:
self.train_predictions = self.alg.predict(self.data_train[self.predictors])
self.train_pred_prob = self.alg.predict_proba(self.data_train[self.predictors])
#Get test predictions:
self.test_predictions = self.alg.predict(self.data_test[self.predictors])
self.test_pred_prob = self.alg.predict_proba(self.data_test[self.predictors])
self.calc_model_characteristics(performCV)
self.printReport()
#Export the model into the model file as well as create a submission with model index. This will be used for creating an ensemble.
def export_model(self, IDcol):
self.create_ensemble_dir()
filename = os.path.join(os.getcwd(),'ensemble/rf_models.csv')
comb_series = self.classification_output.append(self.model_output, verify_integrity=True)
if os.path.exists(filename):
models = pd.read_csv(filename)
mID = int(max(models['ModelID'])+1)
else:
mID = 1
models = pd.DataFrame(columns=comb_series.index)
comb_series['ModelID'] = mID
models = models.append(comb_series, ignore_index=True)
models.to_csv(filename, index=False, float_format="%.5f")
model_filename = os.path.join(os.getcwd(),'ensemble/rf_'+str(mID)+'.csv')
self.submission(IDcol, model_filename)
#######################################################################################################################
##### EXTRA TREES FOREST
#######################################################################################################################
class ExtraTrees_Class(GenericModelClass):
def __init__(self,data_train, data_test, target, predictors=[],cv_folds=10,scoring_metric='accuracy'):
GenericModelClass.__init__(self, alg=ExtraTreesClassifier(), data_train=data_train,
data_test=data_test, target=target, predictors=predictors,cv_folds=cv_folds,scoring_metric=scoring_metric)
self.default_parameters = {
'n_estimators':10, 'criterion':'gini', 'max_depth':None,' min_samples_split':2,
'min_samples_leaf':1, 'max_features':'auto', 'max_leaf_nodes':None,
'oob_score':False, 'random_state':None, 'class_weight':'balanced', 'n_jobs':1
}
self.model_output = pd.Series(self.default_parameters)
self.model_output['Feature_Importance'] = "-"
self.model_output['OOB_Score'] = "-"
#Set parameters to default values:
self.set_parameters(set_default=True)
# Set the parameters of the model.
# Note:
# > only the parameters to be updated are required to be passed
# > if set_default is True, the passed parameters are ignored and default parameters are set which are defined in scikit learn module
def set_parameters(self, param=None, set_default=False):
#Set param to default values if default set
if set_default:
param = self.default_parameters
#trees in forest:
if 'n_estimators' in param:
self.alg.set_params(n_estimators=param['n_estimators'])
self.model_output['n_estimators'] = param['n_estimators']
#decision tree split criteria
if 'criterion' in param:
self.alg.set_params(criterion=param['criterion'])
self.model_output['criterion'] = param['criterion']
#maximum depth of each tree (ignored if max_leaf_nodes is not None)
if 'max_depth' in param:
self.alg.set_params(max_depth=param['max_depth'])
self.model_output['max_depth'] = param['max_depth']
#min #samples required to split an internal node; typically around 20-50
if 'min_samples_split' in param:
self.alg.set_params(min_samples_split=param['min_samples_split'])
self.model_output['min_samples_split'] = param['min_samples_split']
#The minimum number of samples in newly created leaves.
if 'min_samples_leaf' in param:
self.alg.set_params(min_samples_leaf=param['min_samples_leaf'])
self.model_output['min_samples_leaf'] = param['min_samples_leaf']
#max features to be considered for each split
if 'max_features' in param:
self.alg.set_params(max_features=param['max_features'])
self.model_output['max_features'] = param['max_features']
#for replication of results
if 'random_state' in param:
self.alg.set_params(random_state=param['random_state'])
self.model_output['random_state'] = param['random_state']
#to research
if 'max_leaf_nodes' in param:
self.alg.set_params(max_leaf_nodes=param['max_leaf_nodes'])
self.model_output['max_leaf_nodes'] = param['max_leaf_nodes']
#whether to use Out of Bag samples for calculate generalization error
if 'oob_score' in param:
self.alg.set_params(oob_score=param['oob_score'])
self.model_output['oob_score'] = param['oob_score']
if 'class_weight' in param:
self.alg.set_params(class_weight=param['class_weight'])
self.model_output['class_weight'] = param['class_weight']
if 'n_jobs' in param:
self.alg.set_params(n_jobs=param['n_jobs'])
self.model_output['n_jobs'] = param['n_jobs']
#cross validation folds
if 'cv_folds' in param:
self.cv_folds = param['cv_folds']
#Fit the model using predictors and parameters specified before.
# Inputs:
# printCV - if True, CV is performed
def modelfit(self, performCV=True, printTopN='all'):
#Outpute the parameters for the model for cross-checking:
print 'Model being built with the following parameters:'
print self.alg.get_params()
self.alg.fit(self.data_train[self.predictors], self.data_train[self.target])
# print Feature Importance Scores table
self.feature_imp = pd.Series(self.alg.feature_importances_, index=self.predictors).sort_values(ascending=False)
num_print = len(self.feature_imp)
if printTopN != 'all':
num_print = min(printTopN,len(self.feature_imp))
self.feature_imp.iloc[:num_print-1].plot(kind='bar', title='Feature Importances')
plt.ylabel('Feature Importance Score')
plt.show(block=False)
self.model_output['Feature_Importance'] = self.feature_imp.to_string()
if self.model_output['oob_score']:
print 'OOB Score : %f' % self.alg.oob_score_
self.model_output['OOB_Score'] = self.alg.oob_score_
#Get train predictions:
self.train_predictions = self.alg.predict(self.data_train[self.predictors])
self.train_pred_prob = self.alg.predict_proba(self.data_train[self.predictors])
#Get test predictions:
self.test_predictions = self.alg.predict(self.data_test[self.predictors])
self.test_pred_prob = self.alg.predict_proba(self.data_test[self.predictors])
self.calc_model_characteristics(performCV)
self.printReport()
#Export the model into the model file as well as create a submission with model index. This will be used for creating an ensemble.
def export_model(self, IDcol):
self.create_ensemble_dir()
filename = os.path.join(os.getcwd(),'ensemble/extree_models.csv')
comb_series = self.classification_output.append(self.model_output, verify_integrity=True)
if os.path.exists(filename):
models = pd.read_csv(filename)
mID = int(max(models['ModelID'])+1)
else:
mID = 1
models = pd.DataFrame(columns=comb_series.index)
comb_series['ModelID'] = mID
models = models.append(comb_series, ignore_index=True)
models.to_csv(filename, index=False, float_format="%.5f")
model_filename = os.path.join(os.getcwd(),'ensemble/extree_'+str(mID)+'.csv')
self.submission(IDcol, model_filename)
#######################################################################################################################
##### ADABOOST CLASSIFICATION
#######################################################################################################################
class AdaBoost_Class(GenericModelClass):
def __init__(self,data_train, data_test, target, predictors=[],cv_folds=10,scoring_metric='accuracy'):
GenericModelClass.__init__(self, alg=AdaBoostClassifier(), data_train=data_train,
data_test=data_test, target=target, predictors=predictors,cv_folds=cv_folds,scoring_metric=scoring_metric)
self.default_parameters = { 'n_estimators':50, 'learning_rate':1.0 }
self.model_output = pd.Series(self.default_parameters)
self.model_output['Feature_Importance'] = "-"
#Set parameters to default values:
self.set_parameters(set_default=True)
# Set the parameters of the model.
# Note:
# > only the parameters to be updated are required to be passed
# > if set_default is True, the passed parameters are ignored and default parameters are set which are defined in scikit learn module
def set_parameters(self, param=None, set_default=False):
#Set param to default values if default set
if set_default:
param = self.default_parameters
#trees in forest:
if 'n_estimators' in param:
self.alg.set_params(n_estimators=param['n_estimators'])
self.model_output['n_estimators'] = param['n_estimators']
#decision tree split criteria
if 'learning_rate' in param:
self.alg.set_params(learning_rate=param['learning_rate'])
self.model_output['learning_rate'] = param['learning_rate']
if 'cv_folds' in param:
self.cv_folds = param['cv_folds']
#Fit the model using predictors and parameters specified before.
# Inputs:
# printCV - if True, CV is performed
def modelfit(self, performCV=True):
#Outpute the parameters for the model for cross-checking:
print 'Model being built with the following parameters:'
print self.alg.get_params()
self.alg.fit(self.data_train[self.predictors], self.data_train[self.target])
# print Feature Importance Scores table
self.feature_imp = pd.Series(self.alg.feature_importances_, index=self.predictors).sort_values(ascending=False)
self.feature_imp.plot(kind='bar', title='Feature Importances')
plt.ylabel('Feature Importance Score')
plt.show(block=False)
self.model_output['Feature_Importance'] = self.feature_imp.to_string()
plt.xlabel("AdaBoost Estimator")
plt.ylabel("Estimator Error")
plt.plot(range(1, self.model_output['n_estimators']+1), self.alg.estimator_errors_)
plt.plot(range(1, self.model_output['n_estimators']+1), self.alg.estimator_weights_)
plt.legend(['estimator_errors','estimator_weights'], loc='upper left')
plt.show(block=False)
#Get train predictions:
self.train_predictions = self.alg.predict(self.data_train[self.predictors])
self.train_pred_prob = self.alg.predict_proba(self.data_train[self.predictors])
#Get test predictions:
self.test_predictions = self.alg.predict(self.data_test[self.predictors])
self.test_pred_prob = self.alg.predict_proba(self.data_test[self.predictors])
self.calc_model_characteristics(performCVl)
self.printReport()
#Export the model into the model file as well as create a submission with model index. This will be used for creating an ensemble.
def export_model(self, IDcol):
self.create_ensemble_dir()
filename = os.path.join(os.getcwd(),'ensemble/adaboost_models.csv')
comb_series = self.classification_output.append(self.model_output, verify_integrity=True)
if os.path.exists(filename):
models = pd.read_csv(filename)
mID = int(max(models['ModelID'])+1)
else:
mID = 1
models = pd.DataFrame(columns=comb_series.index)
comb_series['ModelID'] = mID
models = models.append(comb_series, ignore_index=True)
models.to_csv(filename, index=False, float_format="%.5f")
model_filename = os.path.join(os.getcwd(),'ensemble/adaboost_'+str(mID)+'.csv')
self.submission(IDcol, model_filename)
#######################################################################################################################
##### GRADIENT BOOSTING MACHINE
#######################################################################################################################
class GradientBoosting_Class(GenericModelClass):
def __init__(self,data_train, data_test, target, predictors=[],cv_folds=10,scoring_metric='accuracy'):
GenericModelClass.__init__(self, alg=GradientBoostingClassifier(), data_train=data_train,
data_test=data_test, target=target, predictors=predictors,cv_folds=cv_folds,scoring_metric=scoring_metric)
self.default_parameters = {
'loss':'deviance', 'learning_rate':0.1, 'n_estimators':100, 'subsample':1.0, 'min_samples_split':2, 'min_samples_leaf':1,
'max_depth':3, 'init':None, 'random_state':None, 'max_features':None, 'verbose':0,
'max_leaf_nodes':None, 'warm_start':False, 'presort':'auto'
}
self.model_output = pd.Series(self.default_parameters)
self.model_output['Feature_Importance'] = "-"
#Set parameters to default values:
self.set_parameters(set_default=True)
# Set the parameters of the model.
# Note:
# > only the parameters to be updated are required to be passed
# > if set_default is True, the passed parameters are ignored and default parameters are set which are defined in scikit learn module
def set_parameters(self, param=None, set_default=False):
#Set param to default values if default set
if set_default:
param = self.default_parameters
#Loss function to be used - deviance or exponential
if 'loss' in param:
self.alg.set_params(loss=param['loss'])
self.model_output['loss'] = param['loss']
if 'learning_rate' in param:
self.alg.set_params(learning_rate=param['learning_rate'])
self.model_output['learning_rate'] = param['learning_rate']
#trees in forest:
if 'n_estimators' in param:
self.alg.set_params(n_estimators=param['n_estimators'])
self.model_output['n_estimators'] = param['n_estimators']
if 'subsample' in param:
self.alg.set_params(subsample=param['subsample'])
self.model_output['subsample'] = param['subsample']
#maximum depth of each tree (ignored if max_leaf_nodes is not None)
if 'max_depth' in param:
self.alg.set_params(max_depth=param['max_depth'])
self.model_output['max_depth'] = param['max_depth']
#min #samples required to split an internal node; typically around 20-50
if 'min_samples_split' in param:
self.alg.set_params(min_samples_split=param['min_samples_split'])
self.model_output['min_samples_split'] = param['min_samples_split']
#The minimum number of samples in newly created leaves.
if 'min_samples_leaf' in param:
self.alg.set_params(min_samples_leaf=param['min_samples_leaf'])
self.model_output['min_samples_leaf'] = param['min_samples_leaf']
#max features to be considered for each split
if 'max_features' in param:
self.alg.set_params(max_features=param['max_features'])
self.model_output['max_features'] = param['max_features']
#for replication of results
if 'random_state' in param:
self.alg.set_params(random_state=param['random_state'])
self.model_output['random_state'] = param['random_state']
#to research
if 'max_leaf_nodes' in param:
self.alg.set_params(max_leaf_nodes=param['max_leaf_nodes'])
self.model_output['max_leaf_nodes'] = param['max_leaf_nodes']
#whether to use Out of Bag samples for calculate generalization error
if 'presort' in param:
self.alg.set_params(presort=param['presort'])
self.model_output['presort'] = param['presort']
if 'verbost' in param:
self.alg.set_params(verbose=param['verbose'])
self.model_output['verbose'] = param['verbose']
if 'warm_start' in param:
self.alg.set_params(warm_start=param['warm_start'])
self.model_output['warm_start'] = param['warm_start']
#cross validation folds
if 'cv_folds' in param:
self.cv_folds = param['cv_folds']
#Fit the model using predictors and parameters specified before.
# Inputs:
# printCV - if True, CV is performed
def modelfit(self, performCV=True):
#Outpute the parameters for the model for cross-checking:
print 'Model being built with the following parameters:'
print self.alg.get_params()
self.alg.fit(self.data_train[self.predictors], self.data_train[self.target])
# print Feature Importance Scores table
self.feature_imp = pd.Series(self.alg.feature_importances_, index=self.predictors).sort_values(ascending=False)
self.feature_imp.plot(kind='bar', title='Feature Importances')
plt.ylabel('Feature Importance Score')
plt.show(block=False)
self.model_output['Feature_Importance'] = self.feature_imp.to_string()
#Plot OOB estimates if subsample <1:
if self.model_output['subsample']<1:
plt.xlabel("GBM Iteration")
plt.ylabel("Score")
plt.plot(range(1, self.model_output['n_estimators']+1), self.alg.oob_improvement_)
# plt.plot(range(1, self.model_output['n_estimators']+1), self.alg.train_score_)
plt.legend(['oob_improvement_','train_score_'], loc='upper left')
plt.show(block=False)
#Get train predictions:
self.train_predictions = self.alg.predict(self.data_train[self.predictors])
self.train_pred_prob = self.alg.predict_proba(self.data_train[self.predictors])
#Get test predictions:
self.test_predictions = self.alg.predict(self.data_test[self.predictors])
self.test_pred_prob = self.alg.predict_proba(self.data_test[self.predictors])
self.calc_model_characteristics(performCV)
self.printReport()
#Export the model into the model file as well as create a submission with model index. This will be used for creating an ensemble.
def export_model(self, IDcol):
self.create_ensemble_dir()
filename = os.path.join(os.getcwd(),'ensemble/gbm_models.csv')
comb_series = self.classification_output.append(self.model_output, verify_integrity=True)
if os.path.exists(filename):
models = pd.read_csv(filename)
mID = int(max(models['ModelID'])+1)
else:
mID = 1
models = pd.DataFrame(columns=comb_series.index)
comb_series['ModelID'] = mID
models = models.append(comb_series, ignore_index=True)
models.to_csv(filename, index=False, float_format="%.5f")
model_filename = os.path.join(os.getcwd(),'ensemble/gbm_'+str(mID)+'.csv')
self.submission(IDcol, model_filename)
#######################################################################################################################
##### XGBOOST ALGORITHM
#######################################################################################################################
#Define the class similar to the overall classification class
class XGBoost_Class(GenericModelClass):
def __init__(self,data_train, data_test, target, predictors, cv_folds=10,scoring_metric_skl='accuracy', scoring_metric_xgb='error'):
GenericModelClass.__init__(self, alg=XGBClassifier(), data_train=data_train,
data_test=data_test, target=target, predictors=predictors,cv_folds=cv_folds,scoring_metric=scoring_metric_skl)
#Define default parameters on your own:
self.default_parameters = {
'max_depth':3, 'learning_rate':0.1,