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_inversion_attack.py 5.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. # Copyright 2021 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. # ============================================================================
  15. """
  16. Examples of image inversion attack
  17. """
  18. import numpy as np
  19. import matplotlib.pyplot as plt
  20. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  21. from mindspore import Tensor, context
  22. from mindspore import nn
  23. from mindarmour.privacy.evaluation.inversion_attack import ImageInversionAttack
  24. from mindarmour.utils.logger import LogUtil
  25. from examples.common.networks.lenet5.lenet5_net import LeNet5, conv, fc_with_initialize
  26. from examples.common.dataset.data_processing import generate_mnist_dataset
  27. LOGGER = LogUtil.get_instance()
  28. LOGGER.set_level('INFO')
  29. TAG = 'InversionAttack'
  30. # pylint: disable=invalid-name
  31. class LeNet5_part(nn.Cell):
  32. """
  33. Part of LeNet5 network.
  34. """
  35. def __init__(self):
  36. super(LeNet5_part, self).__init__()
  37. self.conv1 = conv(1, 6, 5)
  38. self.conv2 = conv(6, 16, 5)
  39. self.fc1 = fc_with_initialize(16*5*5, 120)
  40. self.fc2 = fc_with_initialize(120, 84)
  41. self.fc3 = fc_with_initialize(84, 10)
  42. self.relu = nn.ReLU()
  43. self.max_pool2d = nn.MaxPool2d(kernel_size=2, stride=2)
  44. self.flatten = nn.Flatten()
  45. def construct(self, x):
  46. x = self.conv1(x)
  47. x = self.relu(x)
  48. x = self.max_pool2d(x)
  49. x = self.conv2(x)
  50. x = self.relu(x)
  51. x = self.max_pool2d(x)
  52. return x
  53. def mnist_inversion_attack(net):
  54. """
  55. Image inversion attack based on LeNet5 and MNIST dataset.
  56. """
  57. # upload trained network
  58. ckpt_path = '../../common/networks/lenet5/trained_ckpt_file/checkpoint_lenet-10_1875.ckpt'
  59. load_dict = load_checkpoint(ckpt_path)
  60. load_param_into_net(net, load_dict)
  61. # get original data and their inferred fearures
  62. data_list = "../../common/dataset/MNIST/train"
  63. batch_size = 32
  64. ds = generate_mnist_dataset(data_list, batch_size)
  65. i = 0
  66. batch_num = 1
  67. sample_num = 30
  68. for data in ds.create_tuple_iterator(output_numpy=True):
  69. i += 1
  70. images = data[0].astype(np.float32)
  71. true_labels = data[1][: sample_num]
  72. target_features = net(Tensor(images)).asnumpy()[:sample_num]
  73. original_images = images[: sample_num]
  74. if i >= batch_num:
  75. break
  76. # run attacking
  77. inversion_attack = ImageInversionAttack(net, input_shape=(1, 32, 32), input_bound=(0, 1), loss_weights=[1, 0.1, 5])
  78. inversion_images = inversion_attack.generate(target_features, iters=100)
  79. # get the predict results of inversion images on a new trained model
  80. net2 = LeNet5()
  81. new_ckpt_path = '../../common/networks/lenet5/new_trained_ckpt_file/checkpoint_lenet-10_1875.ckpt'
  82. new_load_dict = load_checkpoint(new_ckpt_path)
  83. load_param_into_net(net2, new_load_dict)
  84. pred_labels = np.argmax(net2(Tensor(inversion_images).astype(np.float32)).asnumpy(), axis=1)
  85. # evaluate the quality of inversion images
  86. avg_l2_dis, avg_ssim, avg_confi = inversion_attack.evaluate(original_images, inversion_images, true_labels, net2)
  87. LOGGER.info(TAG, 'The average L2 distance between original images and inverted images is: {}'.format(avg_l2_dis))
  88. LOGGER.info(TAG, 'The average ssim value between original images and inverted images is: {}'.format(avg_ssim))
  89. LOGGER.info(TAG, 'The average prediction confidence on true labels of inverted images is: {}'.format(avg_confi))
  90. LOGGER.info(TAG, 'True labels of original images are: %s' % true_labels)
  91. LOGGER.info(TAG, 'Predicted labels of inverted images are: %s' % pred_labels)
  92. # plot 10 images
  93. plot_num = min(sample_num, 10)
  94. for n in range(1, plot_num+1):
  95. plt.subplot(2, plot_num, n)
  96. if n == 1:
  97. plt.title('Original images', fontsize=16, loc='left')
  98. plt.gray()
  99. plt.imshow(images[n - 1].reshape(32, 32))
  100. plt.subplot(2, plot_num, n + plot_num)
  101. if n == 1:
  102. plt.title('Inverted images', fontsize=16, loc='left')
  103. plt.gray()
  104. plt.imshow(inversion_images[n - 1].reshape(32, 32))
  105. plt.show()
  106. if __name__ == '__main__':
  107. # device_target can be "CPU", "GPU" or "Ascend"
  108. context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
  109. # attack based on complete LeNet5
  110. mnist_inversion_attack(LeNet5())
  111. # attack based on part of LeNet5. The network is more shallower and can lead to a better attack result
  112. mnist_inversion_attack(LeNet5_part())

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