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_evaluation.py 14 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
5 years ago
4 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
5 years ago
5 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
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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. """evaluate example"""
  15. import os
  16. import time
  17. import numpy as np
  18. from mindspore import Model
  19. from mindspore import Tensor
  20. from mindspore import context
  21. from mindspore import nn
  22. from mindspore.nn import Cell
  23. from mindspore.nn import SoftmaxCrossEntropyWithLogits
  24. from mindspore.ops.operations import Add
  25. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  26. from scipy.special import softmax
  27. from mindarmour.adv_robustness.attacks import FastGradientSignMethod
  28. from mindarmour.adv_robustness.attacks import GeneticAttack
  29. from mindarmour.adv_robustness.attacks.black.black_model import BlackModel
  30. from mindarmour.adv_robustness.defenses import NaturalAdversarialDefense
  31. from mindarmour.adv_robustness.detectors import SimilarityDetector
  32. from mindarmour.adv_robustness.evaluations import BlackDefenseEvaluate
  33. from mindarmour.adv_robustness.evaluations import DefenseEvaluate
  34. from mindarmour.utils.logger import LogUtil
  35. from examples.common.dataset.data_processing import generate_mnist_dataset
  36. from examples.common.networks.lenet5.lenet5_net import LeNet5
  37. LOGGER = LogUtil.get_instance()
  38. LOGGER.set_level('INFO')
  39. TAG = 'Defense_Evaluate_Example'
  40. def get_detector(train_images):
  41. encoder = Model(EncoderNet(encode_dim=256))
  42. detector = SimilarityDetector(max_k_neighbor=50, trans_model=encoder)
  43. detector.fit(inputs=train_images)
  44. return detector
  45. class EncoderNet(Cell):
  46. """
  47. Similarity encoder for input data
  48. """
  49. def __init__(self, encode_dim):
  50. super(EncoderNet, self).__init__()
  51. self._encode_dim = encode_dim
  52. self.add = Add()
  53. def construct(self, inputs):
  54. """
  55. construct the neural network
  56. Args:
  57. inputs (Tensor): input data to neural network.
  58. Returns:
  59. Tensor, output of neural network.
  60. """
  61. return self.add(inputs, inputs)
  62. def get_encode_dim(self):
  63. """
  64. Get the dimension of encoded inputs
  65. Returns:
  66. int, dimension of encoded inputs.
  67. """
  68. return self._encode_dim
  69. class ModelToBeAttacked(BlackModel):
  70. """
  71. model to be attack
  72. """
  73. def __init__(self, network, defense=False, train_images=None):
  74. super(ModelToBeAttacked, self).__init__()
  75. self._network = network
  76. self._queries = []
  77. self._defense = defense
  78. self._detector = None
  79. self._detected_res = []
  80. if self._defense:
  81. self._detector = get_detector(train_images)
  82. def predict(self, inputs):
  83. """
  84. predict function
  85. """
  86. if len(inputs.shape) == 3:
  87. inputs = np.expand_dims(inputs, axis=0)
  88. query_num = inputs.shape[0]
  89. results = []
  90. if self._detector:
  91. for i in range(query_num):
  92. query = np.expand_dims(inputs[i].astype(np.float32), axis=0)
  93. result = self._network(Tensor(query)).asnumpy()
  94. det_num = len(self._detector.get_detected_queries())
  95. self._detector.detect(np.array([query]))
  96. new_det_num = len(self._detector.get_detected_queries())
  97. # If attack query detected, return random predict result
  98. if new_det_num > det_num:
  99. results.append(result + np.random.rand(*result.shape))
  100. self._detected_res.append(True)
  101. else:
  102. results.append(result)
  103. self._detected_res.append(False)
  104. results = np.concatenate(results)
  105. else:
  106. if len(inputs.shape) == 3:
  107. inputs = np.expand_dims(inputs, axis=0)
  108. results = self._network(Tensor(inputs.astype(np.float32))).asnumpy()
  109. return results
  110. def get_detected_result(self):
  111. return self._detected_res
  112. def test_defense_evaluation():
  113. # load trained network
  114. current_dir = os.path.dirname(os.path.abspath(__file__))
  115. ckpt_path = os.path.abspath(os.path.join(
  116. current_dir, '../../common/networks/lenet5/trained_ckpt_file/checkpoint_lenet-10_1875.ckpt'))
  117. wb_net = LeNet5()
  118. load_dict = load_checkpoint(ckpt_path)
  119. load_param_into_net(wb_net, load_dict)
  120. # get test data
  121. data_list = "../../common/dataset/MNIST/test"
  122. batch_size = 32
  123. ds_test = generate_mnist_dataset(data_list, batch_size=batch_size)
  124. inputs = []
  125. labels = []
  126. for data in ds_test.create_tuple_iterator(output_numpy=True):
  127. inputs.append(data[0].astype(np.float32))
  128. labels.append(data[1])
  129. inputs = np.concatenate(inputs).astype(np.float32)
  130. labels = np.concatenate(labels).astype(np.int32)
  131. target_label = np.random.randint(0, 10, size=labels.shape[0])
  132. for idx in range(labels.shape[0]):
  133. while target_label[idx] == labels[idx]:
  134. target_label[idx] = np.random.randint(0, 10)
  135. target_label = np.eye(10)[target_label].astype(np.float32)
  136. attacked_size = 50
  137. benign_size = 500
  138. attacked_sample = inputs[:attacked_size]
  139. attacked_true_label = labels[:attacked_size]
  140. benign_sample = inputs[attacked_size:attacked_size + benign_size]
  141. wb_model = ModelToBeAttacked(wb_net)
  142. # gen white-box adversarial examples of test data
  143. loss = SoftmaxCrossEntropyWithLogits(sparse=True)
  144. wb_attack = FastGradientSignMethod(wb_net, eps=0.3, loss_fn=loss)
  145. wb_adv_sample = wb_attack.generate(attacked_sample,
  146. attacked_true_label)
  147. wb_raw_preds = softmax(wb_model.predict(wb_adv_sample), axis=1)
  148. accuracy_test = np.mean(
  149. np.equal(np.argmax(wb_model.predict(attacked_sample), axis=1),
  150. attacked_true_label))
  151. LOGGER.info(TAG, "prediction accuracy before white-box attack is : %s",
  152. accuracy_test)
  153. accuracy_adv = np.mean(np.equal(np.argmax(wb_raw_preds, axis=1),
  154. attacked_true_label))
  155. LOGGER.info(TAG, "prediction accuracy after white-box attack is : %s",
  156. accuracy_adv)
  157. # improve the robustness of model with white-box adversarial examples
  158. opt = nn.Momentum(wb_net.trainable_params(), 0.01, 0.09)
  159. nad = NaturalAdversarialDefense(wb_net, loss_fn=loss, optimizer=opt,
  160. bounds=(0.0, 1.0), eps=0.3)
  161. wb_net.set_train(False)
  162. nad.batch_defense(inputs[:5000], labels[:5000], batch_size=32, epochs=10)
  163. wb_def_preds = wb_net(Tensor(wb_adv_sample)).asnumpy()
  164. wb_def_preds = softmax(wb_def_preds, axis=1)
  165. accuracy_def = np.mean(np.equal(np.argmax(wb_def_preds, axis=1),
  166. attacked_true_label))
  167. LOGGER.info(TAG, "prediction accuracy after defense is : %s", accuracy_def)
  168. # calculate defense evaluation metrics for defense against white-box attack
  169. wb_def_evaluate = DefenseEvaluate(wb_raw_preds, wb_def_preds,
  170. attacked_true_label)
  171. LOGGER.info(TAG, 'defense evaluation for white-box adversarial attack')
  172. LOGGER.info(TAG,
  173. 'classification accuracy variance (CAV) is : {:.2f}'.format(
  174. wb_def_evaluate.cav()))
  175. LOGGER.info(TAG, 'classification rectify ratio (CRR) is : {:.2f}'.format(
  176. wb_def_evaluate.crr()))
  177. LOGGER.info(TAG, 'classification sacrifice ratio (CSR) is : {:.2f}'.format(
  178. wb_def_evaluate.csr()))
  179. LOGGER.info(TAG,
  180. 'classification confidence variance (CCV) is : {:.2f}'.format(
  181. wb_def_evaluate.ccv()))
  182. LOGGER.info(TAG, 'classification output stability is : {:.2f}'.format(
  183. wb_def_evaluate.cos()))
  184. # calculate defense evaluation metrics for defense against black-box attack
  185. LOGGER.info(TAG, 'defense evaluation for black-box adversarial attack')
  186. bb_raw_preds = []
  187. bb_def_preds = []
  188. raw_query_counts = []
  189. raw_query_time = []
  190. def_query_counts = []
  191. def_query_time = []
  192. def_detection_counts = []
  193. # gen black-box adversarial examples of test data
  194. bb_net = LeNet5()
  195. load_param_into_net(bb_net, load_dict)
  196. bb_model = ModelToBeAttacked(bb_net, defense=False)
  197. attack_rm = GeneticAttack(model=bb_model, pop_size=6, mutation_rate=0.05,
  198. per_bounds=0.5, step_size=0.25, temp=0.1,
  199. sparse=False)
  200. attack_target_label = target_label[:attacked_size]
  201. true_label = labels[:attacked_size + benign_size]
  202. # evaluate robustness of original model
  203. # gen black-box adversarial examples of test data
  204. for idx in range(attacked_size):
  205. raw_st = time.time()
  206. _, raw_a, raw_qc = attack_rm.generate(
  207. np.expand_dims(attacked_sample[idx], axis=0),
  208. np.expand_dims(attack_target_label[idx], axis=0))
  209. raw_t = time.time() - raw_st
  210. bb_raw_preds.extend(softmax(bb_model.predict(raw_a), axis=1))
  211. raw_query_counts.extend(raw_qc)
  212. raw_query_time.append(raw_t)
  213. for idx in range(benign_size):
  214. raw_st = time.time()
  215. bb_raw_pred = softmax(
  216. bb_model.predict(np.expand_dims(benign_sample[idx], axis=0)),
  217. axis=1)
  218. raw_t = time.time() - raw_st
  219. bb_raw_preds.extend(bb_raw_pred)
  220. raw_query_counts.extend([0])
  221. raw_query_time.append(raw_t)
  222. accuracy_test = np.mean(
  223. np.equal(np.argmax(bb_raw_preds[0:len(attack_target_label)], axis=1),
  224. np.argmax(attack_target_label, axis=1)))
  225. LOGGER.info(TAG, "attack success before adv defense is : %s",
  226. accuracy_test)
  227. # improve the robustness of model with similarity-based detector
  228. bb_def_model = ModelToBeAttacked(bb_net, defense=True,
  229. train_images=inputs[0:6000])
  230. # attack defensed model
  231. attack_dm = GeneticAttack(model=bb_def_model, pop_size=6,
  232. mutation_rate=0.05,
  233. per_bounds=0.5, step_size=0.25, temp=0.1,
  234. sparse=False)
  235. for idx in range(attacked_size):
  236. def_st = time.time()
  237. _, def_a, def_qc = attack_dm.generate(
  238. np.expand_dims(attacked_sample[idx], axis=0),
  239. np.expand_dims(attack_target_label[idx], axis=0))
  240. def_t = time.time() - def_st
  241. det_res = bb_def_model.get_detected_result()
  242. def_detection_counts.append(np.sum(det_res[-def_qc[0]:]))
  243. bb_def_preds.extend(softmax(bb_def_model.predict(def_a), axis=1))
  244. def_query_counts.extend(def_qc)
  245. def_query_time.append(def_t)
  246. for idx in range(benign_size):
  247. def_st = time.time()
  248. bb_def_pred = softmax(
  249. bb_def_model.predict(np.expand_dims(benign_sample[idx], axis=0)),
  250. axis=1)
  251. def_t = time.time() - def_st
  252. det_res = bb_def_model.get_detected_result()
  253. def_detection_counts.append(np.sum(det_res[-1]))
  254. bb_def_preds.extend(bb_def_pred)
  255. def_query_counts.extend([0])
  256. def_query_time.append(def_t)
  257. accuracy_adv = np.mean(
  258. np.equal(np.argmax(bb_def_preds[0:len(attack_target_label)], axis=1),
  259. np.argmax(attack_target_label, axis=1)))
  260. LOGGER.info(TAG, "attack success rate after adv defense is : %s",
  261. accuracy_adv)
  262. bb_raw_preds = np.array(bb_raw_preds).astype(np.float32)
  263. bb_def_preds = np.array(bb_def_preds).astype(np.float32)
  264. # check evaluate data
  265. max_queries = 6000
  266. def_evaluate = BlackDefenseEvaluate(bb_raw_preds, bb_def_preds,
  267. np.array(raw_query_counts),
  268. np.array(def_query_counts),
  269. np.array(raw_query_time),
  270. np.array(def_query_time),
  271. np.array(def_detection_counts),
  272. true_label, max_queries)
  273. LOGGER.info(TAG, 'query count variance of adversaries is : {:.2f}'.format(
  274. def_evaluate.qcv()))
  275. LOGGER.info(TAG, 'attack success rate variance of adversaries '
  276. 'is : {:.2f}'.format(def_evaluate.asv()))
  277. LOGGER.info(TAG, 'false positive rate (FPR) of the query-based detector '
  278. 'is : {:.2f}'.format(def_evaluate.fpr()))
  279. LOGGER.info(TAG, 'the benign query response time variance (QRV) '
  280. 'is : {:.2f}'.format(def_evaluate.qrv()))
  281. if __name__ == '__main__':
  282. # device_target can be "CPU", "GPU" or "Ascend"
  283. context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
  284. DEVICE = context.get_context("device_target")
  285. if DEVICE in ("Ascend", "GPU"):
  286. test_defense_evaluation()

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