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 13 kB

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

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