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_cw.py 4.6 kB

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

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