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

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