-
Notifications
You must be signed in to change notification settings - Fork 0
/
ANE-PoCS-20-postprocedural_atrial_fibrillation.py
1763 lines (1341 loc) · 62.6 KB
/
ANE-PoCS-20-postprocedural_atrial_fibrillation.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 python
# coding: utf-8
# # 读取数据
# In[2]:
import warnings
warnings.filterwarnings("ignore")
import matplotlib.pyplot as plt
import numpy as np
from sklearn import metrics
import seaborn as sns
import matplotlib
import pandas as pd
import warnings
warnings.filterwarnings("ignore")
plt.rcParams['figure.dpi'] = 150 # 修改图片分辨率
plt.rcParams.update({'font.size': 12})
plt.rc('font',family='Times New Roman')
# In[3]:
y_list=['postprocedural_atrial_fibrillation']
# In[4]:
excel_file = pd.ExcelFile('数据简化特征版本.xlsx')
sheet_names = excel_file.sheet_names
for sheet_name in sheet_names:
print(sheet_name)
# In[6]:
data=pd.read_excel('数据简化特征版本.xlsx',sheet_name='atrial_fibrillation')
# In[7]:
data=data[pd.isnull(data['postprocedural_atrial_fibrillation'])==False]
# In[8]:
data=data.reset_index(drop=True)
# # 数据处理
# In[9]:
for col in data.columns:
try:
data[col]=data[col].astype('float32')
except:
pass
# In[10]:
data.gender=data.gender.map(lambda x: 1 if x=='M' else 0).astype('float32')
data.admission_age=data.admission_age.map(lambda x: 90 if x=='> 89' else x).astype('float32')
# # 缺失值
# In[13]:
tmp=data.isnull().sum()/data.shape[0]
tmp=tmp.sort_values(ascending=False)
tmp
# In[14]:
from sklearnex import patch_sklearn
patch_sklearn() # 这个函数用于开启加速sklearn,出现如下语句就表示OK!
# In[15]:
#KNN均值替换
from sklearn.impute import KNNImputer
imputer = KNNImputer()
X=data.drop(columns=['postprocedural_atrial_fibrillation'],axis=1)
X=pd.DataFrame(imputer.fit_transform(X),columns=X.columns)
# # 异常值
# In[16]:
data=data.reset_index(drop=True)
# In[17]:
data=pd.concat([X,data['postprocedural_atrial_fibrillation']],axis=1)
# In[18]:
data=data[data['BMI']<100].reset_index(drop=True)
# In[19]:
# LOF异常值处理
from sklearn.neighbors import LocalOutlierFactor
detector = LocalOutlierFactor(n_neighbors=10) # 构造异常值识别器
data['LOF']=detector.fit_predict(data)
# In[20]:
data['LOF'].value_counts()
# In[21]:
#-1为异常值,去除异常值
data=data[data['LOF']==1]
data.drop(columns=['LOF'],axis=1,inplace=True)
# In[22]:
data=data.reset_index(drop=True)
# # 数据标准化
# In[23]:
cols=[i for i in data.columns if i not in y_list]
# In[24]:
from sklearn.preprocessing import StandardScaler
ss=StandardScaler()
df=pd.DataFrame(ss.fit_transform(data[cols]),columns=cols)
df['postprocedural_atrial_fibrillation']=data['postprocedural_atrial_fibrillation']
# In[25]:
import joblib
joblib.dump(ss,'ss.pkl')
# # postprocedural_atrial_fibrillation
# In[26]:
name='postprocedural_atrial_fibrillation'
# ## 数据不平衡数据
# In[27]:
X=df[cols]
y=df['postprocedural_atrial_fibrillation']
from imblearn.over_sampling import SMOTE, ADASYN
from imblearn.combine import SMOTEENN
X_resampled, y_resampled = SMOTEENN(random_state=1).fit_resample(X, y)
# In[29]:
from collections import Counter
print(sorted(Counter(y_resampled).items()))
# In[30]:
#取交集
lasso_svm_selcet=cols
lasso_svm_selcet
# ## 定义模型评估函数
# In[31]:
from sklearn.metrics import precision_score, recall_score, f1_score ,roc_curve, auc,confusion_matrix ,accuracy_score,roc_auc_score,auc,brier_score_loss
def try_different_method(y_pred_train1,y_pred_train2,y_pred_test1,y_pred_test2,y_pred_val1,y_pred_val2):
print('Train:')
precision = precision_score(y_train,y_pred_train1)
recall = recall_score(y_train,y_pred_train1)
f1score = f1_score(y_train, y_pred_train1)
accuracy=accuracy_score(y_train, y_pred_train1)
cnf_matrix=metrics.confusion_matrix(y_train,y_pred_train1)
TP=cnf_matrix[1,1] # 1-->1
TN=cnf_matrix[0,0] # 0-->0
FP=cnf_matrix[0,1] # 0-->1
FN=cnf_matrix[1,0] # 1-->0
fpr, tpr, thresholds = roc_curve(y_train, y_pred_train2)
AUC = auc(fpr, tpr)
print("AUC: ", '%.4f'%float(AUC),"ACC: ", '%.4f'%float(accuracy),"F1:", '%.4f'%float(f1score),"Precision:", '%.4f'%float(precision),\
"Recall: ",'%.4f'%float(recall),"Sensitivity : ",'%.4f'%float(TP/(TP+FN)),"Specificity: ",'%.4f'%float(TN/(FP+TN)))
print('Model Train Report: \n',metrics.classification_report(y_train,y_pred_train1,digits=4))
print('*'*50)
print('Test:')
precision = precision_score(y_test,y_pred_test1)
recall = recall_score(y_test,y_pred_test1)
f1score = f1_score(y_test, y_pred_test1)
accuracy=accuracy_score(y_test, y_pred_test1)
cnf_matrix=metrics.confusion_matrix(y_test,y_pred_test1)
TP=cnf_matrix[1,1] # 1-->1
TN=cnf_matrix[0,0] # 0-->0
FP=cnf_matrix[0,1] # 0-->1
FN=cnf_matrix[1,0] # 1-->0
fpr, tpr, thresholds = roc_curve(y_test, y_pred_test2)
AUC = auc(fpr, tpr)
print("AUC: ", '%.4f'%float(AUC),"ACC: ", '%.4f'%float(accuracy),"F1:", '%.4f'%float(f1score),"Precision:", '%.4f'%float(precision),\
"Recall: ",'%.4f'%float(recall),"Sensitivity: ",'%.4f'%float(TP/(TP+FN)),"Specificity: ",'%.4f'%float(TN/(FP+TN)))
print('Model Test Report: \n',metrics.classification_report(y_test,y_pred_test1,digits=4))
print('*'*50)
print('Valid:')
precision = precision_score(y_val,y_pred_val1)
recall = recall_score(y_val,y_pred_val1)
f1score = f1_score(y_val, y_pred_val1)
accuracy=accuracy_score(y_val, y_pred_val1)
cnf_matrix=metrics.confusion_matrix(y_val,y_pred_val1)
TP=cnf_matrix[1,1] # 1-->1
TN=cnf_matrix[0,0] # 0-->0
FP=cnf_matrix[0,1] # 0-->1
FN=cnf_matrix[1,0] # 1-->0
fpr, tpr, thresholds = roc_curve(y_val, y_pred_val2)
AUC = auc(fpr, tpr)
print("AUC: ", '%.4f'%float(AUC),"ACC: ", '%.4f'%float(accuracy),"F1:", '%.4f'%float(f1score),"Precision:", '%.4f'%float(precision),\
"Recall: ",'%.4f'%float(recall),"Sensitivity: ",'%.4f'%float(TP/(TP+FN)),"Specificity: ",'%.4f'%float(TN/(FP+TN)))
print('Model Valid Report: \n',metrics.classification_report(y_val,y_pred_val1,digits=4))
import itertools
def plot_roc(k,y_pred_undersample_score,labels_test,classifiers,color,title):
fpr, tpr, thresholds = metrics.roc_curve(labels_test.values.ravel(),y_pred_undersample_score)
roc_auc = metrics.auc(fpr,tpr)
plt.figure(figsize=(20,16))
plt.figure(k)
plt.title(title)
plt.plot(fpr, tpr, 'b',color=color,label='%s AUC = %0.4f'% (classifiers,roc_auc))
plt.legend(loc='lower right',fontsize=10)
plt.plot([0,1],[0,1],'r--')
plt.xlim([-0.1,1.0])
plt.ylim([-0.1,1.01])
plt.ylabel('True Positive Rate')
plt.xlabel('False Positive Rate')
def plot_confusion_matrix(cm, classes,title='Confusion matrix',cmap=plt.cm.Blues):
# plt.figure(figsize=(12,6))
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar(fraction=0.05)
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=0)
plt.yticks(tick_marks, classes)
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, cm[i, j], horizontalalignment="center",color="white" if cm[i, j] > thresh else "black",fontsize = 10,weight = 'heavy')
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
def plot_confusion_matrix2(cm, classes,title='Confusion matrix',cmap='red',fontsize=15):
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title,fontsize = fontsize)
plt.xticks([])
plt.yticks([])
# plt.colorbar(fraction=0.05)
tick_marks = np.arange(len(classes))
# plt.xticks(tick_marks, classes, rotation=0)
# plt.yticks(tick_marks, classes)
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, '{:.0%}'.format(cm[i, j]), horizontalalignment="center",color="black",fontsize = 15,weight = 'heavy')
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
from sklearn.model_selection import KFold
# 设置k-fold交叉验证
from sklearn import metrics
def model_cv_score1(model,X,y,random_state=3,a=0.5):
kfold = KFold(n_splits=5,random_state=random_state,shuffle=True)
# 对数据进行交叉验证
train_acc_list=[]
test_acc_list=[]
train_Precision_list=[]
test_Precision_list=[]
train_recall_list=[]
test_recall_list=[]
train_f1_list=[]
test_f1_list=[]
train_auc_list=[]
test_auc_list=[]
for i,(train_index, test_index) in enumerate(kfold.split(X)):
# 获取训练集和测试集
X_train1, X_test1 = X.loc[train_index], X.loc[test_index]
y_train1, y_test1 = y.loc[train_index], y.loc[test_index]
model.fit(X_train1, y_train1) #打乱标签
# 在测试集上进行预测
# y_pred_test1 = model.predict(X_test1)
# y_pred_train1 = model.predict(X_train1)
y_pred_test2 = model.predict_proba(X_test1)[:,1]
y_pred_train2 = model.predict_proba(X_train1)[:,1]
y_pred_test1=[int(i>a) for i in y_pred_test2]
y_pred_train1=[int(i>a) for i in y_pred_train2]
# 输出模型的准确率
train_acc= metrics.accuracy_score(y_train1,y_pred_train1)
test_acc=metrics.accuracy_score(y_test1,y_pred_test1)
train_acc_list.append(train_acc)
test_acc_list.append(test_acc)
# 输出模型的精度率
train_Precision= metrics.precision_score(y_train1,y_pred_train1)
test_Precision=metrics.precision_score(y_test1,y_pred_test1)
train_Precision_list.append(train_Precision)
test_Precision_list.append(test_Precision)
# 输出模型的召回率
train_recall= metrics.recall_score(y_train1,y_pred_train1)
test_recall=metrics.recall_score(y_test1,y_pred_test1)
train_recall_list.append(train_recall)
test_recall_list.append(test_recall)
# 输出模型的F1
train_f1= metrics.f1_score(y_train1,y_pred_train1)
test_f1=metrics.f1_score(y_test1,y_pred_test1)
train_f1_list.append(train_f1)
test_f1_list.append(test_f1)
# 输出模型AUC
train_auc= metrics.roc_auc_score(y_train1,y_pred_train2)
test_auc=metrics.roc_auc_score(y_test1,y_pred_test2)
train_auc_list.append(train_auc)
test_auc_list.append(test_auc)
print('Fold %s'%(i+1),'*'*50)
print("train ACC:", train_acc,"train Precision:", train_Precision,"train Recall:", train_recall,"train F1:", train_f1,"train AUC:", train_auc)
print("test ACC:", test_acc,"test Precision:", test_Precision,"test Recall:", test_recall,"test F1:", test_f1,"test AUC:", test_auc)
print('\n')
print('cross validation','*'*50)
print('train Mean ACC',np.array(train_acc_list).mean(),'train Mean Precision',np.array(train_Precision_list).mean(),'train Mean Recall',np.array(train_recall_list).mean(),'train Mean F1',np.array(train_f1_list).mean(),'train Mean AUC',np.array(train_auc_list).mean())
print('test Mean ACC',np.array(test_acc_list).mean(),'test Mean Precision',np.array(test_Precision_list).mean(),'test Mean Recall',np.array(test_recall_list).mean(),'test Mean F1',np.array(test_f1_list).mean(),'test Mean AUC',np.array(test_auc_list).mean())
print('\n')
print('\n')
return np.array(train_acc_list),np.array(train_Precision_list),np.array(train_recall_list),np.array(train_f1_list),np.array(train_auc_list),\
np.array(test_acc_list),np.array(test_Precision_list),np.array(test_recall_list),np.array(test_f1_list),np.array(test_auc_list)
# In[32]:
for i in ['atrial_fibrillation']:
if i in lasso_svm_selcet:
lasso_svm_selcet.remove(i)
# In[33]:
# 数据分割
# 7比3划分训练集,测试集,设置随机种子random_state,保证实验能够复现
from sklearn.model_selection import train_test_split
X_train, _x, y_train, _y = train_test_split(X_resampled[lasso_svm_selcet],y_resampled,test_size=0.3,random_state=1)
X_test, X_val, y_test, y_val = train_test_split(_x,_y,test_size=0.333,random_state=1)
print(X_train.shape,X_test.shape,X_val.shape)
# In[34]:
from sklearn.model_selection import cross_val_score,StratifiedKFold,LeaveOneOut,KFold
from sklearn.model_selection import learning_curve,validation_curve
def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None, n_jobs=1,train_sizes=np.linspace(.05, 1., 20), verbose=0,plot=True):
train_sizes, train_scores, test_scores = \
learning_curve(estimator, X, y, cv=cv, n_jobs=-1, train_sizes=train_sizes, verbose=verbose,scoring='roc_auc')
train_scores_mean = np.mean(train_scores, axis=1)
train_scores_std = np.std(train_scores, axis=1)
test_scores_mean = np.mean(test_scores, axis=1)
test_scores_std = np.std(test_scores, axis=1)
if plot:
plt.figure(figsize=(10,5),dpi=120)
plt.title(title)
if ylim is not None:
plt.ylim(*ylim)
# plt.xlabel("train_size")
plt.ylabel("score")
plt.gca().invert_yaxis()
plt.grid()
plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std,
alpha=0.1, color="b")
plt.fill_between(train_sizes, test_scores_mean - test_scores_std, test_scores_mean + test_scores_std,
alpha=0.1, color="r")
plt.plot(train_sizes, train_scores_mean, 'o-', color="green", label="train_score")
plt.plot(train_sizes, test_scores_mean, 'o-', color="red", label="cv_score")
plt.legend(loc="best")
# plt.ylim(1,0.7)
plt.draw()
plt.gca().invert_yaxis()
# plt.show()
midpoint = ((train_scores_mean[-1] + train_scores_std[-1]) + (test_scores_mean[-1] - test_scores_std[-1])) / 2
diff = (train_scores_mean[-1] + train_scores_std[-1]) - (test_scores_mean[-1] - test_scores_std[-1])
return midpoint, diff
# ## LR
# ### 默认参数
# In[35]:
from sklearn.linear_model import LogisticRegression
clf=LogisticRegression(random_state=1,C=1)
clf.fit(X_train,y_train)
threshold=0.5
# y_pred_train1=clf.predict(X_train)
y_pred_train2=clf.predict_proba(X_train)[:,1]
y_pred_train1=[int(i>threshold) for i in y_pred_train2]
# y_pred_test1=clf.predict(X_test)
y_pred_test2=clf.predict_proba(X_test)[:,1]
y_pred_test1=[int(i>threshold) for i in y_pred_test2]
# y_pred_val1=clf.predict(X_val)
y_pred_val2=clf.predict_proba(X_val)[:,1]
y_pred_val1=[int(i>threshold) for i in y_pred_val2]
try_different_method(y_pred_train1,y_pred_train2,y_pred_test1,y_pred_test2,y_pred_val1,y_pred_val2)
# ### GA调参
# In[36]:
class GAIndividual:
'''
individual of genetic algorithm
'''
def __init__(self, vardim, bound):
'''
vardim: dimension of variables
bound: boundaries of variables
'''
self.vardim = vardim
self.bound = bound
self.fitness = 0.
def generate(self):
'''
generate a random chromsome for genetic algorithm
'''
len = self.vardim
rnd = np.random.random(size=len)
self.chrom = np.zeros(len)
for i in range(0, len):
self.chrom[i] = self.bound[0, i] + \
(self.bound[1, i] - self.bound[0, i]) * rnd[i]
def calculateFitness(self):
'''
calculate the fitness of the chromsome
'''
self.fitness = clfResult(self.vardim, self.chrom, self.bound)
import random
import copy
np.set_printoptions(suppress=True)
class GeneticAlgorithm:
'''
The class for genetic algorithm
'''
def __init__(self, sizepop, vardim, bound, MAXGEN, params):
'''
sizepop: population sizepop
vardim: dimension of variables
bound: boundaries of variables
MAXGEN: termination condition
param: algorithm required parameters, it is a list which is consisting of crossover rate, mutation rate, alpha
'''
self.sizepop = sizepop
self.MAXGEN = MAXGEN
self.vardim = vardim
self.bound = bound
self.population = []
self.fitness = np.zeros((self.sizepop, 1))
self.trace = np.zeros((self.MAXGEN, 3))
self.params = params
def initialize(self):
'''
initialize the population
'''
for i in range(0, self.sizepop):
ind = GAIndividual(self.vardim, self.bound)
ind.generate()
self.population.append(ind)
def evaluate(self):
'''
evaluation of the population fitnesses
'''
for i in range(0, self.sizepop):
self.population[i].calculateFitness()
self.fitness[i] = self.population[i].fitness
def solve(self):
'''
evolution process of genetic algorithm
'''
self.t = 0
self.initialize()
self.evaluate()
best = np.max(self.fitness)
bestIndex = np.argmax(self.fitness)
self.best = copy.deepcopy(self.population[bestIndex])
self.avefitness = np.mean(self.fitness)
self.maxfitness = np.max(self.fitness)
self.trace[self.t, 0] = self.best.fitness
self.trace[self.t, 1] = self.avefitness
self.trace[self.t, 2] = self.maxfitness
print("Generation %d: optimal function value is: %f; average function value is %f;max function value is %f"% (
self.t, self.trace[self.t, 0], self.trace[self.t, 1],self.trace[self.t, 2]))
while (self.t < self.MAXGEN - 1):
self.t += 1
self.selectionOperation()
self.crossoverOperation()
self.mutationOperation()
self.evaluate()
best = np.max(self.fitness)
bestIndex = np.argmax(self.fitness)
if best > self.best.fitness:
self.best = copy.deepcopy(self.population[bestIndex])
self.avefitness = np.mean(self.fitness)
self.maxfitness = np.max(self.fitness)
self.trace[self.t, 0] = self.best.fitness
self.trace[self.t, 1] = self.avefitness
self.trace[self.t, 2] = self.maxfitness
print("Generation %d: optimal function value is: %f; average function value is %f;max function value is %f"% (
self.t, self.trace[self.t, 0], self.trace[self.t, 1],self.trace[self.t, 2]))
print("Optimal function value is: %f; " %
self.trace[self.t, 0])
print ("Optimal solution is:")
print (self.best.chrom)
def selectionOperation(self):
'''
selection operation for Genetic Algorithm
'''
newpop = []
totalFitness = np.sum(self.fitness)
accuFitness = np.zeros((self.sizepop, 1))
sum1 = 0.
for i in range(0, self.sizepop):
accuFitness[i] = sum1 + self.fitness[i] / totalFitness
sum1 = accuFitness[i]
for i in range(0, self.sizepop):
r = random.random()
idx = 0
for j in range(0, self.sizepop - 1):
if j == 0 and r < accuFitness[j]:
idx = 0
break
elif r >= accuFitness[j] and r < accuFitness[j + 1]:
idx = j + 1
break
newpop.append(self.population[idx])
self.population = newpop
def crossoverOperation(self):
'''
crossover operation for genetic algorithm
'''
newpop = []
for i in range(0, self.sizepop, 2):
idx1 = random.randint(0, self.sizepop - 1)
idx2 = random.randint(0, self.sizepop - 1)
while idx2 == idx1:
idx2 = random.randint(0, self.sizepop - 1)
newpop.append(copy.deepcopy(self.population[idx1]))
newpop.append(copy.deepcopy(self.population[idx2]))
r = random.random()
if r < self.params[0]:
crossPos = random.randint(1, self.vardim - 1)
for j in range(crossPos, self.vardim):
newpop[i].chrom[j] = newpop[i].chrom[
j] * self.params[2] + (1 - self.params[2]) * newpop[i + 1].chrom[j]
newpop[i + 1].chrom[j] = newpop[i + 1].chrom[j] * self.params[2] + \
(1 - self.params[2]) * newpop[i].chrom[j]
self.population = newpop
def mutationOperation(self):
'''
mutation operation for genetic algorithm
'''
newpop = []
for i in range(0, self.sizepop):
newpop.append(copy.deepcopy(self.population[i]))
r = random.random()
if r < self.params[1]:
mutatePos = random.randint(0, self.vardim - 1)
theta = random.random()
if theta > 0.5:
newpop[i].chrom[mutatePos] = newpop[i].chrom[
mutatePos] - (newpop[i].chrom[mutatePos] - self.bound[0, mutatePos]) * (1 - random.random() ** (1 - self.t / self.MAXGEN))
else:
newpop[i].chrom[mutatePos] = newpop[i].chrom[
mutatePos] + (self.bound[1, mutatePos] - newpop[i].chrom[mutatePos]) * (1 - random.random() ** (1 - self.t / self.MAXGEN))
self.population = newpop
# In[37]:
##10.adding GA
def clfResult(vardim, x, bound):
c=float(x[0])
print("C:",round(c,4))
clf = LogisticRegression(C=c,random_state=1)
clf.fit(X_train, y_train)
predictval=clf.predict_proba(X_test)[:,1]
print("ACC = ",metrics.roc_auc_score(y_test,predictval)) # R2
return metrics.roc_auc_score(y_test,predictval)
bound = (np.array([[1e-6],[1000]]))
ga = GeneticAlgorithm(19, 1, bound, 1, [0.75, 0.25, 0.5])
ga.solve()
# ### 最优参数模型
# In[38]:
from sklearn.linear_model import LogisticRegression
clf=LogisticRegression(random_state=1,C=63.67482608)
clf.fit(X_train,y_train)
threshold=0.5
# y_pred_train1=clf.predict(X_train)
y_pred_train2=clf.predict_proba(X_train)[:,1]
y_pred_train1=[int(i>threshold) for i in y_pred_train2]
# y_pred_test1=clf.predict(X_test)
y_pred_test2=clf.predict_proba(X_test)[:,1]
y_pred_test1=[int(i>threshold) for i in y_pred_test2]
# y_pred_val1=clf.predict(X_val)
y_pred_val2=clf.predict_proba(X_val)[:,1]
y_pred_val1=[int(i>threshold) for i in y_pred_val2]
try_different_method(y_pred_train1,y_pred_train2,y_pred_test1,y_pred_test2,y_pred_val1,y_pred_val2)
# In[39]:
joblib.dump(clf,'./%s/clf_lr.pkl'%name)
# In[40]:
# 函数用来计算最佳阙值
def calculate_best_threshold(y, y_scores):
fpr, tpr, thresholds = roc_curve(y, y_scores)
j_scores = tpr-fpr
j_ordered = sorted(zip(j_scores,thresholds))
return j_ordered[-1][0],j_ordered[-1][1] # 返回最佳阙值
def bootstrap_auc(y, pred, classes, bootstraps = 1000, fold_size = 1000):
statistics_auc = np.zeros((len(classes), bootstraps))
statistics_acc = np.zeros((len(classes), bootstraps))
statistics_f1 = np.zeros((len(classes), bootstraps))
statistics_precision = np.zeros((len(classes), bootstraps))
statistics_recall = np.zeros((len(classes), bootstraps))
statistics_sens = np.zeros((len(classes), bootstraps))
statistics_spec = np.zeros((len(classes), bootstraps))
for c in range(len(classes)):
df = pd.DataFrame(columns=['y', 'pred'])
# df.
df.loc[:, 'y'] = y
df.loc[:, 'pred'] = pred
df_pos = df[df.y == 1]
df_neg = df[df.y == 0]
prevalence = len(df_pos) / len(df)
for i in range(bootstraps):
pos_sample = df_pos.sample(n = int(fold_size * prevalence), replace=True)
neg_sample = df_neg.sample(n = int(fold_size * (1-prevalence)), replace=True)
y_sample = np.concatenate([pos_sample.y.values, neg_sample.y.values])
pred_sample = np.concatenate([pos_sample.pred.values, neg_sample.pred.values])
j_ordered,threshold = calculate_best_threshold(y_sample, pred_sample)
statistics_auc[c][i] = metrics.roc_auc_score(y_sample, pred_sample)
y_pred=[int(i>threshold) for i in pred_sample]
statistics_acc[c][i] = metrics.accuracy_score(y_sample,y_pred)
statistics_f1[c][i] = metrics.f1_score(y_sample,y_pred)
statistics_precision[c][i] = metrics.precision_score(y_sample,y_pred)
statistics_recall[c][i] = metrics.recall_score(y_sample,y_pred)
cnf_matrix=metrics.confusion_matrix(y_sample,y_pred)
TP=cnf_matrix[1,1] # 1-->1
TN=cnf_matrix[0,0] # 0-->0
FP=cnf_matrix[0,1] # 0-->1
FN=cnf_matrix[1,0] # 1-->0
statistics_sens[c][i]=TP/(TP+FN)
statistics_spec[c][i]=TN/(FP+TN)
return statistics_auc,statistics_acc,statistics_f1,statistics_precision,statistics_recall,statistics_sens,statistics_spec
statistics_auc,statistics_acc,statistics_f1,statistics_precision,statistics_recall,statistics_sens,statistics_spec = bootstrap_auc(y_train,clf.predict_proba(X_train)[:,1],[0,1])
list1=['AUC','ACC','F1','Precision','Recall','Sensitivity','Specificity']
list2=[statistics_auc,statistics_acc,statistics_f1,statistics_precision,statistics_recall,statistics_sens,statistics_spec]
for i,j in zip(list1,list2):
print("LR Train ",i," (95% CI):",round(np.mean(j,axis=1)[1],4),'(',round(np.min(j,axis=1)[1],4),'-',round(np.max(j,axis=1)[1],4),')')
# In[41]:
statistics_auc,statistics_acc,statistics_f1,statistics_precision,statistics_recall,statistics_sens,statistics_spec = bootstrap_auc(y_test,clf.predict_proba(X_test)[:,1],[0,1])
list1=['AUC','ACC','F1','Precision','Recall','Sensitivity','Specificity']
list2=[statistics_auc,statistics_acc,statistics_f1,statistics_precision,statistics_recall,statistics_sens,statistics_spec]
for i,j in zip(list1,list2):
print("LR Test ",i," (95% CI):",round(np.mean(j,axis=1)[1],4),'(',round(np.min(j,axis=1)[1],4),'-',round(np.max(j,axis=1)[1],4),')')
# In[42]:
statistics_auc,statistics_acc,statistics_f1,statistics_precision,statistics_recall,statistics_sens,statistics_spec = bootstrap_auc(y_val,clf.predict_proba(X_val)[:,1],[0,1])
list1=['AUC','ACC','F1','Precision','Recall','Sensitivity','Specificity']
list2=[statistics_auc,statistics_acc,statistics_f1,statistics_precision,statistics_recall,statistics_sens,statistics_spec]
for i,j in zip(list1,list2):
print("LR Valid ",i," (95% CI):",round(np.mean(j,axis=1)[1],4),'(',round(np.min(j,axis=1)[1],4),'-',round(np.max(j,axis=1)[1],4),')')
# ### 模型评估
# In[43]:
plt.figure(figsize=(15,12), dpi=120)
plt.subplot(1, 3, 1)
#训练
cnf_matrix=metrics.confusion_matrix(y_train,y_pred_train1)
plot_confusion_matrix(cnf_matrix,[0,1],title='LR Train',cmap=plt.cm.Blues)
#测试
plt.subplot(1, 3, 2)
cnf_matrix=metrics.confusion_matrix(y_test,y_pred_test1)
plot_confusion_matrix(cnf_matrix,[0,1],title='LR Test',cmap=plt.cm.Blues)
#验证
plt.subplot(1, 3, 3)
cnf_matrix=metrics.confusion_matrix(y_val,y_pred_val1)
plot_confusion_matrix(cnf_matrix,[0,1],title='LR Valid',cmap=plt.cm.Blues)
plt.tight_layout()
plt.savefig('./%s/LR-confusion_matrix1.jpg'%name,dpi=300,bbox_inches = 'tight')
plt.show()
plt.figure(figsize=(8,5), dpi=120)
plt.subplot(1, 3, 1)
#训练
cnf_matrix=metrics.confusion_matrix(y_train,y_pred_train1)
cnf_matrix=cnf_matrix/cnf_matrix.sum(axis=0)
plot_confusion_matrix2(cnf_matrix,[0,1],title='LR Train',cmap='tab20')
#测试
plt.subplot(1, 3, 2)
cnf_matrix=metrics.confusion_matrix(y_test,y_pred_test1)
cnf_matrix=cnf_matrix/cnf_matrix.sum(axis=0)
plot_confusion_matrix2(cnf_matrix,[0,1],title='LR Test',cmap='Greens_r')
#验证
plt.subplot(1, 3, 3)
cnf_matrix=metrics.confusion_matrix(y_val,y_pred_val1)
cnf_matrix=cnf_matrix/cnf_matrix.sum(axis=0)
plot_confusion_matrix2(cnf_matrix,[0,1],title='LR Valid',cmap='Oranges_r')
plt.tight_layout()
plt.savefig('./%s/LR-confusion_matrix2.jpg'%name,dpi=300,bbox_inches = 'tight')
plt.show()
# ### 交叉验证
# In[44]:
clf=joblib.load('./%s/clf_lr.pkl'%name)
train_acc_list_lr,train_Precision_list_lr,train_recall_list_lr,train_f1_list_lr,train_auc_list_lr,\
test_acc_list_lr,test_Precision_list_lr,test_recall_list_lr,test_f1_list_lr,test_auc_list_lr=model_cv_score1(clf,X_resampled[lasso_svm_selcet],y_resampled,a=0.5,random_state=3)
# In[45]:
clf=joblib.load('./%s/clf_lr.pkl'%name)
cv = KFold(n_splits=3,shuffle=True,random_state=0)
plot_learning_curve(clf, u" learning_curve", np.array(X_train), np.array(y_train),cv=cv)
plt.savefig('./%s/LR-CV-学习曲线.jpg'%name,dpi=600,bbox_inches = 'tight')
plt.show()
# ## lightgbm
# ### 默认参数
# In[46]:
import lightgbm as lgb
threshold=0.5
clf=lgb.LGBMClassifier(random_state=1,max_depth=1,n_estimators=100)
clf.fit(X_train,y_train)
# y_pred_train1=clf.predict(X_train)
y_pred_train2=clf.predict_proba(X_train)[:,1]
y_pred_train1=[int(i>threshold) for i in y_pred_train2]
# y_pred_test1=clf.predict(X_test)
y_pred_test2=clf.predict_proba(X_test)[:,1]
y_pred_test1=[int(i>threshold) for i in y_pred_test2]
# y_pred_val1=clf.predict(X_val)
y_pred_val2=clf.predict_proba(X_val)[:,1]
y_pred_val1=[int(i>threshold) for i in y_pred_val2]
try_different_method(y_pred_train1,y_pred_train2,y_pred_test1,y_pred_test2,y_pred_val1,y_pred_val2)
# ### GA调参
# In[47]:
##10.adding GA
def clfResult(vardim, x, bound):
max_depth=round(x[0])
n_estimators=round(x[1])
print("max_depth:",round(max_depth),'n_estimators:',round(n_estimators))
clf = lgb.LGBMClassifier(random_state=1,max_depth=max_depth,n_estimators=n_estimators)
clf.fit(X_train, y_train)
predictval=clf.predict_proba(X_test)[:,1]
print("ACC = ",metrics.roc_auc_score(y_test,predictval)) # R2
return metrics.roc_auc_score(y_test,predictval)
bound = (np.array([[1,1],[2,60]]))
ga = GeneticAlgorithm(19, 2, bound, 2, [0.75, 0.25, 0.5])
ga.solve()
# ### 最优参数模型
# In[48]:
import lightgbm as lgb
threshold=0.48
clf=lgb.LGBMClassifier(random_state=1,max_depth=2,n_estimators=57)
clf.fit(X_train,y_train)
# y_pred_train1=clf.predict(X_train)
y_pred_train2=clf.predict_proba(X_train)[:,1]
y_pred_train1=[int(i>threshold) for i in y_pred_train2]
# y_pred_test1=clf.predict(X_test)
y_pred_test2=clf.predict_proba(X_test)[:,1]
y_pred_test1=[int(i>threshold) for i in y_pred_test2]
# y_pred_val1=clf.predict(X_val)
y_pred_val2=clf.predict_proba(X_val)[:,1]
y_pred_val1=[int(i>threshold) for i in y_pred_val2]
try_different_method(y_pred_train1,y_pred_train2,y_pred_test1,y_pred_test2,y_pred_val1,y_pred_val2)
# In[49]:
joblib.dump(clf,'./%s/clf_lgb.pkl'%name)
# ### 模型评估
# In[50]:
plt.figure(figsize=(15,12), dpi=120)
plt.subplot(1, 3, 1)
#训练
cnf_matrix=metrics.confusion_matrix(y_train,y_pred_train1)
plot_confusion_matrix(cnf_matrix,[0,1],title='lgb Train',cmap=plt.cm.Blues)
#测试
plt.subplot(1, 3, 2)
cnf_matrix=metrics.confusion_matrix(y_test,y_pred_test1)
plot_confusion_matrix(cnf_matrix,[0,1],title='lgb Test',cmap=plt.cm.Blues)
#验证
plt.subplot(1, 3, 3)
cnf_matrix=metrics.confusion_matrix(y_val,y_pred_val1)
plot_confusion_matrix(cnf_matrix,[0,1],title='lgb Valid',cmap=plt.cm.Blues)
plt.tight_layout()
plt.savefig('./%s/lgb-confusion_matrix1.jpg'%name,dpi=300,bbox_inches = 'tight')
plt.show()
plt.figure(figsize=(8,5), dpi=120)
plt.subplot(1, 3, 1)
#训练
cnf_matrix=metrics.confusion_matrix(y_train,y_pred_train1)
cnf_matrix=cnf_matrix/cnf_matrix.sum(axis=0)
plot_confusion_matrix2(cnf_matrix,[0,1],title='lgb Train',cmap='tab20')
#测试
plt.subplot(1, 3, 2)
cnf_matrix=metrics.confusion_matrix(y_test,y_pred_test1)
cnf_matrix=cnf_matrix/cnf_matrix.sum(axis=0)
plot_confusion_matrix2(cnf_matrix,[0,1],title='lgb Test',cmap='Greens_r')
#验证
plt.subplot(1, 3, 3)
cnf_matrix=metrics.confusion_matrix(y_val,y_pred_val1)
cnf_matrix=cnf_matrix/cnf_matrix.sum(axis=0)
plot_confusion_matrix2(cnf_matrix,[0,1],title='lgb Valid',cmap='Oranges_r')
plt.tight_layout()
plt.savefig('./%s/lgb-confusion_matrix2.jpg'%name,dpi=300,bbox_inches = 'tight')
plt.show()
# ### 交叉验证
# In[51]:
clf=joblib.load('./%s/clf_lgb.pkl'%name)
train_acc_list_lgb,train_Precision_list_lgb,train_recall_list_lgb,train_f1_list_lgb,train_auc_list_lgb,\
test_acc_list_lgb,test_Precision_list_lgb,test_recall_list_lgb,test_f1_list_lgb,test_auc_list_lgb=model_cv_score1(clf,X_resampled[lasso_svm_selcet],y_resampled,a=0.5,random_state=3)
# In[52]:
clf=joblib.load('./%s/clf_lgb.pkl'%name)
cv = KFold(n_splits=3,shuffle=True,random_state=3)
plot_learning_curve(clf, u" learning_curve", np.array(X_train), np.array(y_train),cv=cv)
plt.savefig('./%s/lgb-CV-学习曲线.jpg'%name,dpi=600,bbox_inches = 'tight')
plt.show()
# In[53]:
clf=joblib.load('./%s/clf_lgb.pkl'%name)
statistics_auc,statistics_acc,statistics_f1,statistics_precision,statistics_recall,statistics_sens,statistics_spec = bootstrap_auc(y_train,clf.predict_proba(X_train)[:,1],[0,1],bootstraps=1000)
list1=['AUC','ACC','F1','Precision','Recall','Sensitivity','Specificity']
list2=[statistics_auc,statistics_acc,statistics_f1,statistics_precision,statistics_recall,statistics_sens,statistics_spec]
for i,j in zip(list1,list2):
print("LGB Train ",i," (95% CI):",round(np.mean(j,axis=1)[1],4),'(',round(np.min(j,axis=1)[1],4),'-',round(np.max(j,axis=1)[1],4),')')
statistics_auc,statistics_acc,statistics_f1,statistics_precision,statistics_recall,statistics_sens,statistics_spec = bootstrap_auc(y_test,clf.predict_proba(X_test)[:,1],[0,1],bootstraps=1000)
list1=['AUC','ACC','F1','Precision','Recall','Sensitivity','Specificity']
list2=[statistics_auc,statistics_acc,statistics_f1,statistics_precision,statistics_recall,statistics_sens,statistics_spec]
for i,j in zip(list1,list2):
print("LGB Test ",i," (95% CI):",round(np.mean(j,axis=1)[1],4),'(',round(np.min(j,axis=1)[1],4),'-',round(np.max(j,axis=1)[1],4),')')
statistics_auc,statistics_acc,statistics_f1,statistics_precision,statistics_recall,statistics_sens,statistics_spec = bootstrap_auc(y_val,clf.predict_proba(X_val)[:,1],[0,1],bootstraps=1000)
list1=['AUC','ACC','F1','Precision','Recall','Sensitivity','Specificity']
list2=[statistics_auc,statistics_acc,statistics_f1,statistics_precision,statistics_recall,statistics_sens,statistics_spec]
for i,j in zip(list1,list2):
print("LGB Valid ",i," (95% CI):",round(np.mean(j,axis=1)[1],4),'(',round(np.min(j,axis=1)[1],4),'-',round(np.max(j,axis=1)[1],4),')')
# ## catboost
# ### 默认参数
# In[54]:
import catboost as cgb
clf=cgb.CatBoostClassifier(random_seed=1,depth=1,iterations=50,verbose=0)
clf.fit(X_train,y_train)
threshold=0.5
# y_pred_train1=clf.predict(X_train)
y_pred_train2=clf.predict_proba(X_train)[:,1]
y_pred_train1=[int(i>threshold) for i in y_pred_train2]
# y_pred_test1=clf.predict(X_test)