-
Notifications
You must be signed in to change notification settings - Fork 5
/
helperFunctions.py
1331 lines (992 loc) · 45 KB
/
helperFunctions.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 27 13:46:15 2022
@author: akshay
"""
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
def getAlgoNames(comIDS):
comIDS=comIDS.split(",")
comIDS = [sub[1 : ] for sub in comIDS]
#get all the algo names
global algoName
algoName=[]
for item in comIDS:
if "-" not in item and "_" not in item:
algoName.append(item)
return algoName
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
def removeModelId(model_id,paraList):
return {key.replace(model_id+"-", ""): value for key, value in paraList.items()}
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
def getActiveAlgo(userInputData,tabNAME,models,rs,classification_Com_IDS):
#Check if there is any algo has been selected bs user.
#Execute only if there is atleast one algo has been selected.
if tabNAME in userInputData.keys():
tab_para=userInputData[tabNAME]
models_ids=getAlgoNames(classification_Com_IDS)
#save all actie models
models_active={}
i=0
for model_id in models_ids:
#check if a algo is active by looking at the user input data
if model_id in tab_para.keys():
model=models[i]
#set random state for the algorithm
if ("random_state") in list(model.get_params().keys()):
model.set_params(random_state=rs)
##set no of cpu's for the algorithm only if it is not None(default)
if ("n_jobs") in list(model.get_params().keys()) \
and userInputData["n_jobs"]!=None:
model.set_params(n_jobs=userInputData["n_jobs"])
#set other parameters of respective algorithms
paraList=tab_para[model_id]
if len(paraList)!=0:
#remove model id prefix from para name
paraList=removeModelId(model_id,paraList)
#remove parameters without any Input from User
#parameters containing None values
for k, v in list(paraList.items()):
if v == None:
del paraList[k]
#convert rangslider input (list by default) into tuple
#make sure it wont break remaing code ^^^^^^^^^^
for k, v in list(paraList.items()):
if type(v) == list:
paraList[k]=tuple(paraList[k])
#^^^ Specially for ADASYN
#^^^ we need to change universal k_neighbors to n_neighbors.
if model_id=="ADASYN":
paraList["n_neighbors"] = paraList.pop("k_neighbors")
#^^^ Specially for RandomOverSampler
#^^^ since n_neighbors parameter is not required
#for random oversampler, delete it
if model_id=="RandomOverSampler":
paraList.pop("k_neighbors", None)
#del paraList["k_neighbors"]
model.set_params(**paraList)
models_active[model_id]=model
i+=1
return models_active
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
from sklearn.model_selection import *
def getMoedlEvalActive(userInputData,tabNAME,modelEval_Com_IDS,rs):
tab_para=userInputData[tabNAME]
models_ids=getAlgoNames(modelEval_Com_IDS)
#save all actie models
models_active={}
for model_id in models_ids:
#check if a algo is active by looking at the user input data
if model_id in tab_para.keys():
#set other parameters of respective algorithms
paraList=tab_para[model_id]
if len(paraList)!=0:
#remove model id prefix from para name
paraList=removeModelId(model_id,paraList)
#ValueError: Setting a random_state has no effect since shuffle is False.
#You should leave random_state to its default (None), or set shuffle=True.
if "Leave" not in model_id and "shuffle" in paraList.keys():
if paraList["shuffle"]==False:
rs=None
#remove parameters without any Input from User
#parameters containing None values
for k, v in list(paraList.items()):
if v == None:
del paraList[k]
#convert rangslider input (list by default) into tuple
#make sure it wont break remaing code ^^^^^^^^^^
for k, v in list(paraList.items()):
if type(v) == list:
paraList[k]=tuple(paraList[k])
#intialize model
if model_id=="KFold":
model=KFold(**paraList,random_state=rs)
elif model_id=="StratifiedKFold":
model=StratifiedKFold(**paraList,random_state=rs)
elif model_id=="RepeatedKFold":
model=RepeatedKFold(**paraList,random_state=rs)
elif model_id=="RepeatedStratifiedKFold":
model=RepeatedStratifiedKFold(**paraList,random_state=rs)
elif model_id=="LeaveOneOut":
model=LeaveOneOut(**paraList)
elif model_id=="LeavePOut":
model=LeavePOut(**paraList)
elif model_id=="ShuffleSplit":
model=ShuffleSplit(**paraList,random_state=rs)
elif model_id=="StratifiedShuffleSplit":
model=StratifiedShuffleSplit(**paraList,random_state=rs)
elif model_id=="NestedCV":
model=StratifiedKFold(**paraList,random_state=rs)
else:
print(model_id)
print(paraList)
print("Something is wrong")
break
else:
#intialize model without para list
if model_id=="KFold":
model=KFold(random_state=rs)
elif model_id=="StratifiedKFold":
model=StratifiedKFold(random_state=rs)
elif model_id=="RepeatedKFold":
model=RepeatedKFold(random_state=rs)
elif model_id=="RepeatedStratifiedKFold":
model=RepeatedStratifiedKFold(random_state=rs)
elif model_id=="LeaveOneOut":
model=LeaveOneOut()
elif model_id=="LeavePOut":
model=LeavePOut(p=10)
elif model_id=="ShuffleSplit":
model=ShuffleSplit(random_state=rs)
elif model_id=="StratifiedShuffleSplit":
model=StratifiedShuffleSplit(random_state=rs)
elif model_id=="NestedCV":
model=StratifiedKFold(random_state=rs)
else:
print("Something is wrong 2")
break
print(model)
models_active[model_id]=model
return models_active
from sklearn.feature_selection import f_classif,chi2
featSel_scoreFun={"f_classif":f_classif,"chi2":chi2}
def getActiveAlgoFeatSel(userInputData,tabNAME,models,rs,classification_Com_IDS,featSel_est):
#Check if there is any algo has been selected bs user.
#Execute only if there is atleast one algo has been selected.
if tabNAME in userInputData.keys():
tab_para=userInputData[tabNAME]
models_ids=getAlgoNames(classification_Com_IDS)
#save all actie models
models_active={}
i=0
for model_id in models_ids:
#check if a algo is active by looking at the user input data
if model_id in tab_para.keys():
model=models[i]
#set random state for the algorithm
if ("random_state") in list(model.get_params().keys()):
model.set_params(random_state=rs)
##set no of cpu's for the algorithm only if it is not None(default)
if ("n_jobs") in list(model.get_params().keys()) \
and userInputData["n_jobs"]!=None:
model.set_params(n_jobs=userInputData["n_jobs"])
#set other parameters of respective algorithms
paraList=tab_para[model_id]
if len(paraList)!=0:
#remove model id prefix from para name
paraList=removeModelId(model_id,paraList)
#remove parameters without any Input from User
#parameters containing None values
for k, v in list(paraList.items()):
if v == None:
del paraList[k]
#convert rangslider input (list by default) into tuple
#make sure it wont break remaing code ^^^^^^^^^^
for k, v in list(paraList.items()):
if type(v) == list:
paraList[k]=tuple(paraList[k])
#change estimator name with actual estimator in parameter list
if "estimator" in paraList.keys():
estimatorname=paraList["estimator"]
paraList["estimator"]=featSel_est[estimatorname]
if "score_func" in paraList.keys():
estimatorname=paraList["score_func"]
paraList["score_func"]=featSel_scoreFun[estimatorname]
model.set_params(**paraList)
models_active[model_id]=model
i+=1
return models_active
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
from UI.componentIDs import classification_Com_IDS,classification_models,\
undersampling_Com_IDS,underSamp_models,\
overrsampling_Com_IDS, overSamp_models, \
modelEval_Com_IDS,\
scaling_Com_IDS,scaling_models, \
featSel_Com_IDS, featSel_models,featSel_est
import pickle
import numpy as np
from zipfile import ZipFile
import os
from datetime import datetime
def saveUserInputData(userInputData):
#get random state4
if("random_seed" in userInputData.keys()):
rs=userInputData["random_seed"]
else:
rs=12345
#set numpy random seed
np.random.seed(rs)
scaling_tab_active=getActiveAlgo(userInputData,"scaling_tab_data",
scaling_models,rs,scaling_Com_IDS)
underSamp_tab_active=getActiveAlgo(userInputData,"underSamp_tab_para",
underSamp_models,rs,undersampling_Com_IDS)
overSamp_tab_active=getActiveAlgo(userInputData,"overSamp_tab_para",
overSamp_models,rs,overrsampling_Com_IDS)
featSel_tab_active=getActiveAlgoFeatSel(userInputData,"featSel_tab_para",
featSel_models,rs,featSel_Com_IDS,featSel_est)
classification_tab_active=getActiveAlgo(userInputData,"classification_tab_para",
classification_models,rs,classification_Com_IDS)
modelEval_tab_active=getMoedlEvalActive(userInputData,"modelEval_tab_para",
modelEval_Com_IDS,rs)
userInputData={"random_state":rs,"n_jobs":userInputData["n_jobs"],"refit_Metric":userInputData["refit_Metric"],\
"scaling_tab_active":scaling_tab_active,"underSamp_tab_active":underSamp_tab_active,\
"overSamp_tab_active":overSamp_tab_active,"classification_tab_active":classification_tab_active,
"featSel_tab_active":featSel_tab_active,\
"modelEval_tab_active":modelEval_tab_active,\
"indepTestSet":userInputData["indepTestSet"],\
"modelEval_metrices":userInputData["modelEval_metrices_tab_para"][0]
}
#return userInputData
#temp location
folder="userInputData"
#del all file from templ loc if there are too much
filelist = [ f for f in os.listdir(folder) if f.endswith(".zip") ]
if len(filelist)>2:
for f in filelist:
os.remove(os.path.join(folder, f))
#create filenames
current_time = datetime.now().strftime("%H_%M_%S")
fileName="inputParameters_"+current_time+".pkl"
zipfileName=folder+"_"+current_time+".zip"
#Save user input data as pkl object
with open(fileName, 'wb') as handle:
pickle.dump(userInputData, handle)
#zipped them
with ZipFile(zipfileName, 'w') as zipObj2:
# Add multiple files to the zip
zipObj2.write(fileName)
zipObj2.write("scriptTemplate.py")
zipObj2.write("README.txt")
#delete pkl file
if os.path.exists(fileName):
os.remove(fileName)
return zipfileName
# =============================================================================
# with open('userInputData_test.pkl', 'wb') as handle:
# pickle.dump(userInputData, handle)
# =============================================================================
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#dash table styling
from dash import Dash, dash_table, html
import pandas as pd
from collections import OrderedDict
def discrete_background_color_bins(df, n_bins=5, columns='all'):
import colorlover
bounds = [i * (1.0 / n_bins) for i in range(n_bins + 1)]
if columns == 'all':
if 'id' in df:
df_numeric_columns = df.select_dtypes('number').drop(['id'], axis=1)
else:
df_numeric_columns = df.select_dtypes('number')
else:
df_numeric_columns = df[columns]
df_max = df_numeric_columns.max().max()
df_min = df_numeric_columns.min().min()
ranges = [
((df_max - df_min) * i) + df_min
for i in bounds
]
styles = []
legend = []
for i in range(1, len(bounds)):
min_bound = ranges[i - 1]
max_bound = ranges[i]
backgroundColor = colorlover.scales[str(n_bins)]['seq']['GnBu'][i - 1]
color = 'black' if i > len(bounds) / 2. else 'black'
for column in df_numeric_columns:
styles.append({
'if': {
'filter_query': (
'{{{column}}} >= {min_bound}' +
(' && {{{column}}} < {max_bound}' if (i < len(bounds) - 1) else '')
).format(column=column, min_bound=min_bound, max_bound=max_bound),
'column_id': column
},
'backgroundColor': backgroundColor,
'color': color
})
legend.append(
html.Div(style={'display': 'inline-block', 'width': '60px'}, children=[
html.Div(
style={
'backgroundColor': backgroundColor,
'borderLeft': '1px rgb(50, 50, 50) solid',
'height': '10px'
}
),
html.Small(round(min_bound, 2), style={'paddingLeft': '2px'})
])
)
return (styles, html.Div(legend, style={'padding': '5px 0 5px 0'}))
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# get dash table
import pandas
def getTable(df):
modelName=pandas.DataFrame({"Algorithm-Evaluation Method":df.index},index=df.index)
result = pandas.concat([modelName, df], axis=1)
df=result
(styles, legend) = discrete_background_color_bins(df)
return html.Div([
html.Div(legend, style={'float': 'right'}),
dash_table.DataTable(
id='datatable-paging',
data=df.to_dict('records'),
columns=[{"name": i, "id": i} for i in sorted(df.columns)],
style_data={'color': 'black','backgroundColor': 'white'},
style_header={'backgroundColor': 'black','color': 'white','fontWeight': 'bold'},
style_table={'overflow': 'scroll','minWidth': '100%'},
#fixed_columns={ 'headers': True, 'data': 1 },
style_cell={'textAlign': 'left'},
sort_action='native',
style_data_conditional=styles ,
export_format='xlsx',
export_headers='display',
)
])
def getInputDataTable(df):
modelName=pandas.DataFrame({"Index":df.index},index=df.index)
result = pandas.concat([modelName, df], axis=1)
df=result
(styles, legend) = discrete_background_color_bins(df)
return html.Div([
html.Div(legend, style={'float': 'right'}),
dash_table.DataTable(
id='datatable-paging',
data=df.to_dict('records'),
columns=[{"name": i, "id": i} for i in df.columns],
style_data={'color': 'white','backgroundColor': '#444'},
style_header={'backgroundColor': 'black','color': 'white','fontWeight': 'bold'},
style_table={'overflow': 'scroll','minWidth': '100%'},
#fixed_columns={ 'headers': True, 'data': 1 },
style_cell={'textAlign': 'left'},
sort_action='native',
style_data_conditional=styles ,
export_format='xlsx',
export_headers='display',
)
])
def getSelFeat_Table(df):
modelName=pandas.DataFrame({"Algorithm-Evaluation Method":df.index},index=df.index)
result = pandas.concat([modelName, df], axis=1)
df=result
#convert list to string
for index, row in df.iterrows():
if str(row["Selected Features"]):
continue
else:
df.loc[index,"Selected Features"]=','.join(str(e) for e in row["Selected Features"])
df.dropna(inplace=True)
return html.Div([
dash_table.DataTable(
id='datatable-paging',
data=df.to_dict('records'),
columns=[{"name": i, "id": i} for i in sorted(df.columns)],
style_data={'color': 'black','backgroundColor': 'white'},
style_header={'backgroundColor': 'black','color': 'white','fontWeight': 'bold'},
style_table={'overflow': 'scroll','minWidth': '100%'},
#fixed_columns={ 'headers': True, 'data': 1 },
style_cell={'textAlign': 'left'},
sort_action='native',
export_format='xlsx',
export_headers='display',
)
])
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
def getSelFeat_df(featureIndex_name):
selFeat_df = pd.DataFrame(index=list(featureIndex_name.keys()),columns =[ "Selected Features"])
for key in featureIndex_name.keys():
features=featureIndex_name[key]
features=','.join(str(e) for e in features)
selFeat_df.loc[key,"Selected Features"]=features
return selFeat_df
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import plotly.express as px
from dash import dcc
import plotly.io as pio
pio.renderers.default = 'browser'
config={'displaylogo': False,
'toImageButtonOptions': {'format': 'png','scale':5}}
def getSpyderPlot(df_sorted,line_color):
rows=int(df_sorted.shape[0]/3)+1
cols=3
width=1000
height=rows*300
title_font=14
marker_size=4
label_size=10
tick_size=10
#line_color="#B9E4E8"
specs=[]
for row in range(1,rows+1):
a=[]
for col in range(1,cols+1):
a.append({"type": "polar"})
specs.append(a)
fig = make_subplots(rows=rows, cols=cols,
subplot_titles=[i.replace('__', '-') for i in df_sorted.index.tolist()],
specs=specs)
row=1
col=1
for model in df_sorted.index:
name=[]
value=[]
model_score=df_sorted.loc[model]
for score in model_score.index:
if score=="model":
continue
name.append(score)
value.append(model_score.loc[score]*100)
fig_tem=go.Scatterpolar(r=value,name=model,dtheta=20,
theta=name,fill='toself',
line_color=line_color)
fig.add_trace(fig_tem,
row=row, col=col)
if col ==cols:
col=1
row+=1
else:
col+=1
for i in fig['layout']['annotations']:
i['font'] = dict(size=title_font,family="Arial",color='black')
i['borderpad'] =15
fig.update_layout(font_size =label_size,template="plotly_white",
font_family="Arial",
width=width,height=height,
showlegend=False,margin=dict(t=50, b=50, r=50, l=50,))
fig.update_polars(radialaxis=dict(
visible=True,nticks=7,
angle=1,
range=[30, 100],
tickfont=dict(size=tick_size)
),
angularaxis = dict(showticklabels=False, ticks='', linewidth = 0.2,showline=True,linecolor='black'))
#fig.update_traces(marker=dict(size=6,line_color="black",color=px.colors.qualitative.Set1), selector=dict(type='scatterpolar'))
fig.update_traces(marker=dict(size=marker_size,line_color="black",color=px.colors.sequential.Viridis), selector=dict(type='scatterpolar'))
fig.update_polars(angularaxis = dict(showticklabels=True))
fig.update_layout(
dragmode='drawopenpath',
newshape_line_color='#B32900',
modebar_add=['drawline',
'drawopenpath',
'drawclosedpath',
'drawcircle',
'drawrect',
'eraseshape']
)
return dcc.Graph(figure=fig,config=config)
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
def getHeatmap(df_sorted,heatmapColor,heatmapText):
#set plot height
if df_sorted.shape[0]<5:
height=500
else:
height=int(df_sorted.shape[0]/2)*150
fig = px.imshow(df_sorted,text_auto=heatmapText,color_continuous_scale=heatmapColor, aspect="auto")
fig.update_xaxes(side="top",tickangle = 90)
fig.update_layout( height= height ,
dragmode='drawopenpath',
newshape_line_color='#B32900',
modebar_add=['drawline',
'drawopenpath',
'drawclosedpath',
'drawcircle',
'drawrect',
'eraseshape']
)
return dcc.Graph(figure=fig,config=config)
from bokeh.palettes import all_palettes
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
def getBarPlot(df,pal,barPlotText):
#pal="Viridis"
models=list(df.index)
metrics=list(df.columns)
#color
colIndex=0
groupColorPal=all_palettes[pal]
#if no of model is larger than the second largest available color list of corr pallete, use last list that is longest one.
if len(groupColorPal)<len(models):
groupColor=groupColorPal[list(groupColorPal.keys())[-1]]
else:
#else choose the one with no of color equal to no of models
if len(models)<3:
groupColor=groupColorPal[3]
else:
groupColor=groupColorPal[len(models)]
#find out number of rows, cols for traces
totalrows=round(len(models)/2+0.1)
totalcols=2
fig = make_subplots(rows=totalrows, cols=totalcols,shared_yaxes=True)
row=1
col=1
#set plot height
if totalrows<1:
height=400
else:
height=totalrows*250
for model in models:
if colIndex>len(groupColor)-3:
colIndex=0
if len(groupColor)==256:
colIndex+=round(len(groupColor)/len(models))-1
#add trace
if barPlotText:
trace=go.Bar(name=model, y=metrics, x=list(df.loc[model]),
orientation='h', text=list(df.loc[model]),
cliponaxis= False,
marker=dict(color=groupColor[colIndex])
)
else:
trace=go.Bar(name=model, y=metrics, x=list(df.loc[model]),
orientation='h',
marker=dict(color=groupColor[colIndex])
)
#fig.append_trace(trace, row,col)
fig.add_trace(trace, row,col)
#inc rows and col indexer for traces
if col ==totalcols:
col=1
row+=1
else:
col+=1
#update color indexer
colIndex+=1
fig.update_traces(textposition='outside', textfont_size=14)
fig.update_layout(template="plotly_white",height=totalrows*250,width=1000)
#fig.update_layout(legend=dict(orientation="h",yanchor="bottom",y=1.05,xanchor="center",x=0.5))
return dcc.Graph(figure=fig,config=config)
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
def getLinePlot(df,pal):
nmodels=df.shape[0]
if df.shape[1]<3:
width=400
else:
width=df.shape[1]*100
# =============================================================================
# #create a list of colors for each line
# =============================================================================
if len(all_palettes[pal])<nmodels:
lineColor=all_palettes[pal][list(all_palettes[pal].keys())[-1]]
#too much color need to remove some of them
if len(lineColor)==256:
#subset of colors based on totoal no of models
colSubs=list(range(0,len(lineColor),round(len(lineColor)/nmodels)-1))
lineColor =[list(lineColor)[i] for i in colSubs]
#evel longest list has less color than actually needed
elif len(lineColor)<nmodels:
lineColor=list(lineColor)*50
else:
if nmodels<3:
lineColor=all_palettes[pal][3]
else:
lineColor=all_palettes[pal][nmodels]
modelName=pd.DataFrame({"Algorithm-Evaluation Method":df.index},index=df.index)
df = pd.concat([modelName, df], axis=1)
df=pd.melt(df, id_vars =['Algorithm-Evaluation Method'], value_vars =list(df.columns)[1:],
var_name ='Metrics', value_name ='Score')
fig = px.line(df, x='Metrics', y='Score', color='Algorithm-Evaluation Method',
color_discrete_sequence = lineColor)
fig.update_layout(template="plotly_white",height=700,width=1050)
# =============================================================================
# fig.update_layout(legend=dict(
# orientation="h",
# yanchor="bottom",
# y=1.02,
# xanchor="right",
# x=1
# ))
# =============================================================================
return dcc.Graph(figure=fig,config=config)
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#update subset dropdrown option
modelOtionList=[
{"label": "All", "value": "all"},
{"label": "Top 10", "value": "top10"},
{"label": "Top 20", "value": "top20"},
{"label": "Top-Bottom 5", "value": "top_bot5"}
]
metricOtionList=options=[{"label": "All", "value": "all"}]
dropdown={"models":modelOtionList,
"metric":metricOtionList}
def getOptionList(list_,whichOne):
dictList=dropdown[whichOne]
temp=[{'label': i, 'value': i} for i in list_]
return dictList+temp
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#susbet result df based on dropdrown option
def subsetResltDF(df,rows,cols,sortBy):
nrow=df.shape[0]
#handle first entry
if cols is None:
cols=[]
if rows is None:
rows=[]
#sorting
if (sortBy is None) or (sortBy not in list(df.columns)):
df=df
else:
df=df.sort_values(by=sortBy, ascending=False)
#metric subset
if ("all" not in cols) and (len(cols)>0):
results_subset = df[cols]
else:
results_subset = df
#model subset
if ("all" in rows) or (len(rows)==0):
results_subset = results_subset
elif "top10" in rows:
if nrow>=10:
results_subset=results_subset.iloc[:10]
else:
results_subset = results_subset
elif "top20" in rows:
if nrow>=20:
results_subset=results_subset.iloc[:20]
else:
results_subset = results_subset
elif "top_bot5" in rows:
if nrow>=10:
select=list(range(0,5,1))+list(range(-5,0,1))
results_subset=results_subset.iloc[select]
else:
results_subset = results_subset
else:
results_subset=results_subset.loc[rows]
return results_subset
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#for negative range metrics such as MCC
def bring_To_Positive_Scale(score_list):
from_min = -1
from_max = 1
to_max = 1
to_min = 0
score_list_new=[]
for item in score_list:
score_list_new.append((item - from_min) * (to_max - to_min) / (from_max - from_min) + to_min)
return score_list_new
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#change pkl into dfs
import pickle,sklearn
import pandas as pd
import numpy as np
from numpy import mean
#replace _ with -
def changeColIndex(df):
#replace _ with -
df.columns = df.columns.str.replace(r"_", "-")
df.index = df.index.str.replace(r"_", "-")
return df
def getResultDF(trainedModels,refitBy):
results_df = pd.DataFrame(index=list(trainedModels.keys()))
failedModels={}
for modelName in trainedModels.keys():
CV=trainedModels[modelName]
#check if this model failed
if isinstance(CV, UserWarning) or isinstance(CV, sklearn.exceptions.FitFailedWarning):
failedModels[modelName]=str(CV)
continue
try:
#check if it is nested CV
if isinstance(CV, dict):
results=CV["nested_results"]
for met in results.keys():
if "test_" in met:
metName=met.replace("test_","")
results_df.loc[modelName,metName]=np.around(mean(results[met]),4)
else:
results=CV.cv_results_
rank=list(results["rank_test_"+refitBy]).index(1)
for met in results.keys():
if "mean_test_" in met:
metName=met.replace("mean_test_","")
results_df.loc[modelName,metName]=np.around(results[met][rank] ,4)
except:
failedModels[modelName]=str(CV)
continue
results_NA= results_df[results_df.isna().any(axis=1)]
results_df.dropna(inplace=True)
failedModels_df=pd.DataFrame(failedModels,index=["Error/Warning"]).T
if refitBy in results_df:
results_df= results_df.sort_values(refitBy)
#if there is negative brier score metric or mcc metric, bring it to positive scale
if "neg_brier_score" in list(results_df.columns):
results_df['neg_brier_score']=bring_To_Positive_Scale(list(results_df['neg_brier_score']))
if "matthews_corrcoef" in list(results_df.columns):
results_df['matthews_corrcoef']=bring_To_Positive_Scale(list(results_df['matthews_corrcoef']))
if refitBy in results_df:
results_df=results_df.sort_values(by=refitBy, ascending=False)
results_df=changeColIndex(results_df)
results_NA=changeColIndex(results_NA)
failedModels_df=changeColIndex(failedModels_df)
return(results_df,results_NA,failedModels_df)
#!!!!!!!!!!!!!!! Area Plot
def getAreaPlot(df_all,goi,pal):
#set color list
groupColorPal=all_palettes[pal]
#if no of goi is larger than the second largest available color list of corr pallete, use last list that is longest one.
if len(groupColorPal)<len(goi):
groupColor=groupColorPal[list(groupColorPal.keys())[-1]]
else:
#else choose the one with no of color equal to no of goi
if len(goi)<3:
groupColor=groupColorPal[3]
else:
groupColor=groupColorPal[len(goi)]
#find out no of classes
targetClasses=set(df_all.iloc[:,-1])