-
Notifications
You must be signed in to change notification settings - Fork 10
/
pywedge.py
4706 lines (4032 loc) · 256 KB
/
pywedge.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
class Pywedge_Charts():
'''
Makes 8 different types of interactive Charts with interactive axis selection widgets in a single line of code for the given dataset.
Different types of Charts viz,
1. Scatter Plot
2. Pie Chart
3. Bar Plot
4. Violin Plot
5. Box Plot
6. Distribution Plot
7. Histogram
8. Correlation Plot
Inputs:
1. Dataframe
2. c = any redundant column to be removed (like ID column etc., at present supports a single column removal, subsequent version will provision multiple column removal requirements)
3. y = target column name as a string
Returns:
Charts widget
'''
def __init__(self, train, c, y, manual=True):
self.train = train
self.c = c
self.y = y
self.X = self.train.drop(self.y,1)
self.manual = manual
def make_charts(self):
import pandas as pd
import ipywidgets as widgets
import plotly.express as px
import plotly.figure_factory as ff
import plotly.offline as pyo
from ipywidgets import HBox, VBox, Button
from ipywidgets import interact, interact_manual, interactive
import plotly.graph_objects as go
from plotly.offline import iplot
header = widgets.HTML(value="<h2>Pywedge Make_Charts </h2>")
display(header)
if len(self.train) > 500:
from sklearn.model_selection import train_test_split
test_size = 500/len(self.train)
if self.c!=None:
data = self.X.drop(self.c,1)
else:
data = self.X
target = self.train[self.y]
X_train, X_test, y_train, y_test = train_test_split(data, target, test_size=test_size, random_state=1)
train_mc = pd.concat([X_test, y_test], axis=1)
else:
train_mc = self.train
train_numeric = train_mc.select_dtypes('number')
train_cat = train_mc.select_dtypes(exclude='number')
out1 = widgets.Output()
out2 = widgets.Output()
out3 = widgets.Output()
out4 = widgets.Output()
out5 = widgets.Output()
out6 = widgets.Output()
out7 = widgets.Output()
out8 = widgets.Output()
out8 = widgets.Output()
tab = widgets.Tab(children = [out1, out2, out3, out4, out5, out6, out7, out8])
tab.set_title(0, 'Scatter Plot')
tab.set_title(1, 'Pie Chart')
tab.set_title(2, 'Bar Plot')
tab.set_title(3, 'Violin Plot')
tab.set_title(4, 'Box Plot')
tab.set_title(5, 'Distribution Plot')
tab.set_title(6, 'Histogram')
tab.set_title(7, 'Correlation plot')
display(tab)
with out1:
header = widgets.HTML(value="<h1>Scatter Plots </h1>")
display(header)
x = widgets.Dropdown(options=list(train_mc.select_dtypes('number').columns))
def scatter_plot(X_Axis=list(train_mc.select_dtypes('number').columns),
Y_Axis=list(train_mc.select_dtypes('number').columns)[1:],
Color=list(train_mc.select_dtypes('number').columns)):
fig = go.FigureWidget(data=go.Scatter(x=train_mc[X_Axis],
y=train_mc[Y_Axis],
mode='markers',
text=list(train_cat),
marker_color=train_mc[Color]))
fig.update_layout(title=f'{Y_Axis.title()} vs {X_Axis.title()}',
xaxis_title=f'{X_Axis.title()}',
yaxis_title=f'{Y_Axis.title()}',
autosize=False,width=600,height=600)
fig.show()
widgets.interact_manual.opts['manual_name'] = 'Make_Chart'
one = interactive(scatter_plot, {'manual': self.manual, 'manual_name':'Make_Chart'})
two = interactive(scatter_plot, {'manual': self.manual, 'manual_name':'Make_Chart'})
three = interactive(scatter_plot, {'manual': self.manual, 'manual_name':'Make_Chart'})
four = interactive(scatter_plot, {'manual': self.manual, 'manual_name':'Make_Chart'})
g = widgets.HBox([one, two])
h = widgets.HBox([three, four])
i = widgets.VBox([g,h])
display(i)
with out2:
header = widgets.HTML(value="<h1>Pie Charts </h1>")
display(header)
def pie_chart(Labels=list(train_mc.select_dtypes(exclude='number').columns),
Values=list(train_mc.select_dtypes('number').columns)[0:]):
fig = go.FigureWidget(data=[go.Pie(labels=train_mc[Labels], values=train_mc[Values])])
fig.update_layout(title=f'{Values.title()} vs {Labels.title()}',
autosize=False,width=500,height=500)
fig.show()
one = interactive(pie_chart, {'manual': self.manual, 'manual_name':'Make_Chart'})
two = interactive(pie_chart, {'manual': self.manual, 'manual_name':'Make_Chart'})
three = interactive(pie_chart, {'manual': self.manual, 'manual_name':'Make_Chart'})
four = interactive(pie_chart, {'manual': self.manual, 'manual_name':'Make_Chart'})
g = widgets.HBox([one, two])
h = widgets.HBox([three, four])
i = widgets.VBox([g,h])
display(i)
with out3:
header = widgets.HTML(value="<h1>Bar Plots </h1>")
display(header)
def bar_plot(X_Axis=list(train_mc.select_dtypes(exclude='number').columns),
Y_Axis=list(train_mc.select_dtypes('number').columns)[1:],
Color=list(train_mc.select_dtypes(exclude='number').columns)):
fig1 = px.bar(train_mc, x=train_mc[X_Axis], y=train_mc[Y_Axis], color=train_mc[Color])
fig1.update_layout(barmode='group',
title=f'{X_Axis.title()} vs {Y_Axis.title()}',
xaxis_title=f'{X_Axis.title()}',
yaxis_title=f'{Y_Axis.title()}',
autosize=False,width=600,height=600)
fig1.show()
one = interactive(bar_plot, {'manual': self.manual, 'manual_name':'Make_Chart'})
two = interactive(bar_plot, {'manual': self.manual, 'manual_name':'Make_Chart'})
three = interactive(bar_plot, {'manual': self.manual, 'manual_name':'Make_Chart'})
four = interactive(bar_plot, {'manual': self.manual, 'manual_name':'Make_Chart'})
g = widgets.HBox([one, two])
h = widgets.HBox([three, four])
i = widgets.VBox([g,h])
display(i)
with out4:
header = widgets.HTML(value="<h1>Violin Plots </h1>")
display(header)
def viol_plot(X_Axis=list(train_mc.select_dtypes('number').columns),
Y_Axis=list(train_mc.select_dtypes('number').columns)[1:],
Color=list(train_mc.select_dtypes(exclude='number').columns)):
fig2 = px.violin(train_mc, X_Axis, Y_Axis, Color, box=True, hover_data=train_mc.columns)
fig2.update_layout(title=f'{X_Axis.title()} vs {Y_Axis.title()}',
xaxis_title=f'{X_Axis.title()}',
autosize=False,width=600,height=600)
fig2.show()
one = interactive(viol_plot, {'manual': self.manual, 'manual_name':'Make_Chart'})
two = interactive(viol_plot, {'manual': self.manual, 'manual_name':'Make_Chart'})
three = interactive(viol_plot, {'manual': self.manual, 'manual_name':'Make_Chart'})
four = interactive(viol_plot, {'manual': self.manual, 'manual_name':'Make_Chart'})
g = widgets.HBox([one, two])
h = widgets.HBox([three, four])
i = widgets.VBox([g,h])
display(i)
with out5:
header = widgets.HTML(value="<h1>Box Plots </h1>")
display(header)
def box_plot(X_Axis=list(train_mc.select_dtypes(exclude='number').columns),
Y_Axis=list(train_mc.select_dtypes('number').columns)[0:],
Color=list(train_mc.select_dtypes(exclude='number').columns)):
fig4 = px.box(train_mc, x=X_Axis, y=Y_Axis, color=Color, points="all")
fig4.update_layout(barmode='group',
title=f'{X_Axis.title()} vs {Y_Axis.title()}',
xaxis_title=f'{X_Axis.title()}',
yaxis_title=f'{Y_Axis.title()}',
autosize=False,width=600,height=600)
fig4.show()
one = interactive(box_plot, {'manual': self.manual, 'manual_name':'Make_Chart'})
two = interactive(box_plot, {'manual': self.manual, 'manual_name':'Make_Chart'})
three = interactive(box_plot, {'manual': self.manual, 'manual_name':'Make_Chart'})
four = interactive(box_plot, {'manual': self.manual, 'manual_name':'Make_Chart'})
g = widgets.HBox([one, two])
h = widgets.HBox([three, four])
i = widgets.VBox([g,h])
display(i)
with out6:
header = widgets.HTML(value="<h1>Distribution Plots </h1>")
display(header)
def dist_plot(X_Axis=list(train_mc.select_dtypes('number').columns),
Y_Axis=list(train_mc.select_dtypes('number').columns)[1:],
Color=list(train_mc.select_dtypes(exclude='number').columns)):
fig2 = px.histogram(train_mc, X_Axis, Y_Axis, Color, marginal='violin', hover_data=train_mc.columns)
fig2.update_layout(title=f'{X_Axis.title()} vs {Y_Axis.title()}',
xaxis_title=f'{X_Axis.title()}',
autosize=False,width=600,height=600)
fig2.show()
one = interactive(dist_plot, {'manual': self.manual, 'manual_name':'Make_Chart'})
two = interactive(dist_plot, {'manual': self.manual, 'manual_name':'Make_Chart'})
three = interactive(dist_plot, {'manual': self.manual, 'manual_name':'Make_Chart'})
four = interactive(dist_plot, {'manual': self.manual, 'manual_name':'Make_Chart'})
g = widgets.HBox([one, two])
h = widgets.HBox([three, four])
i = widgets.VBox([g,h])
display(i)
with out7:
header = widgets.HTML(value="<h1>Histogram </h1>")
display(header)
def hist_plot(X_Axis=list(train_mc.columns)):
fig2 = px.histogram(train_mc, X_Axis)
fig2.update_layout(title=f'{X_Axis.title()}',
xaxis_title=f'{X_Axis.title()}',
autosize=False,width=600,height=600)
fig2.show()
one = interactive(hist_plot, {'manual': self.manual, 'manual_name':'Make_Chart'})
two = interactive(hist_plot, {'manual': self.manual, 'manual_name':'Make_Chart'})
three = interactive(hist_plot, {'manual': self.manual, 'manual_name':'Make_Chart'})
four = interactive(hist_plot, {'manual': self.manual, 'manual_name':'Make_Chart'})
g = widgets.HBox([one, two])
h = widgets.HBox([three, four])
i = widgets.VBox([g,h])
display(i)
with out8:
header = widgets.HTML(value="<h1>Correlation Plots </h1>")
display(header)
import plotly.figure_factory as ff
corrs = train_mc.corr()
colorscale = ['Greys', 'Greens', 'Bluered', 'RdBu',
'Reds', 'Blues', 'Picnic', 'Rainbow', 'Portland', 'Jet',
'Hot', 'Blackbody', 'Earth', 'Electric', 'Viridis', 'Cividis']
@interact_manual
def plot_corrs(colorscale=colorscale):
figure = ff.create_annotated_heatmap(z = corrs.round(2).values,
x =list(corrs.columns),
y=list(corrs.index),
colorscale=colorscale,
annotation_text=corrs.round(2).values)
iplot(figure)
class baseline_model():
'''
Cleans the raw dataframe to fed into ML models and runs various baseline models. Following data pre_processing will be carried out,
1) segregating numeric & categorical columns
2) missing values imputation for numeric & categorical columns
3) standardization
4) feature importance
5) SMOTE
6) baseline model
Inputs:
1) train = train dataframe
2) test = stand out test dataframe (without target column)
2) c = any redundant column to be removed (like ID column etc., at present supports a single column removal, subsequent version will provision multiple column removal requirements)
3) y = target column name as a string
4) type = Classification / Regression
Returns:
1) Various classification/regressions models & model performances
2) new_X (cleaned feature columns in dataframe)
3) new_y (cleaned target column in dataframe)
4) new_test (cleaned stand out test dataframe
'''
def __init__(self, train, test, c, y, type="Classification"):
self.train = train
self.test = test
self.c = c
self.y = y
self.type = type
self.X = train.drop(self.y,1)
def classification_summary(self):
import ipywidgets as widgets
from ipywidgets import HBox, VBox, Button
from IPython.display import display, Markdown, clear_output
header = widgets.HTML(value="<h2>Pywedge Baseline Models </h2>")
display(header)
out1 = widgets.Output()
out2 = widgets.Output()
tab = widgets.Tab(children = [out1, out2])
tab.set_title(0,'Baseline Models')
tab.set_title(1, 'Predict Baseline Model')
display(tab)
with out1:
import ipywidgets as widgets
from ipywidgets import HBox, VBox, Button
from IPython.display import display, Markdown, clear_output
header = widgets.HTML(value="<h2>Pre_processing </h2>")
display(header)
import pandas as pd
cat_info = widgets.Dropdown(
options = [('cat_codes', '1'), ('get_dummies', '2')],
value = '1',
description = 'Select categorical conversion',
style = {'description_width': 'initial'},
disabled=False)
std_scr = widgets.Dropdown(
options = [('StandardScalar', '1'), ('RobustScalar', '2'), ('MinMaxScalar', '3'), ('No Standardization', 'n')],
value = 'n',
description = 'Select Standardization methods',
style = {'description_width': 'initial'},
disabled=False)
apply_smote = widgets.Dropdown(
options = [('Yes', 'y'), ('No', 'n')],
value = 'y',
description = 'Do you want to apply SMOTE?',
style = {'description_width': 'initial'},
disabled=False)
pp_class = widgets.VBox([cat_info, std_scr, apply_smote])
pp_reg = widgets.VBox([cat_info, std_scr])
if self.type == 'Classification':
display(pp_class)
else:
display(pp_reg)
test_size = widgets.BoundedFloatText(
value=0.20,
min=0.05,
max=0.5,
step=0.05,
description='Text Size %',
disabled=False)
display(test_size)
button_1 = widgets.Button(description = 'Run Baseline models')
out = widgets.Output()
def on_button_clicked(_):
with out:
clear_output()
import pandas as pd
self.new_X = self.X.copy(deep=True)
self.new_y = self.y
self.new_test = self.test.copy(deep=True)
categorical_cols = self.new_X.select_dtypes('object').columns.to_list()
for col in categorical_cols:
self.new_X[col].fillna(self.new_X[col].mode()[0], inplace=True)
numeric_cols = self.new_X.select_dtypes(['float64', 'int64']).columns.to_list()
for col in numeric_cols:
self.new_X[col].fillna(self.new_X[col].mean(), inplace=True)
test_categorical_cols = self.new_test.select_dtypes('object').columns.to_list()
for col in test_categorical_cols:
self.new_test[col].fillna(self.new_test[col].mode()[0], inplace=True)
numeric_cols = self.new_test.select_dtypes(['float64', 'int64']).columns.to_list()
for col in numeric_cols:
self.new_test[col].fillna(self.new_test[col].mean(), inplace=True)
if cat_info.value == '1':
for col in categorical_cols:
self.new_X[col] = self.new_X[col].astype('category')
self.new_X[col] = self.new_X[col].cat.codes
self.new_test[col] = self.new_test[col].astype('category')
self.new_test[col] = self.new_test[col].cat.codes
print('> Categorical columns converted using Catcodes')
if cat_info.value == '2':
self.new_X = pd.get_dummies(self.new_X,drop_first=True)
self.new_test = pd.get_dummies(self.new_test,drop_first=True)
print('> Categorical columns converted using Get_Dummies')
self.new_y = pd.DataFrame(self.train[[self.y]])
self.new_y = pd.get_dummies(self.new_y,drop_first=True)
if std_scr.value == '1':
from sklearn.preprocessing import StandardScaler
scalar = StandardScaler()
self.new_X = pd.DataFrame(scalar.fit_transform(self.new_X), columns=self.new_X.columns, index=self.new_X.index)
self.new_test = pd.DataFrame(scalar.fit_transform(self.new_test), columns=self.new_test.columns, index=self.new_test.index)
print('> standardization using Standard Scalar completed')
elif std_scr.value == '2':
from sklearn.preprocessing import RobustScaler
scalar = RobustScaler()
self.new_X= pd.DataFrame(scalar.fit_transform(self.new_X), columns=self.new_X.columns, index=self.new_X.index)
self.new_test= pd.DataFrame(scalar.fit_transform(self.new_test), columns=self.new_test.columns, index=self.new_test.index)
print('> standardization using Roubust Scalar completed')
elif std_scr.value == '3':
from sklearn.preprocessing import MinMaxScaler
scalar = MinMaxScaler()
self.new_X= pd.DataFrame(scalar.fit_transform(self.new_X), columns=self.new_X.columns, index=self.new_X.index)
self.new_test= pd.DataFrame(scalar.fit_transform(self.new_test), columns=self.new_test.columns, index=self.new_test.index)
print('> standardization using Minmax Scalar completed')
elif std_scr.value == 'n':
print('> No standardization done')
if self.type=="Classification":
if apply_smote.value == 'y':
from imblearn.over_sampling import SMOTE
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
from sklearn.exceptions import DataConversionWarning
warnings.filterwarnings(action='ignore', category=DataConversionWarning)
warnings.filterwarnings('ignore', 'FutureWarning')
sm = SMOTE(random_state=42, n_jobs=-1)
new_X_cols = self.new_X.columns
new_y_cols = self.new_y.columns
self.new_X, self.new_y= sm.fit_resample(self.new_X, self.new_y)
self.new_X = pd.DataFrame(self.new_X, columns=new_X_cols)
self.new_y= pd.DataFrame(self.new_y, columns=new_y_cols)
print('> Oversampling using SMOTE completed')
else:
print('> No oversampling done')
print('\nStarting classification_summary...')
print('TOP 10 FEATURE IMPORTANCE - USING ADABOOST CLASSIFIER')
from sklearn.ensemble import AdaBoostClassifier
import pandas as pd
import warnings
warnings.filterwarnings('ignore')
ab = AdaBoostClassifier().fit(self.new_X, self.new_y)
print(pd.Series(ab.feature_importances_, index=self.new_X.columns).sort_values(ascending=False).head(10))
from sklearn.model_selection import train_test_split
self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(
self.new_X.values, self.new_y.values, test_size=test_size.value, random_state=1)
from sklearn.neural_network import MLPClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.svm import LinearSVC
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF
from sklearn.tree import DecisionTreeClassifier
from sklearn.experimental import enable_hist_gradient_boosting
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier, GradientBoostingClassifier, ExtraTreesClassifier, HistGradientBoostingClassifier
from catboost import CatBoostClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
from sklearn.linear_model import LogisticRegression
import xgboost as xgb
from sklearn.metrics import accuracy_score, f1_score
from sklearn.metrics import roc_auc_score
import warnings
warnings.filterwarnings('ignore')
from tqdm.notebook import trange, tqdm
classifiers = {
"Logistic" : LogisticRegression(n_jobs=-1),
"KNN(3)" : KNeighborsClassifier(3, n_jobs=-1),
"Decision Tree": DecisionTreeClassifier(max_depth=7),
"Random Forest": RandomForestClassifier(max_depth=7, n_estimators=10, max_features=4, n_jobs=-1),
"AdaBoost" : AdaBoostClassifier(),
"GB Classifier": GradientBoostingClassifier(),
"ExtraTree Cls": ExtraTreesClassifier(n_jobs=-1),
"Hist GB Cls" : HistGradientBoostingClassifier(),
"MLP Cls." : MLPClassifier(alpha=1),
"XGBoost" : xgb.XGBClassifier(max_depth=4, n_estimators=10, learning_rate=0.1, n_jobs=-1),
"CatBoost" : CatBoostClassifier(silent=True),
"Naive Bayes" : GaussianNB(),
"QDA" : QuadraticDiscriminantAnalysis(),
"Linear SVC" : LinearSVC(),
}
from time import time
k = 14
head = list(classifiers.items())[:k]
for name, classifier in tqdm(head):
start = time()
classifier.fit(self.X_train, self.y_train)
train_time = time() - start
start = time()
predictions = classifier.predict(self.X_test)
predict_time = time()-start
acc_score= (accuracy_score(self.y_test,predictions))
roc_score= (roc_auc_score(self.y_test,predictions))
f1_macro= (f1_score(self.y_test, predictions, average='macro'))
print("{:<15}| acc_score = {:.3f} | roc_score = {:,.3f} | f1_score(macro) = {:,.3f} | Train time = {:,.3f}s | Pred. time = {:,.3f}s".format(name, acc_score, roc_score, f1_macro, train_time, predict_time))
button_1.on_click(on_button_clicked)
a = widgets.VBox([button_1, out])
display(a)
with out2:
base_model = widgets.Dropdown(
options=['Logistic Regression', 'KNN', 'Decision Tree', 'Random Forest', 'MLP Classifier', 'AdaBoost', 'CatBoost', 'GB Classifier', 'ExtraTree Cls', 'Hist GB Cls' ],
value='Logistic Regression',
description='Choose Base Model: ',
style = {'description_width': 'initial'},
disabled=False)
display(base_model)
button_2 = widgets.Button(description = 'Predict Baseline models')
out2 = widgets.Output()
def on_pred_button_clicked(_):
with out2:
from sklearn.neural_network import MLPClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier, GradientBoostingClassifier, ExtraTreesClassifier, HistGradientBoostingClassifier
from catboost import CatBoostClassifier
from sklearn.linear_model import LogisticRegression
import xgboost as xgb
clear_output()
print(base_model.value)
if base_model.value == 'Logistic Regression':
classifier = LogisticRegression(max_iter=1000, n_jobs=-1)
classifier.fit(self.X_train, self.y_train)
self.predictions_baseline = classifier.predict(self.new_test)
print('> Prediction completed. \n> Use dot operator in below code cell to access predict, for eg., blm.predictions_baseline, where blm is pywedge_baseline_model class object')
if base_model.value == 'KNN':
classifier = KNeighborsClassifier(3, n_jobs=-1)
classifier.fit(self.X_train, self.y_train)
self.predictions_baseline = classifier.predict(self.new_test)
print('Prediction completed. \nUse dot operator in below code cell to access predict, for eg., blm.predictions_baseline, where blm is pywedge_baseline_model class object')
if base_model.value == 'Decision Tree':
classifier = DecisionTreeClassifier(max_depth=7)
classifier.fit(self.X_train, self.y_train)
self.predictions_baseline = classifier.predict(self.new_test)
print('Prediction completed. \nUse dot operator in below code cell to access predict, for eg., blm.predictions_baseline, where blm is pywedge_baseline_model class object')
if base_model.value == 'Random Forest':
classifier = RandomForestClassifier(max_depth=7, n_estimators=10, max_features=4, n_jobs=-1)
classifier.fit(self.X_train, self.y_train)
self.predictions_baseline = classifier.predict(self.new_test)
print('Prediction completed. \nUse dot operator in below code cell to access predict, for eg., blm.predictions_baseline, where blm is pywedge_baseline_model class object')
if base_model.value == 'MLP Classifier':
classifier = MLPClassifier(alpha=1)
classifier.fit(self.X_train, self.y_train)
self.predictions_baseline = classifier.predict(self.new_test)
print('Prediction completed. \nUse dot operator in below code cell to access predict, for eg., blm.predictions_baseline, where blm is pywedge_baseline_model class object')
if base_model.value == 'AdaBoost':
classifier = AdaBoostClassifier()
classifier.fit(self.X_train, self.y_train)
self.predictions_baseline = classifier.predict(self.new_test)
print('Prediction completed. \nUse dot operator in below code cell to access predict, for eg., blm.predictions_baseline, where blm is pywedge_baseline_model class object')
if base_model.value == 'CatBoost':
classifier = CatBoostClassifier(silent=True)
classifier.fit(self.X_train, self.y_train)
self.predictions_baseline = classifier.predict(self.new_test)
print('Prediction completed. \nUse dot operator in below code cell to access predict, for eg., blm.predictions_baseline, where blm is pywedge_baseline_model class object')
if base_model.value == 'GB Classifier':
classifier = GradientBoostingClassifier()
classifier.fit(self.X_train, self.y_train)
self.predictions_baseline = classifier.predict(self.new_test)
self.predict_proba_baseline = classifier.predict_proba(self.new_test)
print('Prediction completed. \nUse dot operator in below code cell to access predict, for eg., blm.predictions_baseline (for predictions) & blm.predict_proba_baseline (for predict_proba), where blm is pywedge_baseline_model class object')
if base_model.value == 'ExtraTree Cls':
classifier = ExtraTreesClassifier(n_jobs=-1)
classifier.fit(self.X_train, self.y_train)
self.predictions_baseline = classifier.predict(self.new_test)
self.predict_proba_baseline = classifier.predict_proba(self.new_test)
print('Prediction completed. \nUse dot operator in below code cell to access predict, for eg., blm.predictions_baseline (for predictions) & blm.predict_proba_baseline (for predict_proba), where blm is pywedge_baseline_model class object')
if base_model.value == 'Hist GB Cls':
classifier = HistGradientBoostingClassifier()
classifier.fit(self.X_train, self.y_train)
self.predictions_baseline = classifier.predict(self.new_test)
self.predict_proba_baseline = classifier.predict_proba(self.new_test)
print('Prediction completed. \nUse dot operator in below code cell to access predict, for eg., blm.predictions_baseline (for predictions) & blm.predict_proba_baseline (for predict_proba), where blm is pywedge_baseline_model class object')
button_2.on_click(on_pred_button_clicked)
b = widgets.VBox([button_2, out2])
display(b)
def Regression_summary(self):
import ipywidgets as widgets
from ipywidgets import HBox, VBox, Button
from IPython.display import display, Markdown, clear_output
header = widgets.HTML(value="<h2>Pywedge Baseline Models </h2>")
display(header)
out1 = widgets.Output()
out2 = widgets.Output()
tab = widgets.Tab(children = [out1, out2])
tab.set_title(0,'Baseline Models')
tab.set_title(1, 'Predict Baseline Model')
display(tab)
with out1:
import ipywidgets as widgets
from ipywidgets import HBox, VBox, Button
from IPython.display import display, Markdown, clear_output
header = widgets.HTML(value="<h2>Pre_processing </h2>")
display(header)
import pandas as pd
cat_info = widgets.Dropdown(
options = [('cat_codes', '1'), ('get_dummies', '2')],
value = '1',
description = 'Select categorical conversion',
style = {'description_width': 'initial'},
disabled=False)
std_scr = widgets.Dropdown(
options = [('StandardScalar', '1'), ('RobustScalar', '2'), ('MinMaxScalar', '3'), ('No Standardization', 'n')],
value = 'n',
description = 'Select Standardization methods',
style = {'description_width': 'initial'},
disabled=False)
apply_smote = widgets.Dropdown(
options = [('Yes', 'y'), ('No', 'n')],
value = 'y',
description = 'Do you want to apply SMOTE?',
style = {'description_width': 'initial'},
disabled=False)
pp_class = widgets.VBox([cat_info, std_scr, apply_smote])
pp_reg = widgets.VBox([cat_info, std_scr])
if self.type == 'Classification':
display(pp_class)
else:
display(pp_reg)
test_size = widgets.BoundedFloatText(
value=0.20,
min=0.05,
max=0.5,
step=0.05,
description='Text Size %',
disabled=False)
display(test_size)
button_1 = widgets.Button(description = 'Run Baseline models')
out = widgets.Output()
def on_button_clicked(_):
with out:
clear_output()
import pandas as pd
self.new_X = self.X.copy(deep=True)
self.new_y = self.y
self.new_test = self.test.copy(deep=True)
categorical_cols = self.new_X.select_dtypes('object').columns.to_list()
for col in categorical_cols:
self.new_X[col].fillna(self.new_X[col].mode()[0], inplace=True)
numeric_cols = self.new_X.select_dtypes(['float64', 'int64']).columns.to_list()
for col in numeric_cols:
self.new_X[col].fillna(self.new_X[col].mean(), inplace=True)
test_categorical_cols = self.new_test.select_dtypes('object').columns.to_list()
for col in test_categorical_cols:
self.new_test[col].fillna(self.new_test[col].mode()[0], inplace=True)
numeric_cols = self.new_test.select_dtypes(['float64', 'int64']).columns.to_list()
for col in numeric_cols:
self.new_test[col].fillna(self.new_test[col].mean(), inplace=True)
if cat_info.value == '1':
for col in categorical_cols:
self.new_X[col] = self.new_X[col].astype('category')
self.new_X[col] = self.new_X[col].cat.codes
self.new_test[col] = self.new_test[col].astype('category')
self.new_test[col] = self.new_test[col].cat.codes
print('> Categorical columns converted using Catcodes')
if cat_info.value == '2':
self.new_X = pd.get_dummies(self.new_X,drop_first=True)
self.new_test = pd.get_dummies(self.new_test,drop_first=True)
print('> Categorical columns converted using Get_Dummies')
self.new_y = pd.DataFrame(self.train[[self.y]])
self.new_y = pd.get_dummies(self.new_y,drop_first=True)
if std_scr.value == '1':
from sklearn.preprocessing import StandardScaler
scalar = StandardScaler()
self.new_X = pd.DataFrame(scalar.fit_transform(self.new_X), columns=self.new_X.columns, index=self.new_X.index)
self.new_test = pd.DataFrame(scalar.fit_transform(self.new_test), columns=self.new_test.columns, index=self.new_test.index)
print('> standardization using Standard Scalar completed')
elif std_scr.value == '2':
from sklearn.preprocessing import RobustScaler
scalar = RobustScaler()
self.new_X= pd.DataFrame(scalar.fit_transform(self.new_X), columns=self.new_X.columns, index=self.new_X.index)
self.new_test= pd.DataFrame(scalar.fit_transform(self.new_test), columns=self.new_test.columns, index=self.new_test.index)
print('> standardization using Roubust Scalar completed')
elif std_scr.value == '3':
from sklearn.preprocessing import MinMaxScaler
scalar = MinMaxScaler()
self.new_X= pd.DataFrame(scalar.fit_transform(self.new_X), columns=self.new_X.columns, index=self.new_X.index)
self.new_test= pd.DataFrame(scalar.fit_transform(self.new_test), columns=self.new_test.columns, index=self.new_test.index)
print('> standardization using Minmax Scalar completed')
elif std_scr.value == 'n':
print('> No standardization done')
print('Starting regression summary...')
print('TOP 10 FEATURE IMPORTANCE TABLE')
from sklearn.ensemble import AdaBoostRegressor
import pandas as pd
import warnings
warnings.filterwarnings('ignore')
ab = AdaBoostRegressor().fit(self.new_X, self.new_y)
print(pd.Series(ab.feature_importances_, index=self.new_X.columns).sort_values(ascending=False).head(10))
from sklearn.model_selection import train_test_split
self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(
self.new_X.values, self.new_y.values, test_size=test_size.value, random_state=1)
from time import time
from sklearn.neighbors import KNeighborsRegressor
from sklearn.linear_model import LinearRegression
from sklearn.svm import SVR
from sklearn.svm import LinearSVR
from sklearn.linear_model import Lasso, Ridge
from sklearn.metrics import explained_variance_score
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import r2_score
from sklearn.tree import DecisionTreeRegressor
from sklearn.experimental import enable_hist_gradient_boosting
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor, AdaBoostRegressor, ExtraTreesRegressor, HistGradientBoostingRegressor
from catboost import CatBoostRegressor
from sklearn.neural_network import MLPRegressor
import xgboost as xgb
from math import sqrt
from tqdm.notebook import trange, tqdm
import warnings
warnings.filterwarnings('ignore')
print('--------------------------LINEAR MODELS---------------------------------')
lin_regressors = {
'Linear Reg' : LinearRegression(n_jobs=-1),
'KNN' : KNeighborsRegressor(n_jobs=-1),
'LinearSVR' : LinearSVR(),
'Lasso' : Lasso(),
'Ridge' : Ridge(),
}
from time import time
k = 10
head = list(lin_regressors.items())[:k]
for name, lin_regressors in tqdm(head):
start = time()
lin_regressors.fit(self.X_train, self.y_train)
train_time = time() - start
start = time()
predictions = lin_regressors.predict(self.X_test)
predict_time = time()-start
exp_var = explained_variance_score(self.y_test, predictions)
mae = mean_absolute_error(self.y_test, predictions)
rmse = sqrt(mean_absolute_error(self.y_test, predictions))
r2 = r2_score(self.y_test, predictions)
print("{:<15}| exp_var = {:.3f} | mae = {:,.3f} | rmse = {:,.3f} | r2 = {:,.3f} | Train time = {:,.3f}s | Pred. time = {:,.3f}s".format(name, exp_var, mae, rmse, r2, train_time, predict_time))
print('------------------------NON LINEAR MODELS----------------------------------')
print('---------------------THIS MIGHT TAKE A WHILE-------------------------------')
non_lin_regressors = {
#'SVR' : SVR(),
'Decision Tree' : DecisionTreeRegressor(max_depth=5),
'Random Forest' : RandomForestRegressor(max_depth=10, n_jobs=-1),
'GB Regressor' : GradientBoostingRegressor(n_estimators=200),
'CB Regressor' : CatBoostRegressor(silent=True),
'ADAB Regressor': AdaBoostRegressor(),
'MLP Regressor' : MLPRegressor(),
'XGB Regressor' : xgb.XGBRegressor(n_jobs=-1),
'Extra tree Reg': ExtraTreesRegressor(n_jobs=-1),
'Hist GB Reg' : HistGradientBoostingRegressor()
}
from time import time
k = 10
head = list(non_lin_regressors.items())[:k]
for name, non_lin_regressors in tqdm(head):
start = time()
non_lin_regressors.fit(self.X_train, self.y_train)
train_time = time() - start
start = time()
predictions = non_lin_regressors.predict(self.X_test)
predict_time = time()-start
exp_var = explained_variance_score(self.y_test, predictions)
mae = mean_absolute_error(self.y_test, predictions)
rmse = sqrt(mean_absolute_error(self.y_test, predictions))
r2 = r2_score(self.y_test, predictions)
print("{:<15}| exp_var = {:.3f} | mae = {:,.3f} | rmse = {:,.3f} | r2 = {:,.3f} | Train time = {:,.3f}s | Pred. time = {:,.3f}s".format(name, exp_var, mae, rmse, r2, train_time, predict_time))
button_1.on_click(on_button_clicked)
a = widgets.VBox([button_1, out])
display(a)
with out2:
base_model = widgets.Dropdown(
options=['Linear Regression', 'KNN', 'Decision Tree', 'Random Forest', 'MLP Regressor', 'AdaBoost', 'Grad-Boost''CatBoost'],
value='Linear Regression',
description='Choose Base Model: ',
style = {'description_width': 'initial'},
disabled=False)
display(base_model)
button_2 = widgets.Button(description = 'Predict Baseline models')
out2 = widgets.Output()
def on_pred_button_clicked(_):
with out2:
from sklearn.neighbors import KNeighborsRegressor
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor, AdaBoostRegressor
from catboost import CatBoostRegressor
from sklearn.neural_network import MLPRegressor
import xgboost as xgb
clear_output()
print(base_model.value)
if base_model.value == 'Linear Regression':
regressor = LinearRegression()
regressor.fit(self.X_train, self.y_train)
self.predictions_baseline = regressor.predict(self.new_test)
print('Prediction completed. \nUse dot operator in below code cell to access predict, for eg., blm.predictions_baseline, where blm is pywedge_baseline_model class object')
if base_model.value == 'KNN':
regressor = KNeighborsRegressor()
regressor.fit(self.X_train, self.y_train)
self.predictions_baseline = regressor.predict(self.new_test)
print('Prediction completed. \nUse dot operator in below code cell to access predict, for eg., blm.predictions_baseline, where blm is pywedge_baseline_model class object')
if base_model.value == 'Decision Tree':
regressor = DecisionTreeRegressor(max_depth=5)
regressor.fit(self.X_train, self.y_train)
self.predictions_baseline = regressor.predict(self.new_test)
print('Prediction completed. \nUse dot operator in below code cell to access predict, for eg., blm.predictions_baseline, where blm is pywedge_baseline_model class object')
if base_model.value == 'Random Forest':
regressor = RandomForestRegressor(max_depth=10)
regressor.fit(self.X_train, self.y_train)
self.predictions_baseline = regressor.predict(self.new_test)
print('Prediction completed. \nUse dot operator in below code cell to access predict, for eg., blm.predictions_baseline, where blm is pywedge_baseline_model class object')
if base_model.value == 'MLP Regressor':
regressor = MLPRegressor()
regressor.fit(self.X_train, self.y_train)
self.predictions_baseline = regressor.predict(self.new_test)
print('Prediction completed. \nUse dot operator in below code cell to access predict, for eg., blm.predictions_baseline, where blm is pywedge_baseline_model class object')
if base_model.value == 'AdaBoost':
regressor = AdaBoostRegressor()
regressor.fit(self.X_train, self.y_train)
self.predictions_baseline = regressor.predict(self.new_test)
print('Prediction completed. \nUse dot operator in below code cell to access predict, for eg., blm.predictions_baseline, where blm is pywedge_baseline_model class object')
if base_model.value == 'Grad-Boost':
regressor = GradientBoostingRegressor(n_estimators=200)
regressor.fit(self.X_train, self.y_train)
self.predictions_baseline = regressor.predict(self.new_test)
print('Prediction completed. \nUse dot operator in below code cell to access predict, for eg., blm.predictions_baseline, where blm is pywedge_baseline_model class object')
if base_model.value == 'CatBoost':
regressor = CatBoostRegressor(silent=True)
regressor.fit(self.X_train, self.y_train)
self.predictions_baseline = regressor.predict(self.new_test)
print('Prediction completed. \nUse dot operator in below code cell to access predict, for eg., blm.predictions_baseline, where blm is pywedge_baseline_model class object')
button_2.on_click(on_pred_button_clicked)
b = widgets.VBox([button_2, out2])
display(b)
class Pywedge_HP():
'''
Creates interative widget based Hyperparameter selection tool for both Classification & Regression.
For Classification, following baseline estimators are covered in Gridsearch & Randomized search options
1) Logistic Regression
2) Decision Tree
3) Random Forest
4) KNN Classifier
For Regression, following baseline estimators are covered in Gridsearch & Randomized search options
1) Linear Regression
2) Decision Tree Regressor
3) Random Forest Regressor
4) KNN Regressor
Inputs:
1) train = train dataframe
2) test = stand out test dataframe (without target column)
3) c = any redundant column to be removed (like ID column etc., at present supports a single column removal,
subsequent version will provision multiple column removal requirements)
4) y = target column name as a string
Ouputs:
1) Hyperparameter tuning results
2) Prediction on standout test dataset
'''
def __init__(self, train, test, c, y, tracking=False):
self.train = train
self.test = test
self.c = c
self.y = y
self.X = train.drop(self.y,1)
self.tracking = tracking
def HP_Tune_Classification(self):
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier, ExtraTreesClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV
import ipywidgets as widgets
from ipywidgets import HBox, VBox, Button, Label
from ipywidgets import interact_manual, interactive, interact
import logging
from IPython.display import display, Markdown, clear_output
import warnings
warnings.filterwarnings('ignore')
header_1 = widgets.HTML(value="<h2>Pywedge HP_Tune</h2>")
display(header_1)
out1 = widgets.Output()
out2 = widgets.Output()
out3 = widgets.Output()
tab = widgets.Tab(children = [out1, out2, out3])
tab.set_title(0, 'Input')
tab.set_title(1, 'Output')
tab.set_title(2, 'Helper Page')
display(tab)
with out1:
header = widgets.HTML(value="<h3>Base Estimator</h3>")
display(header)
import pandas as pd
cat_info = widgets.Dropdown(
options = [('cat_codes', '1'), ('get_dummies', '2')],
value = '1',
description = 'Select categorical conversion',
style = {'description_width': 'initial'},
disabled=False)
std_scr = widgets.Dropdown(
options = [('StandardScalar', '1'), ('RobustScalar', '2'), ('MinMaxScalar', '3'), ('No Standardization', 'n')],
value = 'n',
description = 'Select Standardization methods',
style = {'description_width': 'initial'},
disabled=False)
apply_smote = widgets.Dropdown(
options = [('Yes', 'y'), ('No', 'n')],
value = 'y',
description = 'Do you want to apply SMOTE?',
style = {'description_width': 'initial'},
disabled=False)
pp_class = widgets.HBox([cat_info, std_scr, apply_smote])
header_2 = widgets.HTML(value="<h3>Pre_processing </h3>")
base_estimator = widgets.Dropdown(
options=['Logistic Regression', 'Decision Tree', 'Random Forest','AdaBoost', 'ExtraTree Classifier', 'KNN Classifier'],
value='Logistic Regression',
description='Choose Base Estimator: ',
style = {'description_width': 'initial'},
disabled=False)
display(base_estimator)