forked from pycaret/pycaret
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathregression.py
7906 lines (5733 loc) · 273 KB
/
regression.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
def setup(data,
target,
train_size=0.7,
sampling=True,
sample_estimator = None,
session_id = None,
profile = False):
"""
Description:
------------
This function initialize the environment in pycaret. setup() must called before
executing any other function in pycaret. It takes two mandatory parameters i.e.
dataframe {array-like, sparse matrix} and name of the target column.
All other parameters are optional.
Example
-------
experiment_name = setup(data, 'target')
data is a pandas DataFrame and 'target' is the name of the column in dataframe.
Parameters
----------
data : {array-like, sparse matrix}, shape (n_samples, n_features) where n_samples
is the number of samples and n_features is the number of features.
target: string
Name of target column to be passed in as string.
train_size: float, default = 0.7
Size of training set. By default 70% of the data will be used for training and
validation.
sampling: bool, default = True
When sample size exceed 25,000 samples, pycaret creates base estimator at various
sample level of the original dataset. This will return the performance plot of
R2 at various sample level, that will help you decide sample size for modeling.
You are then required to enter the desired sample size that will be considered
for training and validation in the pycaret environment. 1 - sample size
will be discarded and not be used any further.
sample_estimator: object, default = None
If None, Linear Regression is used by default.
session_id: int, default = None
If None, random seed is generated and returned in Information grid. The unique
number is then distributed as a seed in all other functions used during experiment.
This can be used later for reproducibility of entire experiment.
profile: bool, default = False
If set to true, it will display data profile for Exploratory Data Analysis in
interactive HTML report.
Returns:
--------
info grid: Information grid is printed.
-----------
environment: This function returns various outputs that are stored in variable
----------- as tuple. They are being used by other functions in pycaret.
Warnings:
---------
None
"""
#exception checking
import sys
#checking train size parameter
if type(train_size) is not float:
sys.exit('(Type Error): train_size parameter only accepts float value.')
#checking sampling parameter
if type(sampling) is not bool:
sys.exit('(Type Error): sampling parameter only accepts True or False.')
#checking sampling parameter
if target not in data.columns:
sys.exit('(Value Error): Target parameter doesnt exist in the data provided.')
#checking session_id
if session_id is not None:
if type(session_id) is not int:
sys.exit('(Type Error): session_id parameter must be an integer.')
#checking sampling parameter
if type(profile) is not bool:
sys.exit('(Type Error): profile parameter only accepts True or False.')
#pre-load libraries
import pandas as pd
import ipywidgets as ipw
from IPython.display import display, HTML, clear_output, update_display
import datetime, time
#progress bar
if sampling:
max = 10 + 2
else:
max = 2
progress = ipw.IntProgress(value=0, min=0, max=max, step=1 , description='Processing: ')
display(progress)
timestampStr = datetime.datetime.now().strftime("%H:%M:%S")
monitor = pd.DataFrame( [ ['Initiated' , '. . . . . . . . . . . . . . . . . .', timestampStr ],
['Status' , '. . . . . . . . . . . . . . . . . .' , 'Loading Dependencies' ],
['ETC' , '. . . . . . . . . . . . . . . . . .', 'Calculating ETC'] ],
columns=['', ' ', ' ']).set_index('')
display(monitor, display_id = 'monitor')
#general dependencies
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn import metrics
import random
import seaborn as sns
import matplotlib.pyplot as plt
import plotly.express as px
#cufflinks
import cufflinks as cf
cf.go_offline()
cf.set_config_file(offline=False, world_readable=True)
#ignore warnings
import warnings
warnings.filterwarnings('ignore')
#declaring global variables to be accessed by other functions
global X, y, X_train, X_test, y_train, y_test, seed, experiment__
#generate seed to be used globally
if session_id is None:
seed = random.randint(150,9000)
else:
seed = session_id
#create an empty list for pickling later.
experiment__ = []
#sample estimator
if sample_estimator is None:
model = LinearRegression()
else:
model = sample_estimator
model_name = str(model).split("(")[0]
if 'CatBoostRegressor' in model_name:
model_name = 'CatBoostRegressor'
#creating variables to be used later in the function
X = data.drop(target,axis=1)
y = data[target]
#copy original data for pandas profiler
data_before_preprocess = data.copy()
progress.value += 1
if sampling is True and data.shape[0] > 25000: #change back to 25000
split_perc = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,0.99]
split_perc_text = ['10%','20%','30%','40%','50%','60%', '70%', '80%', '90%', '100%']
split_perc_tt = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,0.99]
split_perc_tt_total = []
split_percent = []
metric_results = []
metric_name = []
counter = 0
for i in split_perc:
progress.value += 1
t0 = time.time()
'''
MONITOR UPDATE STARTS
'''
perc_text = split_perc_text[counter]
monitor.iloc[1,1:] = 'Fitting Model on ' + perc_text + ' sample'
update_display(monitor, display_id = 'monitor')
'''
MONITOR UPDATE ENDS
'''
X_, X__, y_, y__ = train_test_split(X, y, test_size=1-i)
X_train, X_test, y_train, y_test = train_test_split(X_, y_, test_size=0.3, random_state=seed)
model.fit(X_train,y_train)
pred_ = model.predict(X_test)
r2 = metrics.r2_score(y_test,pred_)
metric_results.append(r2)
metric_name.append('R2')
split_percent.append(i)
t1 = time.time()
'''
Time calculation begins
'''
tt = t1 - t0
total_tt = tt / i
split_perc_tt.pop(0)
for remain in split_perc_tt:
ss = total_tt * remain
split_perc_tt_total.append(ss)
ttt = sum(split_perc_tt_total) / 60
ttt = np.around(ttt, 2)
if ttt < 1:
ttt = str(np.around((ttt * 60), 2))
ETC = ttt + ' Seconds Remaining'
else:
ttt = str (ttt)
ETC = ttt + ' Minutes Remaining'
monitor.iloc[2,1:] = ETC
update_display(monitor, display_id = 'monitor')
'''
Time calculation Ends
'''
split_perc_tt_total = []
counter += 1
model_results = pd.DataFrame({'Sample Size' : split_percent, 'Metric' : metric_results, 'Metric Name': metric_name})
model_results = pd.DataFrame({'Sample Size' : split_percent, 'Metric' : metric_results, 'Metric Name': metric_name})
fig = px.line(model_results, x='Sample Size', y='Metric', color='Metric Name', line_shape='linear', range_y = [0,1])
fig.update_layout(plot_bgcolor='rgb(245,245,245)')
title= str(model_name) + ' Metric and Sample %'
fig.update_layout(title={'text': title, 'y':0.95,'x':0.45,'xanchor': 'center','yanchor': 'top'})
fig.show()
monitor.iloc[1,1:] = 'Waiting for input'
update_display(monitor, display_id = 'monitor')
print('Please Enter the sample % of data you would like to use for modeling. Example: Enter 0.3 for 30%.')
print('Press Enter if you would like to use 100% of the data.')
print(' ')
sample_size = input("Sample Size: ")
if sample_size == '' or sample_size == '1':
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=1-train_size, random_state=seed)
'''
Final display Starts
'''
clear_output()
print(' ')
if profile:
print('Setup Succesfully Completed! Loading Profile Now... Please Wait!')
else:
print('Setup Succesfully Completed!')
functions = pd.DataFrame ( [ ['session_id', seed ],
['Original Data',X.shape ],
['Sampled Data',X.shape ],
['Sample %',X.shape[0] / X.shape[0]],
['Training Set', X_train.shape ],
['Testing Set',X_test.shape ],
], columns = ['Description', 'Value'] )
functions_ = functions.style.hide_index()
display(functions_)
if profile:
try:
import pandas_profiling
pf = pandas_profiling.ProfileReport(data_before_preprocess)
clear_output()
display(pf)
except:
print('Data Profiler Failed. No output to show, please continue with Modeling.')
'''
Final display Ends
'''
#log into experiment
experiment__.append(('Info', functions))
experiment__.append(('X_training Set', X_train))
experiment__.append(('y_training Set', y_train))
experiment__.append(('X_test Set', X_test))
experiment__.append(('y_test Set', y_test))
return X, y, X_train, X_test, y_train, y_test, seed, experiment__
else:
sample_n = float(sample_size)
X_selected, X_discard, y_selected, y_discard = train_test_split(X, y, test_size=1-sample_n,
random_state=seed)
X_train, X_test, y_train, y_test = train_test_split(X_selected, y_selected, test_size=1-train_size,
random_state=seed)
clear_output()
'''
Final display Starts
'''
clear_output()
print(' ')
if profile:
print('Setup Succesfully Completed! Loading Profile Now... Please Wait!')
else:
print('Setup Succesfully Completed!')
functions = pd.DataFrame ( [ ['session_id', seed ],
['Original Data',X.shape ],
['Sampled Data',X_selected.shape ],
['Sample %',X_selected.shape[0] / X.shape[0]],
['Training Set', X_train.shape ],
['Testing Set',X_test.shape ],
], columns = ['Description', 'Value'] )
functions_ = functions.style.hide_index()
display(functions_)
if profile:
try:
import pandas_profiling
pf = pandas_profiling.ProfileReport(data_before_preprocess)
clear_output()
display(pf)
except:
print('Data Profiler Failed. No output to show, please continue with Modeling.')
'''
Final display Ends
'''
#log into experiment
experiment__.append(('Info', functions))
experiment__.append(('X_training Set', X_train))
experiment__.append(('y_training Set', y_train))
experiment__.append(('X_test Set', X_test))
experiment__.append(('y_test Set', y_test))
return X, y, X_train, X_test, y_train, y_test, seed, experiment__
else:
monitor.iloc[1,1:] = 'Splitting Data'
update_display(monitor, display_id = 'monitor')
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=1-train_size, random_state=seed)
progress.value += 1
clear_output()
'''
Final display Starts
'''
clear_output()
print(' ')
if profile:
print('Setup Succesfully Completed! Loading Profile Now... Please Wait!')
else:
print('Setup Succesfully Completed!')
functions = pd.DataFrame ( [ ['session_id', seed ],
['Original Data',X.shape ],
['Sampled Data',X.shape ],
['Sample %',X.shape[0] / X.shape[0]],
['Training Set', X_train.shape ],
['Testing Set',X_test.shape ],
], columns = ['Description', 'Value'] )
functions_ = functions.style.hide_index()
display(functions_)
if profile:
try:
import pandas_profiling
pf = pandas_profiling.ProfileReport(data_before_preprocess)
clear_output()
display(pf)
except:
print('Data Profiler Failed. No output to show, please continue with Modeling.')
'''
Final display Ends
'''
#log into experiment
experiment__.append(('Regression Info', functions))
experiment__.append(('X_training Set', X_train))
experiment__.append(('y_training Set', y_train))
experiment__.append(('X_test Set', X_test))
experiment__.append(('y_test Set', y_test))
return X, y, X_train, X_test, y_train, y_test, seed, experiment__
def create_model(estimator = None,
ensemble = False,
method = None,
fold = 10,
round = 4,
verbose = True):
"""
Description:
------------
This function creates a model and scores it using Kfold Cross Validation.
(default = 10 Fold). The output prints the score grid that shows MAE, MSE,
RMSE, R2 and Max Error (ME).
Function also returns a trained model object that can be used for further
processing in pycaret or can be used to call any method available in sklearn.
setup() function must be called before using create_model()
Example
-------
lr = create_model('lr')
This will return trained Linear Regression.
Parameters
----------
estimator : string, default = None
Enter abbreviated string of the estimator class. List of estimators supported:
Estimator Abbreviated String Original Implementation
--------- ------------------ -----------------------
Linear Regression 'lr' linear_model.LinearRegression
Lasso Regression 'lasso' linear_model.Lasso
Ridge Regression 'ridge' linear_model.Ridge
Elastic Net 'en' linear_model.ElasticNet
Least Angle Regression 'lar' linear_model.Lars
Lasso Least Angle Regression 'llar' linear_model.LassoLars
Orthogonal Matching Pursuit 'omp' linear_model.OMP
Bayesian Ridge 'br' linear_model.BayesianRidge
Automatic Relevance Determ. 'ard' linear_model.ARDRegression
Passive Aggressive Regressor 'par' linear_model.PAR
Random Sample Consensus 'ransac' linear_model.RANSACRegressor
TheilSen Regressor 'tr' linear_model.TheilSenRegressor
Huber Regressor 'huber' linear_model.HuberRegressor
Kernel Ridge 'kr' kernel_ridge.KernelRidge
Support Vector Machine 'svm' svm.SVR
K Neighbors Regressor 'knn' neighbors.KNeighborsRegressor
Decision Tree 'dt' tree.DecisionTreeRegressor
Random Forest 'rf' ensemble.RandomForestRegressor
Extra Trees Regressor 'et' ensemble.ExtraTreesRegressor
AdaBoost Regressor 'ada' ensemble.AdaBoostRegressor
Gradient Boosting 'gbr' ensemble.GradientBoostingRegressor
Multi Level Perceptron 'mlp' neural_network.MLPRegressor
Extreme Gradient Boosting 'xgboost' xgboost.readthedocs.io
Light Gradient Boosting 'lightgbm' github.com/microsoft/LightGBM
CatBoost Regressor 'catboost' https://catboost.ai
ensemble: Boolean, default = False
True would result in ensemble of estimator using the method parameter defined (see below).
method: String, 'Bagging' or 'Boosting', default = None.
method must be defined when ensemble is set to True. Default method is set to None.
fold: integer, default = 10
Number of folds to be used in Kfold CV. Must be at least 2.
round: integer, default = 4
Number of decimal places metrics in score grid will be rounded to.
verbose: Boolean, default = True
Score grid is not printed when verbose is set to False.
Returns:
--------
score grid: A table containing the scores of the model across the kfolds.
----------- Scoring metrics used are MAE, MSE, RMSE, R2 and ME. Mean and
standard deviation of the scores across the folds is also returned.
model: trained model object
-----------
Warnings:
---------
None
"""
'''
ERROR HANDLING STARTS HERE
'''
#exception checking
import sys
#checking error for estimator (string)
available_estimators = ['lr', 'lasso', 'ridge', 'en', 'lar', 'llar', 'omp', 'br', 'ard', 'par',
'ransac', 'tr', 'huber', 'kr', 'svm', 'knn', 'dt', 'rf', 'et', 'ada', 'gbr',
'mlp', 'xgboost', 'lightgbm', 'catboost']
if estimator not in available_estimators:
sys.exit('(Value Error): Estimator Not Available. Please see docstring for list of available estimators.')
#checking error for ensemble:
if type(ensemble) is not bool:
sys.exit('(Type Error): Ensemble parameter can only take argument as True or False.')
#checking error for method:
#1 Check When method given and ensemble is not set to True.
if ensemble is False and method is not None:
sys.exit('(Type Error): Method parameter only accepts value when ensemble is set to True.')
#2 Check when ensemble is set to True and method is not passed.
if ensemble is True and method is None:
sys.exit("(Type Error): Method parameter missing. Pass method = 'Bagging' or 'Boosting'.")
#3 Check when ensemble is set to True and method is passed but not allowed.
available_method = ['Bagging', 'Boosting']
if ensemble is True and method not in available_method:
sys.exit("(Value Error): Method parameter only accepts two values 'Bagging' or 'Boosting'.")
#checking fold parameter
if type(fold) is not int:
sys.exit('(Type Error): Fold parameter only accepts integer value.')
#checking round parameter
if type(round) is not int:
sys.exit('(Type Error): Round parameter only accepts integer value.')
#checking verbose parameter
if type(verbose) is not bool:
sys.exit('(Type Error): Verbose parameter can only take argument as True or False.')
'''
ERROR HANDLING ENDS HERE
'''
#pre-load libraries
import pandas as pd
import ipywidgets as ipw
from IPython.display import display, HTML, clear_output, update_display
import datetime, time
#progress bar
progress = ipw.IntProgress(value=0, min=0, max=fold+4, step=1 , description='Processing: ')
master_display = pd.DataFrame(columns=['MAE','MSE','RMSE', 'R2', 'ME'])
display(progress)
#display monitor
timestampStr = datetime.datetime.now().strftime("%H:%M:%S")
monitor = pd.DataFrame( [ ['Initiated' , '. . . . . . . . . . . . . . . . . .', timestampStr ],
['Status' , '. . . . . . . . . . . . . . . . . .' , 'Loading Dependencies' ],
['ETC' , '. . . . . . . . . . . . . . . . . .', 'Calculating ETC'] ],
columns=['', ' ', ' ']).set_index('')
display(monitor, display_id = 'monitor')
if verbose:
display_ = display(master_display, display_id=True)
display_id = display_.display_id
#ignore warnings
import warnings
warnings.filterwarnings('ignore')
#Storing X_train and y_train in data_X and data_y parameter
data_X = X_train.copy()
data_y = y_train.copy()
#reset index
data_X.reset_index(drop=True, inplace=True)
data_y.reset_index(drop=True, inplace=True)
#general dependencies
import numpy as np
from sklearn import metrics
from sklearn.model_selection import KFold
progress.value += 1
#cross validation setup starts here
kf = KFold(fold, random_state=seed)
score_mae =np.empty((0,0))
score_mse =np.empty((0,0))
score_rmse =np.empty((0,0))
score_r2 =np.empty((0,0))
score_max_error =np.empty((0,0))
avgs_mae =np.empty((0,0))
avgs_mse =np.empty((0,0))
avgs_rmse =np.empty((0,0))
avgs_r2 =np.empty((0,0))
avgs_max_error =np.empty((0,0))
'''
MONITOR UPDATE STARTS
'''
monitor.iloc[1,1:] = 'Selecting Estimator'
update_display(monitor, display_id = 'monitor')
'''
MONITOR UPDATE ENDS
'''
if estimator == 'lr':
from sklearn.linear_model import LinearRegression
model = LinearRegression()
full_name = 'Linear Regression'
elif estimator == 'lasso':
from sklearn.linear_model import Lasso
model = Lasso(random_state=seed)
full_name = 'Lasso Regression'
elif estimator == 'ridge':
from sklearn.linear_model import Ridge
model = Ridge(random_state=seed)
full_name = 'Ridge Regression'
elif estimator == 'en':
from sklearn.linear_model import ElasticNet
model = ElasticNet(random_state=seed)
full_name = 'Elastic Net'
elif estimator == 'lar':
from sklearn.linear_model import Lars
model = Lars()
full_name = 'Least Angle Regression'
elif estimator == 'llar':
from sklearn.linear_model import LassoLars
model = LassoLars()
full_name = 'Lasso Least Angle Regression'
elif estimator == 'omp':
from sklearn.linear_model import OrthogonalMatchingPursuit
model = OrthogonalMatchingPursuit()
full_name = 'Orthogonal Matching Pursuit'
elif estimator == 'br':
from sklearn.linear_model import BayesianRidge
model = BayesianRidge()
full_name = 'Bayesian Ridge Regression'
elif estimator == 'ard':
from sklearn.linear_model import ARDRegression
model = ARDRegression()
full_name = 'Automatic Relevance Determination'
elif estimator == 'par':
from sklearn.linear_model import PassiveAggressiveRegressor
model = PassiveAggressiveRegressor(random_state=seed)
full_name = 'Passive Aggressive Regressor'
elif estimator == 'ransac':
from sklearn.linear_model import RANSACRegressor
model = RANSACRegressor(random_state=seed)
full_name = 'Random Sample Consensus'
elif estimator == 'tr':
from sklearn.linear_model import TheilSenRegressor
model = TheilSenRegressor(random_state=seed)
full_name = 'TheilSen Regressor'
elif estimator == 'huber':
from sklearn.linear_model import HuberRegressor
model = HuberRegressor()
full_name = 'Huber Regressor'
elif estimator == 'kr':
from sklearn.kernel_ridge import KernelRidge
model = KernelRidge()
full_name = 'Kernel Ridge'
elif estimator == 'svm':
from sklearn.svm import SVR
model = SVR()
full_name = 'Support Vector Regression'
elif estimator == 'knn':
from sklearn.neighbors import KNeighborsRegressor
model = KNeighborsRegressor()
full_name = 'Nearest Neighbors Regression'
elif estimator == 'dt':
from sklearn.tree import DecisionTreeRegressor
model = DecisionTreeRegressor(random_state=seed)
full_name = 'Decision Tree Regressor'
elif estimator == 'rf':
from sklearn.ensemble import RandomForestRegressor
model = RandomForestRegressor(random_state=seed)
full_name = 'Random Forest Regressor'
elif estimator == 'et':
from sklearn.ensemble import ExtraTreesRegressor
model = ExtraTreesRegressor(random_state=seed)
full_name = 'Extra Trees Regressor'
elif estimator == 'ada':
from sklearn.ensemble import AdaBoostRegressor
model = AdaBoostRegressor(random_state=seed)
full_name = 'AdaBoost Regressor'
elif estimator == 'gbr':
from sklearn.ensemble import GradientBoostingRegressor
model = GradientBoostingRegressor(random_state=seed)
full_name = 'Gradient Boosting Regressor'
elif estimator == 'mlp':
from sklearn.neural_network import MLPRegressor
model = MLPRegressor(random_state=seed)
full_name = 'MLP Regressor'
elif estimator == 'xgboost':
from xgboost import XGBRegressor
model = XGBRegressor(random_state=seed, n_jobs=-1, verbosity=0)
full_name = 'Extreme Gradient Boosting Regressor'
elif estimator == 'lightgbm':
import lightgbm as lgb
model = lgb.LGBMRegressor(random_state=seed)
full_name = 'Light Gradient Boosting Machine'
elif estimator == 'catboost':
from catboost import CatBoostRegressor
model = CatBoostRegressor(random_state=seed, silent = True)
full_name = 'CatBoost Regressor'
else:
model = estimator
full_name = str(model).split("(")[0]
progress.value += 1
#checking method when ensemble is set to True.
if method == 'Bagging':
from sklearn.ensemble import BaggingRegressor
model = BaggingRegressor(model,bootstrap=True,n_estimators=10, random_state=seed)
elif method == 'Boosting':
from sklearn.ensemble import AdaBoostRegressor
model = AdaBoostRegressor(model, n_estimators=10, random_state=seed)
'''
MONITOR UPDATE STARTS
'''
monitor.iloc[1,1:] = 'Initializing CV'
update_display(monitor, display_id = 'monitor')
'''
MONITOR UPDATE ENDS
'''
fold_num = 1
for train_i , test_i in kf.split(data_X,data_y):
t0 = time.time()
'''
MONITOR UPDATE STARTS
'''
monitor.iloc[1,1:] = 'Fitting Fold ' + str(fold_num) + ' of ' + str(fold)
update_display(monitor, display_id = 'monitor')
'''
MONITOR UPDATE ENDS
'''
Xtrain,Xtest = data_X.iloc[train_i], data_X.iloc[test_i]
ytrain,ytest = data_y.iloc[train_i], data_y.iloc[test_i]
model.fit(Xtrain,ytrain)
pred_ = model.predict(Xtest)
mae = metrics.mean_absolute_error(ytest,pred_)
mse = metrics.mean_squared_error(ytest,pred_)
rmse = np.sqrt(mse)
r2 = metrics.r2_score(ytest,pred_)
max_error_ = metrics.max_error(ytest,pred_)
score_mae = np.append(score_mae,mae)
score_mse = np.append(score_mse,mse)
score_rmse = np.append(score_rmse,rmse)
score_r2 =np.append(score_r2,r2)
score_max_error = np.append(score_max_error,max_error_)
progress.value += 1
'''
This section handles time calculation and is created to update_display() as code loops through
the fold defined.
'''
fold_results = pd.DataFrame({'MAE':[mae], 'MSE': [mse], 'RMSE': [rmse],
'R2': [r2], 'ME': [max_error_] }).round(round)
master_display = pd.concat([master_display, fold_results],ignore_index=True)
fold_results = []
'''
TIME CALCULATION SUB-SECTION STARTS HERE
'''
t1 = time.time()
tt = (t1 - t0) * (fold-fold_num) / 60
tt = np.around(tt, 2)
if tt < 1:
tt = str(np.around((tt * 60), 2))
ETC = tt + ' Seconds Remaining'
else:
tt = str (tt)
ETC = tt + ' Minutes Remaining'
'''
MONITOR UPDATE STARTS
'''
monitor.iloc[2,1:] = ETC
update_display(monitor, display_id = 'monitor')
'''
MONITOR UPDATE ENDS
'''
fold_num += 1
'''
TIME CALCULATION ENDS HERE
'''
if verbose:
update_display(master_display, display_id = display_id)
'''
Update_display() ends here
'''
mean_mae=np.mean(score_mae)
mean_mse=np.mean(score_mse)
mean_rmse=np.mean(score_rmse)
mean_r2=np.mean(score_r2)
mean_max_error=np.mean(score_max_error)
std_mae=np.std(score_mae)
std_mse=np.std(score_mse)
std_rmse=np.std(score_rmse)
std_r2=np.std(score_r2)
std_max_error=np.std(score_max_error)
avgs_mae = np.append(avgs_mae, mean_mae)
avgs_mae = np.append(avgs_mae, std_mae)
avgs_mse = np.append(avgs_mse, mean_mse)
avgs_mse = np.append(avgs_mse, std_mse)
avgs_rmse = np.append(avgs_rmse, mean_rmse)
avgs_rmse = np.append(avgs_rmse, std_rmse)
avgs_r2 = np.append(avgs_r2, mean_r2)
avgs_r2 = np.append(avgs_r2, std_r2)
avgs_max_error = np.append(avgs_max_error, mean_max_error)
avgs_max_error = np.append(avgs_max_error, std_max_error)
progress.value += 1
model_results = pd.DataFrame({'MAE': score_mae, 'MSE': score_mse, 'RMSE' : score_rmse, 'R2' : score_r2,
'ME' : score_max_error})
model_avgs = pd.DataFrame({'MAE': avgs_mae, 'MSE': avgs_mse, 'RMSE' : avgs_rmse, 'R2' : avgs_r2 ,
'ME' : avgs_max_error},index=['Mean', 'SD'])
model_results = model_results.append(model_avgs)
model_results = model_results.round(round)
#refitting the model on complete X_train, y_train
monitor.iloc[1,1:] = 'Compiling Final Model'
update_display(monitor, display_id = 'monitor')
model.fit(data_X, data_y)
progress.value += 1
#storing into experiment
tup = (full_name,model)
experiment__.append(tup)
nam = str(full_name) + ' Score Grid'
tup = (nam, model_results)
experiment__.append(tup)
if verbose:
clear_output()
display(model_results)
return model
else:
clear_output()
return model
def ensemble_model(estimator,
method = 'Bagging',
fold = 10,
n_estimators = 10,
round = 4,
verbose = True):
"""
Description:
------------
This function ensemble the trained base estimator using method defined in 'method'
param (by default method = 'Bagging'). The output prints the score grid that shows
MAE, MSE, RMSE, R2 and Max Error (ME) by fold (default CV = 10 Folds).
Function also returns a trained model object that can be used for further
processing in pycaret or can be used to call any method available in sklearn.
Model must be created using create_model() or tune_model() in pycaret or using any
other package that returns sklearn object.
Example:
--------
ensembled_lr = ensemble_model(lr)
This will return ensembled Linear Regression.
variable 'lr' is created used lr = create_model('lr')
Using ensemble = True and method = 'Bagging' in create_model() is equivalent
to using ensemble_model(lr) where lr is created using create_model().
Parameters
----------