-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpaper_code.py
1624 lines (1470 loc) · 83.4 KB
/
paper_code.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
# ruff: noqa
import datetime
from functools import reduce
import math
import random
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
from sklearn import clone
from sklearn.calibration import calibration_curve, label_binarize
from sklearn.decomposition import PCA
from sklearn.feature_selection import RFECV
from sklearn.linear_model import LassoCV
from sklearn.metrics import auc, brier_score_loss
from sklearn.model_selection import StratifiedKFold, train_test_split
from sklearn.svm import SVC
from xgboost import XGBClassifier
def ML_Classfication(
df: pd.DataFrame,
group: str,
features: list[str],
decimal_num=3,
validation_ratio=0.15,
scoring='roc_auc',
method='KNeighborsClassifier',
n_splits=10,
explain=True,
shapSet=2,
explain_numvar=2,
explain_sample=2,
searching=False,
validationCurve=False,
smooth=False,
savePath=None,
dpi=600,
picFormat='jpeg',
label='LABEL',
trainSet=False,
modelSave=True,
trainLabel=0,
randomState=1,
resultType=0,
**kwargs,
):
"""
Machine learning classification analysis
Input:
df: DataFrame Input data to be processed
group_name:str Group name (label)
validation_ratio:float Test set proportion
scoring:str Target evaluation index
method:str Machine learning classification methods used/Model
'LogisticRegression':LogisticRegression(**kwargs),
'XGBClassifier':XGBClassifier(**kwargs),
'RandomForestClassifier':RandomForestClassifier(**kwargs),
'SVC':SVC(**kwargs),
'KNeighborsClassifier':KNeighborsClassifier(**kwargs),
n_splits:int Number of subsets for cross-validation
explain:bool Whether to perform model interpretation
explain_numvar:int Number of variables to explain
explain_sample:int Number of samples requiring explanation
searching:bool Whether to perform automatic parameter search, defaults to No
savePath:str Image storage path
**kwargs:dict Parameters for using machine learning classification methods
Return:
df_dict: dataframe Dictionary, containing:
df_train_result: Model performance on the training set
df_test_result: Model performance on the test set
str_result: Summary of analysis results
plot_name_list: Image file name list
"""
name_dict = {
'LogisticRegression': 'logistic',
'XGBClassifier': 'XGBoost',
'RandomForestClassifier': 'RandomForest',
'LGBMClassifier': 'LightGBM',
'SVC': 'SVM',
'MLPClassifier': 'MLP',
'GaussianNB': 'GNB',
'ComplementNB': 'CNB',
'AdaBoostClassifier': 'AdaBoost',
'KNeighborsClassifier': 'KNN',
'DecisionTreeClassifier': 'DecisionTree',
'BaggingClassifier': 'Bagging',
}
list_name = [group]
plot_name_dict_save = {} ## Store pictures
result_model_save = {} ## Model storage
resThreshold = 0 ## Used to store the final threshold
conf_dic_train, conf_dic_valid, conf_dic_test = {}, {}, {}
if trainSet:
df = df[features + [group] + [label]].dropna()
for fea in features:
if fea == label or label == group:
return {'error': 'The label column cannot be in the model, please reselect the label column for data division!'}
else:
df = df[features + [group]].dropna()
binary = True
u = np.sort(np.unique(np.array(df[group])))
if len(u) == 2 and set(u) != set([0, 1]):
y_result = label_binarize(df[group], classes=[ii for ii in u]) # Binarize labels
y_result_pd = pd.DataFrame(y_result, columns=[group])
df = pd.concat([df.drop(group, axis=1), y_result_pd], axis=1)
elif len(u) > 2:
if len(u) > 10:
return {'error': 'The number of categories greater than 10 is not allowed for the time being. Please check the value of the dependent variable'}
binary = False
if scoring == 'roc_auc':
scoring = scoring + '_ovo'
else:
scoring = scoring + '_macro'
return {'error': 'Currently only two categories are supported. Please check the value of the dependent variable'}
if trainSet:
if isinstance(df[label][0], str):
trainLabel = str(trainLabel)
df = df[features + [group] + [label]].dropna()
train_a = df[df[label] == trainLabel]
test_a = df[df[label] != trainLabel]
train_all = train_a.drop(label, axis=1)
test_all = test_a.drop(label, axis=1)
# features.remove(fea)
df = df.drop(label, axis=1)
Xtrain = train_all.drop(group, axis=1)
Ytrain = train_all.loc[:, list_name].squeeze(axis=1)
Xtest = test_all.drop(group, axis=1)
Ytest = test_all.loc[:, list_name].squeeze(axis=1)
else:
df = df[features + [group]].dropna()
X = df.drop(group, axis=1)
Y = df.loc[:, list_name].squeeze(axis=1)
Xtrain, Xtest, Ytrain, Ytest = train_test_split(X, Y, test_size=validation_ratio, random_state=randomState, )
df_dict = {}
str_result = "The %s machine learning method is used for classification. The classification variable is %s. The variables in the model include" % (method, group)
str_result += '|'.join(features)
if searching == True:
if method == 'LGBMClassifier':
searcher = GridSearcherCV('Classification', globals()[method]())
clf = searcher(Xtrain, Ytrain);
searcher.report()
else:
searcher = RandSearcherCV('Classification', globals()[method]())
clf = searcher(Xtrain, Ytrain);
searcher.report()
elif searching == 'Handle':
if (method == 'SVC'):
kwargs['probability'] = True
if (method == 'RandomForestClassifier' and kwargs['max_depth'] == 'None'):
kwargs['max_depth'] = None
if (method == 'MLPClassifier'):
hls_vals = str(kwargs['hidden_layer_sizes']).split(',')
hls_value = ()
for hls_val in hls_vals:
try:
if int(hls_val) >= 5 and int(hls_val) <= 200:
hls_value = hls_value + (int(hls_val),)
else:
return {'error': 'Please reset the hidden layer width as required!'}
except Exception:
return {'error': 'Please reset the hidden layer width in the neural network model'}
kwargs['hidden_layer_sizes'] = hls_value
if (method == 'GaussianNB' and kwargs['priors'] == 'None'):
kwargs['priors'] = None
elif (method == 'GaussianNB'):
pri_vals = str(kwargs['priors']).split(',')
pri_value = ()
pri_sum = 0.0
for pri_val in pri_vals:
try:
pri_sum = float(pri_val) + pri_sum
pri_value = pri_value + (float(pri_val),)
except:
return {'error': 'Please reset the prior probability in the naive Bayes model'}
if len(pri_vals) == len(Y.unique()) and pri_sum == 1.0:
kwargs['priors'] = pri_value
else:
return {'error': 'Please reset the prior probability in the naive Bayes model'}
clf = globals()[method](**kwargs).fit(Xtrain, Ytrain)
elif searching == False:
# if (method == 'SVC'): kwargs['probability'] = True
if method == 'SVC':
kwargs['probability'] = True
elif method == 'MLPClassifier':
kwargs['hidden_layer_sizes'] = (20, 10)
kwargs['max_iter'] = 20
elif method == 'RandomForestClassifier':
kwargs['n_estimators'] = 20
clf = globals()[method](**kwargs).fit(Xtrain, Ytrain)
str_result += "\nThe model parameters are:\n%s" % dic2str(clf.get_params(), clf.__class__.__name__)
str_result += "\nTotal number of samples in the datasetN=%dFor example, the category information contained in the strain variable is:\n" % (df.shape[0])
group_labels = df[group].unique()
group_labels.sort()
for label in group_labels:
n = sum(df[group] == label)
str_result += "\t category(" + str(label) + "): N=" + str(n) + "example\n"
plot_name_list = x5.plot_learning_curve(
clf,
Xtrain,
Ytrain,
cv=n_splits,
scoring=scoring,
path=savePath,
dpi=dpi,
picFormat=picFormat,
)
plot_name_dict_save['learning curve'] = plot_name_list[1]
plot_name_list.pop(len(plot_name_list) - 1)
### draw calibration curve
calibration_curve_name, _ = plot_calibration_curve(clf, Xtrain, Xtest, Ytrain, Ytest, name=method, path=savePath,
smooth=smooth,
picFormat=picFormat, dpi=dpi, )
plot_name_list.append(calibration_curve_name[0])
plot_name_dict_save['calibration curve'] = calibration_curve_name[1]
if binary:
fig = plt.figure(figsize=(4, 4), dpi=dpi)
# draw diagonal lines
plt.plot(
[0, 1], [0, 1],
linestyle='--',
lw=1, color='r',
alpha=0.8,
)
plt.grid(which='major', axis='both', linestyle='-.', alpha=0.08, color='grey')
best_auc = 0.0
tprs_train, tprs_valid = [], []
fpr_train_alls, tpr_train_alls = [], []
mean_fpr = np.linspace(0, 1, 100)
list_evaluate_dic_train = make_class_metrics_dict()
list_evaluate_dic_valid = make_class_metrics_dict()
# KF = KFold(n_splits=n_splits, random_state=randomState,shuffle=True)##StratifiedKFold
KF = StratifiedKFold(n_splits=n_splits, random_state=randomState, shuffle=True)
for i, (train_index, valid_index) in enumerate(KF.split(Xtrain, Ytrain)):
# Divide training set and validation set
X_train, X_valid = Xtrain.iloc[train_index], Xtrain.iloc[valid_index]
Y_train, Y_valid = Ytrain.iloc[train_index], Ytrain.iloc[valid_index]
# Build the model (the model has been defined) and train
model = clone(clf).fit(X_train, Y_train)
# Use the classification_metric_evaluate function to obtain the predicted value in the validation set
fpr_train, tpr_train, metric_dic_train, _ = classification_metric_evaluate(model, X_train, Y_train, binary)
fpr_valid, tpr_valid, metric_dic_valid, _ = classification_metric_evaluate(model, X_valid, Y_valid, binary,
Threshold=metric_dic_train['cutoff'])
metric_dic_valid.update({'cutoff': metric_dic_train['cutoff']})
# model selection using validation set
if metric_dic_valid['AUC'] > best_auc:
clf = model
resThreshold = metric_dic_train['cutoff']
# Calculate all evaluation indicators
for key in list_evaluate_dic_train.keys():
list_evaluate_dic_train[key].append(metric_dic_train[key])
list_evaluate_dic_valid[key].append(metric_dic_valid[key])
if binary:
# interp: Interpolate and add the result to the tprs list
tprs_valid.append(np.interp(mean_fpr, fpr_valid, tpr_valid))
tprs_valid[-1][0] = 0.0
# To draw a picture, you only need plt.plot(fpr,tpr). The variable roc_auc just records the value of auc and calculates it through the auc() function.
if validationCurve:
plt.plot(
fpr_valid, tpr_valid,
lw=1, alpha=0.4,
label='ROC fold %4d (auc=%0.3f 95%%CI (%0.3f-%0.3f))' % (
i + 1, metric_dic_valid['AUC'], metric_dic_valid['AUC_L'], metric_dic_valid['AUC_U']),
)
##Training set ROC
fpr_train_alls.append(fpr_train)
tpr_train_alls.append(tpr_train)
tprs_train.append(np.interp(mean_fpr, fpr_train, tpr_train))
tprs_train[-1][0] = 0.0
if modelSave:
import pickle
modelfile = open(savePath + method + str_time + '.pkl', 'wb')
pickle.dump(clf, modelfile)
modelfile.close()
result_model_save['modelFile'] = method + str_time + '.pkl'
result_model_save['modelFeature'] = features
if binary:
mean_tpr_valid = np.mean(tprs_valid, axis=0)
mean_tpr_valid[-1] = 1.0
mean_auc = auc(mean_fpr, mean_tpr_valid) # Calculate average AUC value
aucs_lower, aucs_upper = ci(list_evaluate_dic_valid['AUC'])
plt.plot(
mean_fpr, mean_tpr_valid,
color='b',
lw=2, alpha=0.8,
label=r'Mean (validation) ROC (auc=%0.3f 95%%CI (%0.3f-%0.3f))' % (
mean_auc, np.mean(list_evaluate_dic_valid['AUC_L']), np.mean(list_evaluate_dic_valid['AUC_U'])),
# label = r'Mean ROC (auc=%0.3f 0.95CI(%0.3f-%0.3f)' % (mean_auc, aucs_lower, aucs_upper),
)
mean_dic_train, stdv_dic_train = {}, {}
mean_dic_valid, stdv_dic_valid = {}, {}
for key in list_evaluate_dic_valid.keys():
mean_dic_train[key] = np.mean(list_evaluate_dic_train[key])
mean_dic_valid[key] = np.mean(list_evaluate_dic_valid[key])
if resultType == 0: ##SD
stdv_dic_train[key] = np.std(list_evaluate_dic_train[key], axis=0)
stdv_dic_valid[key] = np.std(list_evaluate_dic_valid[key], axis=0)
elif resultType == 1: ##CI
conf_dic_train[key] = list(ci(list_evaluate_dic_train[key]))
conf_dic_valid[key] = list(ci(list_evaluate_dic_valid[key]))
# if resultType == 0: ##SD
# df_train_result = pd.DataFrame([mean_dic_train, stdv_dic_train], index=['Mean', 'SD'])
# df_train_result = df_train_result.applymap(lambda x: round_dec(x, d=decimal_num))
# df_valid_result = pd.DataFrame([mean_dic_valid, stdv_dic_valid], index=['Mean', 'SD'])
# df_valid_result = df_valid_result.applymap(lambda x: round_dec(x, d=decimal_num))
fpr_test, tpr_test, metric_dic_test, df_test_result = classification_metric_evaluate(clf, Xtest, Ytest, binary,
Threshold=resThreshold)
metric_dic_test.update({'cutoff': resThreshold})
# plt.plot(
# fpr_test, tpr_test,
# lw=1.5, alpha=0.6,
# label='Test Set ROC (auc=%0.3f) ' % metric_dic_test['AUC'],
# )
plt.xlim([-0.02, 1.02])
plt.ylim([-0.02, 1.02])
plt.xlabel('1-Specificity')
plt.ylabel('Sensitivity')
plt.title('Validation ROC')
plt.legend(loc='lower right', fontsize=5)
if savePath is not None:
plot_name_list.append(save_fig(savePath, 'ROC_curve', 'png', fig, str_time=str_time))
plot_name_dict_save['Validation set ROC curve'] = save_fig(savePath, 'ROC_curve', picFormat, fig, str_time=str_time)
plt.close()
##Draw training set ROC
if binary:
fig = plt.figure(figsize=(4, 4), dpi=dpi)
# draw diagonal lines
plt.plot(
[0, 1], [0, 1],
linestyle='--',
lw=1, color='r',
alpha=0.8,
)
plt.grid(which='major', axis='both', linestyle='-.', alpha=0.08, color='grey')
if validationCurve:
for i in range(len(tpr_train_alls)):
plt.plot(
fpr_train_alls[i], tpr_train_alls[i],
lw=1, alpha=0.4,
label='ROC fold %4d (auc=%0.3f 95%%CI (%0.3f-%0.3f)) ' % (
i + 1, list_evaluate_dic_train['AUC'][i], list_evaluate_dic_train['AUC_L'][i],
list_evaluate_dic_train['AUC_U'][i]),
)
mean_tpr_train = np.mean(tprs_train, axis=0)
mean_tpr_train[-1] = 1.0
mean_auc_train = auc(mean_fpr, mean_tpr_train) # Calculate average AUC value
plt.plot(
mean_fpr, mean_tpr_train,
color='b',
lw=1.8, alpha=0.7,
label=r'Mean (train) ROC (auc=%0.3f 95%%CI (%0.3f-%0.3f))' % (
mean_auc_train, np.mean(list_evaluate_dic_train['AUC_L']), np.mean(list_evaluate_dic_train['AUC_U'])),
# label = r'Mean ROC (auc=%0.3f 0.95CI(%0.3f-%0.3f)' % (mean_auc, aucs_lower, aucs_upper),
)
plt.xlim([-0.02, 1.02])
plt.ylim([-0.02, 1.02])
plt.xlabel('1-Specificity')
plt.ylabel('Sensitivity')
plt.title('Train ROC')
plt.legend(loc='lower right', fontsize=5)
if savePath is not None:
plot_name_list.append(save_fig(savePath, 'ROC_curve_train', 'png', fig, str_time=str_time))
plot_name_dict_save['Training set ROC curve'] = save_fig(savePath, 'ROC_curve_train', picFormat, fig, str_time=str_time)
plt.close()
plot_name_list.reverse() ### All images upside down
### Draw test set ROC
fig = plt.figure(figsize=(4, 4), dpi=dpi)
# draw diagonal lines
plt.plot(
[0, 1], [0, 1],
linestyle='--',
lw=1, color='r',
alpha=0.8,
)
plt.grid(which='major', axis='both', linestyle='-.', alpha=0.08, color='grey')
if smooth:
from scipy.interpolate import interp1d
tpr_test_unique, tpr_test_index = np.unique(fpr_test, return_index=True)
fpr_test_new = np.linspace(min(fpr_test), max(fpr_test), len(fpr_test))
f = interp1d(tpr_test_unique, tpr_test[tpr_test_index], kind='linear') ##cubic
tpr_test_new = f(fpr_test_new)
else:
fpr_test_new = fpr_test
tpr_test_new = tpr_test
plt.plot(
fpr_test_new, tpr_test_new,
lw=1.5, alpha=0.6, color='b',
label='Test Set ROC (auc=%0.3f 95%%CI (%0.3f-%0.3f)) ' % (
metric_dic_test['AUC'], metric_dic_test['AUC_L'], metric_dic_test['AUC_U']),
)
plt.xlim([-0.02, 1.02])
plt.ylim([-0.02, 1.02])
plt.xlabel('1-Specificity')
plt.ylabel('Sensitivity')
plt.title('Test ROC')
plt.legend(loc='lower right', fontsize=5)
if savePath is not None:
plot_name_list.append(save_fig(savePath, 'ROC_curve_test', 'png', fig, str_time=str_time))
plot_name_dict_save['Test set ROC curve'] = save_fig(savePath, 'ROC_curve_test', picFormat, fig, str_time=str_time)
plt.close()
# df_test_result = df_test_result.applymap(lambda x: round_dec(x, d=decimal_num))
if trainSet:
df_count_c = Xtest.shape[0]
df_count_r = (Xtest.shape[0] / df.shape[0]) * 100
else:
df_count_c = df.shape[0] * validation_ratio
df_count_r = validation_ratio * 100
diff, ratio = 0, 0
if resultType == 1: ##CI
str_result += "Among them, the test set N=%d examples (%3.2f%%) were randomly selected from the overall sample, and the remaining samples were used as training sets for %d-fold cross-validation, and AUC=%5.4f(%5.4f-%) was obtained in the validation set 5.4f). \nThe AUC of the final model in the test set=%5.4f, and the accuracy=%5.4f. \n" % (
df_count_c,
df_count_r,
n_splits,
mean_dic_valid['AUC'],
mean_dic_valid['AUC_L'],
mean_dic_valid['AUC_U'],
df_test_result['AUC'].values[0],
df_test_result['Accuracy'].values[0]
)
diff = mean_dic_valid['AUC'] - float(df_test_result.loc['Mean', 'AUC'])
ratio = diff / float(df_test_result.loc['Mean', 'AUC'])
elif resultType == 0: ##SD
str_result += "Among them, the test set N=%d examples (%3.2f%%) were randomly selected from the overall sample, and the remaining samples were used as training sets for %d-fold cross-validation, and AUC=%5.4f±%5.4f was obtained in the validation set. \nThe AUC of the final model in the test set=%5.4f, and the accuracy=%5.4f. \n" % (
df_count_c,
df_count_r,
n_splits,
mean_dic_valid['AUC'],
stdv_dic_valid['AUC'],
df_test_result['AUC'].values[0],
df_test_result['Accuracy'].values[0]
)
diff = float(stdv_dic_valid['AUC']) - float(df_test_result.loc['Mean', 'AUC'])
ratio = diff / float(df_test_result.loc['Mean', 'AUC'])
if (not np.isnan(float(diff)) and diff > 0 and (ratio > 0.1)):
str_result += 'It is noted that the performance of the validation set under the AUC index exceeds the test set by {} by about {}%, and there may be overfitting. It is recommended to change the model or reset the parameters.'.format(round(diff, decimal_num),
round(ratio * 100, decimal_num))
else:
str_result += 'Since the performance of the validation set under the AUC index does not exceed that of the test set or the excess ratio is less than 10%, it can be considered that the fitting is successful and the {} model can be used for the classification modeling task of this data set.'.format(name_dict[method])
str_result += "\nIf you want to further compare the performance of more classification models, you can use the ‘Classification Multi-Model Comprehensive Analysis’ function in the intelligent analysis on the left column."
df_test_result = df_test_result.applymap(lambda x: round_dec(x, d=decimal_num))
if resultType == 1: ##CI
for tem in ['AUC', 'AUC_L', 'AUC_U']:
del conf_dic_train[tem]
del conf_dic_valid[tem]
for key in conf_dic_train.keys():
mean_dic_train[key] = str(round_dec(float(mean_dic_train[key]), d=decimal_num)) + '(' + \
str(round_dec(float(conf_dic_train[key][0]), d=decimal_num)) + '-' + \
str(round_dec(float(conf_dic_train[key][1]), d=decimal_num)) + ')'
mean_dic_valid[key] = str(round_dec(float(mean_dic_valid[key]), d=decimal_num)) + '(' + \
str(round_dec(float(conf_dic_valid[key][0]), d=decimal_num)) + '-' + \
str(round_dec(float(conf_dic_valid[key][1]), d=decimal_num)) + ')'
df_train_result = pd.DataFrame([mean_dic_train], index=['Mean'])
# df_train_result = df_train_result.applymap(lambda x: round_dec(x, d=decimal_num))
df_valid_result = pd.DataFrame([mean_dic_valid], index=['Mean'])
df_train_result.iloc[0, 0] = str(round_dec(float(df_train_result.iloc[0, 0]), d=decimal_num)) + '(' + \
str(round_dec(float(df_train_result.iloc[0, -2]), d=decimal_num)) + '-' + \
str(round_dec(float(df_train_result.iloc[0, -1]), d=decimal_num)) + ')'
df_valid_result.iloc[0, 0] = str(round_dec(float(df_valid_result.iloc[0, 0]), d=decimal_num)) + '(' + \
str(round_dec(float(df_valid_result.iloc[0, -2]), d=decimal_num)) + '-' + \
str(round_dec(float(df_valid_result.iloc[0, -1]), d=decimal_num)) + ')'
df_train_result.rename(columns={"AUC": 'AUC(95%CI)', 'cutoff': 'cutoff(95%CI)', 'Accuracy': 'Accuracy(95%CI)',
'Sensitivity': 'Sensitivity(95%CI)', 'Specificity': 'Specificity(95%CI)',
'positive predictive value': 'positive predictive value(95%CI)', 'negative predictive value': 'negative predictive value(95%CI)',
'F1 score': 'F1 score(95%CI)', 'Kappa': 'Kappa(95%CI)'}, inplace=True)
df_valid_result.rename(columns={"AUC": 'AUC(95%CI)', 'cutoff': 'cutoff(95%CI)', 'Accuracy': 'Accuracy(95%CI)',
'Sensitivity': 'Sensitivity(95%CI)', 'Specificity': 'Specificity(95%CI)',
'positive predictive value': 'positive predictive value(95%CI)', 'negative predictive value': 'negative predictive value(95%CI)',
'F1 score': 'F1 score(95%CI)', 'Kappa': 'Kappa(95%CI)'}, inplace=True)
df_test_result.iloc[0, 0] = str(df_test_result.iloc[0, 0]) + ' (' + str(df_test_result.iloc[0, -2]) + '-' + str(
df_test_result.iloc[0, -1]) + ')'
df_test_result.rename(columns={"AUC": 'AUC (95%CI)'}, inplace=True)
elif resultType == 0: ##SD
for tem in ['AUC_L', 'AUC_U']:
del stdv_dic_train[tem]
del stdv_dic_valid[tem]
for key in stdv_dic_train.keys():
mean_dic_train[key] = str(round_dec(float(mean_dic_train[key]), d=decimal_num)) + ' (' + \
str(round_dec(float(stdv_dic_train[key]), d=decimal_num)) + ')'
mean_dic_valid[key] = str(round_dec(float(mean_dic_valid[key]), d=decimal_num)) + ' (' + \
str(round_dec(float(stdv_dic_valid[key]), d=decimal_num)) + ')'
df_train_result = pd.DataFrame([mean_dic_train], index=['Mean'])
df_valid_result = pd.DataFrame([mean_dic_valid], index=['Mean'])
df_train_result.rename(columns={"AUC": 'AUC(SD)', 'cutoff': 'cutoff(SD)', 'Accuracy': 'Accuracy(SD)',
'Sensitivity': 'Sensitivity(SD)', 'Specificity': 'Specificity(SD)',
'positive predictive value': 'positive predictive value(SD)', 'negative predictive value': 'negative predictive value(SD)',
'F1 score': 'F1 score(SD)', 'Kappa': 'Kappa(SD)'}, inplace=True)
df_valid_result.rename(columns={"AUC": 'AUC(SD)', 'cutoff': 'cutoff(SD)', 'Accuracy': 'Accuracy(SD)',
'Sensitivity': 'Sensitivity(SD)', 'Specificity': 'Specificity(SD)',
'positive predictive value': 'positive predictive value(SD)', 'negative predictive value': 'negative predictive value(SD)',
'F1 score': 'F1 score(SD)', 'Kappa': 'Kappa(SD)'}, inplace=True)
df_dictjq = {
'Summary of training set results': df_train_result.iloc[0:2, 0:8],
'Summary of validation set results': df_valid_result.iloc[0:2, 0:8],
'Summary of test set results': df_test_result.iloc[0:2, 0:8],
}
df_dict.update(df_dictjq)
plot_name_dict = {
'Training set ROC curve chart': plot_name_list[0],
'Validation set ROC curve chart': plot_name_list[1],
'Test set ROC curve chart': plot_name_list[4],
'learning curve chart': plot_name_list[3],
'Model calibration curve': plot_name_list[2],
}
if binary: ###Draw DCA curve
DCA_dict = {}
prob_pos, p_serie, net_benefit_serie, net_benefit_serie_All = calculate_net_benefit(clf, Xtest, Ytest)
DCA_dict[name_dict[method]] = {'p_serie': p_serie, 'net_b_s': net_benefit_serie,
'net_b_s_A': net_benefit_serie_All}
decision_curve_p = plot_decision_curves(DCA_dict, colors=colors, name='Test', savePath=savePath, dpi=dpi,
picFormat=picFormat)
plot_name_dict['Test set DCA curve chart'] = decision_curve_p[0]
plot_name_dict_save['Test set DCA curve chart'] = decision_curve_p[1]
if explain or modelSave:
import shap
# from interpret.blackbox import LimeTabular, PartialDependence
f = lambda x: clf.predict_proba(x)[:, 1]
med = Xtrain.median().values.reshape((1, Xtrain.shape[1]))
result_model_save['modelShapValue'] = list(med[0])
result_model_save['modelName'] = method
result_model_save['modelClass'] = 'Machine learning classification'
result_model_save['Threshold'] = resThreshold
df_shapValue = Xtest
df_shapValue_show = pd.DataFrame()
shapValue_list = []
shapValue_name = []
if explain:
if shapSet == 2: ##Xtrain, Xtest, Ytrain, Ytest
df_shapValue = Xtest
if (explain_sample == 4):
flage1, flage2, flage3, flage4 = True, True, True, True
for i in range(len(Ytest)):
if (flage1 and f(df_shapValue.iloc[i:i + 1, :])[0] >= resThreshold and Ytest.iloc[i,] == 1):
df_shapValue_show = pd.concat([df_shapValue_show, df_shapValue.iloc[i:i + 1, :]], axis=0)
shapValue_list.append(i)
shapValue_name.append('shap_sample_predicted value is 1 actual value is 1')
flage1 = False
elif (flage2 and f(df_shapValue.iloc[i:i + 1, :])[0] >= resThreshold and Ytest.iloc[i,] == 0):
df_shapValue_show = pd.concat([df_shapValue_show, df_shapValue.iloc[i:i + 1, :]], axis=0)
shapValue_list.append(i)
shapValue_name.append('shap_sample_predicted value is 1 and actual value is 0')
flage2 = False
elif (flage3 and f(df_shapValue.iloc[i:i + 1, :])[0] < resThreshold and Ytest.iloc[i,] == 1):
df_shapValue_show = pd.concat([df_shapValue_show, df_shapValue.iloc[i:i + 1, :]], axis=0)
shapValue_name.append('shap_sample_predicted value is 0 and actual value is 1')
shapValue_list.append(i)
flage3 = False
elif (flage4 and f(df_shapValue.iloc[i:i + 1, :])[0] < resThreshold and Ytest.iloc[i,] == 0):
df_shapValue_show = pd.concat([df_shapValue_show, df_shapValue.iloc[i:i + 1, :]], axis=0)
shapValue_name.append('shap_sample_predicted value is 0 actual value is 0')
shapValue_list.append(i)
flage4 = False
if (not flage1 and not flage2 and not flage3 and not flage4):
break
else:
df_shapValue_show = pd.concat([df_shapValue_show, df_shapValue.iloc[0:explain_sample, :]], axis=0)
shapValue_list.extend(i for i in range(explain_sample))
shapValue_name.extend('shap_sample_' + str(i) for i in range(explain_sample))
elif shapSet == 1:
df_shapValue = Xtrain
if (explain_sample == 4):
flage1, flage2, flage3, flage4 = True, True, True, True
for i in range(len(Ytrain)):
if (flage1 and f(df_shapValue.iloc[i:i + 1, :])[0] >= resThreshold and Ytrain.iloc[i,] == 1):
df_shapValue_show = pd.concat([df_shapValue_show, df_shapValue.iloc[i:i + 1, :]], axis=0)
shapValue_name.append('shap_sample_predicted value is 1 actual value is 1')
shapValue_list.append(i)
flage1 = False
elif (flage2 and f(df_shapValue.iloc[i:i + 1, :])[0] >= resThreshold and Ytrain.iloc[i,] == 0):
df_shapValue_show = pd.concat([df_shapValue_show, df_shapValue.iloc[i:i + 1, :]], axis=0)
shapValue_name.append('shap_sample_predicted value is 1 and actual value is 0')
shapValue_list.append(i)
flage2 = False
elif (flage3 and f(df_shapValue.iloc[i:i + 1, :])[0] < resThreshold and Ytrain.iloc[i,] == 1):
df_shapValue_show = pd.concat([df_shapValue_show, df_shapValue.iloc[i:i + 1, :]], axis=0)
shapValue_name.append('shap_sample_predicted value is 0 and actual value is 1')
shapValue_list.append(i)
flage3 = False
elif (flage4 and f(df_shapValue.iloc[i:i + 1, :])[0] < resThreshold and Ytrain.iloc[i,] == 0):
df_shapValue_show = pd.concat([df_shapValue_show, df_shapValue.iloc[i:i + 1, :]], axis=0)
shapValue_name.append('shap_sample_predicted value is 0 actual value is 0')
shapValue_list.append(i)
flage4 = False
if (not flage1 and not flage2 and not flage3 and not flage4):
break
else:
df_shapValue_show = pd.concat([df_shapValue_show, df_shapValue.iloc[0:explain_sample, :]], axis=0)
shapValue_list.extend(i for i in range(explain_sample))
shapValue_name.extend('shap_sample_' + str(i) for i in range(explain_sample))
elif shapSet == 0:
df_shapValue = pd.concat([Xtrain, Xtest], axis=0)
df_shapValue_Y = pd.concat([Ytrain, Ytest], axis=0)
if (explain_sample == 4):
flage1, flage2, flage3, flage4 = True, True, True, True
for i in range(len(df_shapValue_Y)):
if (flage1 and f(df_shapValue.iloc[i:i + 1, :])[0] >= resThreshold and df_shapValue_Y.iloc[i,] == 1):
df_shapValue_show = pd.concat([df_shapValue_show, df_shapValue.iloc[i:i + 1, :]], axis=0)
shapValue_name.append('shap_sample_predicted value is 1 actual value is 1')
shapValue_list.append(i)
flage1 = False
elif (flage2 and f(df_shapValue.iloc[i:i + 1, :])[0] >= resThreshold and df_shapValue_Y.iloc[
i,] == 0):
df_shapValue_show = pd.concat([df_shapValue_show, df_shapValue.iloc[i:i + 1, :]], axis=0)
shapValue_name.append('shap_sample_predicted value is 1 and actual value is 0')
shapValue_list.append(i)
flage2 = False
elif (flage3 and f(df_shapValue.iloc[i:i + 1, :])[0] < resThreshold and df_shapValue_Y.iloc[
i,] == 1):
df_shapValue_show = pd.concat([df_shapValue_show, df_shapValue.iloc[i:i + 1, :]], axis=0)
shapValue_name.append('shap_sample_predicted value is 0 and actual value is 1')
shapValue_list.append(i)
flage3 = False
elif (flage4 and f(df_shapValue.iloc[i:i + 1, :])[0] < resThreshold and df_shapValue_Y.iloc[
i,] == 0):
df_shapValue_show = pd.concat([df_shapValue_show, df_shapValue.iloc[i:i + 1, :]], axis=0)
shapValue_name.append('shap_sample_predicted value is 0 actual value is 0')
shapValue_list.append(i)
flage4 = False
if (not flage1 and not flage2 and not flage3 and not flage4):
break
else:
df_shapValue_show = pd.concat([df_shapValue_show, df_shapValue.iloc[0:explain_sample, :]], axis=0)
shapValue_list.extend(i for i in range(explain_sample))
shapValue_name.extend('shap_sample_' + str(i) for i in range(explain_sample))
explainer = shap.KernelExplainer(f, med)
shap_values = explainer.shap_values(df_shapValue)
if explain_numvar > 0:
# SHAP beeswarm summary plot
assert explain_numvar <= len(features)
fig = shap.summary_plot(shap_values, df_shapValue, show=False)
if savePath is not None:
plot_name_dict['SHAP_Variable contribution summary'] = save_fig(savePath, 'shap_summary', 'png', fig, str_time=str_time)
plot_name_dict_save['SHAP_Variable contribution summary'] = save_fig(savePath, 'shap_summary', picFormat, fig,
str_time=str_time)
plt.close()
fig1 = shap.summary_plot(shap_values, df_shapValue, plot_type='bar', show=False)
if savePath is not None:
plot_name_dict['SHAP_Importance Map'] = save_fig(savePath, 'shap_import', 'png', fig1, str_time=str_time)
plot_name_dict_save['SHAP_Importance Map'] = save_fig(savePath, 'shap_import', picFormat, fig1,
str_time=str_time)
plt.close()
# # single feature (Partial Dependence)
# pdp = PartialDependence(predict_fn=clf.predict_proba, data=Xtrain)
# pdp_global = pdp.explain_global(name='Partial Dependence')
# for i in range(explain_numvar):
# fig = pdp_global.visualize(key=i)
# if savePath is not None:
# plot_name_dict['Differential Dependence_Variable{}'.format(i+1)] = save_fig(savePath, 'partial_dependence_{}'.format(features[i]), '.jpeg', fig)
# plt.close()
if explain_sample > 0:
assert explain_sample <= len(Ytest)
# lime = LimeTabular(predict_fn=clf.predict_proba, data=Xtest, random_state=1)
# lime_local = lime.explain_local(Xtest[:explain_sample], Ytest[:explain_sample], name='LIME')
for i in range(len(shapValue_list)):
# SHAP explain
fig = shap.force_plot(explainer.expected_value, shap_values[shapValue_list[i]],
df_shapValue_show.iloc[i, :], show=False,
figsize=(15, 3), matplotlib=True)
if savePath is not None:
plot_name_dict[shapValue_name[i]] = save_fig(savePath, 'shap_sample_{}'.format(i + 1),
'png', fig, str_time=str_time)
plot_name_dict_save[shapValue_name[i]] = save_fig(savePath, 'shap_sample_{}'.format(i + 1),
picFormat, fig, str_time=str_time)
plt.close()
# # LIME explain
# fig = lime_local.visualize(key=i)
# if savePath is not None:
# plot_name_dict['LIME_Sample{}'.format(i+1)] = save_fig(savePath, 'lime_{}'.format(i), '.jpeg', fig)
# plt.close()
result_dict = {'str_result': {'Description of analysis results': str_result}, 'tables': df_dict,
'pics': plot_name_dict, 'save_pics': plot_name_dict_save,
'model': result_model_save}
return result_dict
# -------------------------------------------------------------
# ----------------------Classification multi-model comprehensive analysis------------------------
# -------------------------------------------------------------
def two_groups_classfication_multimodels(
df_input,
group,
features,
methods=[],
decimal_num=3,
testsize=0.2,
boostrap=5,
randomState=42,
smooth=False,
searching=False,
dpi=600,
picFormat='jpeg',
isKFold=True,
savePath=None,
resultType=0,
delong=False,
**kwargs,
):
"""
df_input: Dataframe
features: Argument list
group: dependent variable str
testsize: Test set proportion
boostrap:Number of resamples
searching:bool Whether to perform automatic parameter search,Default is no
savePath:str Image storage path
"""
str_time = str(datetime.datetime.now().hour) + str(datetime.datetime.now().minute) + str(datetime.datetime.now().second)
random_number = random.randint(1, 100)
str_time = str_time + str(random_number)
dftemp = df_input[features + [group]].dropna()
features_flag = False
x = dftemp[features]
y = dftemp[[group]]
u = np.sort(np.unique(np.array(dftemp[group])))
if len(u) == 2 and set(u) != set([0, 1]):
y_result = label_binarize(dftemp[group], classes=[ii for ii in u]) # Binarize labels
y_result_pd = pd.DataFrame(y_result, columns=[group])
df = pd.concat([dftemp.drop(group, axis=1), y_result_pd], axis=1)
x = df[features]
y = df[[group]]
elif len(u) > 2:
return {'error': 'Currently only supports two categories.Please check the value of the dependent variable.'}
name_dict = {
'LogisticRegression': 'logistic',
'XGBClassifier': 'XGBoost',
'RandomForestClassifier': 'RandomForest',
'LGBMClassifier': 'LightGBM',
'SVC': 'SVM',
'MLPClassifier': 'MLP',
'GaussianNB': 'GNB',
'ComplementNB': 'CNB',
'AdaBoostClassifier': 'AdaBoost',
'KNeighborsClassifier': 'KNN',
'DecisionTreeClassifier': 'DecisionTree',
'BaggingClassifier': 'Bagging',
}
if len(methods) == 0:
methods = [
'LogisticRegression',
'XGBClassifier',
'RandomForestClassifier',
# 'SVC',
# 'MLPClassifier',
# 'AdaBoostClassifier',
# 'KNeighborsClassifier',
# 'DecisionTreeClassifier',
# 'BaggingClassifier',
]
str_result = 'A variety of machine learning models have been used to try to complete the data sample classification task,include:{}.The selection of parameter values for each model is as follows::\n\n'.format(methods)
plot_name_list = []
plot_name_dict_save = {}
plot_name_dict ={}
fig, ax = plt.subplots(figsize=(4, 4), dpi=dpi)
# draw diagonal lines
ax.plot(
[0, 1], [0, 1],
linestyle='--',
lw=1, color='r',
alpha=1.0,
)
ax.grid(which='major', axis='both', linestyle='-.', alpha=0.3, color='grey')
ax.set_xlim([-0.02, 1.02])
ax.set_ylim([-0.02, 1.02])
ax.tick_params(top=False, right=False)
# ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0)
ax.set_xlabel('1-Specificity')
ax.set_ylabel('Sensitivity')
ax.set_title('Validation ROC Curve')
mean_fpr = np.linspace(0, 1, 100)
colors = x5.CB91_Grad_BP
df_0 = pd.DataFrame(columns=list(make_class_metrics_dict().keys()), index=[0])
df_0_test = df_0.copy()
df_plot = pd.DataFrame(columns=['method', 'mean', 'std'])
fpr_train_alls, tpr_train_alls, train_method_alls, mean_auc_train_alls = [], [], [], []
fraction_of_positives_alls, mean_predicted_value_alls, clf_score_alls = [], [], []
AUC_95CI_test, AUC_95CI_SD_test, AUC_95CI_train, AUC_95CI_SD_train = [], [], [], []
DCA_dict = {}
model_test_data_all = {}
X_train_ps, Y_train_ps, model_train_s = [], [], []
X_test_ps, Y_test_ps = [], []
name = []
for i, method in enumerate(methods):
tprs_train, tprs_test = [], []
name.append(name_dict[method])
if searching == True:
if method == 'LGBMClassifier':
searcher = GridSearcherCV('Classification', globals()[method]())
selected_model = searcher(x, y)
else:
searcher = RandSearcherCV('Classification', globals()[method]())
selected_model = searcher(x, y) # ; searcher.report()
elif searching == False:
# selected_model = globals()[method]() if (method != 'SVC') else globals()[method](probability=True)
if method == 'SVC':
selected_model = globals()[method](probability=True)
elif method == 'MLPClassifier':
selected_model = globals()[method](hidden_layer_sizes=(20, 10), max_iter=20)
elif method == 'RandomForestClassifier':
selected_model = globals()[method](n_estimators=20)
else:
selected_model = globals()[method]()
elif searching == 'Handle':
method_dicts = kwargs
if i == 0:
me_count = True
for me_list in methods:
if me_list in method_dicts.keys():
me_count = False
continue
if me_count:
return {'error': 'Please set the model to be adjusted!'}
if method in method_dicts.keys():
method_dict = {}
if (method == 'SVC'):
method_dict.update({'probability': True})
method_dict.update(method_dicts[method])
if (method == 'RandomForestClassifier' and method_dict['max_depth'] == 'None'):
method_dict['max_depth'] = None
if (method == 'MLPClassifier'):
hls_vals = str(method_dict['hidden_layer_sizes']).split(',')
hls_value = ()
for hls_val in hls_vals:
try:
if int(hls_val) >= 5 and int(hls_val) <= 200:
hls_value = hls_value + (int(hls_val),)
else:
return {'error': 'Please reset the hidden layer width as required!'}
except:
return {'error': 'Please reset the hidden layer width in the neural network model!'}
method_dict['hidden_layer_sizes'] = hls_value
if (method == 'GaussianNB' and method_dict['priors'] == 'None'):
method_dict['priors'] = None
elif (method == 'GaussianNB'):
pri_vals = str(method_dict['priors']).split(',')
pri_value = ()
pri_sum = 0.0
for pri_val in pri_vals:
try:
pri_sum = float(pri_val) + pri_sum
pri_value = pri_value + (float(pri_val),)
except:
return {'error': 'Please reset the prior probability in the naive Bayes model!'}
if len(pri_vals) == len(y.unique()) and pri_sum == 1.0:
method_dict['priors'] = pri_value
else:
return {'error': 'Please reset the prior probability in the naive Bayes model!'}
selected_model = globals()[method](**method_dict)
else:
if method == 'LGBMClassifier':
searcher = GridSearcherCV('Classification', globals()[method]())
selected_model = searcher(x, y)
else:
searcher = RandSearcherCV('Classification', globals()[method]())
selected_model = searcher(x, y) # ; searcher.report()
list_evaluate_dic_train = make_class_metrics_dict()
list_evaluate_dic_test = make_class_metrics_dict()
clf_score = 1
fraction_of_positives = np.array([1])
mean_predicted_value = np.array([1])
p_serie_s_te, net_benefit_serie_s_te, net_benefit_serie_All_s_te = [], [], []
data_all = {}
test_data_delong = {}
conf_dic_train, conf_dic_test = {}, {}
if isKFold:
# KF = KFold(n_splits=boostrap, random_state=42,shuffle=True)
KF = StratifiedKFold(n_splits=boostrap, random_state=randomState, shuffle=True)
for i_k, (train_index, valid_index) in enumerate(KF.split(x, y)):
# Divide training set and validation set
Xtrain, Xtest = x.iloc[train_index], x.iloc[valid_index]
Ytrain, Ytest = y.iloc[train_index], y.iloc[valid_index]
data_all.update({i_k: {'Xtrain': Xtrain, 'Ytrain': Ytrain, 'Xtest': Xtest, 'Ytest': Ytest}})
test_data_delong.update({i_k: np.array(Ytest).T[0]})
else:
for index in range(0, boostrap):
if searching == 'Handle':
Xtrain, Xtest, Ytrain, Ytest = TTS(x, y, test_size=testsize, random_state=index)
else:
Xtrain, Xtest, Ytrain, Ytest = TTS(x, y, test_size=testsize)
data_all.update({index: {'Xtrain': Xtrain, 'Ytrain': Ytrain, 'Xtest': Xtest, 'Ytest': Ytest}})
test_data_delong.update({index: np.array(Ytest).T[0]})
if method == methods[0]:
model_test_data_all.update({'original': test_data_delong})
# for index in range(0, boostrap):
test_all_data_delong = {}
X_train_p, Y_train_p, model_train = [], [], []
X_test_p, Y_test_p = [], []
for data_key, data_value in data_all.items():
Xtrain, Ytrain, Xtest, Ytest = data_value['Xtrain'], data_value['Ytrain'], data_value['Xtest'], data_value[
'Ytest']
model = clone(selected_model).fit(Xtrain, Ytrain)
####################################
# if data_key == 0:
X_train_p.append(Xtrain)
Y_train_p.append(Ytrain)
model_train.append(model)
X_test_p.append(Xtest)
Y_test_p.append(Ytest)
##########################################
Yprob = model.predict_proba(Xtest)[:, 1]
test_all_data_delong.update({data_key: Yprob})
prob_pos, p_serie, net_benefit_serie, net_benefit_serie_All = calculate_net_benefit(model, Xtest, Ytest)
p_serie_s_te.append(p_serie)
net_benefit_serie_s_te.append(net_benefit_serie)
net_benefit_serie_All_s_te.append(net_benefit_serie_All)
"""
if hasattr(model, "predict_proba"):
prob_pos = model.predict_proba(Xtest)[:, 1]
else: # use decision function
prob_pos = model.decision_function(Xtest)
prob_pos = (prob_pos - prob_pos.min()) / (prob_pos.max() - prob_pos.min())
"""
clf_score1 = brier_score_loss(Ytest, prob_pos, pos_label=y[group].max()) ##strategy='quantile',