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_pointwise.py 5.2 kB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  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 scipy.special import softmax
  18. from mindspore import Tensor
  19. from mindspore import context
  20. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  21. from mindarmour.attacks.black.pointwise_attack import PointWiseAttack
  22. from mindarmour.attacks.black.black_model import BlackModel
  23. from mindarmour.utils.logger import LogUtil
  24. from mindarmour.evaluations.attack_evaluation import AttackEvaluate
  25. from lenet5_net import LeNet5
  26. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
  27. sys.path.append("..")
  28. from data_processing import generate_mnist_dataset
  29. LOGGER = LogUtil.get_instance()
  30. TAG = 'Pointwise_Attack'
  31. LOGGER.set_level('INFO')
  32. class ModelToBeAttacked(BlackModel):
  33. """model to be attack"""
  34. def __init__(self, network):
  35. super(ModelToBeAttacked, self).__init__()
  36. self._network = network
  37. def predict(self, inputs):
  38. """predict"""
  39. if len(inputs.shape) == 3:
  40. inputs = inputs[np.newaxis, :]
  41. result = self._network(Tensor(inputs.astype(np.float32)))
  42. return result.asnumpy()
  43. @pytest.mark.level1
  44. @pytest.mark.platform_arm_ascend_training
  45. @pytest.mark.platform_x86_ascend_training
  46. @pytest.mark.env_card
  47. @pytest.mark.component_mindarmour
  48. def test_pointwise_attack_on_mnist():
  49. """
  50. Salt-and-Pepper-Attack test
  51. """
  52. # upload trained network
  53. ckpt_name = './trained_ckpt_file/checkpoint_lenet-10_1875.ckpt'
  54. net = LeNet5()
  55. load_dict = load_checkpoint(ckpt_name)
  56. load_param_into_net(net, load_dict)
  57. # get test data
  58. data_list = "./MNIST_unzip/test"
  59. batch_size = 32
  60. ds = generate_mnist_dataset(data_list, batch_size=batch_size)
  61. # prediction accuracy before attack
  62. model = ModelToBeAttacked(net)
  63. batch_num = 3 # the number of batches of attacking samples
  64. test_images = []
  65. test_labels = []
  66. predict_labels = []
  67. i = 0
  68. for data in ds.create_tuple_iterator():
  69. i += 1
  70. images = data[0].astype(np.float32)
  71. labels = data[1]
  72. test_images.append(images)
  73. test_labels.append(labels)
  74. pred_labels = np.argmax(model.predict(images), axis=1)
  75. predict_labels.append(pred_labels)
  76. if i >= batch_num:
  77. break
  78. predict_labels = np.concatenate(predict_labels)
  79. true_labels = np.concatenate(test_labels)
  80. accuracy = np.mean(np.equal(predict_labels, true_labels))
  81. LOGGER.info(TAG, "prediction accuracy before attacking is : %g", accuracy)
  82. # attacking
  83. is_target = False
  84. attack = PointWiseAttack(model=model, is_targeted=is_target)
  85. if is_target:
  86. targeted_labels = np.random.randint(0, 10, size=len(true_labels))
  87. for i in range(len(true_labels)):
  88. if targeted_labels[i] == true_labels[i]:
  89. targeted_labels[i] = (targeted_labels[i] + 1) % 10
  90. else:
  91. targeted_labels = true_labels
  92. success_list, adv_data, query_list = attack.generate(
  93. np.concatenate(test_images), targeted_labels)
  94. success_list = np.arange(success_list.shape[0])[success_list]
  95. LOGGER.info(TAG, 'success_list: %s', success_list)
  96. LOGGER.info(TAG, 'average of query times is : %s', np.mean(query_list))
  97. adv_preds = []
  98. for ite_data in adv_data:
  99. pred_logits_adv = model.predict(ite_data)
  100. # rescale predict confidences into (0, 1).
  101. pred_logits_adv = softmax(pred_logits_adv, axis=1)
  102. adv_preds.extend(pred_logits_adv)
  103. accuracy_adv = np.mean(np.equal(np.max(adv_preds, axis=1), true_labels))
  104. LOGGER.info(TAG, "prediction accuracy after attacking is : %g",
  105. accuracy_adv)
  106. test_labels_onehot = np.eye(10)[true_labels]
  107. attack_evaluate = AttackEvaluate(np.concatenate(test_images),
  108. test_labels_onehot, adv_data,
  109. adv_preds, targeted=is_target,
  110. target_label=targeted_labels)
  111. LOGGER.info(TAG, 'mis-classification rate of adversaries is : %s',
  112. attack_evaluate.mis_classification_rate())
  113. LOGGER.info(TAG, 'The average confidence of adversarial class is : %s',
  114. attack_evaluate.avg_conf_adv_class())
  115. LOGGER.info(TAG, 'The average confidence of true class is : %s',
  116. attack_evaluate.avg_conf_true_class())
  117. LOGGER.info(TAG, 'The average distance (l0, l2, linf) between original '
  118. 'samples and adversarial samples are: %s',
  119. attack_evaluate.avg_lp_distance())
  120. if __name__ == '__main__':
  121. test_pointwise_attack_on_mnist()

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