You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

lenet5_mnist_fuzzing.py 5.9 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. # Copyright 2019 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import numpy as np
  15. from mindspore import Model
  16. from mindspore import context
  17. from mindspore import load_checkpoint, load_param_into_net
  18. from mindarmour.fuzz_testing import Fuzzer
  19. from mindarmour.fuzz_testing import KMultisectionNeuronCoverage
  20. from mindarmour.utils import LogUtil
  21. from examples.common.dataset.data_processing import generate_mnist_dataset
  22. from examples.common.networks.lenet5.lenet5_net_for_fuzzing import LeNet5
  23. LOGGER = LogUtil.get_instance()
  24. TAG = 'Fuzz_test'
  25. LOGGER.set_level('INFO')
  26. def test_lenet_mnist_fuzzing():
  27. # upload trained network
  28. ckpt_path = '../common/networks/lenet5/trained_ckpt_file/checkpoint_lenet-10_1875.ckpt'
  29. net = LeNet5()
  30. load_dict = load_checkpoint(ckpt_path)
  31. load_param_into_net(net, load_dict)
  32. model = Model(net)
  33. mutate_config = [
  34. {'method': 'GaussianBlur',
  35. 'params': {'ksize': [1, 2, 3, 5],
  36. 'auto_param': [True, False]}},
  37. {'method': 'MotionBlur',
  38. 'params': {'degree': [1, 2, 5], 'angle': [45, 10, 100, 140, 210, 270, 300], 'auto_param': [True]}},
  39. {'method': 'GradientBlur',
  40. 'params': {'point': [[10, 10]], 'auto_param': [True]}},
  41. {'method': 'UniformNoise',
  42. 'params': {'factor': [0.1, 0.2, 0.3], 'auto_param': [False, True]}},
  43. {'method': 'GaussianNoise',
  44. 'params': {'factor': [0.1, 0.2, 0.3], 'auto_param': [False, True]}},
  45. {'method': 'SaltAndPepperNoise',
  46. 'params': {'factor': [0.1, 0.2, 0.3], 'auto_param': [False, True]}},
  47. {'method': 'NaturalNoise',
  48. 'params': {'ratio': [0.1, 0.2, 0.3], 'k_x_range': [(1, 3), (1, 5)], 'k_y_range': [(1, 5)],
  49. 'auto_param': [False, True]}},
  50. {'method': 'Contrast',
  51. 'params': {'alpha': [0.5, 1, 1.5], 'beta': [-10, 0, 10], 'auto_param': [False, True]}},
  52. {'method': 'GradientLuminance',
  53. 'params': {'color_start': [(0, 0, 0)], 'color_end': [(255, 255, 255)], 'start_point': [(10, 10)],
  54. 'scope': [0.5], 'pattern': ['light'], 'bright_rate': [0.3], 'mode': ['circle'],
  55. 'auto_param': [False, True]}},
  56. {'method': 'Translate',
  57. 'params': {'x_bias': [0, 0.05, -0.05], 'y_bias': [0, -0.05, 0.05], 'auto_param': [False, True]}},
  58. {'method': 'Scale',
  59. 'params': {'factor_x': [1, 0.9], 'factor_y': [1, 0.9], 'auto_param': [False, True]}},
  60. {'method': 'Shear',
  61. 'params': {'factor': [0.2, 0.1], 'direction': ['horizontal', 'vertical'], 'auto_param': [False, True]}},
  62. {'method': 'Rotate',
  63. 'params': {'angle': [20, 90], 'auto_param': [False, True]}},
  64. {'method': 'Perspective',
  65. 'params': {'ori_pos': [[[0, 0], [0, 800], [800, 0], [800, 800]]],
  66. 'dst_pos': [[[50, 0], [0, 800], [780, 0], [800, 800]]], 'auto_param': [False, True]}},
  67. {'method': 'Curve',
  68. 'params': {'curves': [5], 'depth': [2], 'mode': ['vertical'], 'auto_param': [False, True]}},
  69. {'method': 'FGSM',
  70. 'params': {'eps': [0.3, 0.2, 0.4], 'alpha': [0.1], 'bounds': [(0, 1)]}},
  71. {'method': 'PGD',
  72. 'params': {'eps': [0.1, 0.2, 0.4], 'eps_iter': [0.05, 0.1], 'nb_iter': [1, 3]}},
  73. {'method': 'MDIIM',
  74. 'params': {'eps': [0.1, 0.2, 0.4], 'prob': [0.5, 0.1],
  75. 'norm_level': [1, 2, '1', '2', 'l1', 'l2', 'inf', 'np.inf', 'linf']}}
  76. ]
  77. # get training data
  78. data_list = "../common/dataset/MNIST/train"
  79. batch_size = 32
  80. ds = generate_mnist_dataset(data_list, batch_size, sparse=False)
  81. train_images = []
  82. for data in ds.create_tuple_iterator(output_numpy=True):
  83. images = data[0].astype(np.float32)
  84. train_images.append(images)
  85. train_images = np.concatenate(train_images, axis=0)
  86. # fuzz test with original test data
  87. # get test data
  88. data_list = "../common/dataset/MNIST/test"
  89. batch_size = 32
  90. ds = generate_mnist_dataset(data_list, batch_size, sparse=False)
  91. test_images = []
  92. test_labels = []
  93. for data in ds.create_tuple_iterator(output_numpy=True):
  94. images = data[0].astype(np.float32)
  95. labels = data[1]
  96. test_images.append(images)
  97. test_labels.append(labels)
  98. test_images = np.concatenate(test_images, axis=0)
  99. test_labels = np.concatenate(test_labels, axis=0)
  100. initial_seeds = []
  101. # make initial seeds
  102. for img, label in zip(test_images, test_labels):
  103. initial_seeds.append([img, label])
  104. coverage = KMultisectionNeuronCoverage(model, train_images, segmented_num=100, incremental=True)
  105. kmnc = coverage.get_metrics(test_images[:100])
  106. print('KMNC of initial seeds is: ', kmnc)
  107. initial_seeds = initial_seeds[:100]
  108. model_fuzz_test = Fuzzer(model)
  109. _, _, _, _, metrics = model_fuzz_test.fuzzing(mutate_config,
  110. initial_seeds, coverage,
  111. evaluate=True,
  112. max_iters=10,
  113. mutate_num_per_seed=20)
  114. if metrics:
  115. for key in metrics:
  116. print(key + ': ', metrics[key])
  117. if __name__ == '__main__':
  118. # device_target can be "CPU"GPU, "" or "Ascend"
  119. context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
  120. test_lenet_mnist_fuzzing()

MindArmour关注AI的安全和隐私问题。致力于增强模型的安全可信、保护用户的数据隐私。主要包含3个模块:对抗样本鲁棒性模块、Fuzz Testing模块、隐私保护与评估模块。 对抗样本鲁棒性模块 对抗样本鲁棒性模块用于评估模型对于对抗样本的鲁棒性,并提供模型增强方法用于增强模型抗对抗样本攻击的能力,提升模型鲁棒性。对抗样本鲁棒性模块包含了4个子模块:对抗样本的生成、对抗样本的检测、模型防御、攻防评估。