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.

mnist_attack_mdi2fgsm.py 4.7 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  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 sys
  15. import time
  16. import numpy as np
  17. from mindspore import Model
  18. from mindspore import Tensor
  19. from mindspore import context
  20. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  21. from mindspore.nn import SoftmaxCrossEntropyWithLogits
  22. from scipy.special import softmax
  23. from lenet5_net import LeNet5
  24. from mindarmour.adv_robustness.attacks import MomentumDiverseInputIterativeMethod
  25. from mindarmour.adv_robustness.evaluations import AttackEvaluate
  26. from mindarmour.utils.logger import LogUtil
  27. sys.path.append("..")
  28. from data_processing import generate_mnist_dataset
  29. LOGGER = LogUtil.get_instance()
  30. TAG = 'M_DI2_FGSM_Test'
  31. LOGGER.set_level('INFO')
  32. def test_momentum_diverse_input_iterative_method():
  33. """
  34. M-DI2-FGSM Attack Test for CPU device.
  35. """
  36. context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
  37. # upload trained network
  38. ckpt_name = './trained_ckpt_file/checkpoint_lenet-10_1875.ckpt'
  39. net = LeNet5()
  40. load_dict = load_checkpoint(ckpt_name)
  41. load_param_into_net(net, load_dict)
  42. # get test data
  43. data_list = "./MNIST_unzip/test"
  44. batch_size = 32
  45. ds = generate_mnist_dataset(data_list, batch_size)
  46. # prediction accuracy before attack
  47. model = Model(net)
  48. batch_num = 32 # the number of batches of attacking samples
  49. test_images = []
  50. test_labels = []
  51. predict_labels = []
  52. i = 0
  53. for data in ds.create_tuple_iterator():
  54. i += 1
  55. images = data[0].astype(np.float32)
  56. labels = data[1]
  57. test_images.append(images)
  58. test_labels.append(labels)
  59. pred_labels = np.argmax(model.predict(Tensor(images)).asnumpy(),
  60. axis=1)
  61. predict_labels.append(pred_labels)
  62. if i >= batch_num:
  63. break
  64. predict_labels = np.concatenate(predict_labels)
  65. true_labels = np.concatenate(test_labels)
  66. accuracy = np.mean(np.equal(predict_labels, true_labels))
  67. LOGGER.info(TAG, "prediction accuracy before attacking is : %s", accuracy)
  68. # attacking
  69. loss = SoftmaxCrossEntropyWithLogits(sparse=True)
  70. attack = MomentumDiverseInputIterativeMethod(net, loss_fn=loss)
  71. start_time = time.clock()
  72. adv_data = attack.batch_generate(np.concatenate(test_images),
  73. true_labels, batch_size=32)
  74. stop_time = time.clock()
  75. pred_logits_adv = model.predict(Tensor(adv_data)).asnumpy()
  76. # rescale predict confidences into (0, 1).
  77. pred_logits_adv = softmax(pred_logits_adv, axis=1)
  78. pred_labels_adv = np.argmax(pred_logits_adv, axis=1)
  79. accuracy_adv = np.mean(np.equal(pred_labels_adv, true_labels))
  80. LOGGER.info(TAG, "prediction accuracy after attacking is : %s", accuracy_adv)
  81. attack_evaluate = AttackEvaluate(np.concatenate(test_images).transpose(0, 2, 3, 1),
  82. np.eye(10)[true_labels],
  83. adv_data.transpose(0, 2, 3, 1),
  84. pred_logits_adv)
  85. LOGGER.info(TAG, 'mis-classification rate of adversaries is : %s',
  86. attack_evaluate.mis_classification_rate())
  87. LOGGER.info(TAG, 'The average confidence of adversarial class is : %s',
  88. attack_evaluate.avg_conf_adv_class())
  89. LOGGER.info(TAG, 'The average confidence of true class is : %s',
  90. attack_evaluate.avg_conf_true_class())
  91. LOGGER.info(TAG, 'The average distance (l0, l2, linf) between original '
  92. 'samples and adversarial samples are: %s',
  93. attack_evaluate.avg_lp_distance())
  94. LOGGER.info(TAG, 'The average structural similarity between original '
  95. 'samples and adversarial samples are: %s',
  96. attack_evaluate.avg_ssim())
  97. LOGGER.info(TAG, 'The average costing time is %s',
  98. (stop_time - start_time)/(batch_num*batch_size))
  99. if __name__ == '__main__':
  100. # device_target can be "CPU", "GPU" or "Ascend"
  101. context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
  102. test_momentum_diverse_input_iterative_method()

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