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_similarity_detector.py 6.1 kB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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 Model
  19. from mindspore import context
  20. from mindspore import Tensor
  21. from mindspore.nn import Cell
  22. from mindspore.ops.operations import TensorAdd
  23. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  24. from mindarmour.utils.logger import LogUtil
  25. from mindarmour.attacks.black.pso_attack import PSOAttack
  26. from mindarmour.attacks.black.black_model import BlackModel
  27. from mindarmour.detectors.black.similarity_detector import SimilarityDetector
  28. from lenet5_net import LeNet5
  29. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
  30. sys.path.append("..")
  31. from data_processing import generate_mnist_dataset
  32. LOGGER = LogUtil.get_instance()
  33. TAG = 'Similarity Detector test'
  34. class ModelToBeAttacked(BlackModel):
  35. """
  36. model to be attack
  37. """
  38. def __init__(self, network):
  39. super(ModelToBeAttacked, self).__init__()
  40. self._network = network
  41. self._queries = []
  42. def predict(self, inputs):
  43. """
  44. predict function
  45. """
  46. query_num = inputs.shape[0]
  47. for i in range(query_num):
  48. self._queries.append(inputs[i].astype(np.float32))
  49. result = self._network(Tensor(inputs.astype(np.float32)))
  50. return result.asnumpy()
  51. def get_queries(self):
  52. return self._queries
  53. class EncoderNet(Cell):
  54. """
  55. Similarity encoder for input data
  56. """
  57. def __init__(self, encode_dim):
  58. super(EncoderNet, self).__init__()
  59. self._encode_dim = encode_dim
  60. self.add = TensorAdd()
  61. def construct(self, inputs):
  62. """
  63. construct the neural network
  64. Args:
  65. inputs (Tensor): input data to neural network.
  66. Returns:
  67. Tensor, output of neural network.
  68. """
  69. return self.add(inputs, inputs)
  70. def get_encode_dim(self):
  71. """
  72. Get the dimension of encoded inputs
  73. Returns:
  74. int, dimension of encoded inputs.
  75. """
  76. return self._encode_dim
  77. @pytest.mark.level1
  78. @pytest.mark.platform_arm_ascend_training
  79. @pytest.mark.platform_x86_ascend_training
  80. @pytest.mark.env_card
  81. @pytest.mark.component_mindarmour
  82. def test_similarity_detector():
  83. """
  84. Similarity Detector test.
  85. """
  86. # load trained network
  87. ckpt_name = './trained_ckpt_file/checkpoint_lenet-10_1875.ckpt'
  88. net = LeNet5()
  89. load_dict = load_checkpoint(ckpt_name)
  90. load_param_into_net(net, load_dict)
  91. # get mnist data
  92. data_list = "./MNIST_unzip/test"
  93. batch_size = 1000
  94. ds = generate_mnist_dataset(data_list, batch_size=batch_size)
  95. model = ModelToBeAttacked(net)
  96. batch_num = 10 # the number of batches of input samples
  97. all_images = []
  98. true_labels = []
  99. predict_labels = []
  100. i = 0
  101. for data in ds.create_tuple_iterator():
  102. i += 1
  103. images = data[0].astype(np.float32)
  104. labels = data[1]
  105. all_images.append(images)
  106. true_labels.append(labels)
  107. pred_labels = np.argmax(model.predict(images), axis=1)
  108. predict_labels.append(pred_labels)
  109. if i >= batch_num:
  110. break
  111. all_images = np.concatenate(all_images)
  112. true_labels = np.concatenate(true_labels)
  113. predict_labels = np.concatenate(predict_labels)
  114. accuracy = np.mean(np.equal(predict_labels, true_labels))
  115. LOGGER.info(TAG, "prediction accuracy before attacking is : %s", accuracy)
  116. train_images = all_images[0:6000, :, :, :]
  117. attacked_images = all_images[0:10, :, :, :]
  118. attacked_labels = true_labels[0:10]
  119. # generate malicious query sequence of black attack
  120. attack = PSOAttack(model, bounds=(0.0, 1.0), pm=0.5, sparse=True,
  121. t_max=1000)
  122. success_list, adv_data, query_list = attack.generate(attacked_images,
  123. attacked_labels)
  124. LOGGER.info(TAG, 'pso attack success_list: %s', success_list)
  125. LOGGER.info(TAG, 'average of query counts is : %s', np.mean(query_list))
  126. pred_logits_adv = model.predict(adv_data)
  127. # rescale predict confidences into (0, 1).
  128. pred_logits_adv = softmax(pred_logits_adv, axis=1)
  129. pred_lables_adv = np.argmax(pred_logits_adv, axis=1)
  130. accuracy_adv = np.mean(np.equal(pred_lables_adv, attacked_labels))
  131. LOGGER.info(TAG, "prediction accuracy after attacking is : %g",
  132. accuracy_adv)
  133. benign_queries = all_images[6000:10000, :, :, :]
  134. suspicious_queries = model.get_queries()
  135. # explicit threshold not provided, calculate threshold for K
  136. encoder = Model(EncoderNet(encode_dim=256))
  137. detector = SimilarityDetector(max_k_neighbor=50, trans_model=encoder)
  138. detector.fit(inputs=train_images)
  139. # test benign queries
  140. detector.detect(benign_queries)
  141. fpr = len(detector.get_detected_queries()) / benign_queries.shape[0]
  142. LOGGER.info(TAG, 'Number of false positive of attack detector is : %s',
  143. len(detector.get_detected_queries()))
  144. LOGGER.info(TAG, 'False positive rate of attack detector is : %s', fpr)
  145. # test attack queries
  146. detector.clear_buffer()
  147. detector.detect(suspicious_queries)
  148. LOGGER.info(TAG, 'Number of detected attack queries is : %s',
  149. len(detector.get_detected_queries()))
  150. LOGGER.info(TAG, 'The detected attack query indexes are : %s',
  151. detector.get_detected_queries())
  152. if __name__ == '__main__':
  153. test_similarity_detector()

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