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_hsja.py 4.9 kB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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 numpy as np
  16. import pytest
  17. from mindspore import Tensor
  18. from mindspore import context
  19. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  20. from mindarmour.attacks.black.hop_skip_jump_attack import HopSkipJumpAttack
  21. from mindarmour.attacks.black.black_model import BlackModel
  22. from mindarmour.utils.logger import LogUtil
  23. from lenet5_net import LeNet5
  24. sys.path.append("..")
  25. from data_processing import generate_mnist_dataset
  26. context.set_context(mode=context.GRAPH_MODE)
  27. context.set_context(device_target="Ascend")
  28. LOGGER = LogUtil.get_instance()
  29. TAG = 'HopSkipJumpAttack'
  30. class ModelToBeAttacked(BlackModel):
  31. """model to be attack"""
  32. def __init__(self, network):
  33. super(ModelToBeAttacked, self).__init__()
  34. self._network = network
  35. def predict(self, inputs):
  36. """predict"""
  37. if len(inputs.shape) == 3:
  38. inputs = inputs[np.newaxis, :]
  39. result = self._network(Tensor(inputs.astype(np.float32)))
  40. return result.asnumpy()
  41. def random_target_labels(true_labels):
  42. target_labels = []
  43. for label in true_labels:
  44. while True:
  45. target_label = np.random.randint(0, 10)
  46. if target_label != label:
  47. target_labels.append(target_label)
  48. break
  49. return target_labels
  50. def create_target_images(dataset, data_labels, target_labels):
  51. res = []
  52. for label in target_labels:
  53. for i in range(len(data_labels)):
  54. if data_labels[i] == label:
  55. res.append(dataset[i])
  56. break
  57. return np.array(res)
  58. @pytest.mark.level1
  59. @pytest.mark.platform_arm_ascend_training
  60. @pytest.mark.platform_x86_ascend_training
  61. @pytest.mark.env_card
  62. @pytest.mark.component_mindarmour
  63. def test_hsja_mnist_attack():
  64. """
  65. hsja-Attack test
  66. """
  67. # upload trained network
  68. ckpt_name = './trained_ckpt_file/checkpoint_lenet-10_1875.ckpt'
  69. net = LeNet5()
  70. load_dict = load_checkpoint(ckpt_name)
  71. load_param_into_net(net, load_dict)
  72. net.set_train(False)
  73. # get test data
  74. data_list = "./MNIST_unzip/test"
  75. batch_size = 32
  76. ds = generate_mnist_dataset(data_list, batch_size=batch_size)
  77. # prediction accuracy before attack
  78. model = ModelToBeAttacked(net)
  79. batch_num = 5 # the number of batches of attacking samples
  80. test_images = []
  81. test_labels = []
  82. predict_labels = []
  83. i = 0
  84. for data in ds.create_tuple_iterator():
  85. i += 1
  86. images = data[0].astype(np.float32)
  87. labels = data[1]
  88. test_images.append(images)
  89. test_labels.append(labels)
  90. pred_labels = np.argmax(model.predict(images), axis=1)
  91. predict_labels.append(pred_labels)
  92. if i >= batch_num:
  93. break
  94. predict_labels = np.concatenate(predict_labels)
  95. true_labels = np.concatenate(test_labels)
  96. accuracy = np.mean(np.equal(predict_labels, true_labels))
  97. LOGGER.info(TAG, "prediction accuracy before attacking is : %s",
  98. accuracy)
  99. test_images = np.concatenate(test_images)
  100. # attacking
  101. norm = 'l2'
  102. search = 'grid_search'
  103. target = False
  104. attack = HopSkipJumpAttack(model, constraint=norm, stepsize_search=search)
  105. if target:
  106. target_labels = random_target_labels(true_labels)
  107. target_images = create_target_images(test_images, predict_labels,
  108. target_labels)
  109. attack.set_target_images(target_images)
  110. success_list, adv_data, query_list = attack.generate(test_images, target_labels)
  111. else:
  112. success_list, adv_data, query_list = attack.generate(test_images, None)
  113. adv_datas = []
  114. gts = []
  115. for success, adv, gt in zip(success_list, adv_data, true_labels):
  116. if success:
  117. adv_datas.append(adv)
  118. gts.append(gt)
  119. if len(gts) > 0:
  120. adv_datas = np.concatenate(np.asarray(adv_datas), axis=0)
  121. gts = np.asarray(gts)
  122. pred_logits_adv = model.predict(adv_datas)
  123. pred_lables_adv = np.argmax(pred_logits_adv, axis=1)
  124. accuracy_adv = np.mean(np.equal(pred_lables_adv, gts))
  125. LOGGER.info(TAG, 'mis-classification rate of adversaries is : %s',
  126. accuracy_adv)
  127. if __name__ == '__main__':
  128. test_hsja_mnist_attack()

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