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.4 kB

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

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