-
Notifications
You must be signed in to change notification settings - Fork 0
/
MI_flow_in_forward.py
1523 lines (1300 loc) · 75.4 KB
/
MI_flow_in_forward.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 matplotlib.pyplot as plt
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
from pylab import mpl
import datetime
from MI_estimator import mutual_info_estimator
from utils import *
from torchattacks import PGD
import pickle
import torch.nn.functional as F
# mpl.rcParams['savefig.dpi'] = 400 # 保存图片分辨率
# mpl.rcParams["figure.subplot.left"], mpl.rcParams["figure.subplot.right"] = 0.1, 0.95
# mpl.rcParams["figure.subplot.bottom"], mpl.rcParams["figure.subplot.top"] = 0.1, 0.9
# mpl.rcParams["figure.subplot.wspace"], mpl.rcParams["figure.subplot.hspace"] = 0.2, 0.4
# mpl.rcParams['figure.constrained_layout.use'] = True
# 选择模型
# Activation_F = 'Tanh'
# Activation_F = 'ReLU'
class Forward():
def __init__(self, Origin_Model, args):
self.Args = args
self.Origin_Model = Origin_Model
self.Model_Name = args.Model_Name
self.Data_Set = args.Data_Set
# self.Enable_Show = True
# self.Std_Epoch_Num = args.Std_Epoch_Num
self.Forward_Size, self.Forward_Repeat = args.Forward_Size, args.Forward_Repeat
# self.Train_Batch_Size = args.batch_size
self.Device = torch.device("cuda:%d" % (args.GPU) if torch.cuda.is_available() else "cpu")
# 在 forward之前设定一下测试集的装载
self.Test_Loader = None # self.get_test_loader(Data_Set)
self.std_estimator = mutual_info_estimator(self.Origin_Model.modules_to_hook, By_Layer_Name=False)
self.adv_estimator = mutual_info_estimator(self.Origin_Model.modules_to_hook, By_Layer_Name=False)
self.Patch_Split_L = [0, 2, 4, 8] # 0
self.Saturation_L = [2, 8, 16, 64, 1024] # 2
self.Loss_Acc = None
def get_test_loader(self):
# 全局取消证书验证
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
data_tf_test = transforms.Compose([
transforms.ToTensor(),
# Saturation_Transform(saturation_level=1024.),
# Patch_Transform(k=4),
# Extra_Transform
])
data_tf_mnist = transforms.Compose([
transforms.ToTensor(),
])
Data_Set = self.Data_Set
if Data_Set == 'CIFAR10':
# train_dataset = datasets.CIFAR10(root='./DataSet/CIFAR10', train=True, transform=data_tf_cifar10,
# download=True)
test_dataset = datasets.CIFAR10(root='./DataSet/CIFAR10', train=False, transform=data_tf_test)
elif Data_Set == 'STL10':
# train_dataset = datasets.CIFAR10(root='./DataSet/CIFAR10', train=True, transform=data_tf_cifar10,
# download=True)
test_dataset = datasets.STL10(root='./DataSet/STL10', split='test', transform=data_tf_test)
elif Data_Set == 'MNIST':
# train_dataset = datasets.MNIST(root='./DataSet/MNIST', train=True, transform=data_tf_mnist, download=True)
test_dataset = datasets.MNIST(root='./DataSet/MNIST', train=False, transform=data_tf_mnist)
else:
print(Data_Set)
raise RuntimeError('Unknown Dataset')
# Train_Loader = DataLoader(dataset=train_dataset, batch_size=self.Train_Batch_Size, shuffle=True)
Test_Loader = DataLoader(dataset=test_dataset, batch_size=self.Forward_Size, shuffle=True)
return Test_Loader
def train_attack(self, Model, Random_Start=False):
# atk = PGD(Model, eps=args.Eps, alpha=args.Eps * 1.2 / 7, steps=7, random_start=Random_Start)
atk = PGD(Model, eps=self.Args.Eps, alpha=self.Args.Alpha, steps=self.Args.Step, random_start=Random_Start)
# atk = PGD(Model, eps=30 / 255, alpha=5 / 255, steps=7, random_start=Random_Start)
return atk
def test_attack(self, Model, Random_Start=False):
# atk = PGD(Model, eps=args.Eps, alpha=args.Eps * 1.2 / 7, steps=7, random_start=Random_Start)
atk = PGD(Model, eps=self.Args.Eps, alpha=self.Args.Alpha, steps=self.Args.Step, random_start=Random_Start)
# atk = PGD(Model, eps=12 / 255, alpha=3 / 255, steps=7, random_start=Random_Start)
# atk = PGD(Model, eps=16 / 255, alpha=4 / 255, steps=7, random_start=Random_Start)
# atk = PGD(Model, eps=30 / 255, alpha=5 / 255, steps=7, random_start=Random_Start)
return atk
def save_mutual_info_data(self, Transform_Type, Enable_Adv_Training):
Is_Adv_Training = 'Adv_Train' if Enable_Adv_Training else 'Std_Train'
Model_Name, Forward_Size, Forward_Repeat = self.Model_Name, self.Forward_Size, self.Forward_Repeat
dir = 'Checkpoint/%s/%s' % (Model_Name, Transform_Type)
# 对于每一个模型产生的数据, 使用一个文件夹单独存放
if not os.path.exists(dir):
os.makedirs(dir)
mi_loss_acc = {'Model': Model_Name,
'Enable_Adv_Training': Enable_Adv_Training,
'Forward_Size': Forward_Size,
'Forward_Repeat': Forward_Repeat,
'std_estimator': self.std_estimator,
'adv_estimator': self.adv_estimator,
'loss_acc': self.Loss_Acc
}
with open('./Checkpoint/%s/%s/mi_loss_acc_%s.pkl' % (Model_Name, Transform_Type, Is_Adv_Training), 'wb') as f:
pickle.dump(mi_loss_acc, f)
@torch.no_grad()
def get_clean_or_adv_image(self, Model, Keep_Clean):
atk = self.test_attack(Model, Random_Start=False)
batch_images, batch_labels = next(iter(self.Test_Loader))
batch_images = batch_images.to(self.Device)
batch_labels = batch_labels.to(self.Device)
if Keep_Clean:
return batch_images, batch_labels
else:
with torch.enable_grad():
adv_images = atk(batch_images, batch_labels)
return adv_images, batch_labels
@torch.no_grad()
def calculate_acc_and_mutual_info(self, Model, Transform_Type, Level, Keep_Clean):
import random
# 这里的epoch_i没必要指定,因为epochi就是列表当中的最后一个元素
# a = list[-1]就是最后一个元素
Model.eval()
correct_N = 0
total_N = 0
loss = 0.
image_chunk = None
label_chunk = None
layer_activation_chunk = None
def Saturation_Transform(batch_images, level=2):
'''
for each pixel v: v' = sign(2v - 1) * |2v - 1|^{2/p} * 0.5 + 0.5
then clip -> (0, 1)
'''
p = level * 1.0
ones = torch.ones_like(batch_images)
# print(img.size(), torch.max(img), torch.min(img))
ret_img = torch.sign(2 * batch_images - ones) * torch.pow(torch.abs(2 * batch_images - ones), 2.0 / p)
ret_img = ret_img * 0.5 + ones * 0.5
ret_img = torch.clamp(ret_img, 0, 1)
return ret_img
def Patch_Transform(batch_images, level=2):
'''
X: torch.Tensor of shape(c, h, w) h % self.k == 0
:param images:
:return:
'''
# K==0则不分割数据
k = level
if k == 0:
return batch_images
b, c, h, w = batch_images.size()
for idx in range(b):
patches = []
images = batch_images[idx]
dh = h // k
dw = w // k
# print(dh, dw)
sh = 0
for i in range(h // dh):
eh = sh + dh
eh = min(eh, h)
sw = 0
for j in range(w // dw):
ew = sw + dw
ew = min(ew, w)
patches.append(images[:, sh:eh, sw:ew])
# print(sh, eh, sw, ew)
sw = ew
sh = eh
random.shuffle(patches)
start = 0
imgs = []
for i in range(k):
end = start + k
imgs.append(torch.cat(patches[start:end], dim=1))
start = end
img = torch.cat(imgs, dim=2)
batch_images[idx] = img
return batch_images
if Transform_Type == 'Saturation':
Extra_Transform = Saturation_Transform
elif Transform_Type == 'Patch':
Extra_Transform = Patch_Transform
else:
raise RuntimeError('Unknown Transformation')
if Keep_Clean:
estimator = self.std_estimator
else:
estimator = self.adv_estimator
for i in range(self.Forward_Repeat):
batch_images, labels = self.get_clean_or_adv_image(Model, Keep_Clean)
'''
对正常样本和对抗样本进行变换
'''
images = Extra_Transform(batch_images, Level)
# labels = labels.to(Device)
# # print('std_test_size', images.size(0))
# images = images.to(Device)
"""
forward之前先clear
"""
estimator.clear_activations()
# register hook
estimator.do_forward_hook(Model)
"""
计算模型的准确率
"""
outputs = Model(images)
loss_i = F.cross_entropy(outputs, labels)
# predicted_prob, predicted, labels 都可以看成是一个列表或者是一个向量,列表中元素的个数为 batch_size 个
# 先对神经网络的输出结果做一个 softmax 获取概率值
# predicted_prob, predicted = torch.max(F.softmax(outputs, dim=1), dim=1)
predicted_prob, predicted = torch.max(outputs, dim=1)
correct_N += (predicted == labels).sum().item()
total_N += labels.size(0)
loss += loss_i.item()
"""
发现并修改了一个重大bug, 这里每forward一次,caculate_MI 函数计算出的互信息值都直接挂在列表的后面,那么 Forward_Repeat 会成倍放大列表的长度
且会混乱每一个 epoch 中的互信息变化情况,Forward_Repeat 一旦超过 epoch_num ,那么每一个 epoch 的曲线就会
"""
# 给定初始值
if i == 0:
# print("---> layer activations size {} <---".format(layer_activations_size))
image_chunk = images.clone().detach()
label_chunk = labels.clone().detach()
'''
注意, 这里如果简单赋值就会出现传递引用的现象,需要手动调用copy,复制列表
'''
layer_activation_chunk = estimator.layer_activations.copy()
# 计算所有循环的和
else:
image_chunk = torch.cat((image_chunk, images.clone().detach()), dim=0)
label_chunk = torch.cat((label_chunk, labels.clone().detach()), dim=0)
"""
这里 layer_activations 是一个 list, list 里的每一个元素时 tesnor (gpu:0)
"""
for idx, item in enumerate(estimator.layer_activations):
layer_activation_chunk[idx] = torch.cat((layer_activation_chunk[idx], item.clone().detach()), dim=0)
"""
forward 之后例行收尾工作
"""
estimator.cancel_hook()
estimator.clear_activations()
# 计算存储互信息
# calculate mutual info
estimator.layer_activations = layer_activation_chunk
estimator.caculate_MI(image_chunk.cpu(), label_chunk.cpu())
estimator.store_MI()
acc = correct_N * 100. / total_N
return acc, loss / self.Forward_Repeat
def forward(self, Model, Transform_Type, Enable_Adv_Training):
test_clean_acc_L, test_adv_acc_L = [], []
test_clean_loss_L, test_adv_loss_L = [], []
# Load checkpoint.
if Enable_Adv_Training:
# 装载训练好的模型
print('--> Loading AT-Model %s state dict..' % self.Model_Name)
load_model(Model, './Checkpoint/%s/%s_adv.pth' % (self.Model_Name, self.Model_Name))
else:
print('--> Loading STD-Model %s state dict..' % self.Model_Name)
load_model(Model, './Checkpoint/%s/%s_std.pth' % (self.Model_Name, self.Model_Name))
print('--> Load checkpoint successfully! ')
Model = Model.to(self.Device)
Model.eval()
if Transform_Type == 'Saturation':
Level_L = self.Saturation_L
elif Transform_Type == 'Patch':
Level_L = self.Patch_Split_L
else:
Level_L = None
for level in Level_L:
# TODO: 这里的工作流程需要变动一下, 应该是先产生样本, 再对样本进行切片和饱和度调整,
# 设定好特定的装载程序之后前,在验证集上计算干净样本和对抗样本互信息并且计算准确率
self.Test_Loader = self.get_test_loader()
level_i_test_clean_acc, level_i_test_clean_loss = self.calculate_acc_and_mutual_info(Model,
Transform_Type=Transform_Type,
Level=level,
Keep_Clean=True)
level_i_test_adv_acc, level_i_test_adv_loss = self.calculate_acc_and_mutual_info(Model,
Transform_Type=Transform_Type,
Level=level,
Keep_Clean=False)
# 在验证集上的干净样本准确率,对抗样本准确率,loss
test_clean_acc_L.append(level_i_test_clean_acc)
test_adv_acc_L.append(level_i_test_adv_acc)
test_clean_loss_L.append(level_i_test_clean_loss)
test_adv_loss_L.append(level_i_test_adv_loss)
# print some data
print('%s level_i[%d] '
'test_clean_loss[%.2f], test_adv_loss[%.2f] '
'test_clean_acc[%.2f%%],test_adv_acc[%.2f%%]'
% (Transform_Type, level,
level_i_test_clean_loss, level_i_test_adv_loss,
level_i_test_clean_acc, level_i_test_adv_acc))
loss_acc = {
'test_clean_loss': test_clean_loss_L,
'test_adv_loss': test_adv_loss_L,
'test_clean_acc': test_clean_acc_L,
'test_adv_acc': test_adv_acc_L
}
# plot_performance(analytic_data, Enable_Adv_Training)
self.Loss_Acc = loss_acc
'''
在保存数据之前,一定要清除layer_activations, layer_activations数据量真的太大了
'''
self.std_estimator.clear_activations()
self.adv_estimator.clear_activations()
self.save_mutual_info_data(Transform_Type, Enable_Adv_Training)
"""
在退出训练之前完成清理工作
"""
self.std_estimator.clear_all()
self.adv_estimator.clear_all()
self.Loss_Acc = None
print('the training has completed')
def plot_data(self, Transform_Type, Enable_Adv_Training):
from pylab import mpl
mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
# mpl.rcParams['savefig.dpi'] = 400 # 保存图片分辨率
mpl.rcParams['figure.constrained_layout.use'] = True
plt.rcParams['xtick.direction'] = 'in' # 将x周的刻度线方向设置向内
plt.rcParams['ytick.direction'] = 'in' # 将y轴的刻度方向设置向内
from matplotlib.lines import Line2D
line_legends = [Line2D([0], [0], color='purple', linewidth=1, linestyle='-', marker='o'),
Line2D([0], [0], color='purple', linewidth=1, linestyle='--', marker='^')]
Is_Adv_Training = 'Adv_Train' if Enable_Adv_Training else 'Std_Train'
Model_Name = self.Model_Name
with open('./Checkpoint/%s/%s/mi_loss_acc_%s.pkl' % (Model_Name, Transform_Type, Is_Adv_Training), 'rb') as f:
mi_loss_acc = pickle.load(f)
Forward_Size, Forward_Repeat = mi_loss_acc['Forward_Size'], mi_loss_acc['Forward_Repeat']
std, adv = mi_loss_acc['std_estimator'], mi_loss_acc['adv_estimator']
# Model_Name = basic_info['Model']
Activation_F = 'relu'
Learning_Rate = 0.08
Std_Epoch_Num = len(std.epoch_MI_hM_X_upper)
Epochs = [i for i in range(Std_Epoch_Num)]
Layer_Num = len(std.epoch_MI_hM_X_upper[0])
Layer_Name = [str(i) for i in range(Layer_Num)]
# sm = plt.cm.ScalarMappable(cmap='Blues', norm=plt.Normalize(vmin=0, vmax=Std_Epoch_Num))
sm = plt.cm.ScalarMappable(cmap='gnuplot', norm=plt.Normalize(vmin=0, vmax=Std_Epoch_Num))
title = "%s(%s),LR(%.3f),Upper/Lower/Bin,Clean(Adv),Sample_N(%d),%s,%s" % (
Model_Name, Activation_F, Learning_Rate, Forward_Repeat * Forward_Size, Is_Adv_Training, Transform_Type
)
def axs_plot(axs, std_I_TX, std_I_TY, adv_I_TX, adv_I_TY, Std_Epoch_Num, MI_Type):
std_I_TX = np.array(std_I_TX)
std_I_TY = np.array(std_I_TY)
adv_I_TX = np.array(adv_I_TX)
adv_I_TY = np.array(adv_I_TY)
# 设定坐标范围
# i_tx_min = math.floor(min(np.min(std_I_TX), np.min(adv_I_TX))) - 0.1
# i_tx_max = math.ceil(max(np.max(std_I_TX), np.max(adv_I_TX))) + 0.1
#
# i_ty_min = math.floor(min(np.min(std_I_TY), np.min(adv_I_TY))) - 0.1
# i_ty_max = math.ceil(max(np.max(std_I_TY), np.max(adv_I_TY))) + 0.1
i_tx_min = min(np.min(std_I_TX), np.min(adv_I_TX)) - 0.1
i_tx_max = max(np.max(std_I_TX), np.max(adv_I_TX)) + 0.1
i_ty_min = min(np.min(std_I_TY), np.min(adv_I_TY)) - 0.1
i_ty_max = max(np.max(std_I_TY), np.max(adv_I_TY)) + 0.1
for epoch_i in range(Std_Epoch_Num):
c = sm.to_rgba(epoch_i + 1)
# layers = [i for i in range(1,len(I_TX)+1)]
std_I_TX_epoch_i, std_I_TY_epoch_i = std_I_TX[epoch_i], std_I_TY[epoch_i]
adv_I_TX_epoch_i, adv_I_TY_epoch_i = adv_I_TX[epoch_i], adv_I_TY[epoch_i]
axs[0].set_title(MI_Type)
axs[0].legend(line_legends, ['std', 'adv'])
axs[1].legend(line_legends, ['std', 'adv'])
axs[0].plot(Layer_Name, std_I_TX_epoch_i,
color=c, marker='o',
linestyle='-', linewidth=1,
)
axs[1].plot(Layer_Name, adv_I_TX_epoch_i,
color=c, marker='^',
linestyle='--', linewidth=1,
)
# 设定 x 轴坐标范围
axs[0].set_ylim((i_tx_min, i_tx_max))
axs[1].set_ylim((i_tx_min, i_tx_max))
axs[2].plot(Layer_Name, std_I_TY_epoch_i,
color=c, marker='o',
linestyle='-', linewidth=1,
)
axs[3].plot(Layer_Name, adv_I_TY_epoch_i,
color=c, marker='^',
linestyle='--', linewidth=1,
)
# 设定 y 轴坐标范围
axs[2].set_ylim((i_ty_min, i_ty_max))
axs[3].set_ylim((i_ty_min, i_ty_max))
# fig size, 先列后行
nrows = 4
ncols = 4
fig, axs = plt.subplots(nrows, ncols, figsize=(15, 15), )
# 初始化 xlabel, y_label
for i in range(nrows - 1):
for j in range(ncols):
axs[i][j].grid(True)
if j < 2:
axs[i][j].set_xlabel('layers')
axs[i][j].set_ylabel(r'$I(T;X)$')
else:
axs[i][j].set_xlabel('layers')
axs[i][j].set_ylabel(r'$I(T;Y)$')
# range(开始,结束,步长)
# 绘制每一轮次的信息曲线
# std/adv Upper
axs_plot(axs[0],
std.epoch_MI_hM_X_upper, std.epoch_MI_hM_Y_upper,
adv.epoch_MI_hM_X_upper, adv.epoch_MI_hM_Y_upper,
Std_Epoch_Num, MI_Type='upper'
)
# std/adv Lower
axs_plot(axs[1],
std.epoch_MI_hM_X_lower, std.epoch_MI_hM_Y_lower,
adv.epoch_MI_hM_X_lower, adv.epoch_MI_hM_Y_lower,
Std_Epoch_Num, MI_Type='lower'
)
# std/adv Bin
axs_plot(axs[2],
std.epoch_MI_hM_X_bin, std.epoch_MI_hM_Y_bin,
adv.epoch_MI_hM_X_bin, adv.epoch_MI_hM_Y_bin,
Std_Epoch_Num, MI_Type='bin'
)
# plt.scatter(I_TX, I_TY,
# color=c,
# linestyle='-', linewidth=0.1,
# zorder=2
# )
# -------------------------------------------Loss and Accuracy Detail---------------------
# for idx, (k, v) in enumerate(analytic_data.items()):
axs[nrows - 1][0].set_xlabel('epochs')
axs[nrows - 1][0].set_title('loss')
# axs[nrows - 1][0].plot(Epochs, mi_loss_acc['train_loss'], label='train_loss')
axs[nrows - 1][0].plot(Epochs, mi_loss_acc['loss_acc']['test_clean_loss'], label='test_clean_loss')
axs[nrows - 1][0].plot(Epochs, mi_loss_acc['loss_acc']['test_adv_loss'], label='test_adv_loss')
axs[nrows - 1][0].legend()
# -------------------
axs[nrows - 1][1].set_xlabel('epochs')
axs[nrows - 1][1].set_title('acc')
# axs[nrows - 1][1].plot(Epochs, analytic_data['train_acc'], label='train_acc')
axs[nrows - 1][1].plot(Epochs, mi_loss_acc['loss_acc']['test_clean_acc'], label='test_clean_acc')
axs[nrows - 1][1].plot(Epochs, mi_loss_acc['loss_acc']['test_adv_acc'], label='test_adv_acc')
axs[nrows - 1][1].legend()
# plt.scatter(epoch_MI_hM_X_upper[0], epoch_MI_hM_Y_upper[0])
# plt.legend()
fig.suptitle(title)
fig.colorbar(sm, ax=axs, label='Epoch')
# fig = plt.gcf()
# if Enable_Show:
plt.show()
fig.savefig('mutual_info_%s_%s_%s.pdf' % (
Model_Name, Is_Adv_Training,
datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S")))
# -------------------------------------------Mutual Information Detail---------------------
# 设定坐标范围
# i_tx_min = math.floor(min(np.min(std_I_TX), np.min(adv_I_TX))) - 0.5
# i_tx_max = math.ceil(max(np.max(std_I_TX), np.max(adv_I_TX)))
#
# i_ty_min = math.floor(min(np.min(std_I_TY), np.min(adv_I_TY))) - 0.5
# i_ty_max = math.ceil(max(np.max(std_I_TY), np.max(adv_I_TY)))
Enable_Detail = False
if Enable_Detail:
fig, axs = plt.subplots(nrows=2, ncols=Layer_Num, figsize=(17, 7))
std_lower_detail = np.array(std.epoch_MI_hM_Y_lower_detail)
adv_lower_detail = np.array(adv.epoch_MI_hM_Y_lower_detail)
# C0-C9 是 matplotlib 里经常使用的色条
COLOR = ['C0', 'C1', 'C2', 'C3', 'C4', 'C5',
'C6', 'C7', 'C8', 'C9', 'olive', 'peach', ]
for layer_i in range(Layer_Num):
axs[0][layer_i].set_xlabel('epochs')
axs[0][layer_i].set_title('Std Layer %d' % layer_i)
# epoch_i, layer_i, label_i
axs[0][layer_i].plot(Epochs, std_lower_detail[..., layer_i, -1],
color=COLOR[0],
label=r'$H_{Lower}(T_i)$')
axs[1][layer_i].set_xlabel('epochs')
axs[1][layer_i].set_title('Adv Layer %d' % layer_i)
axs[1][layer_i].plot(Epochs, adv_lower_detail[..., layer_i, -1],
color=COLOR[0],
label=r'$H_{Lower}(T_i)$')
for label_i in [i for i in range(10)]:
# epoch_i, layer_i, label_i
std_temp_data = std_lower_detail[..., layer_i, label_i]
axs[0][layer_i].plot(Epochs, std_temp_data,
color=COLOR[label_i + 1],
label=r'$H(T_i|y_%d)$' % (label_i))
adv_temp_data = std_lower_detail[..., layer_i, label_i]
axs[1][layer_i].plot(Epochs, adv_temp_data,
color=COLOR[label_i + 1],
label=r'$H(T_i|y_%d)$' % (label_i))
if layer_i == 0:
axs[0][0].legend(ncol=2)
title = "%s(%s),LR(%.3f),MI Lower Bound detail,Clean(Adv),Sample_N(%d),%s" % (
Model_Name, Activation_F, Learning_Rate, Forward_Repeat * Forward_Size, Is_Adv_Training
)
fig.suptitle(title)
plt.show()
fig.savefig('mutual_info_detail_%s_%s.pdf' % (Model_Name, Is_Adv_Training))
print("Work has done!")
# 模型的类型固定,分别绘制不同程度的饱和度和分块设置在同一张图里面
def plot_mi_curve_diff_saturation_and_patch_style_1(self):
# TODO: 把不同模型的在 分块,饱和度实验下的结果一起展示。
from pylab import mpl
mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
# mpl.rcParams['savefig.dpi'] = 400 # 保存图片分辨率
mpl.rcParams['figure.constrained_layout.use'] = True
plt.rcParams['xtick.direction'] = 'in' # 将x周的刻度线方向设置向内
plt.rcParams['ytick.direction'] = 'in' # 将y轴的刻度方向设置向内
from matplotlib.lines import Line2D
Is_Adv_Training = 'Std_Train'
Model_Name = self.Model_Name
Transform_Type = 'Saturation'
with open('./Checkpoint/%s/%s/mi_loss_acc_%s.pkl' % (Model_Name, Transform_Type, Is_Adv_Training), 'rb') as f:
st_saturation_mi_loss_acc = pickle.load(f)
Transform_Type = 'Patch'
with open('./Checkpoint/%s/%s/mi_loss_acc_%s.pkl' % (Model_Name, Transform_Type, Is_Adv_Training), 'rb') as f:
st_patch_mi_loss_acc = pickle.load(f)
Is_Adv_Training = 'Adv_Train'
Model_Name = self.Model_Name
Transform_Type = 'Saturation'
with open('./Checkpoint/%s/%s/mi_loss_acc_%s.pkl' % (Model_Name, Transform_Type, Is_Adv_Training), 'rb') as f:
at_saturation_mi_loss_acc = pickle.load(f)
Transform_Type = 'Patch'
with open('./Checkpoint/%s/%s/mi_loss_acc_%s.pkl' % (Model_Name, Transform_Type, Is_Adv_Training), 'rb') as f:
at_patch_mi_loss_acc = pickle.load(f)
Forward_Size, Forward_Repeat = st_saturation_mi_loss_acc['Forward_Size'], \
st_saturation_mi_loss_acc['Forward_Repeat']
st_saturation_std, st_saturation_adv = st_saturation_mi_loss_acc['std_estimator'], \
st_saturation_mi_loss_acc['adv_estimator']
st_patch_std, st_patch_adv = st_patch_mi_loss_acc['std_estimator'], \
st_patch_mi_loss_acc['adv_estimator']
at_saturation_std, at_saturation_adv = at_saturation_mi_loss_acc['std_estimator'], \
at_saturation_mi_loss_acc['adv_estimator']
at_patch_std, at_patch_adv = at_patch_mi_loss_acc['std_estimator'], \
at_patch_mi_loss_acc['adv_estimator']
# Model_Name = basic_info['Model']
Level_Num_Max = max(len(st_saturation_std.epoch_MI_hM_X_upper), len(st_patch_std.epoch_MI_hM_X_upper))
print('Level_Num_Max', Level_Num_Max)
Layer_Num = len(st_saturation_std.epoch_MI_hM_X_upper[0])
Layer_Name = [str(i + 1) for i in range(Layer_Num)]
Saturation_L = [str(i) for i in self.Saturation_L]
Patch_L = [str(i) for i in self.Patch_Split_L]
# sm = plt.cm.ScalarMappable(cmap='Blues', norm=plt.Normalize(vmin=0, vmax=Std_Epoch_Num))
# bins = [i for i in range(Level_Num_Max)]
# nbin = len(bins) - 1
# import matplotlib as mpl
# cmap = mpl.cm.get_cmap('viridis', nbin)
# bd_norm = mpl.colors.BoundaryNorm(bins, nbin)
# sm = mpl.cm.ScalarMappable(norm=bd_norm, cmap=cmap)
# Level_Num_Max = 5 则数据应该在 -0.5 ~ +4.5之间
sm = plt.cm.ScalarMappable(cmap='jet', norm=plt.Normalize(vmin=-0.5, vmax=Level_Num_Max - 0.5))
title = "%s,Upper/Lower/Bin,Clean(Adv),Sample_N(%d),Std/Adv train" % (
Model_Name, Forward_Repeat * Forward_Size,
)
COLOR = ['C0', 'C1', 'C2', 'C3', 'C4', 'C5',
'C6', 'C7', 'C8', 'C9', 'olive', 'peach', ]
# fig size, 先列后行
nrows = 2
ncols = 4
# px = 1 / plt.rcParams['figure.dpi'] # pixel in inches
px = 1
plt.show()
Fig_Size = (5, 11)
fig, axs = plt.subplots(nrows, ncols, figsize=(Fig_Size[1] * px, Fig_Size[0] * px), )
# -------------Saturation (Standard Training) ST Loss and Accuracy Detail -------------------------
axs[0][0].set_xlabel('Saturation level')
axs[0][0].set_ylabel('Loss')
# axs[0][0].plot(Epochs, st_saturation_mi_loss_acc['train_loss'], label='train_loss')
# 颜色表示是ST还是AT, 实线和虚线表示正常样本还是对抗样本, marker 表示是 Saturation 还是 Patch
axs[0][0].plot(Saturation_L, st_saturation_mi_loss_acc['loss_acc']['test_clean_loss'],
linestyle='-', c='C0', marker='x', markerfacecolor='none',
label='ST clean test')
axs[0][0].plot(Saturation_L, st_saturation_mi_loss_acc['loss_acc']['test_adv_loss'],
linestyle=':', c='C0', marker='x', markerfacecolor='none',
label='ST adv test')
axs[0][0].plot(Saturation_L, at_saturation_mi_loss_acc['loss_acc']['test_clean_loss'],
linestyle='-', c='C1', marker='x', markerfacecolor='none',
label='AT clean test')
axs[0][0].plot(Saturation_L, at_saturation_mi_loss_acc['loss_acc']['test_adv_loss'],
linestyle=':', c='C1', marker='x', markerfacecolor='none',
label='AT adv test')
axs[0][0].legend()
axs[0][1].set_xlabel('Saturation level')
axs[0][1].set_ylabel('Accuracy (%)')
# axs[0][1].set_title('Standard training')
# axs[0][1].plot(Epochs, analytic_data['train_acc'], label='train_acc')
axs[0][1].plot(Saturation_L, st_saturation_mi_loss_acc['loss_acc']['test_clean_acc'],
linestyle='-', c='C0', marker='x', markerfacecolor='none', markersize=7)
axs[0][1].plot(Saturation_L, st_saturation_mi_loss_acc['loss_acc']['test_adv_acc'],
linestyle=':', c='C0', marker='x', markerfacecolor='none', markersize=7)
axs[0][1].plot(Saturation_L, at_saturation_mi_loss_acc['loss_acc']['test_clean_acc'],
linestyle='-', c='C1', marker='x', markerfacecolor='none', markersize=7)
axs[0][1].plot(Saturation_L, at_saturation_mi_loss_acc['loss_acc']['test_adv_acc'],
linestyle=':', c='C1', marker='x', markerfacecolor='none', markersize=7)
# ------------- Patch AT Loss and Accuracy Detail -------------------------
axs[0][2].set_xlabel('Patch level')
axs[0][2].set_ylabel('Loss')
# axs[0][2].set_title('Adversarial training')
# axs[0][0].plot(Epochs, st_saturation_mi_loss_acc['train_loss'], label='train_loss')
axs[0][2].plot(Patch_L, st_patch_mi_loss_acc['loss_acc']['test_clean_loss'],
linestyle='-', c='C0', marker='s', markerfacecolor='none', markersize=7,
label='ST clean test')
axs[0][2].plot(Patch_L, st_patch_mi_loss_acc['loss_acc']['test_adv_loss'],
linestyle=':', c='C0', marker='s', markerfacecolor='none', markersize=7,
label='ST adv test')
axs[0][2].plot(Patch_L, at_patch_mi_loss_acc['loss_acc']['test_clean_loss'],
linestyle='-', c='C1', marker='s', markerfacecolor='none', markersize=7,
label='AT clean test')
axs[0][2].plot(Patch_L, at_patch_mi_loss_acc['loss_acc']['test_adv_loss'],
linestyle=':', c='C1', marker='s', markerfacecolor='none', markersize=7,
label='AT adv test')
axs[0][2].legend()
# -------------------
axs[0][3].set_xlabel('Patch level')
axs[0][3].set_ylabel('Accuracy (%)')
# axs[0][3].set_title('Adversarial training')
# axs[0][1].plot(Epochs, analytic_data['train_acc'], label='train_acc')
axs[0][3].plot(Patch_L, st_patch_mi_loss_acc['loss_acc']['test_clean_acc'],
linestyle='-', c='C0', marker='s', markerfacecolor='none', markersize=7)
axs[0][3].plot(Patch_L, st_patch_mi_loss_acc['loss_acc']['test_adv_acc'],
linestyle=':', c='C0', marker='s', markerfacecolor='none', markersize=7)
axs[0][3].plot(Patch_L, at_patch_mi_loss_acc['loss_acc']['test_clean_acc'],
linestyle='-', c='C1', marker='s', markerfacecolor='none', markersize=7)
axs[0][3].plot(Patch_L, at_patch_mi_loss_acc['loss_acc']['test_adv_acc'],
linestyle=':', c='C1', marker='s', markerfacecolor='none', markersize=7)
# axs[0][1].legend()
# 初始化 xlabel, y_label
for i in range(nrows):
for j in range(ncols):
axs[i][j].grid(True)
# range(开始,结束,步长)
# 绘制每一轮次的信息曲线
def axs_plot(axs, std_I_TX, std_I_TY, adv_I_TX, adv_I_TY, levels, transform_type, MI_Type):
std_I_TX = np.array(std_I_TX)
std_I_TY = np.array(std_I_TY)
adv_I_TX = np.array(adv_I_TX)
adv_I_TY = np.array(adv_I_TY)
marker_style = 's' if transform_type == 'Patch' else 'x'
# 设定坐标范围
# i_tx_min = math.floor(min(np.min(std_I_TX), np.min(adv_I_TX))) - 0.1
# i_tx_max = math.ceil(max(np.max(std_I_TX), np.max(adv_I_TX))) + 0.1
#
# i_ty_min = math.floor(min(np.min(std_I_TY), np.min(adv_I_TY))) - 0.1
# i_ty_max = math.ceil(max(np.max(std_I_TY), np.max(adv_I_TY))) + 0.1
i_tx_min = min(np.min(std_I_TX), np.min(adv_I_TX)) - 0.1
i_tx_max = max(np.max(std_I_TX), np.max(adv_I_TX)) + 0.1
i_ty_min = min(np.min(std_I_TY), np.min(adv_I_TY)) - 0.1
i_ty_max = max(np.max(std_I_TY), np.max(adv_I_TY)) + 0.1
for idx, level_i in enumerate(levels):
# c = COLOR[idx]
c = sm.to_rgba(idx)
# layers = [i for i in range(1,len(I_TX)+1)]
std_I_TX_level_i, std_I_TY_level_i = std_I_TX[idx], std_I_TY[idx]
adv_I_TX_level_i, adv_I_TY_level_i = adv_I_TX[idx], adv_I_TY[idx]
# axs[0].set_title(MI_Type)
# axs[0].grid()
axs[0].set_xlabel('Layer index')
axs[0].set_ylabel(r'$I(T;X)$' + ' ' + '(bits)')
# axs[1].grid()
axs[1].set_xlabel('Layer index')
axs[1].set_ylabel(r'$I(T;Y)$' + ' ' + '(bits)')
# axs[1].legend(line_legends, ['st_saturation_std', 'st_saturation_adv'])
axs[0].plot(Layer_Name, std_I_TX_level_i,
linestyle='-', # 对抗样本还是普通样本
color=c, # level 水平
marker=marker_style, # 是 saturation 还是 Patch
markerfacecolor='none',
linewidth=1,
label='%s %s(%s)' % ('std', transform_type, level_i)
)
axs[0].plot(Layer_Name, adv_I_TX_level_i,
linestyle=':',
color=c, marker=marker_style, markerfacecolor='none',
linewidth=1,
label='%s %s(%s)' % ('adv', transform_type, level_i)
)
# 设定 x 轴坐标范围
# axs[0].set_ylim((i_tx_min, i_tx_max))
# axs[1].set_ylim((i_tx_min, i_tx_max))
axs[1].plot(Layer_Name, std_I_TY_level_i,
color=c, marker=marker_style,
linestyle='-', linewidth=1, markerfacecolor='none',
label='%s %s(%s)' % ('std', transform_type, level_i)
)
axs[1].plot(Layer_Name, adv_I_TY_level_i,
color=c, marker=marker_style, markerfacecolor='none',
linestyle=':', linewidth=1,
label='%s %s(%s)' % ('adv', transform_type, level_i)
)
# 设定 y 轴坐标范围
# axs[2].set_ylim((i_ty_min, i_ty_max))
# axs[3].set_ylim((i_ty_min, i_ty_max))
# axs[0].legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0.,prop={'size':8},ncol=2)
# axs[0].legend(bbox_to_anchor=(0, -1.5, 1, 1), loc='upper left', borderaxespad=0.,
# prop={'size': 8}, ncol=len(self.Saturation_L)*2)
# st_saturation_std/st_saturation_adv Upper
saturation_levels = [str(i) for i in self.Saturation_L]
patch_levels = [str(i) for i in self.Patch_Split_L]
# axs_plot(axs[1],
# st_saturation_std.epoch_MI_hM_X_upper, st_saturation_std.epoch_MI_hM_Y_upper,
# st_saturation_adv.epoch_MI_hM_X_upper, st_saturation_adv.epoch_MI_hM_Y_upper,
# saturation_levels, transform_type='Saturation', MI_Type='upper'
# )
#
# axs_plot(axs[1],
# st_patch_std.epoch_MI_hM_X_upper, st_patch_std.epoch_MI_hM_Y_upper,
# st_patch_adv.epoch_MI_hM_X_upper, st_patch_adv.epoch_MI_hM_Y_upper,
# patch_levels, transform_type='Patch', MI_Type='upper'
# )
# st_saturation_std/st_saturation_adv Lower
axs[1][0].set_title('Standard training')
axs[1][1].set_title('Standard training')
axs_plot([axs[1][0], axs[1][1]],
st_saturation_std.epoch_MI_hM_X_lower, st_saturation_std.epoch_MI_hM_Y_lower,
st_saturation_adv.epoch_MI_hM_X_lower, st_saturation_adv.epoch_MI_hM_Y_lower,
saturation_levels, transform_type='Saturation', MI_Type='lower'
)
# # st_saturation_std/st_saturation_adv Bin
axs_plot([axs[1][0], axs[1][1]],
st_patch_std.epoch_MI_hM_X_lower, st_patch_std.epoch_MI_hM_Y_lower,
st_patch_adv.epoch_MI_hM_X_lower, st_patch_adv.epoch_MI_hM_Y_lower,
patch_levels, transform_type='Patch', MI_Type='lower'
)
# axs[1][0].legend(ncol=1, prop={'size': 10}, loc='upper right', bbox_to_anchor=(-0.2, 1))
# axs[1][0].legend(ncol=2, prop={'size': 10})
# axs[1][0].legend(ncol=2,prop={'size': 10})
# st_saturation_std/st_saturation_adv Lower
axs[1][2].set_title('Adversarial training')
axs[1][3].set_title('Adversarial training')
axs_plot([axs[1][2], axs[1][3]],
at_saturation_std.epoch_MI_hM_X_lower, at_saturation_std.epoch_MI_hM_Y_lower,
at_saturation_adv.epoch_MI_hM_X_lower, at_saturation_adv.epoch_MI_hM_Y_lower,
saturation_levels, transform_type='Saturation', MI_Type='lower'
)
# # st_saturation_std/st_saturation_adv Bin
axs_plot([axs[1][2], axs[1][3]],
at_patch_std.epoch_MI_hM_X_lower, at_patch_std.epoch_MI_hM_Y_lower,
at_patch_adv.epoch_MI_hM_X_lower, at_patch_adv.epoch_MI_hM_Y_lower,
patch_levels, transform_type='Patch', MI_Type='lower'
)
# axs[1][3].legend(ncol=2, loc='upper left', bbox_to_anchor=(1, 1))
# axs[1][3].legend(ncol=1, prop={'size': 10})
line_legends = [Line2D([0], [0], linestyle='-', c='C0', marker='x', markerfacecolor='none'),
Line2D([0], [0], linestyle=':', c='C0', marker='x', markerfacecolor='none'),
Line2D([0], [0], linestyle='-', c='C0', marker='s', markerfacecolor='none'),
Line2D([0], [0], linestyle=':', c='C0', marker='s', markerfacecolor='none')
]
axs[1][0].legend(line_legends, ['Saturation clean', 'Saturation adv', 'Patch clean', 'Patch adv'])
ticks_2_labels = ['Saturation 2 (Patch 0)', 'Saturation 8 (Patch 2)', 'Saturation 16 (Patch 4)',
'Saturation 64 (Patch 8)', 'Saturation 1024']
import matplotlib
fmt = matplotlib.ticker.FuncFormatter(lambda x, pos: ticks_2_labels[pos]) # print(x,pos)
fig.colorbar(sm, ax=axs[1][3], ticks=[i for i in range(Level_Num_Max)], format=fmt)
# orientation='horizontal'
# fig.suptitle(title)
# fig.colorbar(sm, ax=axs, label='Epoch')
# if Enable_Show:
# plt.show()
fig.savefig('mi_plane_transformation_%s.pdf' % (Model_Name.lower()))
print("Work has done!")
def plot_mi_curve_diff_saturation_and_patch_style_2(self):
# TODO: 把不同模型的在 分块,饱和度实验下的结果一起展示。
from pylab import mpl
mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
# mpl.rcParams['savefig.dpi'] = 400 # 保存图片分辨率
mpl.rcParams['figure.constrained_layout.use'] = True
plt.rcParams['xtick.direction'] = 'in' # 将x周的刻度线方向设置向内
plt.rcParams['ytick.direction'] = 'in' # 将y轴的刻度方向设置向内
from matplotlib.lines import Line2D
Is_Adv_Training = 'Std_Train'
Model_Name = self.Model_Name
Transform_Type = 'Saturation'
with open('./Checkpoint/%s/%s/mi_loss_acc_%s.pkl' % (Model_Name, Transform_Type, Is_Adv_Training), 'rb') as f:
st_saturation_mi_loss_acc = pickle.load(f)
Transform_Type = 'Patch'
with open('./Checkpoint/%s/%s/mi_loss_acc_%s.pkl' % (Model_Name, Transform_Type, Is_Adv_Training), 'rb') as f:
st_patch_mi_loss_acc = pickle.load(f)
Is_Adv_Training = 'Adv_Train'
Model_Name = self.Model_Name
Transform_Type = 'Saturation'
with open('./Checkpoint/%s/%s/mi_loss_acc_%s.pkl' % (Model_Name, Transform_Type, Is_Adv_Training), 'rb') as f:
at_saturation_mi_loss_acc = pickle.load(f)
Transform_Type = 'Patch'
with open('./Checkpoint/%s/%s/mi_loss_acc_%s.pkl' % (Model_Name, Transform_Type, Is_Adv_Training), 'rb') as f:
at_patch_mi_loss_acc = pickle.load(f)
Forward_Size, Forward_Repeat = st_saturation_mi_loss_acc['Forward_Size'], \
st_saturation_mi_loss_acc['Forward_Repeat']
st_saturation_std, st_saturation_adv = st_saturation_mi_loss_acc['std_estimator'], \
st_saturation_mi_loss_acc['adv_estimator']
st_patch_std, st_patch_adv = st_patch_mi_loss_acc['std_estimator'], \
st_patch_mi_loss_acc['adv_estimator']
at_saturation_std, at_saturation_adv = at_saturation_mi_loss_acc['std_estimator'], \
at_saturation_mi_loss_acc['adv_estimator']
at_patch_std, at_patch_adv = at_patch_mi_loss_acc['std_estimator'], \
at_patch_mi_loss_acc['adv_estimator']
# Model_Name = basic_info['Model']
Level_Num_Max = max(len(st_saturation_std.epoch_MI_hM_X_upper), len(st_patch_std.epoch_MI_hM_X_upper))
print('Level_Num_Max', Level_Num_Max)
Layer_Num = len(st_saturation_std.epoch_MI_hM_X_upper[0])
Layer_Name = [str(i + 1) for i in range(Layer_Num)]
Saturation_L = [str(i) for i in self.Saturation_L]
Patch_L = [str(i) for i in self.Patch_Split_L]
# sm = plt.cm.ScalarMappable(cmap='Blues', norm=plt.Normalize(vmin=0, vmax=Std_Epoch_Num))
# bins = [i for i in range(Level_Num_Max)]
# nbin = len(bins) - 1
# import matplotlib as mpl
# cmap = mpl.cm.get_cmap('viridis', nbin)
# bd_norm = mpl.colors.BoundaryNorm(bins, nbin)
# sm = mpl.cm.ScalarMappable(norm=bd_norm, cmap=cmap)
# Level_Num_Max = 5 则数据应该在 -0.5 ~ +4.5之间
sm = plt.cm.ScalarMappable(cmap='Reds', norm=plt.Normalize(vmin=-0.5, vmax=Level_Num_Max - 0.5))
title = "%s,Upper/Lower/Bin,Clean(Adv),Sample_N(%d),Std/Adv train" % (
Model_Name, Forward_Repeat * Forward_Size,
)
COLOR = ['C0', 'C1', 'C2', 'C3', 'C4', 'C5',
'C6', 'C7', 'C8', 'C9', 'olive', 'peach', ]
# fig size, 先列后行
nrows = 2
ncols = 4
# px = 1 / plt.rcParams['figure.dpi'] # pixel in inches
px = 1
plt.show()
Fig_Size = (5, 11)
fig, axs = plt.subplots(nrows, ncols, figsize=(Fig_Size[1] * px, Fig_Size[0] * px), )
# -------------Saturation (Standard Training) ST Loss and Accuracy Detail -------------------------
axs[0][0].set_xlabel('Saturation level')
axs[0][0].set_ylabel('Loss')
# axs[0][0].plot(Epochs, st_saturation_mi_loss_acc['train_loss'], label='train_loss')
# 颜色表示是ST还是AT, 实线和虚线表示正常样本还是对抗样本, marker 表示是 Saturation 还是 Patch
axs[0][0].plot(Saturation_L, st_saturation_mi_loss_acc['loss_acc']['test_clean_loss'],
linestyle='-', c='C0', marker='x', markerfacecolor='none',
label='ST clean test')
axs[0][0].plot(Saturation_L, st_saturation_mi_loss_acc['loss_acc']['test_adv_loss'],
linestyle=':', c='C0', marker='x', markerfacecolor='none',
label='ST adv test')
axs[0][0].plot(Saturation_L, at_saturation_mi_loss_acc['loss_acc']['test_clean_loss'],
linestyle='-', c='C1', marker='x', markerfacecolor='none',
label='AT clean test')
axs[0][0].plot(Saturation_L, at_saturation_mi_loss_acc['loss_acc']['test_adv_loss'],
linestyle=':', c='C1', marker='x', markerfacecolor='none',
label='AT adv test')
axs[0][0].legend()
axs[0][1].set_xlabel('Saturation level')
axs[0][1].set_ylabel('Accuracy (%)')
# axs[0][1].set_title('Standard training')
# axs[0][1].plot(Epochs, analytic_data['train_acc'], label='train_acc')
axs[0][1].plot(Saturation_L, st_saturation_mi_loss_acc['loss_acc']['test_clean_acc'],
linestyle='-', c='C0', marker='x', markerfacecolor='none', markersize=7)
axs[0][1].plot(Saturation_L, st_saturation_mi_loss_acc['loss_acc']['test_adv_acc'],
linestyle=':', c='C0', marker='x', markerfacecolor='none', markersize=7)
axs[0][1].plot(Saturation_L, at_saturation_mi_loss_acc['loss_acc']['test_clean_acc'],
linestyle='-', c='C1', marker='x', markerfacecolor='none', markersize=7)
axs[0][1].plot(Saturation_L, at_saturation_mi_loss_acc['loss_acc']['test_adv_acc'],
linestyle=':', c='C1', marker='x', markerfacecolor='none', markersize=7)
# ------------- Patch AT Loss and Accuracy Detail -------------------------
axs[0][2].set_xlabel('Patch level')
axs[0][2].set_ylabel('Loss')
# axs[0][2].set_title('Adversarial training')
# axs[0][0].plot(Epochs, st_saturation_mi_loss_acc['train_loss'], label='train_loss')
axs[0][2].plot(Patch_L, st_patch_mi_loss_acc['loss_acc']['test_clean_loss'],
linestyle='-', c='C0', marker='s', markerfacecolor='none', markersize=7,
label='ST clean test')
axs[0][2].plot(Patch_L, st_patch_mi_loss_acc['loss_acc']['test_adv_loss'],
linestyle=':', c='C0', marker='s', markerfacecolor='none', markersize=7,
label='ST adv test')
axs[0][2].plot(Patch_L, at_patch_mi_loss_acc['loss_acc']['test_clean_loss'],
linestyle='-', c='C1', marker='s', markerfacecolor='none', markersize=7,