-
Notifications
You must be signed in to change notification settings - Fork 1
/
learning.py
3124 lines (2770 loc) · 209 KB
/
learning.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
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 15 01:43:24 2022
@author: rimez
"""
import matplotlib.pyplot as plt
import numpy as np
import os.path as op
from numpy import nan
import os
import sys
from sklearn.multioutput import MultiOutputClassifier
import numpy as np
import matplotlib.pyplot as plt
import scipy.io
import random
import pandas as pd
import tables
import seaborn as sns
from sklearn.linear_model import LogisticRegressionCV, LogisticRegression
from matplotlib.gridspec import GridSpec
from matplotlib.legend_handler import HandlerTuple
from sklearn.metrics import accuracy_score, r2_score, median_absolute_error, roc_auc_score
from string import Template
from sklearn.ensemble import RandomForestClassifier, BaggingClassifier
from textwrap import wrap
from sklearn.feature_selection import SelectKBest, f_classif, mutual_info_classif
import seaborn as sns
import bz2
import multiprocessing
from joblib import Parallel, delayed
import _pickle as cPickle
from afqinsight.datasets import download_sarica, load_afq_data
from afqinsight import make_afq_classifier_pipeline, cross_validate_checkpoint
from groupyr_stolen import *
from groupyr_stolen import _stringify_sequence
import groupyr
from groupyr import LogisticSGLCV
from groupyr.decomposition import GroupPCA
from sklearn.svm import SVC
from sklearn.multioutput import MultiOutputClassifier
from sklearn.metrics import confusion_matrix
from sklearn.impute import SimpleImputer
from sklearn.model_selection import cross_validate
import afqinsight as afqi
import joblib
import pandas as pd
from sklearn.pipeline import Pipeline
import pickle
from itertools import product
import seaborn as sns
from abc import ABCMeta, abstractmethod
from sklearn.ensemble import *
from sklearn.ensemble._base import BaseEnsemble
from datetime import datetime
from sklearn.feature_selection import mutual_info_regression
import copy
import gc
from sklearn.ensemble._base import BaseEnsemble, _partition_estimators
from sklearn.base import ClassifierMixin, RegressorMixin
from sklearn.metrics import r2_score, accuracy_score
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
from sklearn.utils import check_random_state, column_or_1d, deprecated
from sklearn.utils import indices_to_mask
from sklearn.utils.metaestimators import if_delegate_has_method
from sklearn.utils.multiclass import check_classification_targets
from sklearn.utils.random import sample_without_replacement
from sklearn.utils.validation import has_fit_parameter, check_is_fitted, _check_sample_weight
from sklearn.utils.fixes import delayed
from sklearn.base import clone
from sklearn.model_selection import RepeatedStratifiedKFold
from sklearn.model_selection import (
TimeSeriesSplit,
KFold,
ShuffleSplit,
StratifiedKFold,
GroupShuffleSplit,
GroupKFold,
StratifiedShuffleSplit,
StratifiedGroupKFold,
)
from sklearn.model_selection import LeaveOneOut, GridSearchCV
from sklearn.metrics import accuracy_score, roc_auc_score
import numbers
from typing import List
from sklearn.inspection import permutation_importance
from sklearn.model_selection import permutation_test_score
import numpy as np
from sklearn.utils import *
from sklearn.base import *
from joblib import effective_n_jobs
from skopt import BayesSearchCV
from skopt.plots import plot_convergence, plot_objective, plot_evaluations
import warnings
warnings.filterwarnings("ignore")
import faulthandler; faulthandler.enable()
refresh = False
"""
checkpoint_path = "/auto/home/users/d/r/drimez/Classify%s/checkpoints"%"_bagging"
checkpoint_path_list = [checkpoint_path + "_SVM", checkpoint_path + "_SGL", checkpoint_path + "_RandForest",
checkpoint_path + "_Lasso", checkpoint_path + "_Ridge", checkpoint_path + "_ElasticNet"]
for checkpt_path in checkpoint_path_list:
if not os.path.isdir(checkpt_path):
os.mkdir(checkpt_path)
checkpoint_path = "/auto/home/users/d/r/drimez/Classify%s/checkpoints"%""
checkpoint_path_list = [checkpoint_path + "_SVM", checkpoint_path + "_SGL", checkpoint_path + "_RandForest",
checkpoint_path + "_Lasso", checkpoint_path + "_Ridge", checkpoint_path + "_ElasticNet"]
for checkpt_path in checkpoint_path_list:
if not os.path.isdir(checkpt_path):
os.mkdir(checkpt_path)
"""
f_path = "/CECI/proj/pilab/PermeableAccess/vertige_LEWuQhzYs9/PROJECT/"
f_path="/CECI/proj/pilab/PermeableAccess/vertige_LEWuQhzYs9/ELIKOPY_subset/PROJECT/"
patient_list = [ 'C_0', 'C_1', 'C_11', 'C_12', 'C_2', 'C_3', 'C_4', 'C_5', 'C_6',
'C_7', 'C_8', 'C_9', 'H_0', 'H_1', 'H_2', 'H_3', 'H_5', 'H_6',
'V_0', 'V_1', 'V_10', 'V_11', 'V_13', 'V_14', 'V_15', 'V_16',
'V_17', 'V_18', 'V_19', 'V_2', 'V_20', 'V_21', 'V_22', 'V_23',
'V_24', 'V_25', 'V_26', 'V_27', 'V_28', 'V_29', 'V_3', 'V_30',
'V_32', 'V_33', 'V_34', 'V_35', 'V_36', 'V_37', 'V_38', 'V_39',
'V_4', 'V_40', 'V_41', 'V_42', 'V_43', 'V_44', 'V_45', 'V_46',
'V_47', 'V_48', 'V_49', 'V_5', 'V_50', 'V_51', 'V_52', 'V_53',
'V_6', 'V_7', 'V_8', 'V_9' ]
MAX_INT = np.iinfo(np.int32).max
def traverse(D): # inspired from https://stackoverflow.com/questions/41523543/how-can-i-create-a-list-of-possible-combination-in-a-dict
if not isinstance(D,list):
D = [D]
for d in D:
K,V = zip(*d.items())
for v in product(*(v if isinstance(v,list) else traverse(v) for v in V)):
yield dict(zip(K,v))
def compressed_pickle(title, data):
with bz2.BZ2File(title + '.pbz2', 'w') as f:
cPickle.dump(data, f)
f.close()
def decompress_pickle(filename):
data = bz2.BZ2File(filename, 'rb')
data = cPickle.load(data)
return data
"""
def generate_data(subjects=patient_list,f_path=f_path,old_subjects=old_subjects):
new_df = None ; errors = []
if os.path.exists("metrics_new.csv"):
new_df = pd.read_csv("metrics_new.csv", index_col=False)
else:
df = pd.DataFrame()
for i_sub, sub in enumerate(old_subjects):
csv_path = f_path + "subjects/" + sub + "/tracking/ROIs/metrics.csv"
if os.path.exists(csv_path):
this_df = pd.read_csv(csv_path,header=0)
this_df['subjectID'].values[:] = subjects[i_sub]
df = pd.concat((df,this_df),axis=0)
else:
errors.append(sub)
new_df = pd.DataFrame()
for n_col,col in enumerate(df.columns.values.flatten()):
if n_col>=3:
column_data = np.array([[elem.split(',')[0][1:],elem.split(',')[-1][:-1]] for elem in df[col].values])
new_df[col] = pd.DataFrame(column_data[:,0], index=df.index)
new_df['std_'+col] = pd.DataFrame(column_data[:,1], index=df.index)
else:
new_df[col] = df[col]
new_df['nodeID'] = new_df['tractID'].values[:]
for lign_id, lign in enumerate(df['tractID'].values):
if np.any([el in ("Cbm","cbm","cerebellum","Cerebellum") for el in lign.split("-")]):
new_df['tractID'].iloc[lign_id] = "cbm"
elif np.any([el in ("White","wm","Chiasm","UnsegmentedWhiteMatter","CC","WM","Stem") for el in lign.split("-")])\
or "CC" in lign.split("_"):
new_df['tractID'].iloc[lign_id] = "wm"
elif np.any([el in ("ctx","Cortex") for el in lign.split("-")]):
new_df['tractID'].iloc[lign_id] = "ctx"
elif np.any([el in ("CSF","VentralDC","vessel","choroid","ventricle","Ventricle","Vent") for el in lign.split("-")]):
new_df['tractID'].iloc[lign_id] = "others"
else:
new_df['tractID'].iloc[lign_id] = "subctx"
new_df.to_csv("/auto/home/users/d/r/drimez/metrics_new.csv", line_terminator="\n", sep=",", index=False)
if len(errors)>=1:
print("Subjects not found: "+str(errors))
return new_df
def generate_afq_data(subjects=patient_list,f_path=f_path,old_subjects=old_subjects):
new_df = None ; errors_det = [] ; errors_prob = []
if os.path.exists("metrics_afq.csv"):
new_df = pd.read_csv("metrics_afq.csv", index_col=False)
else:
df_det = pd.DataFrame() ; df_prob = pd.DataFrame()
for i_sub, sub in enumerate(subjects):
csv_paths = f_path + "subjects/" + sub + "/tracking/AFQ/" + sub + "_dipy.csv"
if os.path.exists(csv_path):
this_df = pd.read_csv(csv_path,header=0)
this_df['subjectID'].values[:] = subjects[i_sub]
df_det = pd.concat((df_det,this_df),axis=0)
else:
errors_det.append(sub)
csv_paths = f_path + "subjects/" + sub + "/tracking/AFQ/" + sub + "_dipy_prob.csv"
if os.path.exists(csv_path):
this_df = pd.read_csv(csv_path,header=0)
this_df['subjectID'].values[:] = subjects[i_sub]
df_prob = pd.concat((df_prob,this_df),axis=0)
else:
errors_prob.append(sub)
new_df_det = pd.DataFrame() ; new_df_prob = pd.DataFrame()
for n_col,col in enumerate(df_det.columns.values.flatten()):
if n_col>=3:
column_data = np.array([[elem.split(',')[0][1:],elem.split(',')[-1][:-1]] for elem in df[col].values])
new_df[col] = pd.DataFrame(column_data[:,0], index=df.index)
new_df['std_'+col] = pd.DataFrame(column_data[:,1], index=df.index)
else:
new_df[col] = df[col]
new_df['nodeID'] = new_df['tractID'].values[:]
for lign_id, lign in enumerate(df['tractID'].values):
if np.any([el in ("Cbm","cbm","cerebellum","Cerebellum") for el in lign.split("-")]):
new_df['tractID'].iloc[lign_id] = "cbm"
elif np.any([el in ("White","wm","Chiasm","UnsegmentedWhiteMatter","CC","WM","Stem") for el in lign.split("-")])\
or "CC" in lign.split("_"):
new_df['tractID'].iloc[lign_id] = "wm"
elif np.any([el in ("ctx","Cortex") for el in lign.split("-")]):
new_df['tractID'].iloc[lign_id] = "ctx"
elif np.any([el in ("CSF","VentralDC","vessel","choroid","ventricle","Ventricle","Vent") for el in lign.split("-")]):
new_df['tractID'].iloc[lign_id] = "others"
else:
new_df['tractID'].iloc[lign_id] = "subctx"
new_df.to_csv("/auto/home/users/d/r/drimez/metrics_new.csv", line_terminator="\n", sep=",", index=False)
if len(errors)>=1:
print("Subjects not found: "+str(errors))
return new_df
"""
def select_groups(X, select, label_seq, columns=True, all=True):
index = 1 if columns else 0
mask = [] ; found = False
for lab in label_seq:
for bund in select:
if np.any(np.array(list(lab))==bund[0]) or all:
found = True
mask.append(1)
if not found:
mask.append(0)
found = False
mask = np.array(mask)==1
if all:
return mask
else:
X_new = X.T[mask].T if columns else X[mask]
return X_new
from sklearn.metrics import multilabel_confusion_matrix
def confusion_matrix_scorer(y_true,y_pred,k=1,*kwargs):
try:
cm = multilabel_confusion_matrix(y_true, y_pred)[k]
return cm[1,1] / np.sum(cm[1])
except Exception:
return 0
def plot_results(final_results,filename,ensemble_or_not):
if isinstance(final_results,str):
final_results_path = final_results
final_results = {} ; final_results_ = None
with open(final_results_path,"r") as reader:
final_results_ = reader.readlines()
reader.close()
perfs_name = [eeeee.replace("\n", "") for eeeee in final_results_[0].split(",")[1:]]
for line in final_results_[1:]:
params, perfs = line.split("},")
try:
results_ = {metric_name:float(a_metric) for metric_name, a_metric in zip(perfs_name,perfs.split(","))}
if (not np.any([res for _,res in results_.items()])==0) \
and results_["test_balanced_accuracy"]>=0.35 and \
(not results_["train_accuracy"]-results_["test_accuracy"]>=0.2):
final_results[params+"}"] = results_
except Exception:
pass
plotting_folder_ = "" if ensemble_or_not is None else "_bagging"
plotting_folder = "/auto/home/users/d/r/drimez/Classify" + plotting_folder_ + "/"
plotting_folder = "Classify" + plotting_folder_ + "/"
def get_cv_split_performance(results, pipeline, performance_metric="test_accuracy"):
args = {keyval.split(":")[0].replace("'", ""):keyval.split(":")[1] for keyval in pipeline[1:-1].split(", ")}
metrics = dict( **{ "metric": results[performance_metric],
"metric_name": performance_metric,
"model": pipeline}, **args )
return pd.DataFrame([metrics]) #, [*args.keys()]
x_axis = "C"
hues = ["scaler","select"]
filenames_split = filename.split("_")
if "RandForest" in filenames_split:
hues.append("max_depth")
x_axis = "n_estimators"
elif "ElasticNet" in filenames_split:
hues.append("l1_ratio")
elif "SVM" in filenames_split:
hues.append("kernel")
if ensemble_or_not=="bagging":
hues.append("n_estimators")
legend_s = None ; legend_k = None ; legend_c = None
figs = [] ; axes = [] ; legends = [] ; n_figs = len(hues)
for nn_figs in range(n_figs):
fig, axe = plt.subplots(2,2,figsize=(24,9),sharex=True)
figs.append(fig) ; axes.append(axe.flatten()) ; legends.append(None)
for im, metric in enumerate(["train_accuracy","test_accuracy","test_corrected_accuracy",
"test_balanced_accuracy"]):
df = pd.concat([ get_cv_split_performance(results=_res, pipeline=_pip, performance_metric=metric)
for _pip,_res in final_results.items() if _res is not None], ignore_index=True)
# ax_scaler = df.boxplot(by='scaler',ax=ax_scaler)
data_ind = df["metric_name"]
data_ind = data_ind.values == metric
data = df.iloc[data_ind]
for il, (ax, hue) in enumerate(zip([_[im] for _ in axes],hues)):
ax = sns.boxplot(x=x_axis,y="metric",hue=str(hue), data=data, palette="muted",ax=ax)
legends[il] = copy.copy(ax.get_legend())._set_loc(2)
ax = sns.scatterplot(x=x_axis, y="metric", hue=hue, data=data, palette="muted", ax=ax,size=2)
ax.set_title(metric)
ax.get_legend().remove()
for fig, hue in zip(figs,hues):
fig.savefig(plotting_folder + filename + "_%s.png"%hue)
# fig_scaler.legend(labels=np.unique(df["scaler"].values).tolist(), loc = 2)
# fig_scaler.add_artist(legend_s)
# fig_scaler.savefig(plotting_folder + filename + "_scaler.png")
# fig_kernel.legend(labels=np.unique(df["kernel"].values).tolist(), loc = 2)
# fig_kernel.add_artist(legend_k).get_legend()._set_loc(2)
# fig_kernel.savefig(plotting_folder + filename + "_kernel.png")
# fig_c.legend(labels=np.unique(df["select"].values).tolist(), loc = 2)
# fig_c.add_artist(legend_c).get_legend()._set_loc(2)
# fig_c.savefig(plotting_folder + filename + "_select.png")
def plot_results_SGD(final_results,filename,ensemble_or_not):
plotting_folder = "" if ensemble_or_not is None else "_bagging"
def get_cv_split_performance(results, pipeline, performance_metric="test_accuracy"):
metrics = { "metric": results[performance_metric],
"metric_name": performance_metric,
"model": pipeline,
"scaler":pipeline.split(",")[0].split(":")[-1],
"l1_ratio":pipeline.split(",")[-1].split(":")[-2].split("}")[0],
"alpha":pipeline.split(",")[1].split(":")[-1],
"select":pipeline.split(",")[-1].split(":")[-1].split("}")[0]}
return pd.DataFrame(metrics)
fig_scaler, axes_scaler = plt.subplots(2,2,figsize=(18,9),sharex=True)
fig_kernel, axes_kernel = plt.subplots(2,2,figsize=(18,9),sharex=True)
fig_c, axes_c = plt.subplots(2,2,figsize=(18,12),sharex=True)
for metric, ax_scaler, ax_kernel, ax_c in zip(["test_balanced_accuracy","test_corrected_accuracy","test_recall",
"test_accuracy","test_precision","test_neg_log_loss"],
axes_scaler.flatten(),axes_kernel.flatten(),axes_c.flatten()):
df = pd.concat([ get_cv_split_performance(results=_res, pipeline=_pip, performance_metric=metric)
for _pip,_res in final_results.items() if _res is not None], ignore_index=True)
# ax_scaler = df.boxplot(by='scaler',ax=ax_scaler)
data_ind = df["metric_name"]
data_ind = data_ind.values == metric
data = df.iloc[data_ind]
ax_scaler = sns.boxplot(x="alpha",y="metric",hue="scaler", data=data, palette="muted",ax=ax_scaler)
ax_scaler = sns.swarmplot(x="alpha", y="metric", hue="scaler", data=data, palette="muted", ax=ax_scaler,size=2)
ax_scaler.set_title(metric)
ax_scaler.get_legend().remove()
ax_kernel = sns.boxplot(x="alpha",y="metric",hue="l1_ratio",data=data, palette="muted",ax=ax_kernel)
ax_kernel = sns.swarmplot(x="alpha", y="metric", hue="l1_ratio", data=data, palette="muted",ax=ax_kernel,size=2)
ax_kernel.set_title(metric)
ax_kernel.get_legend().remove()
ax_c = sns.boxplot(x="alpha",y="metric",hue="select",data=data,ax=ax_c)
ax_c = sns.swarmplot(x="alpha", y="metric", hue="select", data=data, palette="muted",ax=ax_c,size=2)
ax_c.set_title(metric)
ax_c.get_legend().remove()
fig_scaler.legend(labels=np.unique(df["scaler"].values).tolist(), loc = 2, bbox_to_anchor = (1,1))
fig_scaler.savefig("/auto/home/users/d/r/drimez/Classify"+plotting_folder+"/" + filename + "_scaler.png")
fig_kernel.legend(labels=np.unique(df["kernel"].values).tolist(), loc = 2, bbox_to_anchor = (1,1))
fig_kernel.savefig("/auto/home/users/d/r/drimez/Classify"+plotting_folder+"/" + filename + "_kernel.png")
fig_c.legend(labels=np.unique(df["select"].values).tolist(), loc = 2, bbox_to_anchor = (1,1))
fig_c.savefig("/auto/home/users/d/r/drimez/Classify"+plotting_folder+"/" + filename + "_select.png")
def plot_results_sgl(final_results,filename,ensemble_or_not):
plotting_folder = "" if ensemble_or_not is None else "_bagging"
def get_cv_split_performance(results, pipeline, performance_metric="test_accuracy"):
metrics = { "metric": results[performance_metric],
"metric_name": performance_metric,
"model": pipeline,
"scaler":pipeline.split(",")[0].split(":")[-1],
"eps":pipeline.split(",")[-2].split(":")[-1] ,
"select":pipeline.split(",")[-1].split(":")[-1].split("}")[0] }
return pd.DataFrame(metrics)
fig_scaler, axes_scaler = plt.subplots(2,2,figsize=(18,9),sharex=True)
fig_eps, axes_eps = plt.subplots(2,2,figsize=(18,9),sharex=True)
for metric, ax_scaler, ax_eps in zip(["train_accuracy", "train_neg_log_loss",
"test_accuracy", "test_neg_log_loss"],
axes_scaler.flatten(),axes_eps.flatten()):
df = pd.concat([ get_cv_split_performance(results=_res, pipeline=_pip, performance_metric=metric)
for _pip,_res in final_results.items() if _res is not None])
# ax_scaler = df.boxplot(by='scaler',ax=ax_scaler)
data_ind = df["metric_name"]
data_ind = data_ind.values == metric
data = df.iloc[data_ind]
ax_scaler = sns.boxplot(x="eps",y="metric",hue="scaler",data=data, palette="muted",ax=ax_scaler)
ax_scaler = sns.swarmplot(x="eps", y="metric", hue="scaler", data=data, color=".25",ax=ax_scaler,size=2)
ax_scaler.set_title(metric)
ax_scaler.get_legend().remove()
ax_eps = sns.boxplot(x='eps',y="metric",hue="select",data=data,ax=ax_eps)
ax_eps = sns.swarmplot(x="eps", y="metric", hue="select", data=data, color=".25",ax=ax_eps,size=2)
ax_eps.set_title(metric)
ax_eps.get_legend().remove()
fig_scaler.legend(labels=np.unique(df["scaler"].values).tolist(), loc = 2, bbox_to_anchor = (1,1))
fig_scaler.savefig("/auto/home/users/d/r/drimez/Classify"+plotting_folder+"/" + filename + "_scaler.png")
fig_eps.legend(labels=np.unique(df["select"].values).tolist(), loc = 2, bbox_to_anchor = (1,1))
fig_eps.savefig("/auto/home/users/d/r/drimez/Classify"+plotting_folder+"/" + filename + "_select.png")
def plot_results_forest(final_results,filename,ensemble_or_not):
plotting_folder = "" if ensemble_or_not is None else "_bagging"
def get_cv_split_performance(results, pipeline, performance_metric="test_accuracy"):
metrics = { "metric": results[performance_metric],
"metric_name": performance_metric,
"model": pipeline,
"scaler":pipeline.split(",")[0].split(":")[-1],
"n_estimators":pipeline.split(",")[-1].split(":")[-1].split("}")[0],
"select":pipeline.split(",")[-1].split(":")[-1].split("}")[0]}
return pd.DataFrame(metrics)
# final_results = {}
# for pckl_path in os.scandir(final_results_path):
# if pckl_path.path.split("_")[0]==final_results_path:
# final_results = dict(final_results,**decompress_pickle())
fig_scaler, axes_scaler = plt.subplots(2,2,figsize=(18,12),sharex=True)
fig_n_estimators, axes_n_estimators = plt.subplots(2,2,figsize=(18,12),sharex=True)
for metric, ax_scaler, ax_n_estimators in zip(["train_accuracy", "train_neg_log_loss",
"test_accuracy", "test_neg_log_loss"],
axes_scaler.flatten(),axes_n_estimators.flatten()):
df = pd.concat([ get_cv_split_performance(results=_res, pipeline=_pip, performance_metric=metric)
for _pip,_res in final_results.items() if _res is not None])
# ax_scaler = df.boxplot(by='scaler',ax=ax_scaler)
data_ind = df["metric_name"]
data_ind = data_ind.values == metric
data = df.iloc[data_ind]
ax_scaler = sns.boxplot(x="n_estimators",y="metric",hue="scaler",data=data, palette="muted",ax=ax_scaler)
ax_scaler = sns.swarmplot(x="n_estimators", y="metric", hue="scaler", data=data, palette="muted",ax=ax_scaler,size=2)
ax_scaler.set_title(metric)
ax_scaler.get_legend().remove()
ax_n_estimators = sns.boxplot(x='n_estimators',y="metric",hue="select",ax=ax_n_estimators,data=data)
ax_n_estimators = sns.swarmplot(x="n_estimators", y="metric", hue="select", data=data, palette="muted",ax=ax_n_estimators,size=2)
ax_n_estimators.set_title(metric)
ax_n_estimators.get_legend().remove()
fig_scaler.legend(labels=np.unique(df["scaler"].values).tolist(), loc = 2, bbox_to_anchor = (1,1))
fig_scaler.savefig("/auto/home/users/d/r/drimez/Classify"+plotting_folder+"/" + filename + "_scaler.png")
fig_n_estimators.legend(labels=np.unique(df["select"].values).tolist(), loc = 2, bbox_to_anchor = (1,1))
fig_n_estimators.savefig("/auto/home/users/d/r/drimez/Classify"+plotting_folder+"/" + filename + "_select.png")
def plot_results_Logistic(final_results,filename,ensemble_or_not):
if isinstance(final_results,str):
final_results_path = final_results
final_results = {} ; final_results_ = None
with open(final_results_path,"r") as reader:
final_results_ = reader.readlines()
reader.close()
perfs_name = [eeeee.replace("\n", "") for eeeee in final_results_[0].split(",")[1:]]
for line in final_results_[1:]:
params, perfs = line.split("},")
try:
results_ = {metric_name:float(a_metric) for metric_name, a_metric in zip(perfs_name,perfs.split(","))}
if (not np.any([res for _,res in results_.items()])==0) \
and results_["test_balanced_accuracy"]>=0.35 and \
(not results_["train_accuracy"]-results_["test_accuracy"]>=0.2):
final_results[params+"}"] = results_
except Exception:
pass
plotting_folder_ = "" if ensemble_or_not is None else "_bagging"
plotting_folder = "/auto/home/users/d/r/drimez/Classify" + plotting_folder_ + "/"
plotting_folder = "Classify" + plotting_folder_ + "/"
def get_cv_split_performance(results, pipeline, performance_metric="test_accuracy"):
args = {keyval.split(":")[0].replace("'", ""):keyval.split(":")[1] for keyval in pipeline[1:-1].split(", ")}
metrics = dict( **{ "metric": results[performance_metric],
"metric_name": performance_metric,
"model": pipeline}, **args )
return pd.DataFrame([metrics]) #, [*args.keys()]
legend_s = None ; legend_k = None ; legend_c = None
fig_scaler, axes_scaler = plt.subplots(2,2,figsize=(18,12),sharex=True)
fig_n_estimators, axes_n_estimators = plt.subplots(2,2,figsize=(18,12),sharex=True)
for metric, ax_scaler, ax_n_estimators in zip(["train_accuracy","test_accuracy",
"test_corrected_accuracy","test_balanced_accuracy"],
axes_scaler.flatten(),axes_n_estimators.flatten()):
df = pd.concat([ get_cv_split_performance(results=_res, pipeline=_pip, performance_metric=metric)
for _pip,_res in final_results.items() if _res is not None])
# ax_scaler = df.boxplot(by='scaler',ax=ax_scaler)
data_ind = df["metric_name"]
data_ind = data_ind.values == metric
data = df.iloc[data_ind]
ax_scaler = sns.boxplot(x="C",y="metric",hue="scaler",data=data, palette="muted",ax=ax_scaler)
legend_s = copy.copy(ax_scaler.get_legend())._set_loc(2)
ax_scaler = sns.swarmplot(x="C", y="metric", hue="scaler", data=data, palette="muted",ax=ax_scaler,size=4)
ax_scaler.set_title(metric)
ax_scaler.get_legend().remove()
ax_n_estimators = sns.boxplot(x='C',y="metric",hue="select",ax=ax_n_estimators,data=data)
legend_k = copy.copy(ax_n_estimators.get_legend())._set_loc(2)
ax_n_estimators = sns.swarmplot(x="C", y="metric", hue="select", data=data, palette="muted",ax=ax_n_estimators,size=4)
ax_n_estimators.set_title(metric)
ax_n_estimators.get_legend().remove()
ax_n_estimators.set_title(metric)
# fig_scaler.legend(labels=np.unique(df["scaler"].values).tolist(), loc = 2)
# fig_scaler.add_artist(legend_s)
fig_scaler.savefig(plotting_folder + filename + "_scaler.png")
# fig_kernel.legend(labels=np.unique(df["kernel"].values).tolist(), loc = 2)
# fig_kernel.add_artist(legend_k).get_legend()._set_loc(2)
fig_n_estimators.savefig(plotting_folder + filename + "_select.png")
"""
def generate_features(X,X_11,X_1,subjects=pd.read_csv("rename.txt",header=None).values.T[1]):
X1 = pd.DataFrame() ; Xpca = pd.DataFrame()
X1_columns = [] ; groups = [] ; group_names = [] ; groupspca = [] ; group_namespca = []
done = False ; X11_columns = [] ; groups_idx = [] ; groups_idx_pca = [] ; classes = {}
for inid, nid in enumerate(subjects):
if nid.split('_')[0]!='U':
if nid.split('_')[0] in [*classes.keys()]:
classes[nid.split('_')[0]].append(inid)
else:
classes[nid.split('_')[0]] = [inid]
bundles = np.unique(X['tractID'].values[X.index.values[X['subjectID'].values==nid]])
X1_columns = [] ; X11_columns = []
for ilign, lign in enumerate(X.index.values[X['subjectID'].values==nid]):
t = X['tractID'].values[lign]
nni = X['nodeID'].values.flatten()[lign]
groups.append([]) ; groupspca.append([])
for n_col, col in enumerate(X_1.columns.values.flatten()):
X1_columns.append(str((t,nni,col)))
if not tuple((t,nni,col)) in group_names:
group_names.append(tuple((t,nni,col)))
groups[ilign].append(n_col)
for n_col, col in enumerate(X_11.columns.values.flatten()):
X11_columns.append(str((t,nni,col)))
if not tuple((t,nni,col)) in group_namespca:
group_namespca.append(tuple((t,nni,col)))
groupspca[ilign].append(n_col)
X1_columns = np.array(X1_columns).flatten().tolist()
X1 = pd.concat([X1,pd.DataFrame(np.array(X_1.values[X['subjectID'].values==nid]).reshape((1,len(X1_columns))),
columns=X1_columns)], ignore_index=True)
Xpca = pd.concat([Xpca,pd.DataFrame(np.array(X_11.values[X['subjectID'].values==nid]).reshape((1,len(X11_columns))),
columns=X11_columns)], ignore_index=True)
X1 = X1.fillna(0)
toremove = []
Y2 = [0 for a_class in subjects if a_class.split('_')[0]!='U']
for ia_class, a_class in enumerate([*classes.keys()]):
for an_istance in np.array(classes[a_class]):
Y2[int(an_istance)] = ia_class
for classes_ in np.unique(Y2):
toremove.append((X1.values[Y2==classes_] != 0).sum(axis=0)<=len(X1.values[Y2==classes_])/2)
toremove = np.array(toremove).T
to_remove = []
for itr, tr in [_ for _ in enumerate(toremove)][::-1]:
if np.any(tr):
if np.sum(tr)==1:
print(str(group_names.pop(itr))+"%s is missing in class %s"%(100*(len(X1.values[Y2==np.unique(Y2)[tr]])-(X1.values[Y2==np.unique(Y2)[tr]] != 0).sum(axis=0)[itr])/len(X1.values[Y2==np.unique(Y2)[tr]]),
np.array([*classes.keys()])[tr][0]))
elif np.sum(tr)==len(tr):
print(str(group_names.pop(itr))+" Empty feature")
else:
print(str(group_names.pop(itr))+" More than 50% missing for several classes")
groups.pop(itr)
to_remove.append(X1.columns.values[itr])
X1 = X1.drop(to_remove,axis=1)
Xpca = Xpca.fillna(0)
toremove = []
for classes_ in np.unique(Y2):
toremove.append((Xpca.values[Y2==classes_] != 0).sum(axis=0)<=len(Xpca.values[Y2==classes_])/2)
toremove = np.array(toremove).T
to_remove = []
for itr, tr in [_ for _ in enumerate(toremove)][::-1]:
if np.any(tr):
# if np.sum(tr)==1:
# print(str(group_namespca.pop(itr))+"%s is missing in class %s"%(100*(len(Xpca.values[Y2==np.unique(Y2)[tr]])-(Xpca.values[Y2==np.unique(Y2)[tr]] != 0).sum(axis=0)[itr])/len(Xpca.values[Y2==np.unique(Y2)[tr]]),
# np.array([*classes.keys()])[tr][0]))
# elif np.sum(tr)==len(tr):
# print(str(group_namespca.pop(itr))+" Empty feature")
# else:
# print(str(group_namespca.pop(itr))+" More than 50% missing for several classes")
groupspca.pop(itr)
to_remove.append(Xpca.columns.values[itr])
Xpca = Xpca.drop(to_remove,axis=1)
# for inid, nid in enumerate(['H_0','H_1','H_2','H_3','H_4','V_100','V_101','V_102','V_103']):
groups_idx.append([[] for _ in X1.columns])
groups_idx_pca.append([[] for _ in Xpca.columns] )
for nn_col, xt in enumerate(X1):
lmh = np.arange(len(bundles))[bundles==xt.split(',')[0][2:-1]]
groups_idx[0][lmh[0]].append(nn_col)
for nn_col, xt in enumerate(Xpca):
lmh = np.arange(len(bundles))[bundles==xt.split(',')[0][2:-1]]
groups_idx_pca[0][lmh[0]].append(nn_col)
n_samples, n_feats = X1.shape
feats_name = list(X1.columns)
Y1 = np.arange(len(X1.values))
for a_class in [*classes.keys()]:
for ia_class in classes[a_class]:
if a_class=="H":
Y1[ia_class] = 0
elif a_class=="C":
Y1[ia_class] = 1
else:
Y1[ia_class] = 2
return X1, Xpca, Y1, groups, group_names, groupspca, group_namespca, groups_idx[0], groups_idx_pca[0]
"""
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
def my_group_pca(XX,y_true,max_components=4,n_groups=180,p=patient_list,mask=None,pca_type=None):
X = copy.copy(XX)
n_patients=len(X.values)
grp_names = np.unique([_.split(",")[0][2:-1].split(".")[0] for _ in X.columns.values])
side_ = np.array([_.split(",")[0][2:-1].split(".")[1] if len(_.split(",")[0][2:-1].split("."))==2 else "" for _ in X.columns.values])
groups_names = [_.split(",")[0][2:-1].split(".")[0] for _ in X.columns.values]
if (not (pca_type.replace("scale_","") in ("bilat_pca","pca_without_age"))) or len(pca_type.split("unilat"))==2:
grp_names = np.unique([_.split(",")[0][2:-1] for _ in X.columns.values])
groups_names = [_.split(",")[0][2:-1] for _ in X.columns.values]
n_groups = len(grp_names)
if "scale" in pca_type.split("_"):
X = pd.DataFrame(StandardScaler().fit_transform(X),columns=X.columns.values)
pca_models_ = []
components_ = [None for grp in range(n_groups)]
explained_variance_ = [None for grp in range(n_groups)]
explained_variance_ratio_ = [None for grp in range(n_groups)]
singular_values_ = [None for grp in range(n_groups)]
mean_ = [None for grp in range(n_groups)]
n_components_ = [None for grp in range(n_groups)]
noise_variance_ = [None for grp in range(n_groups)]
features_out = [[] for pp in range(n_patients)]
groups_out_ = []
"""
bins = len(y_true)/np.unique(y_true,return_counts=True)[1] ; weights = []
for nnnn, nnn_class in enumerate(np.unique(y_true)):
weights = np.append(weights,[bins[nnnn]/len(bins) for _ in y_true if _==nnn_class])
weights = weights.reshape((70,1))
weights = np.ones((70,1))
"""
ad = [True if str(_).split(",")[-1][2:-2]=="AD" else False for _ in X.columns.values]
md = [True if str(_).split(",")[-1][2:-2]=="MD" else False for _ in X.columns.values]
rd = [True if str(_).split(",")[-1][2:-2]=="RD" else False for _ in X.columns.values]
fa = [True if str(_).split(",")[-1][2:-2]=="FA" else False for _ in X.columns.values]
feature_start_idx = 0 ; idx = -1
# if not (mask is None):
# grp_names = np.unique([_.split(",")[1] for _ in np.array(X.columns.values)[mask==True]])
# groups_names = [_.split(",")[1] for _ in np.array(X.columns.values)[mask==True]]
for idx_ in np.arange(n_groups):
grp = np.zeros((len(groups_names)))
for ig, l in enumerate(groups_names):
if l==grp_names[idx_]:
grp[ig] = 1
else:
grp[ig] = 0
# grp = np.tile(grp==1,(9,1))
grp = (grp==1).flatten()
grp_fa = np.logical_and(grp,fa)
grp_md = np.logical_and(grp,md)
grp_ad = np.logical_and(grp,ad)
grp_rd = np.logical_and(grp,rd)
if pca_type.replace("scale_","") in ("pca_without_age","bilat_pca") and not np.any(np.logical_and(side_=="",grp)):
grp_fa_right = np.logical_and(grp_fa,side_=="right")
grp_md_right = np.logical_and(grp_md,side_=="right")
grp_ad_right = np.logical_and(grp_ad,side_=="right")
grp_rd_right = np.logical_and(grp_rd,side_=="right")
grp_fa_left = np.logical_and(grp_fa,side_=="left")
grp_md_left = np.logical_and(grp_md,side_=="left")
grp_ad_left = np.logical_and(grp_ad,side_=="left")
grp_rd_left = np.logical_and(grp_rd,side_=="left")
if np.sum(grp)>0:
idx += 1
group_x = None
if (pca_type in ("bilat_pca","pca_without_age")) and not np.any(np.logical_and(side_=="",grp)):
group_x = np.concatenate((np.array(np.concatenate([list(np.array([X.values[iii][grp_] for iii in range(n_patients)]).flatten()) for grp_ in [grp_ad_left,grp_ad_right]],axis=0)).reshape((69*np.sum(grp_ad),1)),
np.array(np.concatenate([list(np.array([X.values[iii][grp_] for iii in range(n_patients)]).flatten()) for grp_ in [grp_md_left,grp_md_right]],axis=0)).reshape((69*np.sum(grp_md),1)),
np.array(np.concatenate([list(np.array([X.values[iii][grp_] for iii in range(n_patients)]).flatten()) for grp_ in [grp_rd_left,grp_rd_right]],axis=0)).reshape((69*np.sum(grp_rd),1)),
np.array(np.concatenate([list(np.array([X.values[iii][grp_] for iii in range(n_patients)]).flatten()) for grp_ in [grp_fa_left,grp_fa_right]],axis=0)).reshape((69*np.sum(grp_fa),1))),axis=1)
else:
group_x = np.concatenate((np.reshape([X.values[iii][grp_ad] for iii in range(n_patients)],(-1,1)),
np.reshape([X.values[iii][grp_md] for iii in range(n_patients)],(-1,1)),
np.reshape([X.values[iii][grp_rd] for iii in range(n_patients)],(-1,1)),
np.reshape([X.values[iii][grp_fa] for iii in range(n_patients)],(-1,1))),axis=1)
group_x = np.array(group_x)
pca_models_.append( PCA( n_components=min(max_components,len(group_x[0])),
copy=True, whiten=False ) )
group_x_std = None
group_x_std = StandardScaler().fit_transform(group_x) # _transform
pca_models_[idx].fit(group_x_std)
old_components = pca_models_[idx].components_
if pca_type.replace("scale_","") in ("bilat_pca","pca_without_age"):
this_features_out = pca_models_[idx].transform(group_x)
pca_comp_sign = np.array([np.all(old_components[0]<0),old_components[1][-1]<0,False,False])
if np.any(pca_comp_sign):
old_components[pca_comp_sign] = -old_components[pca_comp_sign]
this_features_out[:,:2] = -this_features_out[:,:2]
this_features_out = np.reshape(this_features_out[:,:2],(69,2*len(this_features_out)//69)) # 2 for each side
else:
this_features_out = pca_models_[idx].transform(group_x)
pca_comp_sign = np.array([np.all(old_components[0]<0),old_components[1][-1]<0,False,False])
if np.any(pca_comp_sign):
old_components[pca_comp_sign] = -old_components[pca_comp_sign]
this_features_out[:,:2] = -this_features_out[:,:2]
this_features_out = np.reshape(this_features_out[:,:2],(69,2*len(this_features_out)//69))
features_out = np.concatenate( (features_out,
this_features_out), axis=1 )
components_[idx] = old_components[:2]
explained_variance_[idx] = pca_models_[idx].explained_variance_[:2]
explained_variance_ratio_[idx] = pca_models_[idx].explained_variance_ratio_[:2]
singular_values_[idx] = pca_models_[idx].singular_values_[:2]
mean_[idx] = pca_models_[idx].mean_[:2]
n_components_[idx] = 2
noise_variance_[idx] = pca_models_[idx].noise_variance_
groups_out_.append(
np.arange(
feature_start_idx,
feature_start_idx + pca_models_[idx].n_components_,
)
)
feature_start_idx += pca_models_[idx].n_components_
else:
print("Empty group: "+str(grp_names[idx_]))
n_features_out_ = np.sum([len(grp) for grp in groups_out_])
def generate_feature_names(pca_models,group_names=grp_names,all_features=np.array(groups_names)[fa],pca_type=pca_type,side_=side_[fa]):
feature_names_out_ = []
for idx, (grp, pca_model) in enumerate(zip(groups_out_, pca_models)):
if group_names is None:
group_name = "group" + str(idx).zfill(
int(np.log10(len(groups_out_)) + 1)
)
else:
group_name = _stringify_sequence(group_names[idx])
if not (pca_type.replace("scale_","") in ("bilat_pca","pca_without_age")):
seg_in_group = [True if group_name==_ else False for _ in all_features]
feature_type = "feature" if pca_model is None else "pc"
for seg_in in range(np.sum(seg_in_group)):
feature_names_out_ += [
"_".join([group_name, str(seg_in), feature_type + str(n)]) for n in range(2)
]
else:
seg_in_group = [True if group_name==_ else False for _ in all_features]
for side in np.unique(np.array(side_)[seg_in_group]):
if side == "": # callosum tracts
feature_type = "feature" if pca_model is None else "pc"
for seg_in in range(np.sum(seg_in_group)):
feature_names_out_ += [
"_".join([group_name, str(seg_in), feature_type + str(n)]) for n in range(2)
]
else:
seg_in_group = [True if (group_name==_) and (side_[i_]==side) else False for i_, _ in enumerate(all_features)]
feature_type = "feature" if pca_model is None else "pc"
for seg_in in range(np.sum(seg_in_group)):
feature_names_out_ += [
"_".join([group_name+"_"+str(side), str(seg_in), feature_type + str(n)]) for n in range(2)
]
return feature_names_out_
pca_features_names = generate_feature_names(pca_models_)
return components_, pca_features_names , explained_variance_, features_out, explained_variance_ratio_, \
singular_values_, mean_, n_components_, noise_variance_, pca_models_, groups_out_
# import shap
# shap.initjs()
from alibi.explainers import KernelShap
def class_labels(classifier, instance, class_names=None):
"""
Creates a set of legend labels based on the decision
scores of a classifier and, optionally, the class names.
"""
decision_scores = classifier.decision_function(instance)
if not class_names:
class_names = [f'Class {i}' for i in range(decision_scores.shape[1])]
for i, score in enumerate(np.nditer(decision_scores)):
class_names[i] = class_names[i] + ' ({})'.format(round(score.item(),3))
return class_names
import cv2
import time
import json
import base64
# import requests
"""
def send_image(img):
#Convert image to sendable format and store in JSON
# _, encimg = cv2.imencode(".png ", img)
# encimg = img.canvas.tostring_rgb()
# img_str = encimg.tostring()
# img_byte = base64.b64encode(img_str)#.decode("utf-8")
# image = open(img, 'rb') #open binary file in read mode
# img_byte = base64.encodebytes(image.read())
# img_json = img_byte.encode('utf-8')
# image.close()
with open(img, mode='rb') as file:
img = file.read()
img_json = base64.encodebytes(img).decode('utf-8')
return img_json
from flask import Flask, request, Response
app = Flask(__name__)
def save_image():
#Data conversion process
data = request.data.decode('utf-8')
data_json = json.loads(data)
image = data_json['image']
image_dec = base64.b64decode(image)
data_np = np.fromstring(image_dec, dtype='uint8')
decimg = cv2.imdecode(data_np, 1)
"""
def plot_to_notebook(img,img_path,section_name,train_results):
print("Plotting to notebook")
means = str({"\nmean_"+key:(np.nanmean(val),np.nanstd(val)) for key, val in train_results.items()})
empty_notebook = { "cells": [],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
}
img_path = img_path.split(".")[0] + "_" + str("_".join([str(vvv) if len(str(vvv).split())<=1 else str(vvv).split()[1]
for vvv in section_name.values()])) + ".ipynb"
if not os.path.exists("/".join(img_path.split("/")[:-1])):
os.makedirs("/".join(img_path.split("/")[:-1]))
if os.path.exists(img_path):
with open(img_path,"r") as _reader:
empty_notebook = json.loads(_reader.read())
_reader.close()
temp_img = img_path.split(".")[0]+"_temp.png"
img.savefig(temp_img)
empty_notebook["cells"].append({"cell_type":"code","metadata":{},"source":["# %s\n"%str(section_name) +
str(means) + "\n"],
"execution_count":1,"outputs":[{"data": {"image/png":send_image(temp_img)},
"metadata": {"needs_background": "light"},
"output_type": "display_data"}]})
os.remove(temp_img)
with open(img_path,"w") as _writer:
json.dump(empty_notebook,_writer)
_writer.close()
def plot_coef(coeff,true_coeff,mp,pv,feat_names,coeff_path,model_name,params,train_results,refresh=True):
if False and (not os.path.exists(coeff_path) or refresh):
print("Plotting feature importances")
if coeff is None:
coeff = true_coeff
if len(coeff.shape)>len(true_coeff.shape):
coeff_ = [coeff[:,_,:] for _ in range(len(coeff[0]))]
dfs = []
most_ = np.argsort(abs(coeff.mean(axis=(0,1))))[::-1]
for ic_, coeff in enumerate(coeff_):
dfs.append(pd.DataFrame(coeff.T[most_].T.reshape((coeff.size,1)),columns=["coeff"]))
dfs[-1]["feature"] = np.array([feat_names[most_] for _ in range(len(coeff))]).flatten()
dfs[-1]["class"] = ic_
coeff = pd.concat(dfs,ignore_index=True)
fig, ax = plt.subplots(1,1,figsize=(24,4*len(coeff_[0][0])//20))
ax = sns.barplot(x="coeff",y="feature",hue="class",data=coeff,ax=ax,orient="h")
# ax = coef_to_plot.plot(kind = "barh",ax=ax, fontsize=8)
try:
ax.get_legend().remove()
except Exception:
pass
ax.boxplot(true_coeff[:,most_],vert=False)
ax.set_yticks(np.arange(len(feat_names[most_])))
ax.set_yticklabels(feat_names[most_])
ax.set_title("Feature importance using %s Model"%model_name)
plot_to_notebook(fig,coeff_path,params,train_results)
else:
most_ = np.argsort(abs(coeff).mean(0))[::-1]
to_plot = most_
fig, ax = plt.subplots(1,1,figsize=(24,4*len(coeff[0][0])//20))
# coef_to_plot = pd.DataFrame(coeff[this_plot],columns=feat_names[this_plot])
ax = sns.barplot(data=coeff[:,this_plot],ax=ax)
# ax = coef_to_plot.plot(kind = "barh",ax=ax, fontsize=8)
try:
ax.get_legend().remove()
except Exception:
pass
ax.boxplot(true_coeff[:,this_plot],vert=False)
ax.set_yticks(np.arange(len(feat_names[this_plot])))
ax.set_yticklabels(feat_names[this_plot])
# if iax%2!=0:
# ax.yaxis.tick_right()
ax.set_title("Feature importance using %s Model"%model_name)
plot_to_notebook(fig,coeff_path,params,train_results)
else:
data = np.array([np.nan_to_num(np.nanmean(true_coeff,axis=0),posinf=0, neginf=0),
np.nan_to_num(np.nanstd(true_coeff,axis=0),posinf=0, neginf=0)])
data = np.nan_to_num(data,posinf=0, neginf=0) # /data[0].sum()
columns = ["true_mean","true_std"]
if not (coeff is None):
coeff_ = np.nan_to_num(np.nanmean(np.array([coeff[:,_,:] for _ in range(len(coeff[0]))]),axis=1),posinf=0, neginf=0)
data = np.concatenate((coeff_,data),axis=0).T
columns = np.append(["coeff_%s"%iop for iop in range(len(coeff_))],columns)
else:
coeff_ = np.nan_to_num(np.nanmean(np.array([coeff[:,_,:] for _ in range(len(coeff[0]))]),axis=1),posinf=0, neginf=0)
data = np.concatenate((coeff_,data),axis=0).T
columns = np.append(["coeff_%s"%iop for iop in range(len(coeff_))],columns)
df = pd.DataFrame(data=data,columns=columns,index=feat_names).sort_values(by="true_mean",ascending=False)
# if os.path.exists(coeff_path):
# old_df = pd.read_csv(coeff_path)
# df = pd.concat((df,old_df),axis=0,ignore_index=True)
df["mean_perf"] = np.nan_to_num(np.nanmean(mp))
df["mean_pval"] = np.nan_to_num(np.nanmean(pv))
if not os.path.exists("/".join(coeff_path.split("/")[:-1])):
os.makedirs("/".join(coeff_path.split("/")[:-1]))
df.to_csv(coeff_path)
import shutup
def get_importance(ensemble_estimator,pipeline,X,y,train,test,attr__=None,feature_names_in_=None,cv=None,shap=False,figname=None):
print("Computing feature importances")
warnings.filterwarnings("ignore")
shutup.please()
def my_getattr(estimator__,attr__=attr__,feature_names_in_=feature_names_in_):
# print("============================="+str(estimator__.__class__.__name__)+"====================================")
if estimator__.__class__.__name__ in ("RandomForestClassifier","My_RandomForestClassifier") \
and (attr__ is None) and not (estimator__.__class__.__name__ == "LogisticRegressionCV"):
all_importances = get_importance(estimator__,attr__=attr__,feature_names_in_=feature_names_in_)
return [{feat_name__:feat_importance for feat_name__,feat_importance in zip(feature_names_in_[an_imp!=0],an_imp[an_imp!=0])}
for an_imp in all_importances]
elif estimator__.__class__.__name__ in ("BaggingClassifier","My_BaggingClassifier") \
and (attr__ is None) and not (estimator__.__class__.__name__ == "LogisticRegressionCV"):
all_importances = get_importance(estimator__,attr__=attr__,feature_names_in_=feature_names_in_)
return [{feat_name__:feat_importance for feat_name__,feat_importance in zip(feature_names_in_[an_imp!=0],an_imp[an_imp!=0])}
for an_imp in all_importances]
elif estimator__.__class__.__name__ == "DecisionTreeClassifier" \
and (attr__ is None) and not (estimator__.__class__.__name__ == "LogisticRegressionCV"):
all_importances = estimator__.feature_importances_
feature_names_in__ = feature_names_in_
return {feat_name__:feat_importance for feat_name__,feat_importance in zip(feature_names_in__,all_importances)}
elif attr__ is None:
return [{feat_name__:feat_importance for feat_name__,feat_importance in zip(feature_names_in_,a_coeff)}
for a_coeff in estimator__.coef_]
elif attr__ == "l1_ratio_":
return {feat_name__:feat_importance for feat_name__,feat_importance in zip(feature_names_in_,estimator__.l1_ratio_)}
else:
print("I don't know this attribute :( : " + str(attr__))