-
Notifications
You must be signed in to change notification settings - Fork 0
/
MIAT_utils.py
1710 lines (1396 loc) · 61.4 KB
/
MIAT_utils.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
import numpy as np
import scipy
from scipy.io import loadmat
import pickle
import torch
import os
import random
import math
from torch.utils import data
from torchvision import datasets, transforms
from torch.utils.data import Dataset, DataLoader, TensorDataset
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Function
from torch.autograd import Variable
from torch.nn.utils.weight_norm import WeightNorm
from sklearn.cluster import KMeans
from itertools import combinations
def get_dataset(source_dataset, target_dataset, n_class=5):
train_record_list = [101, 106, 108, 109, 112, 114, 115, 116, 118, 119, 122, 124, 201, 203,
205, 207, 208, 209, 215, 220, 223, 230]
test_record_list = [100, 103, 105, 111, 113, 117, 121, 123, 200, 202, 210, 212, 213, 214,
219, 221, 222, 228, 231, 232, 233, 234]
if source_dataset == 'DS1':
DS1_train_data_dir = 'data/mitdb_uda_DS1/'
if target_dataset == 'DS2':
DS2_train_data_dir = 'data/mitdb_uda_DS2/DS2_train/'
DS2_test_data_dir = 'data/mitdb_uda_DS2/DS2_test/'
if target_dataset == 'svdb':
DS2_train_data_dir = 'data/svdb_uda_128hz/train/'
DS2_test_data_dir = 'data/svdb_uda_128hz/test/'
if target_dataset == 'incartdb':
DS2_train_data_dir = 'data/incartdb_uda_257hz/train/'
DS2_test_data_dir = 'data/incartdb_uda_257hz/test/'
if source_dataset == 'mitdb':
DS1_train_data_dir = 'data/mitdb_DS1_DS2_whole_data/'
if target_dataset == 'svdb':
DS2_train_data_dir = 'data/svdb_uda_128hz/train/'
DS2_test_data_dir = 'data/svdb_uda_128hz/test/'
if target_dataset == 'incartdb':
DS2_train_data_dir = 'data/incartdb_uda_257hz/train/'
DS2_test_data_dir = 'data/incartdb_uda_257hz/test/'
if source_dataset == 'incartdb':
DS1_train_data_dir = 'data/incartdb_whole_data/'
if target_dataset == 'mitdb':
DS2_train_data_dir = 'data/mitdb_uda_360hz/train/'
DS2_test_data_dir = 'data/mitdb_uda_360hz/test/'
if target_dataset == 'svdb':
DS2_train_data_dir = 'data/svdb_uda_128hz/train/'
DS2_test_data_dir = 'data/svdb_uda_128hz/test/'
if source_dataset == 'svdb':
DS1_train_data_dir = 'data/svdb_whole_data/'
if target_dataset == 'mitdb':
DS2_train_data_dir = 'data/mitdb_uda_360hz/train/'
DS2_test_data_dir = 'data/mitdb_uda_360hz/test/'
if target_dataset == 'incartdb':
DS2_train_data_dir = 'data/incartdb_uda_257hz/train/'
DS2_test_data_dir = 'data/incartdb_uda_257hz/test/'
if source_dataset == 'DS1_and_svdb':
DS1_train_data_dir = 'data/DS1_and_svdb_data/'
if target_dataset == 'DS2':
DS2_train_data_dir = 'data/mitdb_uda_DS2/DS2_train/'
DS2_test_data_dir = 'data/mitdb_uda_DS2/DS2_test/'
if target_dataset == 'svdb':
DS2_train_data_dir = 'data/svdb_uda_128hz/train/'
DS2_test_data_dir = 'data/svdb_uda_128hz/test/'
if target_dataset == 'incartdb':
DS2_train_data_dir = 'data/incartdb_uda_257hz/train/'
DS2_test_data_dir = 'data/incartdb_uda_257hz/test/'
print('source_train_data_dir:', DS1_train_data_dir)
print('target_train_data_dir:', DS2_train_data_dir)
print('target_test_data_dir:', DS2_test_data_dir)
DS1_train_data_list = os.listdir(DS1_train_data_dir)
DS2_train_data_list = os.listdir(DS2_train_data_dir)
DS2_test_data_list = os.listdir(DS2_test_data_dir)
batch_size = 128
nb_epoch = 200 - 100
beat_length = 128
feature_num = 3
channel = 1
class_num = 5
lr = 0.001
dev_x = np.array([]).reshape((0, feature_num, beat_length, 1))
dev_y = np.array([]).reshape((0, class_num))
source_x = np.array([]).reshape((0, feature_num, beat_length, 1))
source_y = np.array([]).reshape((0, class_num))
target_x = np.array([]).reshape((0, feature_num, beat_length, 1))
target_y = np.array([]).reshape((0, class_num))
test_x = np.array([]).reshape((0, feature_num, beat_length, 1))
test_y = np.array([]).reshape((0, class_num))
for rec in DS1_train_data_list:
a = np.load(DS1_train_data_dir + rec)
beat = a['ECG_Data']
Label = a['Label']
source_x = np.concatenate((source_x, beat), axis=0)
source_y = np.concatenate((source_y, Label), axis=0)
for rec in DS2_train_data_list:
a = np.load(DS2_train_data_dir + rec)
beat = a['ECG_Data']
Label = a['Label']
target_x = np.concatenate((target_x, beat), axis=0)
target_y = np.concatenate((target_y, Label), axis=0)
# print('DS2 TRAIN:', rec)
for rec in DS2_test_data_list:
a = np.load(DS2_test_data_dir + rec)
beat = a['ECG_Data']
Label = a['Label']
test_x = np.concatenate((test_x, beat), axis=0)
test_y = np.concatenate((test_y, Label), axis=0)
##对DS1的数据进行shuffle
index = np.arange(source_x.shape[0])
np.random.shuffle(index)
source_x = source_x[index]
source_y = source_y[index]
#从DS1中划分验证集
x_train = source_x
y_train = source_y
source_x = x_train[:int(x_train.shape[0] * 0.8)]
source_y = y_train[:int(x_train.shape[0] * 0.8)]
dev_x = x_train[int(x_train.shape[0] * 0.8):]
dev_y = y_train[int(x_train.shape[0] * 0.8):]
num2char = {0: 'N', 1: 'S', 2: 'V', 3: 'F', 4: 'Q'}
num_class = []
for i in range(n_class):
print('DS1训练集里' + num2char[i] + '类的数量:', int(sum(source_y[:, i])))
num_class.append(sum(source_y[:, i]))
print('\n')
for i in range(n_class):
print('DS1验证集里' + num2char[i] + '类的数量:', int(sum(dev_y[:, i])))
print('\n')
for i in range(n_class):
print('DS2训练集里' + num2char[i] + '类的数量:', int(sum(target_y[:, i])))
print('\n')
for i in range(n_class):
print('DS2测试集里' + num2char[i] + '类的数量:', int(sum(test_y[:, i])))
print('\n')
print('source_x.shape:', source_x.shape)
print('source_y.shape:', source_y.shape)
print('dev_x.shape:', dev_x.shape)
print('dev_y.shape:', dev_y.shape)
print('target_x.shape:', target_x.shape)
print('target_y.shape:', target_y.shape)
print('test_x.shape:', test_x.shape)
print('test_y.shape:', test_y.shape)
print('\n')
source_x = source_x.astype(np.float32)
source_y = source_y.astype(np.int64)
target_x = target_x.astype(np.float32)
target_y = target_y.astype(np.int64)
dev_x = dev_x.astype(np.float32)
dev_y = dev_y.astype(np.int64)
test_x = test_x.astype(np.float32)
test_y = test_y.astype(np.int64)
source_x = np.transpose(source_x, (0, 3, 1, 2))
dev_x = np.transpose(dev_x, (0, 3, 1, 2))
test_x = np.transpose(test_x, (0, 3, 1, 2))
target_x = np.transpose(target_x, (0, 3, 1, 2))
x_train, y_train, x_val, y_val, x_test, y_test, x_target, y_target, num_class = map(torch.tensor,
(source_x, source_y, dev_x,
dev_y, test_x, test_y,
target_x, target_y, num_class))
y_train = torch.argmax(y_train, dim=1)
y_val = torch.argmax(y_val, dim=1)
y_test = torch.argmax(y_test, dim=1)
y_target = torch.argmax(y_target, dim=1)
x_train_N = x_train[y_train == 0]
x_train_S = x_train[y_train == 1]
x_train_V = x_train[y_train == 2]
x_train_F = x_train[y_train == 3]
x_train_Q = x_train[y_train == 4]
class_center = [x_train_N.mean(dim=0).numpy(), x_train_S.mean(dim=0).numpy(), x_train_V.mean(dim=0).numpy(),
x_train_F.mean(dim=0).numpy(), x_train_Q.mean(dim=0).numpy()]
return x_train, y_train, x_val, y_val, x_test, y_test, x_target, y_target, class_center
def visualize(feat, labels, epoch):
plt.ion()
c = ['#ff0000', '#ffff00', '#00ff00', '#00ffff', '#0000ff',
'#ff00ff', '#990000', '#999900', '#009900', '#009999']
plt.clf()
for i in range(10):
plt.plot(feat[labels == i, 0], feat[labels == i, 1], '.', c=c[i])
plt.legend(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], loc='upper right')
plt.xlim(xmin=-8, xmax=8)
plt.ylim(ymin=-8, ymax=8)
plt.text(-7.8, 7.3, "epoch=%d" % epoch)
plt.savefig('./images/epoch=%d.jpg' % epoch)
plt.draw()
plt.pause(0.001)
def judge_entropy_criterion(data, pred1, pred2, feature, thresh=None, num_class=5):
def softmax_entropy(x):
totalSum = np.sum(np.exp(x), axis=-1,keepdims=True)
pred = np.exp(x) / totalSum
ent = -pred * np.log(pred + 1e-6)
return ent.sum(1)
print('thresh:', thresh)
thresh1 = []
data = data.numpy()
pred1 = pred1.numpy()
pred2 = pred2.numpy()
num = pred1.shape[0]
new_data = []
new_label = []
label_proba = []
N_data = []
S_data = []
V_data = []
F_data = []
Q_data = []
for i in range(num):
cand_data = data[i, :, :, :]
label_data = np.zeros((1, num_class))
ind1 = np.argmax(pred1[i, :])
value1 = np.max(pred1[i, :])
ind2 = np.argmax(pred2[i, :])
value2 = np.max(pred2[i, :])
if ind1 == ind2:
new_label.append(ind1)
new_data.append(cand_data)
'''存储每个样本的熵指数'''
# label_proba.append((pred1[i, :]+pred2[i, :])/2)
'''存储每个样本的置信度'''
label_proba.append((value1 + value2) / 2)
new_label = np.array(new_label)
new_data = np.array(new_data)
# label_proba = np.array(softmax_entropy(label_proba))
label_proba = np.array(label_proba)
# print(new_data.shape, new_label.shape, label_proba.shape)
pseudo_data = np.array([]).reshape((0, 1, 3, 128)).astype(np.float32)
pseudo_label = np.array([]).reshape((0)).astype(np.int64)
for i in range(num_class):
class_list = np.array(np.where(new_label == i))[0]
if len(class_list)==0:
continue
# print('class_list shape:',class_list.shape)
temp_ent = label_proba[class_list]
temp_data = new_data[class_list]
temp_label = new_label[class_list]
# ratio = int(thresh * len(temp_label)+1)
ratio = int(np.ceil(thresh * len(temp_label)))
##将置信度降序排列
ent_sort = np.argsort(temp_ent)[::-1]
##取置信度最大的前ratio个样本
ent_sort = ent_sort[:ratio]
thresh1.append(temp_ent[-1])
# print('ent_sort:',ent_sort)
temp_data = temp_data[ent_sort]
temp_label = temp_label[ent_sort]
# print(temp_data.shape, temp_label.shape)
pseudo_data = np.concatenate((pseudo_data,temp_data),axis=0)
pseudo_label = np.concatenate((pseudo_label,temp_label),axis=0)
print('thresh1:', thresh1)
# print('pseudo data:',pseudo_data.shape)
# print('pseudo label:', pseudo_label.shape)
New_Data, New_Label = torch.tensor(pseudo_data), torch.tensor(pseudo_label)
return New_Data, New_Label, New_Label
def select_class(prob, labels, data, num_class=5, per_class=None):
labeled = []
unlabels = []
norm_factor = []
for i in range(num_class):
# class_list = np.array(np.where(classes == i))
class_list = np.array(np.where(labels == i))
class_list = class_list[0]
if len(class_list) != 0:
class_data = prob[class_list]
class_prob = np.argsort(-(class_data[:, i]))
# print(' class_prob:', class_data[:, i])
# print('class_prob_sort:', class_prob)
##选择置信度从高到低前k%的样本
norm_factor.append(-np.log(class_data[class_prob[int((len(class_prob) - 1) * per_class)], i]))
# class_prob_topk = class_prob[:int(len(class_prob) * per_class[i])]
# select_class_index = class_list[class_prob_topk]
# class_ind = labels[np.where(classes == i), :]
# rands = np.random.permutation(len(class_list))
# unlabels.append(class_list[rands[per_class:]])
# labeled.append(class_list[rands[:per_class]])
# label_i = np.zeros((per_class, num_class))
# label_i[:, i] = 1
# new_label = np.concatenate((new_label, labels[select_class_index]), axis=0)
# new_data = np.concatenate((new_data, data[select_class_index]), axis=0)
copy_num = num_class - len(norm_factor)
for i in range(copy_num):
norm_factor.append(100)
# print('norm factor:',norm_factor)
# prob1 = np.zeros((prob.shape[0], prob.shape[1]))
# for i in range(num_class):
# prob1[:, i] = prob[:, i] / np.exp(-norm_factor[i])
new_label = []
new_data = []
for i in range(data.shape[0]):
cand_data = data[i, :, :, :]
ind1 = np.argmax(prob[i, :])
if prob[i, ind1] > np.exp(-norm_factor[ind1]):
new_label.append(ind1)
new_data.append(cand_data)
new_data, new_label = np.array(new_data), np.array(new_label)
# unlabel_ind = []
# for t in unlabels:
# for i in t:
# unlabel_ind.append(i)
# label_ind = []
# for t in new_label:
# for i in t:
# label_ind.append(i)
# new_data = np.array(new_data)
# new_label = np.array(label_ind)
# print(new_data.shape)
# print(new_label.shape)
# unlabel_data = data[unlabel_ind, :, :, :]
# labeled_data = data[label_ind, :, :, :]
# train_label = np.array(train_label).reshape((num_class * per_class, num_class))
# return np.array(labeled_data), np.array(train_label), unlabel_data
return new_data, new_label, norm_factor
def judge_EHTS(data, pred1, pred2, t_feature, s_feature, s_label, thresh=None, num_class=5):
def cos_distance(a, b):
'''a.shape:(batch,fea_dim)
b.shape:(1, fea_dim)'''
a_norm = np.linalg.norm(a, axis=1, keepdims=True)
b_norm = np.linalg.norm(b, axis=1)
similiarity = np.dot(a, b.T) / (a_norm * b_norm)
return similiarity
print('thresh:', thresh)
data = data.numpy()
t_feature = t_feature.numpy()
s_feature = s_feature.numpy()
s_label = s_label.numpy()
num = data.shape[0]
new_label_index = []
for i in range(num):
cand_data = data[i, :, :, :]
ind1 = np.argmax(pred1[i, :])
ind2 = np.argmax(pred2[i, :])
if ind1 == ind2:
new_label_index.append(i)
New_Label_indx = np.array(new_label_index).astype(np.int64)
t_feature = t_feature[New_Label_indx]
data = data[New_Label_indx]
s_center = []
probs = []
for i in range(0, num_class):
cls_idx = np.argwhere(s_label == i)
cls_center = s_feature[cls_idx].mean(axis=0)
probs.append(cos_distance(t_feature, cls_center).reshape(-1))
probs = np.array(probs).T
print('tgt probs shape:', probs.shape)
new_data = []
new_label = []
for i in range(t_feature.shape[0]):
cand_data = data[i, :, :, :]
ind = np.argmax(probs[i, :])
value = np.max(probs[i, :])
if value > thresh:
new_data.append(cand_data)
new_label.append(ind)
New_Data = np.array(new_data).astype(np.float32)
New_Label = np.array(new_label).astype(np.int64)
New_Data, New_Label = torch.tensor(New_Data), torch.tensor(New_Label)
return New_Data, New_Label
def judge_self_paced_learning(data, pred1, pred2, feature, label_ratio, num_class=5):
data = data.numpy()
pred1 = pred1.numpy()
pred2 = pred2.numpy()
feature = feature.numpy()
num = pred1.shape[0]
new_ind = []
new_data = []
new_label = []
new_label_index = []
select_prob = []
select_conf = []
N_data = []
S_data = []
V_data = []
F_data = []
Q_data = []
cls_thresh = 0.99*np.ones(num_class)
if label_ratio >= 1:
label_ratio = 0.99
# cls_thresh = 0.01*np.ones(num_class)
for i in range(num):
cand_data = data[i, :, :, :]
label_data = np.zeros((1, num_class))
ind1 = np.argmax(pred1[i, :])
value1 = np.max(pred1[i, :])
ind2 = np.argmax(pred2[i, :])
value2 = np.max(pred2[i, :])
avg_prob = (pred1[i, :] + pred1[i, :]) / 2
avg_conf = (value1 + value2) / 2
if ind1 == ind2 and ind1 == 0:
new_label.append(ind1)
select_conf.append(avg_conf)
select_prob.append(avg_prob)
new_data.append(cand_data)
if ind1 == ind2 and ind1 == 1:
new_label.append(ind1)
select_conf.append(avg_conf)
select_prob.append(avg_prob)
new_data.append(cand_data)
if ind1 == ind2 and ind1 == 2:
new_label.append(ind1)
select_conf.append(avg_conf)
select_prob.append(avg_prob)
new_data.append(cand_data)
if ind1 == ind2 and ind1 == 3:
new_label.append(ind1)
select_conf.append(avg_conf)
select_prob.append(avg_prob)
new_data.append(cand_data)
if ind1 == ind2 and ind1 == 4:
new_label.append(ind1)
select_conf.append(avg_conf)
select_prob.append(avg_prob)
new_data.append(cand_data)
New_Data, New_Label, Select_Prob, Select_Conf = np.array(new_data), np.array(new_label), np.array(select_prob), \
np.array(select_conf)
for idx_cls in range(num_class):
sample_id = np.argwhere(New_Label == idx_cls)[:, 0]
sample_conf = list(Select_Conf[sample_id])
if len(sample_conf) == 0:
continue
sample_conf.sort(reverse=True) # sort in descending order
len_cls = len(sample_conf)
len_cls_thresh = int(math.floor(len_cls * label_ratio))
# print('len_cls_thresh:', len_cls_thresh)
if len_cls_thresh == 0:
continue
cls_thresh[idx_cls] = sample_conf[len_cls_thresh - 1]
print('label ratio: {:.4f}'.format(label_ratio))
print('cbst thresh:', [t.round(4) for t in cls_thresh])
Select_Prob = Select_Prob / cls_thresh
select_label = []
select_data = []
for i in range(Select_Prob.shape[0]):
if np.max(Select_Prob[i, :]) >= 1:
label = np.argmax(Select_Prob[i, :])
select_label.append(label)
select_data.append(New_Data[i])
New_Data = np.array(select_data).astype(np.float32)
New_Label = np.array(select_label).astype(np.int64)
New_Data, New_Label = torch.tensor(New_Data), torch.tensor(New_Label)
del new_ind, new_data, new_label, new_label_index, select_prob, select_conf
return New_Data, New_Label
def judge_func_my(data, pred1, pred2, feature, thresh=None, num_class=5):
data = data.numpy()
pred1 = pred1.numpy()
pred2 = pred2.numpy()
feature = feature.numpy()
num = pred1.shape[0]
if not thresh:
thresh = [0.85, 0.85, 0.75, 0.65, 0.5]
print('thresh:', thresh)
new_ind = []
new_data = []
new_label = []
new_label_index = []
label_proba = []
N_data = []
S_data = []
V_data = []
F_data = []
Q_data = []
for i in range(num):
cand_data = data[i, :, :, :]
ind1 = np.argmax(pred1[i, :])
value1 = np.max(pred1[i, :])
ind2 = np.argmax(pred2[i, :])
value2 = np.max(pred2[i, :])
# if ind1 == ind2 and ind1 == 0:
if ind2 == 0:
# if max(value1, value2) > thresh[0]: # 0.85
if value2 > thresh[0]:
new_ind.append(ind2)
new_data.append(cand_data)
new_label_index.append(i)
if ind2 == 1:
if value2 > thresh[1]: # 0.85
new_ind.append(ind2)
new_data.append(cand_data)
new_label_index.append(i)
if ind2 == 2:
if value2 > thresh[2]: # 0.75
new_ind.append(ind2)
new_data.append(cand_data)
new_label_index.append(i)
if ind2 == 3:
if value2 > thresh[3]: # 0.65
new_ind.append(ind2)
new_data.append(cand_data)
new_label_index.append(i)
if ind2 == 4:
if value2 > thresh[4]:
new_ind.append(ind2)
new_data.append(cand_data)
new_label_index.append(i)
New_Data, New_Label, New_Label_index = np.array(new_data), np.array(new_ind), np.array(new_label_index)
New_Data = New_Data.astype(np.float32)
New_Label = New_Label.astype(np.int64)
New_Label_index = New_Label_index.astype(np.int64)
New_Data, New_Label = torch.tensor(New_Data), torch.tensor(New_Label)
New_Label_index = torch.tensor(New_Label_index)
return New_Data, New_Label
def judge_func(data, pred1, pred2, feature, thresh=None, num_class=5):
# print('thresh:', [round(t, 4) for t in thresh])
P_H = 0.07
P_L = 0.007
upper = 0.9999
lower = 0.01
step = 0.01
# if not thresh:
# thresh = [0.85, 0.85, 0.75, 0.65, 0.5]
if thresh is None:
thresh = [0.85, 0.85, 0.75, 0.65, 0.5]
# thresh = [0.85, 0.85, 0.85, 0.85, 0.85]
else:
thresh = [thresh] * 5
# print('thresh:', thresh)
# print('thresh:', [t.round(4) for t in thresh])
data = data.numpy()
pred1 = pred1.numpy()
pred2 = pred2.numpy()
feature = feature.numpy()
num = pred1.shape[0]
new_ind = []
new_data = []
new_label = []
new_label_index = []
label_proba = []
N_data = []
S_data = []
V_data = []
F_data = []
Q_data = []
for i in range(num):
cand_data = data[i, :, :, :]
label_data = np.zeros((1, num_class))
ind1 = np.argmax(pred1[i, :])
value1 = np.max(pred1[i, :])
ind2 = np.argmax(pred2[i, :])
value2 = np.max(pred2[i, :])
if ind1 == ind2 and ind1 == 0:
if max(value1, value2) > thresh[0]: # 0.85
label_data[0, ind1] = 1
new_ind.append(ind1)
label_proba.append(max(value1, value2))
new_data.append(cand_data)
new_label_index.append(i)
if ind1 == ind2 and ind1 == 1:
if max(value1, value2) > thresh[1]: # 0.85
label_data[0, ind1] = 1
new_ind.append(ind1)
label_proba.append(max(value1, value2))
new_data.append(cand_data)
new_label_index.append(i)
if ind1 == ind2 and ind1 == 2:
if max(value1, value2) > thresh[2]: # 0.75
label_data[0, ind1] = 1
new_ind.append(ind1)
label_proba.append(max(value1, value2))
new_data.append(cand_data)
new_label_index.append(i)
if ind1 == ind2 and ind1 == 3:
if max(value1, value2) > thresh[3]: # 0.65
label_data[0, ind1] = 1
new_ind.append(ind1)
label_proba.append(max(value1, value2))
new_data.append(cand_data)
new_label_index.append(i)
if ind1 == ind2 and ind1 == 4:
if max(value1, value2) > thresh[4]: # 0.2
label_data[0, ind1] = 1
new_ind.append(ind1)
label_proba.append(max(value1, value2))
new_data.append(cand_data)
new_label_index.append(i)
New_Data, New_Label, New_Label_Prob = np.array(new_data), np.array(new_ind), np.array(label_proba)
New_Label_Index = np.array(new_label_index).astype(np.int64)
New_Data = New_Data.astype(np.float32)
New_Label = New_Label.astype(np.int64)
New_Label_Prob = New_Label_Prob.astype(np.float32)
New_Data, New_Label = torch.tensor(New_Data), torch.tensor(New_Label)
New_Label_Prob = torch.tensor(New_Label_Prob)
New_Label_Index = torch.tensor( New_Label_Index)
return New_Data, New_Label, New_Label_Index
def balance_batch_generator(data, batch_size, shuffle=True, test=False, f1_cls=None):
# if shuffle:
# data = shuffle_aligned_list(data)
# batch_count = 0
#######################################
# Generate balanced labeled source examples.
# Only used on large dataset as
# the training set is quite unbalanced.
#######################################
ecg_data = data[0]
label = data[1]
while True:
data_batch_x = []
data_batch_y = []
# random.seed(666)
for i in range(4):
idx = torch.nonzero(torch.eq(label, i)).numpy().reshape(-1)
# print('idx:',idx)
# print('len idx:', len(idx))
inds = random.sample(list(idx), min(batch_size // 4, len(idx)))
data_batch_x.append(ecg_data[inds])
data_batch_y.append(label[inds])
data_batch_x = torch.cat(data_batch_x, dim=0)
data_batch_y = torch.cat(data_batch_y, dim=0)
# print(data_batch_x.shape, data_batch_y.shape,)
yield [data_batch_x, data_batch_y]
def shuffle_aligned_list(data):
"""Shuffle arrays in a list by shuffling each array identically."""
num = data[0].shape[0]
p = np.random.permutation(num)
return [d[p] for d in data]
def batch_generator(data, batch_size, shuffle=True, test=False, triplet=False):
if shuffle:
data = shuffle_aligned_list(data)
batch_count = 0
while True:
if test:
if batch_count * batch_size >= len(data[0]):
batch_count = 0
if shuffle:
data = shuffle_aligned_list(data)
else:
if batch_count * batch_size + batch_size >= len(data[0]):
batch_count = 0
if shuffle:
data = shuffle_aligned_list(data)
start = batch_count * batch_size
end = start + batch_size
batch_count += 1
yield [d[start:end] for d in data]
def dense_to_one_hot(labels_dense, num_classes=10):
num_labels = labels_dense.shape[0]
labels_one_hot = np.zeros((len(labels_dense), num_classes))
labels_dense = list(labels_dense)
for i, t in enumerate(labels_dense):
labels_one_hot[i, t] = 1
return labels_one_hot
class FocalLoss(nn.Module):
"""
This is a implementation of Focal Loss with smooth label cross entropy supported which is proposed in
'Focal Loss for Dense Object Detection. (https://arxiv.org/abs/1708.02002)'
Focal_Loss= -1*alpha*(1-pt)^gamma*log(pt)
:param num_class:
:param alpha: (tensor) 3D or 4D the scalar factor for this criterion
:param gamma: (float,double) gamma > 0 reduces the relative loss for well-classified examples (p>0.5) putting more
focus on hard misclassified example
:param smooth: (float,double) smooth value when cross entropy
:param balance_index: (int) balance class index, should be specific when alpha is float
:param size_average: (bool, optional) By default, the losses are averaged over each loss element in the batch.
"""
def __init__(self, num_class=5, alpha=0.25, gamma=2, balance_index=1, smooth=None, size_average=True):
super(FocalLoss, self).__init__()
self.num_class = num_class
self.alpha = alpha
self.gamma = gamma
self.smooth = smooth
self.size_average = size_average
if self.alpha is None:
self.alpha = torch.ones(self.num_class, 1)
elif isinstance(self.alpha, (list, np.ndarray)):
assert len(self.alpha) == self.num_class
self.alpha = torch.FloatTensor(alpha).view(self.num_class, 1)
self.alpha = self.alpha / self.alpha.sum()
elif isinstance(self.alpha, float):
alpha = torch.ones(self.num_class, 1)
alpha = alpha * (1 - self.alpha)
alpha[balance_index] = self.alpha
self.alpha = alpha
else:
raise TypeError('Not support alpha type')
if self.smooth is not None:
if self.smooth < 0 or self.smooth > 1.0:
raise ValueError('smooth value should be in [0,1]')
def forward(self, input, target):
epsilon = 1e-6
logit = F.softmax(input, dim=1)
logit = torch.clamp(logit, epsilon, 1 - epsilon)
if logit.dim() > 2:
# N,C,d1,d2 -> N,C,m (m=d1*d2*...)
logit = logit.view(logit.size(0), logit.size(1), -1)
logit = logit.permute(0, 2, 1).contiguous()
logit = logit.view(-1, logit.size(-1))
target = target.view(-1, 1)
alpha = self.alpha
if alpha.device != input.device:
alpha = alpha.to(input.device)
idx = target.cpu().long()
one_hot_key = torch.FloatTensor(target.size(0), self.num_class).zero_()
one_hot_key = one_hot_key.scatter_(1, idx, 1)
if one_hot_key.device != logit.device:
one_hot_key = one_hot_key.to(logit.device)
if self.smooth:
one_hot_key = torch.clamp(one_hot_key, self.smooth, 1.0 - self.smooth)
# pt = (one_hot_key * logit).sum(1) + epsilon
logpt = one_hot_key * torch.log(logit)
# logpt = pt.log()
# alpha = alpha[idx]
# loss = -1 * alpha * torch.pow((1 - pt), gamma) * logpt
loss = - torch.pow((1 - logit), self.gamma) * logpt
if self.size_average:
loss = loss.mean()
else:
loss = loss.sum()
return loss
def focal_loss_zhihu(inputs, target, gamma=1):#0.5
'''
:param input: 使用知乎上面大神给出的方案 https://zhuanlan.zhihu.com/p/28527749
:param target:
:return:
'''
def compute_class_weights(histogram):
classWeights = np.ones(5, dtype=np.float32)
normHist = histogram / np.sum(histogram)
for i in range(5):
classWeights[i] = 1 / (np.log(1.10 + normHist[i]))
return classWeights
# target = target.long()
#
# number_0 = torch.sum(target == 0).item()
# number_1 = torch.sum(target == 1).item()
# number_2 = torch.sum(target == 2).item()
# number_3 = torch.sum(target == 3).item()
# number_4 = torch.sum(target == 4).item()
#
#
# frequency = torch.tensor((number_0, number_1, number_2, number_3, number_4), dtype=torch.float32)
# frequency = frequency.numpy()
# classWeights = compute_class_weights(frequency)
#
# weights = torch.from_numpy(classWeights).float()
# weights = weights[target.view(-1)] # 这行代码非常重要
# weights = weights.to(inputs.device)
epsilon = 1e-10
P = F.softmax(inputs, dim=-1)
P = torch.clamp(P, epsilon, 1-epsilon)
# print('P:',P)# shape [num_samples,num_classes]
target = target.view(-1, 1)
idx = target.cpu().long()
one_hot_key = torch.FloatTensor(target.size(0), 5).zero_()
one_hot_key = one_hot_key.scatter_(1, idx, 1)
if one_hot_key.device != inputs.device:
one_hot_key = one_hot_key.to(inputs.device)
# class_mask = inputs.data.new(N, C).fill_(0)
# class_mask = Variable(class_mask)
# ids = target.view(-1, 1)
# class_mask.scatter_(1, ids.data, 1.)#shape [num_samples,num_classes] one-hot encoding
probs = (P * one_hot_key).sum(1).view(-1, 1) # shape [num_samples,]
log_p = probs.log()
# print('in calculating batch_loss', weights.shape, probs.shape, log_p.shape)
# batch_loss = -weights * (torch.pow((1 - probs), gamma)) * log_p
batch_loss = -(torch.pow((1 - probs), gamma)) * log_p
# print(batch_loss.shape)
loss = batch_loss.mean()
return loss
class LDAMLoss(nn.Module):
'''paper:Learning Imbalanced Datasets with Label-Distribution-Aware Margin Loss'''
def __init__(self, cls_num_list, max_m=0.5, weight=None, s=30):
super(LDAMLoss, self).__init__()
m_list = 1.0 / np.sqrt(np.sqrt(cls_num_list))
m_list = m_list * (max_m / np.max(m_list))
m_list = torch.cuda.FloatTensor(m_list)
self.m_list = m_list
assert s > 0
self.s = s
self.weight = weight
def forward(self, x, target):
index = torch.zeros_like(x, dtype=torch.uint8)
index.scatter_(1, target.data.view(-1, 1), 1)
index_float = index.type(torch.cuda.FloatTensor)
batch_m = torch.matmul(self.m_list[None, :], index_float.transpose(0, 1))
batch_m = batch_m.view((-1, 1))
x_m = x - batch_m
output = torch.where(index, x_m, x)
return F.cross_entropy(self.s * output, target, weight=self.weight)
def separability_loss(s_feature, t_feature, s_label, t_label, num_classes=5):
uni = np.array(np.unique(t_label.cpu().numpy(), return_counts=True))
##uni=[[0, 2],
## [116, 12]]
mi = np.min(uni[1])
if len(uni[1]) < num_classes:
mi = 0
ma = np.max(uni[1])
imbalance_parameter = (mi + 1) / (ma + 1)
# print('imbalance_parameter:', imbalance_parameter)
latents = torch.cat((s_feature, t_feature), 0)
labels = torch.cat((s_label, t_label), 0)
criteria = nn.CosineEmbeddingLoss()
loss_up = 0
one_cuda = torch.ones(1).cuda()
mean = torch.mean(latents, dim=0).to(s_label.device).view(1, -1)
loss_down = 0
for i in range(num_classes):
indexes = labels.eq(i)
mean_i = torch.mean(latents[indexes], dim=0).view(1, -1)
if str(mean_i.norm().item()) != 'nan':
loss_up += criteria(latents[indexes], mean_i, one_cuda)
# for latent in latents[indexes]:
# loss_up += criteria(latent.view(1, -1), mean_i, one_cuda)
loss_down += criteria(mean, mean_i, one_cuda)
loss = (loss_up / loss_down) * imbalance_parameter
return loss
def extract_embeddings(model, dataloader):
model.eval()
n_samples = dataloader.batch_size * len(dataloader)
embeddings = np.zeros((n_samples, model.n_outputs))
labels = np.zeros(n_samples)
k = 0