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_defense_nad.py 5.1 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  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. """defense example using nad"""
  15. import os
  16. import sys
  17. import numpy as np
  18. from mindspore import Tensor
  19. from mindspore import context
  20. from mindspore import nn
  21. from mindspore.nn import SoftmaxCrossEntropyWithLogits
  22. from mindspore.train import Model
  23. from mindspore.train.callback import LossMonitor
  24. from mindarmour.attacks import FastGradientSignMethod
  25. from mindarmour.defenses import NaturalAdversarialDefense
  26. from mindarmour.utils.logger import LogUtil
  27. from lenet5_net import LeNet5
  28. sys.path.append("..")
  29. from data_processing import generate_mnist_dataset
  30. LOGGER = LogUtil.get_instance()
  31. LOGGER.set_level("INFO")
  32. TAG = 'Nad_Example'
  33. def test_nad_method():
  34. """
  35. NAD-Defense test.
  36. """
  37. mnist_path = "./MNIST_unzip/"
  38. batch_size = 32
  39. # 1. train original model
  40. ds_train = generate_mnist_dataset(os.path.join(mnist_path, "train"),
  41. batch_size=batch_size, repeat_size=1)
  42. net = LeNet5()
  43. loss = SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=True)
  44. opt = nn.Momentum(net.trainable_params(), 0.01, 0.09)
  45. model = Model(net, loss, opt, metrics=None)
  46. model.train(10, ds_train, callbacks=[LossMonitor()],
  47. dataset_sink_mode=False)
  48. # 2. get test data
  49. ds_test = generate_mnist_dataset(os.path.join(mnist_path, "test"),
  50. batch_size=batch_size, repeat_size=1)
  51. inputs = []
  52. labels = []
  53. for data in ds_test.create_tuple_iterator():
  54. inputs.append(data[0].astype(np.float32))
  55. labels.append(data[1])
  56. inputs = np.concatenate(inputs)
  57. labels = np.concatenate(labels)
  58. # 3. get accuracy of test data on original model
  59. net.set_train(False)
  60. acc_list = []
  61. batchs = inputs.shape[0] // batch_size
  62. for i in range(batchs):
  63. batch_inputs = inputs[i*batch_size : (i + 1)*batch_size]
  64. batch_labels = labels[i*batch_size : (i + 1)*batch_size]
  65. logits = net(Tensor(batch_inputs)).asnumpy()
  66. label_pred = np.argmax(logits, axis=1)
  67. acc_list.append(np.mean(batch_labels == label_pred))
  68. LOGGER.info(TAG, 'accuracy of TEST data on original model is : %s',
  69. np.mean(acc_list))
  70. # 4. get adv of test data
  71. attack = FastGradientSignMethod(net, eps=0.3, loss_fn=loss)
  72. adv_data = attack.batch_generate(inputs, labels)
  73. LOGGER.info(TAG, 'adv_data.shape is : %s', adv_data.shape)
  74. # 5. get accuracy of adv data on original model
  75. acc_list = []
  76. batchs = adv_data.shape[0] // batch_size
  77. for i in range(batchs):
  78. batch_inputs = adv_data[i*batch_size : (i + 1)*batch_size]
  79. batch_labels = labels[i*batch_size : (i + 1)*batch_size]
  80. logits = net(Tensor(batch_inputs)).asnumpy()
  81. label_pred = np.argmax(logits, axis=1)
  82. acc_list.append(np.mean(batch_labels == label_pred))
  83. LOGGER.info(TAG, 'accuracy of adv data on original model is : %s',
  84. np.mean(acc_list))
  85. # 6. defense
  86. net.set_train()
  87. nad = NaturalAdversarialDefense(net, loss_fn=loss, optimizer=opt,
  88. bounds=(0.0, 1.0), eps=0.3)
  89. nad.batch_defense(inputs, labels, batch_size=32, epochs=10)
  90. # 7. get accuracy of test data on defensed model
  91. net.set_train(False)
  92. acc_list = []
  93. batchs = inputs.shape[0] // batch_size
  94. for i in range(batchs):
  95. batch_inputs = inputs[i*batch_size : (i + 1)*batch_size]
  96. batch_labels = labels[i*batch_size : (i + 1)*batch_size]
  97. logits = net(Tensor(batch_inputs)).asnumpy()
  98. label_pred = np.argmax(logits, axis=1)
  99. acc_list.append(np.mean(batch_labels == label_pred))
  100. LOGGER.info(TAG, 'accuracy of TEST data on defensed model is : %s',
  101. np.mean(acc_list))
  102. # 8. get accuracy of adv data on defensed model
  103. acc_list = []
  104. batchs = adv_data.shape[0] // batch_size
  105. for i in range(batchs):
  106. batch_inputs = adv_data[i*batch_size : (i + 1)*batch_size]
  107. batch_labels = labels[i*batch_size : (i + 1)*batch_size]
  108. logits = net(Tensor(batch_inputs)).asnumpy()
  109. label_pred = np.argmax(logits, axis=1)
  110. acc_list.append(np.mean(batch_labels == label_pred))
  111. LOGGER.info(TAG, 'accuracy of adv data on defensed model is : %s',
  112. np.mean(acc_list))
  113. if __name__ == '__main__':
  114. # device_target can be "CPU", "GPU" or "Ascend"
  115. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
  116. test_nad_method()

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