-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAuto_ViML.py
3196 lines (3162 loc) · 184 KB
/
Auto_ViML.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
##############################################################################
#Copyright 2019 Google LLC
#
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.
#########################################################################################################
#### Automatically Build Variant Interpretable Machine Learning Models (Auto_ViML) ######
#### Developed by Ramadurai Seshadri ######
###### Version 0.57 #########
##### Fixed rare_class finding and ROC charts, added one more target encoding Dated: July 25, 2019 ####
#########################################################################################################
import pandas as pd
import numpy as np
import time
import math
from sklearn import model_selection
from sklearn.linear_model import LogisticRegression, LogisticRegressionCV
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.model_selection import KFold, train_test_split, GridSearchCV
from sklearn.metrics import confusion_matrix, mean_squared_error
from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier
from sklearn.ensemble import ExtraTreesClassifier, ExtraTreesRegressor
from collections import OrderedDict
import warnings
warnings.filterwarnings("ignore")
from sklearn.exceptions import DataConversionWarning
warnings.filterwarnings(action='ignore', category=DataConversionWarning)
from sklearn import metrics
import xgboost as xgb
from xgboost.sklearn import XGBClassifier
from xgboost.sklearn import XGBRegressor
from sklearn.multiclass import OneVsRestClassifier
from sklearn.linear_model import LinearRegression, Lasso, Ridge, LassoCV
from sklearn import model_selection, metrics #Additional sklearn functions
from sklearn.model_selection import GridSearchCV #Performing grid search
from sklearn.model_selection import train_test_split, KFold
from sklearn.model_selection import cross_val_predict
from sklearn.model_selection import cross_val_score, StratifiedShuffleSplit, TimeSeriesSplit
from sklearn.metrics import accuracy_score,f1_score,roc_auc_score,log_loss
import matplotlib.pylab as plt
get_ipython().magic(u'matplotlib inline')
from matplotlib.pylab import rcParams
rcParams['figure.figsize'] = 10, 6
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import KFold,ShuffleSplit
from sklearn.metrics import classification_report, confusion_matrix
import pdb
from functools import reduce
from collections import defaultdict
from sklearn.preprocessing import MinMaxScaler, StandardScaler,LabelEncoder,MaxAbsScaler
from sklearn.multioutput import MultiOutputClassifier, MultiOutputRegressor
import copy
from sklearn.metrics import precision_recall_curve
from sklearn.model_selection import cross_val_score, StratifiedKFold, KFold
from sklearn.metrics import make_scorer
from sklearn.metrics import accuracy_score
from sklearn.metrics import average_precision_score
from sklearn.metrics import f1_score
from sklearn.metrics import log_loss
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import roc_auc_score
from collections import Counter
from Transform_KM_Features import Transform_KM_Features
from sklearn.model_selection import RandomizedSearchCV
from custom_scores import accu, rmse, gini, gini_sklearn, gini_meae
from custom_scores import gini_msle, gini_mae, gini_mse, gini_rmse
from custom_scores import gini_accuracy, gini_bal_accuracy, gini_roc
from custom_scores import gini_precision, gini_average_precision, gini_weighted_precision
from custom_scores import gini_macro_precision, gini_micro_precision
from custom_scores import gini_samples_precision, gini_f1, gini_weighted_f1
from custom_scores import gini_macro_f1, gini_micro_f1, gini_samples_f1
from custom_scores import gini_log_loss, gini_recall, gini_weighted_recall
from custom_scores import gini_samples_recall, gini_macro_recall, gini_micro_recall
##################################################################################
from collections import Counter
def find_rare_class(classes, verbose=0):
######### Print the % count of each class in a Target variable #####
"""
Works on Multi Class too. Prints class percentages count of target variable.
It returns the name of the Rare class (the one with the minimum class member count).
This can also be helpful in using it as pos_label in Binary and Multi Class problems.
"""
counts = OrderedDict(Counter(classes))
total = sum(counts.values())
if verbose >= 1:
print(' Class -> Counts -> Percent')
for cls in counts.keys():
print("%6s: % 7d -> % 5.1f%%" % (cls, counts[cls], counts[cls]/total*100))
if type(pd.Series(counts).idxmin())==str:
return pd.Series(counts).idxmin()
else:
return int(pd.Series(counts).idxmin())
###############################################################################
def return_factorized_dict(ls):
"""
###### Factorize any list of values in a data frame using this neat function
if your data has any NaN's it automatically marks it as -1 and returns that for NaN's
Returns a dictionary mapping previous values with new values.
"""
factos = pd.unique(pd.factorize(ls)[0])
categs = pd.unique(pd.factorize(ls)[1])
if -1 in factos:
categs = np.insert(categs,np.where(factos==-1)[0][0],np.nan)
return dict(zip(categs,factos))
#############################################################################################
def analyze_problem_type(train, targ,verbose=0):
"""
This module analyzes a Target Variable and finds out whether it is a
Regression or Classification type problem
"""
if train[targ].dtype != 'int64' and train[targ].dtype != float :
if len(train[targ].unique()) == 2:
if verbose >= 1:
print('"\n ################### Binary-Class ##################### " ')
model_class = 'Binary_Classification'
elif len(train[targ].unique()) > 1 and len(train[targ].unique()) <= 15:
model_class = 'Multi_Classification'
if verbose >= 1:
print('"\n ################### Multi-Class ######################''')
elif train[targ].dtype == 'int64' or train[targ].dtype == float :
if len(train[targ].unique()) == 2:
if verbose >= 1:
print('"\n ################### Binary-Class ##################### " ')
model_class = 'Binary_Classification'
elif len(train[targ].unique()) > 1 and len(train[targ].unique()) <= 15:
model_class = 'Multi_Classification'
if verbose >= 1:
print('"\n ################### Multi-Class ######################''')
else:
model_class = 'Regression'
if verbose >= 1:
print('"\n ################### Regression ######################''')
elif train[targ].dtype == object:
if len(train[targ].unique()) > 1 and len(train[targ].unique()) <= 2:
model_class = 'Binary_Classification'
if verbose >= 1:
print('"\n ################### Binary-Class ##################### " ')
else:
model_class = 'Multi_Classification'
if verbose >= 1:
print('"\n ################### Multi-Class ######################''')
elif train[targ].dtype == bool:
model_class = 'Binary_Classification'
if verbose >= 1:
print('"\n ################### Binary-Class ######################''')
elif train[targ].dtype == 'int64':
if len(train[targ].unique()) == 2:
if verbose >= 1:
print('"\n ################### Binary-Class ##################### " ')
model_class = 'Binary_Classification'
elif len(train[targ].unique()) > 1 and len(train[targ].unique()) <= 25:
model_class = 'Multi_Classification'
if verbose >= 1:
print('"\n ################### Multi-Class ######################''')
else:
model_class = 'Regression'
if verbose >= 1:
print('"\n ################### Regression ######################''')
else :
if verbose >= 1:
print('\n ###################### REGRESSION #####################')
model_class = 'Regression'
return model_class
#############################################################################################################
def Auto_ViML(train, target, test='',sample_submission='',hyper_param='GS',
scoring_parameter='logloss', Boosting_Flag=None, KMeans_Featurizer=False,
Add_Poly=0, Stacking_Flag=False, Binning_Flag=False,
Imbalanced_Flag=False, verbose=0):
"""
#########################################################################################################
############# This is not an Officially Supported Google Product! #########################
#########################################################################################################
#Copyright 2019 Google LLC #######
# #######
#Licensed under the Apache License, Version 2.0 (the "License"); #######
#you may not use this file except in compliance with the License. #######
#You may obtain a copy of the License at #######
# #######
# https://www.apache.org/licenses/LICENSE-2.0 #######
# #######
#Unless required by applicable law or agreed to in writing, software #######
#distributed under the License is distributed on an "AS IS" BASIS, #######
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #######
#See the License for the specific language governing permissions and #######
#limitations under the License. #######
#########################################################################################################
#### Automatically Build Variant Interpretable Machine Learning Models (Auto_ViML) ######
#### Developed by Ramadurai Seshadri ######
###### Version 0.56 #########
#########################################################################################################
#### Auto_ViML was designed for building a High Performance Interpretable Model With Fewest Vars. ###
#### The "V" in Auto_ViML stands for Variant because it tries Multiple Models and Multiple Features ###
#### to find the Best Performing Model for any data set.The "i" in Auto_ViML stands " Interpretable"###
#### since it selects the fewest Features to build a simpler, more interpretable model. This is key. ##
#### Auto_ViML is built mostly using Scikit-Learn, Numpy, Pandas and Matplotlib. Hence it should run ##
#### on any Python 2 or Python 3 Anaconda installations. You won't have to import any special ####
#### Libraries other than "SHAP" library for SHAP values which provides more interpretability. #####
#### But if you don't have it, Auto_ViML will skip it and show you the regular feature importances. ###
#########################################################################################################
#### INPUTS: ###
#########################################################################################################
#### train: could be a datapath+filename or a dataframe. It will detect which is which and load it.####
#### test: could be a datapath+filename or a dataframe. If you don't have any, just leave it as "". ###
#### submission: must be a datapath+filename. If you don't have any, just leave it as empty string.####
#### target: name of the target variable in the data set. ####
#### sep: if you have a spearator in the file such as "," or "\t" mention it here. Default is ",". ####
#### scoring_parameter: if you want your own scoring parameter such as "f1" give it here. If not, #####
#### it will assume the appropriate scoring param for the problem and it will build the model.#####
#### hyper_param: Tuning options are GridSearch ('GS') and RandomizedSearch ('RS'). Default is 'GS'.###
#### Boosting Flag: you have 3 possible choices (default is False): #####
#### None = This will build a Linear Model #####
#### False = This will build a Random Forest or Extra Trees model (also known as Bagging) #####
#### True = This will build an XGBoost model #####
#### Add_Poly: Default is 0. It has 2 additional settings: #####
#### 1 = Add interaction variables only such as x1*x2, x2*x3,...x9*10 etc. #####
#### 2 = Add Interactions and Squared variables such as x1**2, x2**2, etc. #####
#### Stacking_Flag: Default is False. If set to True, it will add an additional feature which #####
#### is derived from predictions of another model. This is used in some cases but may result#####
#### in overfitting. So be careful turning this flag "on". #####
#### Binning_Flag: Default is False. It set to True, it will convert the top numeric variables #####
#### into binned variables through a technique known as "Entropy" binning. This is very #####
#### helpful for certain datasets (especially hard to build models). #####
#### Imbalanced_Flag: Default is False. If set to True, it will downsample the "Majority Class" #####
#### in an imbalanced dataset and make the "Rare" class at least 5% of the data set. This #####
#### the ideal threshold in my mind to make a model learn. Do it for Highly Imbalanced data.#####
#### verbose: This has 3 possible states: #####
#### 0 = limited output. Great for running this silently and getting fast results. #####
#### 1 = more charts. Great for knowing how results were and making changes to flags in input. #####
#### 2 = lots of charts and output. Great for reproducing what Auto_ViML does on your own. #####
#########################################################################################################
#### OUTPUTS: #####
#########################################################################################################
#### model: It will return your trained model #####
#### features: the fewest number of features in your model to make it perform well #####
#### train_modified: this is the modified train dataframe after removing and adding features #####
#### test_modified: this is the modified test dataframe with the same transformations as train #####
################# A D D I T I O N A L N O T E S ###########
#### Finally, it writes your submission file to disk in the current directory called "mysubmission.csv"
#### This submission file is ready for you to show it clients or submit it to competitions. #####
#### If no submission file was given but as long as you give it a test file name, it will create #####
#### a submission file for you named "mySubmission.csv". #####
#### Auto_ViML works on any Multi-Class, Multi-Label Data Set. So you can have many target labels #####
#### You don't have to tell Auto_ViML whether it is a Regression or Classification problem. #####
#### Suggestions for a Scoring Metric: #####
#### If you have Binary Class and Multi-Class in a Single Label, Choose Accuracy. It will ######
#### do very well. If you want something better, try roc_auc even for Multi-Class which works. ######
#### You can try F1 or Weighted F1 if you want something complex or for Multi-Class. ######
#### Note that For Imbalanced Classes (<=5% classes), it automatically adds Class Weights. ######
#### Also, Note that it handles Multi-Label automatically so you can send Train data ######
#### with multiple Labels (Targets) and it will automatically predict for each Label. ######
#### Finally this is Meant to Be a Fast Algorithm, so use it for just quick POCs ######
#### This is Not Meant for Production Problems. It produces great models but it is not Perfect! ######
######################### HELP OTHERS! PLEASE CONTRIBUTE! OPEN A PULL REQUEST! ##########################
#########################################################################################################
"""
##### These copies are to make sure that the originals are not destroyed ####
test = copy.deepcopy(test)
orig_train = copy.deepcopy(train)
orig_test = copy.deepcopy(test)
start_train = copy.deepcopy(train)
start_test = copy.deepcopy(test)
####### These are Global Settings. If you change them here, it will ripple across the whole code ###
corr_limit = 0.70 #### This decides what the cut-off for defining highly correlated vars to remove is.
scaling = 'MinMax' ### This decides whether to use MinMax scaling or Standard Scaling ("Std").
first_flag = 0 ## This is just a setting to detect which is
seed= 99 ### this maintains repeatability of the whole ML pipeline here ###
subsample=0.5 #### Leave this low so the models generalize better. Increase it if you want overfit models
col_sub_sample = 0.5 ### Leave this low for the same reason above
poly_degree = 2 ### this create 2-degree polynomial variables in Add_Poly. Increase if you want more degrees
booster = 'gbtree' ### this is the booster for XGBoost. The other option is "Linear".
n_splits = 5 ### This controls the number of splits for Cross Validation. Increasing will take longer time.
early_stopping = 4 #### Early stopping rounds for XGBoost ######
########## This is where some more default parameters are set up ######
data_dimension = orig_train.shape[0]*orig_train.shape[1] ### number of cells in the entire data set .
if data_dimension > 1000000:
### if data dimension exceeds 1 million, then reduce no of params
no_iter=30
early_stopping = 5
test_size = 0.2
max_iter = 1000
max_estims = 350
else:
if orig_train.shape[0] <= 1000:
no_iter=20
test_size = 0.1
max_iter = 1000
max_estims = 250
else:
no_iter=30
test_size = 0.2
max_iter = 2000
max_estims = 300
early_stopping = 4
################## This is where the code begins ########################
if Boosting_Flag:
model_name = 'XGBoost'
elif Boosting_Flag is None:
model_name = 'Linear'
else:
model_name = 'Forests'
#### The warnings from Sklearn are so annoying that I have to shut it off ####
import warnings
warnings.filterwarnings("ignore")
def warn(*args, **kwargs):
pass
warnings.warn = warn
### First_Flag is merely a flag for the first time you want to set values of variables
if scaling == 'MinMax':
SS = MinMaxScaler()
elif scaling == 'Std':
SS = StandardScaler()
else:
SS = MinMaxScaler()
### Make target into a list so that we can uniformly process the target label
if not isinstance(target, list):
target = [target]
model_label = 'Single_Label'
elif len(target)==1:
model_label = 'Single_Label'
elif len(target) > 1:
model_label = 'Multi_Label'
else:
print('Target variable is neither a string or a list. Please check input and try again!')
return
##### This is where we run the Traditional models to compare them to XGB #####
start_time = time.time()
####################################################################################
##### Set up your Target Labels and Classes Properly Here #### Label Encoding #####
#### This is for Classification Problems Only where you do Label Encoding of Target
mldict = lambda: defaultdict(mldict)
label_dict = mldict()
first_time = True
print('Train (Size: %d,%d) has %s with target: %s' %(train.shape[0],train.shape[1],model_label,target))
for each_target in target:
c_params = dict()
r_params = dict()
###### Now set the Model Parameters here ####
try:
modeltype = analyze_problem_type(train, each_target,verbose)
except:
print('Cannot find Target variable in data set. Please check input and try again')
return
if modeltype == 'Regression':
scv = KFold(n_splits=n_splits, random_state=seed)
eval_metric = 'rmse'
objective = 'reg:linear'
else:
### This is for Classification Problems Only ########
print('Shuffling the data set before training')
train = train.sample(frac=1.0, random_state=seed)
scv = StratifiedKFold(n_splits=n_splits, random_state=seed, shuffle=True)
if modeltype != 'Regression':
rare_class = find_rare_class(train[each_target].values,verbose=1)
### Perfrom Label Transformation only for Classification Problems ####
classes = np.unique(orig_train[each_target])
if first_time:
print('Selecting %d-Class Classifier...' %len(classes))
if hyper_param == 'GS':
print(' Using GridSearchCV for Hyper Parameter tuning...')
else:
print(' Using RandomizedSearchCV for Hyper Parameter Tuning. This will take time...')
first_time = False
if len(classes) > 2:
##### If Boosting_Flag = True, change it to False here since Multi-Class XGB is VERY SLOW!
max_class_length = len(classes)
if Boosting_Flag:
print('CAUTION: In Multi-Class Boosting (2+ classes), TRAINING WILL TAKE A LOT OF TIME!')
objective = 'multi:softmax'
eval_metric = "mlogloss"
else:
max_class_length = 2
eval_metric="logloss"
objective = 'binary:logistic'
### Do Label Encoding when the Target Classes in each Label are Strings or Multi Class ###
if type(orig_train[each_target].values[0])==str or str(orig_train[each_target].dtype)=='category' or sorted(np.unique(orig_train[each_target].values))[0] != 0:
### if the class is a string or if it has more than 2 classes, then use Factorizer!
label_dict[each_target]['values'] = orig_train[each_target].values
#### Factorizer is the easiest way to convert target in train and predictions in test
#### This takes care of some classes that are present in train and not in predictions
### and vice versa. Hence it is better than Label Encoders which breaks when above happens.
train_targ_categs = list(pd.unique(orig_train[each_target].values))
dict_targ_all = return_factorized_dict(train_targ_categs)
start_train[each_target] = orig_train[each_target].map(dict_targ_all)
rare_class = find_rare_class(start_train[each_target].values)
label_dict[each_target]['dictionary'] = copy.deepcopy(dict_targ_all)
label_dict[each_target]['transformer'] = dict([(v,k) for (k,v) in dict_targ_all.items()])
label_dict[each_target]['classes'] = copy.deepcopy(train_targ_categs)
label_dict[each_target]['class_nums'] = list(dict_targ_all.values())
print('String or Multi Class target: %s transformed as follows: %s' %(each_target,dict_targ_all))
else:
### Since the each_target here is already numeric, you don't have to modify it
rare_class = find_rare_class(orig_train[each_target].values)
label_dict[each_target]['values'] = orig_train[each_target].values
label_dict[each_target]['classes'] = np.unique(orig_train[each_target].values)
label_dict[each_target]['class_nums'] = np.unique(orig_train[each_target].values)
label_dict[each_target]['transformer'] = ''
label_dict[each_target]['dictionary'] = {}
print(' Target %s is already numeric. No transformation done.' %each_target)
###########################################################################################
if orig_train.isnull().sum().sum() > 0:
### If there are missing values print it here ####
top5 = orig_train.isnull().sum().sort_values(ascending=False).index.tolist()[:5]
print(' Top columns in Train with missing values: %s' %(
[x for x in top5 if orig_train[x].isnull().sum()>0]))
print(' and their missing value totals: %s' %([orig_train[x].isnull().sum() for x in
top5 if orig_train[x].isnull().sum()>0]))
###########################################################################################
#### This is where we start doing the iterative hyper tuning parameters #####
params_dict = defaultdict(list)
accu_mean = []
error_rate = []
###### This is where we do the training and hyper parameter tuning ########
orig_preds = [x for x in list(orig_train) if x not in target]
count = 0
################# CLASSIFY COLUMNS HERE ######################
var_df = classify_columns(orig_train[orig_preds], verbose)
##### Classify Columns ################
id_cols = var_df['id_vars']
string_cols = var_df['nlp_vars']+var_df['date_vars']
del_cols = var_df['cols_delete']
preds = [x for x in orig_preds if x not in id_cols+del_cols+string_cols+target]
if len(id_cols+del_cols+string_cols)== 0:
print(' No variables removed since no ID or low-information variables found in data set')
else:
print(' %d variables removed since they were some ID or low-information variables'
%len(id_cols+del_cols+string_cols))
###### Fill Missing Values, Scale Data and Classify Variables Here ###
if len(preds) > 0:
dict_train = {}
for f in preds:
if start_train[f].dtype == object:
#### This is the easiest way to label encode object variables in both train and test
#### This takes care of some categories that are present in train and not in test
### and vice versa
train_categs = list(pd.unique(start_train[f].values))
if type(orig_test) != str:
test_categs = list(pd.unique(start_test[f].values))
categs_all = train_categs+test_categs
dict_all = return_factorized_dict(categs_all)
else:
dict_all = return_factorized_dict(train_categs)
start_train[f] = start_train[f].map(dict_all)
if type(orig_test) != str:
start_test[f] = start_test[f].map(dict_all)
elif start_train[f].dtype == int:
### if there are integer variables, don't scale them. Leave them as is.
fill_num = start_train[f].min() - 1
if start_train[f].isnull().sum() > 0:
start_train[f] = start_train[f].fillna(fill_num)
if type(orig_test) != str:
if start_test[f].isnull().sum() > 0:
start_test[f] = start_test[f].fillna(fill_num)
pass
else:
### for all numeric variables, fill missing values with 1 less than min.
fill_num = start_train[f].min() - 1
if start_train[f].isnull().sum() > 0:
start_train[f] = start_train[f].fillna(fill_num)
if type(orig_test) != str:
if start_test[f].isnull().sum() > 0:
start_test[f] = start_test[f].fillna(fill_num)
##### DO SCALING ON TRAIN HERE ############
with warnings.catch_warnings():
warnings.simplefilter("ignore")
try:
start_train[f] = SS.fit_transform(start_train[f].values.reshape(-1,1))
except:
start_train.loc[start_train[f]==np.inf,f]=0
start_train[f] = SS.fit_transform(start_train[f].values.reshape(-1,1))
##### DO SCALING ON TEST HERE ############
if type(orig_test) != str:
try:
start_test[f] = SS.transform(start_test[f].values.reshape(-1,1))
except:
start_test.loc[start_test[f]==np.inf,f]=0
start_test[f] = SS.fit_transform(start_test[f].values.reshape(-1,1))
if start_train[preds].isnull().sum().sum() > 0:
print(' Completed Missing Value Imputation and Scaling data...')
elif type(orig_test) != str:
if start_test.isnull().sum().sum() > 0:
print('Test data still has some missing values. Fix it.')
else:
print('Test data has no missing values...')
else:
print(' Completed Scaling of numeric data. There are no missing values in train')
else:
print(' Could not find any variables in your data set. Please check input and try again')
return
### Make sure you remove variables that are highly correlated within data set first
numvars = var_df['continuous_vars']
rem_vars = left_subtract(preds,numvars)
if len(numvars) > 0:
numvars = remove_variables_using_fast_correlation(start_train,numvars,corr_limit,verbose)
### Reduced Preds are now free of correlated variables and hence can be used for Poly adds
red_preds = rem_vars + numvars
#### You need to save a copy of this red_preds so you can later on create a start_train
#### with it after each_target cycle is completed. Very important!
orig_red_preds = copy.deepcopy(red_preds)
for each_target in target:
print('\nTarget Ready for Modeling: %s' %each_target)
#### This is where we set the orig train data set with multiple labels to the new start_train
#### start_train has the new features added or reduced with the multi targets in one cycle
### That way, we start each train with one target, and then reset it with multi target
train = start_train[[each_target]+red_preds]
if type(orig_test) != str:
test = start_test[red_preds]
print('Starting Feature Engg, Extraction and Model Training for target %s and %d predictors' %(
each_target,len(red_preds)))
###### Add Polynomial Variables and Interaction Variables to Train ######
if Add_Poly >= 1:
print('\nCAUTION: Adding 2nd degree Polynomial & Interaction Variables may result in Overfitting!')
## Since the data is already scaled, we set scaling to None here ##
### For train data we have to set the fit_flag to True ####
if len(numvars) > 1:
train_sel, lm, train_red,md,fin_xvars = add_poly_vars_select(train,numvars,
each_target,modeltype,poly_degree,Add_Poly,md='',
scaling='None',
fit_flag=True,verbose=verbose)
if len(train_sel) > len(numvars):
#### Do the next step only if new variables were added #############
train = train_red.join(train[rem_vars+[each_target]])
red_preds = list(OrderedDict.fromkeys(train_sel+rem_vars))
if type(test) != str:
######### Add Polynomial and Interaction variables to Test ################
## Since the data is already scaled, we set scaling to None here ##
### For Test data we have to set the fit_flag to False ####
_, _, test_x_vars,_,_ = add_poly_vars_select(test,numvars,each_target,
modeltype,poly_degree,Add_Poly,md,
scaling='None', fit_flag=False,
verbose=verbose)
test_red = test_x_vars[fin_xvars]
#### test_red contain xvars with orig and poly/intxn variables
### we need to convert it into orig text variables
test_red.columns = train_sel
test = test_red[train_sel].join(test[rem_vars])
else:
#### NO new variables were added. so we can skip the rest of the stuff now ###
print(' No new variables were added by polynomial features...')
else:
print('\nAdding Polynomial vars ignored since no numeric vars in data')
train_sel = copy.deepcopy(numvars)
else:
### if there are no Polynomial vars, then all numeric variables are selected
train_sel = copy.deepcopy(numvars)
######### SELECT IMPORTANT FEATURES HERE #############################
important_features,num_vars = find_top_features_xgb(train,red_preds,train_sel,
each_target,
modeltype,corr_limit,verbose)
#####################################################################################
if len(important_features) == 0:
print('No important features found. Using all input features...')
important_features = copy.deepcopy(red_preds)
### Training an XGBoost model to find important features
train = train[important_features+[each_target]]
######################################################################
if type(orig_test) != str:
test = test[important_features]
############# From here on we do some Feature Engg using Target Variable.
### To avoid Model Leakage, we will now split the Data into Train and CV so that Held Out Data
## is Pure and is unadulterated by learning from its own Target. This is known as Data Leakage.
###################################################################################################
X = train[important_features]
y = train[each_target]
train_num = int((1-test_size)*train.shape[0])
part_train = train[:train_num]
part_cv = train[train_num:]
############ Add Entropy Binning of Continuous Variables Here ##############################
saved_important_features = copy.deepcopy(important_features) ### these are original features without '_bin' added
saved_num_vars = copy.deepcopy(num_vars) ### these are original numeric features without '_bin' added
part_train, num_vars, important_features, part_cv = add_entropy_binning(part_train, each_target, num_vars,
important_features, part_cv, modeltype,Binning_Flag)
### Now we add another Feature tied to KMeans clustering using Predictor and Target variables ###
X_train, X_cv, y_train, y_cv = part_train[important_features],part_cv[important_features
],train[each_target][:train_num],train[each_target][train_num:]
if KMeans_Featurizer:
print(' Adding 1 Feature using KMeans_Featurizer...')
X_train, X_cv = Transform_KM_Features(X_train, y_train, X_cv)
#### Since this is returning the each_target in X_train, we need to drop it here ###
X_train.drop(each_target,axis=1,inplace=True)
important_features = [x for x in list(X_train) if x not in [each_target]]
######### This is where you do Stacking of Multi Model Results into One Column ###
if Stacking_Flag:
#### In order to join, you need X_train to be a Pandas Series here ##
from QuickML_Stacking import QuickML_Stacking
print('CAUTION: Stacking can produce Highly Overfit models on Training Data...')
### In order to avoid overfitting, we are going to learn from a small sample of data
### That is why we are using X_cv to train on and using it to predict on X_train!
addcol, stacks1 = QuickML_Stacking(X_train,y_train,X_train,
modeltype, Boosting_Flag, scoring_parameter,verbose)
addcol, stacks2 = QuickML_Stacking(X_train,y_train,X_cv,
modeltype, Boosting_Flag, scoring_parameter,verbose)
##### Adding multiple columns for Stacking is best! Do not do the average of predictions!
X_train = X_train.join(pd.DataFrame(stacks1,index=X_train.index,
columns=addcol))
##### Adding multiple columns for Stacking is best! Do not do the average of predictions!
X_cv = X_cv.join(pd.DataFrame(stacks2,index=X_cv.index,
columns=addcol))
print(' Adding %d Stacking feature(s) to training data' %len(addcol))
###### We make sure that we remove any new features that are highly correlated ! #####
#addcol = remove_variables_using_fast_correlation(X_train,addcol,corr_limit,verbose)
important_features += addcol
#### This is where we divide train and test into Train and CV Test Sets #################
#### Remember that the next 2 lines are crucial: if X and y are dataframes, then predict_proba
### will have to also predict on dataframes. So don't confuse values with df's.
## Be consistent with XGB. That's the best way.
print('Rows in Train data set = %d' %X_train.shape[0])
print('Features in Train data set = %d' %X_train.shape[1])
print(' Rows in held-out data set = %d' %X_cv.shape[0])
data_dim = X_train.shape[0]*X_train.shape[1]
### Setting up the Estimators for Single Label and Multi Label targets only
if modeltype == 'Regression':
metrics_list = ['neg_mean_absolute_error' ,'neg_mean_squared_error',
'neg_mean_squared_log_error','neg_median_absolute_error']
eval_metric = "rmse"
if scoring_parameter == 'neg_mean_absolute_error' or scoring_parameter =='mae':
meae_scorer = make_scorer(gini_meae, greater_is_better=False)
scorer = meae_scorer
elif scoring_parameter == 'neg_mean_squared_error' or scoring_parameter =='mse':
mse_scorer = make_scorer(gini_mse, greater_is_better=False)
scorer = mse_scorer
elif scoring_parameter == 'neg_mean_squared_log_error' or scoring_parameter == 'log_error':
msle_scorer = make_scorer(gini_msle, greater_is_better=False)
print(' Log Error is not recommended since predicted values might be negative and error')
rmse_scorer = make_scorer(gini_rmse, greater_is_better=False)
scorer = rmse_scorer
elif scoring_parameter == 'neg_median_absolute_error' or scoring_parameter == 'median_error':
mae_scorer = make_scorer(gini_mae, greater_is_better=False)
scorer = mae_scorer
elif scoring_parameter =='rmse' or scoring_parameter == 'root_mean_squared_error':
rmse_scorer = make_scorer(gini_rmse, greater_is_better=False)
scorer = rmse_scorer
else:
scoring_parameter = 'rmse'
rmse_scorer = make_scorer(gini_rmse, greater_is_better=False)
scorer = rmse_scorer
#### HYPER PARAMETERS FOR TUNING ARE SETUP HERE ###
if hyper_param == 'GS':
r_params = {
"Forests": {
"n_estimators" : [100, max_estims],
"max_depth": [3, 5, 10],
"criterion" : ['mse','mae'],
},
"Linear": {
'alpha': np.logspace(-3,3),
},
"XGBoost": {
'max_depth': [2,4,8],
'gamma': [0,1,2,4,8,16,32],
"n_estimators" : [100, max_estims],
'learning_rate': [0.10, 0.30, 0.5]
},
}
else:
r_params = {
"Forests": {
"n_estimators" : np.linspace(100, max_estims, 6, dtype = "int"),
"max_depth": [3, 5, 10],
#"min_samples_leaf": np.linspace(2, 50, 20, dtype = "int"),
"criterion" : ['mse','mae'],
},
"Linear": {
'alpha': np.logspace(-3,3),
},
"XGBoost": {
'max_depth': [2,4,8],
'gamma': [0,1,2,4,8,16,32],
'n_estimators': list(np.linspace(100,max_estims,6).astype(int)),
'learning_rate': [0.05,0.10,0.20, 0.30,0.4,0.5]
},
}
if Boosting_Flag:
xgbm = XGBRegressor(seed=seed,n_jobs=-1,random_state=seed,subsample=subsample,
colsample_bytree=col_sub_sample,
objective=objective)
elif Boosting_Flag is None:
xgbm = Lasso(max_iter=max_iter,random_state=seed)
else:
xgbm = ExtraTreesRegressor(
**{
'bootstrap': True, 'n_jobs': -1, 'warm_start': False,
'random_state':seed,'min_samples_leaf':2,
'max_features': "sqrt"
})
else:
#### This is for Binary Classification ##############################
classes = label_dict[each_target]['classes']
metrics_list = ['accuracy_score','roc_auc_score','logloss', 'precision','recall','f1']
# Create regularization hyperparameter distribution with 50 C values ####
if hyper_param == 'GS':
c_params['XGBoost'] = {
'max_depth': [2,4,10],
'gamma': [0,1,2,4,8,16],
'learning_rate': [0.10,0.20, 0.30],
'n_estimators': [100, max_estims]
}
c_params['Linear'] = {
'C': [0.01,0.05,0.01,0.5,1,5,10,50,100],
'solver' :[ 'saga'],#'newton-cg', 'lbfgs', 'liblinear',
'class_weight':[None,'balanced'],
}
c_params["Forests"] = {
##### I have selected these to avoid Overfitting which is a problem for small data sets
'n_estimators': [100, max_estims],
"max_depth": [3, 5, 10],
"criterion":['gini','entropy'],
}
else:
learning_rate = np.linspace(0.01,0.5)
c_params['XGBoost'] = {
'learning_rate': learning_rate,
'max_depth': [2,4,8],
'gamma': [0,1,2,4,8,16,32],
'n_estimators': list(np.linspace(100,max_estims,6).astype(int)),
}
C = np.linspace(0.01,100)
c_params['Linear'] = {
'C': C,
'solver' :[ 'saga'],#'newton-cg', 'lbfgs', 'liblinear',
'class_weight':[None,'balanced'],
}
c_params["Forests"] = {
##### I have selected these to avoid Overfitting which is a problem for small data sets
"n_estimators" : np.linspace(50,max_estims, 6, dtype = "int"),
"max_depth": [3, 5, 10],
#"min_samples_leaf": np.linspace(2, 50, 20, dtype = "int"),
"criterion":['gini','entropy'],
#'max_features': ['log', "sqrt"] ,
#'class_weight':[None,'balanced']
}
# Create regularization hyperparameter distribution using uniform distribution
if len(classes) == 2:
objective = 'binary:logistic'
if scoring_parameter == 'accuracy' or scoring_parameter == 'accuracy_score':
accuracy_scorer = make_scorer(gini_accuracy, greater_is_better=True, needs_proba=False)
scorer =accuracy_scorer
elif scoring_parameter == 'gini':
gini_scorer = make_scorer(gini_sklearn, greater_is_better=False, needs_proba=True)
scorer =gini_scorer
elif scoring_parameter == 'auc' or scoring_parameter == 'roc_auc' or scoring_parameter == 'roc_auc_score':
roc_scorer = make_scorer(gini_roc, greater_is_better=True, needs_threshold=True)
scorer =roc_scorer
elif scoring_parameter == 'log_loss' or scoring_parameter == 'logloss':
scoring_parameter = 'neg_log_loss'
logloss_scorer = make_scorer(gini_log_loss, greater_is_better=False, needs_proba=False)
scorer =logloss_scorer
elif scoring_parameter=='balanced_accuracy' or scoring_parameter=='balanced-accuracy' or scoring_parameter=='average_accuracy':
try:
from sklearn.metrics import balanced_accuracy_score
bal_accuracy_scorer = make_scorer(gini_bal_accuracy, greater_is_better=True,
needs_proba=False)
except:
bal_accuracy_scorer = make_scorer(gini_accuracy, greater_is_better=True,
needs_proba=False)
scorer = bal_accuracy_scorer
elif scoring_parameter == 'precision' or scoring_parameter == 'precision_score':
precision_scorer = make_scorer(gini_precision, greater_is_better=True, needs_proba=False,
pos_label=rare_class)
scorer =precision_scorer
elif scoring_parameter == 'recall' or scoring_parameter == 'recall_score':
recall_scorer = make_scorer(gini_recall, greater_is_better=True, needs_proba=False,
pos_label=rare_class)
scorer =recall_scorer
elif scoring_parameter == 'f1' or scoring_parameter == 'f1_score':
f1_scorer = make_scorer(gini_f1, greater_is_better=True, needs_proba=False,
pos_label=rare_class)
scorer =f1_scorer
else:
f1_scorer = make_scorer(gini_f1, greater_is_better=True, needs_proba=False,
pos_label=rare_class)
scorer = f1_scorer
### DO NOT USE NUM CLASS WITH BINARY CLASSIFICATION ######
if Boosting_Flag:
xgbm = XGBClassifier(seed=seed,n_jobs=-1, random_state=seed,subsample=subsample,
colsample_bytree=col_sub_sample,
objective=objective)
elif Boosting_Flag is None:
#### I have set the Verbose to be False here since it produces too much output ###
xgbm = LogisticRegression(random_state=seed,verbose=False,n_jobs=-1,
warm_start=False, max_iter=max_iter)
else:
xgbm = ExtraTreesClassifier(
**{
'bootstrap': True, 'n_jobs': -1, 'warm_start': False,
'random_state':seed,'min_samples_leaf':2,'oob_score':True,
'max_features': "sqrt"
})
else:
##### This is for MULTI Classification ##########################
objective = 'multi:softmax'
eval_metric = "mlogloss"
if scoring_parameter == 'gini':
gini_scorer = make_scorer(gini_sklearn, greater_is_better=False, needs_proba=True)
scorer = gini_scorer
elif scoring_parameter=='balanced_accuracy' or scoring_parameter=='balanced-accuracy' or scoring_parameter=='average_accuracy':
try:
from sklearn.metrics import balanced_accuracy_score
bal_accuracy_scorer = make_scorer(gini_bal_accuracy, greater_is_better=True,
needs_proba=False)
except:
bal_accuracy_scorer = make_scorer(gini_accuracy, greater_is_better=True,
needs_proba=False)
scorer = bal_accuracy_scorer
elif scoring_parameter == 'roc_auc' or scoring_parameter == 'roc_auc_score':
roc_auc_scorer = make_scorer(gini_sklearn, greater_is_better=False, needs_proba=True)
scorer = roc_auc_scorer
elif scoring_parameter == 'average_precision' or scoring_parameter == 'mean_precision':
average_precision_scorer = make_scorer(gini_average_precision,
greater_is_better=True, needs_proba=True)
scorer = average_precision_scorer
elif scoring_parameter == 'samples_precision':
samples_precision_scorer = make_scorer(gini_samples_precision,
greater_is_better=True, needs_proba=True)
scorer = samples_precision_scorer
elif scoring_parameter == 'weighted_precision':
weighted_precision_scorer = make_scorer(gini_weighted_precision,
greater_is_better=True, needs_proba=True)
scorer = weighted_precision_scorer
elif scoring_parameter == 'macro_precision':
macro_precision_scorer = make_scorer(gini_macro_precision,
greater_is_better=True, needs_proba=True)
scorer = macro_precision_scorer
elif scoring_parameter == 'micro_precision':
scorer = micro_precision_scorer
micro_precision_scorer = make_scorer(gini_micro_precision,
greater_is_better=True, needs_proba=True)
elif scoring_parameter == 'samples_recall':
samples_recall_scorer = make_scorer(gini_samples_recall, greater_is_better=True, needs_proba=True)
scorer = samples_recall_scorer
elif scoring_parameter == 'weighted_recall':
weighted_recall_scorer = make_scorer(gini_weighted_recall,
greater_is_better=True, needs_proba=True)
scorer = weighted_recall_scorer
elif scoring_parameter == 'macro_recall':
macro_recall_scorer = make_scorer(gini_macro_recall,
greater_is_better=True, needs_proba=True)
scorer = macro_recall_scorer
elif scoring_parameter == 'micro_recall':
micro_recall_scorer = make_scorer(gini_micro_recall, greater_is_better=True, needs_proba=True)
scorer = micro_recall_scorer
elif scoring_parameter == 'samples_f1':
samples_f1_scorer = make_scorer(gini_samples_f1,
greater_is_better=True, needs_proba=True)
scorer = samples_f1_scorer
elif scoring_parameter == 'weighted_f1':
weighted_f1_scorer = make_scorer(gini_weighted_f1,
greater_is_better=True, needs_proba=True)
scorer = weighted_f1_scorer
elif scoring_parameter == 'macro_f1':
macro_f1_scorer = make_scorer(gini_macro_f1,
greater_is_better=True, needs_proba=True)
scorer = macro_f1_scorer
elif scoring_parameter == 'micro_f1':
micro_f1_scorer = make_scorer(gini_micro_f1,
greater_is_better=True, needs_proba=True)
scorer = micro_f1_scorer
else:
weighted_f1_scorer = make_scorer(gini_weighted_f1,
greater_is_better=True, needs_proba=True)
scorer = weighted_f1_scorer
if Boosting_Flag:
# Create regularization hyperparameter distribution using uniform distribution
if hyper_param == 'GS':
c_params['XGBoost'] = {
'max_depth': [2,4,10],
'gamma': [0,1,2,4,8,16],
'learning_rate': [0.10,0.20, 0.30],
'n_estimators': [100, max_estims]
}
else:
learning_rate = np.linspace(0.1,0.5)
c_params['XGBoost'] = {
'learning_rate': learning_rate,
'max_depth': [2,4,8],
'gamma': [0,1,2,4,8,16,32],
'n_estimators': list(np.linspace(100,max_estims,6).astype(int)),
}
xgbm = XGBClassifier(seed=seed,n_jobs=-1, random_state=seed,subsample=subsample,
colsample_bytree=col_sub_sample,
num_class= len(classes),
objective=objective)
elif Boosting_Flag is None:
if hyper_param == 'GS':
c_params['Linear'] = {
'C': [0.01,0.05,0.01,0.5,1,5,10,50,100],
'solver' :[ 'newton-cg'],# 'lbfgs', 'liblinear',
'multi_class': ['ovr','multinomial'],
}
else:
# Create regularization hyperparameter distribution with 50 C values ####
C = np.linspace(0.01,100)
c_params['Linear'] = {
'C': C,
'solver' :['newton-cg'],# 'lbfgs', 'saga'],
'multi_class': ['ovr','multinomial'],
}
#### I have set the Verbose to be False here since it produces too much output ###
xgbm = LogisticRegression(random_state=seed,verbose=False,n_jobs=-1,
max_iter=max_iter, warm_start=False,
)
else:
if hyper_param == 'GS':
c_params["Forests"] = {
##### I have selected these to avoid Overfitting which is a problem for small data sets
'n_estimators': [100,max_estims],
"max_depth": [3, 5, 10],
"criterion":['gini','entropy'],
}
c_params["Forests"] = {
##### I have set these to avoid OverFitting which is a problem for small data sets ###
"n_estimators" : np.linspace(100, max_estims, 6, dtype = "int"),
"max_depth": [3, 5, 10],
#"min_samples_leaf": np.linspace(2, 50, 20, dtype = "int"),
"criterion":['gini','entropy'],
#'class_weight':[None,'balanced']
}
xgbm = ExtraTreesClassifier(bootstrap=True, oob_score=True,warm_start=False,
n_estimators=100,max_depth=3,
min_samples_leaf=2,max_features='auto',
random_state=seed,n_jobs=-1)
###### Now do RandomizedSearchCV using # Early-stopping ################
if modeltype == 'Regression':
#scoreFunction = {"mse": "neg_mean_squared_error", "mae": "neg_mean_absolute_error"}
#### I have set the Verbose to be False here since it produces too much output ###
if hyper_param == 'GS':
#### I have set the Verbose to be False here since it produces too much output ###
model = GridSearchCV(xgbm,param_grid=r_params[model_name],
scoring = scorer,
n_jobs=-1,
cv = scv,
verbose=0)
else:
model = RandomizedSearchCV(xgbm,
param_distributions = r_params[model_name],
n_iter = no_iter,
scoring = scorer,
refit = "mae",
return_train_score = True,
random_state = seed,
cv = scv,
n_jobs=-1,
verbose = 0)
else:
if hyper_param == 'GS':
#### I have set the Verbose to be False here since it produces too much output ###
model = GridSearchCV(xgbm,param_grid=c_params[model_name],
scoring = scorer,
n_jobs=-1,
cv = scv,
verbose=0)
else:
#### I have set the Verbose to be False here since it produces too much output ###
model = RandomizedSearchCV(xgbm,
param_distributions = c_params[model_name],
n_iter = no_iter,
scoring = scorer,
refit = "precision",
return_train_score = True,
random_state = seed,
n_jobs=-1,
cv = scv,
verbose = 0)
#trains and optimizes the model
eval_set = [(X_cv, y_cv)]
print('Finding Best Model and Hyper Parameters for Target: %s...' %each_target)
##### Here is where we put the part_train and part_cv together ###########
if modeltype != 'Regression':
### Do this only for Binary Classes and Multi-Classes, both are okay
baseline_accu = 1-(train[each_target].value_counts(1).sort_values())[rare_class]
print('Baseline Accuracy Needed for Model = %0.2f%%' %(baseline_accu*100))
print()
if modeltype == 'Regression':
if Boosting_Flag:
print('Using %s Model, Estimated Training time = %0.1f mins' %(model_name,data_dim/27000.))
elif Boosting_Flag is None:
print('Using %s Model, Estimated Training time = %0.1f mins' %(model_name,data_dim/4000.))
else:
print('Using %s Model, Estimated Training time = %0.1f mins' %(model_name,data_dim/6000.))
else:
if hyper_param == 'GS':
if Boosting_Flag:
print('Using %s Model, Estimated Training time = %0.1f mins' %(model_name,data_dim/3000.))