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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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 test data
  62. data_list = "../../common/dataset/MNIST/test"
  63. batch_size = 32
  64. ds = generate_mnist_dataset(data_list, batch_size)
  65. inversion_attack = ImageInversionAttack(net, input_shape=(1, 32, 32), input_bound=(0, 1), loss_weights=[1, 0.2, 5])
  66. i = 0
  67. batch_num = 1
  68. sample_num = 10
  69. for data in ds.create_tuple_iterator(output_numpy=True):
  70. i += 1
  71. images = data[0].astype(np.float32)
  72. target_features = net(Tensor(images)).asnumpy()
  73. original_images = images[: sample_num]
  74. inversion_images = inversion_attack.generate(target_features[:sample_num], iters=100)
  75. for n in range(1, sample_num+1):
  76. plt.subplot(2, sample_num, n)
  77. plt.gray()
  78. plt.imshow(images[n - 1].reshape(32, 32))
  79. plt.subplot(2, sample_num, n + sample_num)
  80. plt.gray()
  81. plt.imshow(inversion_images[n - 1].reshape(32, 32))
  82. plt.show()
  83. if i >= batch_num:
  84. break
  85. # evaluate the similarity between inversion images and original images
  86. avg_l2_dis, avg_ssim = inversion_attack.evaluate(original_images, inversion_images)
  87. LOGGER.info(TAG, 'The average L2 distance between original images and inversion images is: {}'.format(avg_l2_dis))
  88. LOGGER.info(TAG, 'The average ssim value between original images and inversion images is: {}'.format(avg_ssim))
  89. if __name__ == '__main__':
  90. # device_target can be "CPU", "GPU" or "Ascend"
  91. context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
  92. # attack based on complete LeNet5
  93. mnist_inversion_attack(LeNet5())
  94. # attack based on part of LeNet5. The network is more shallower and can lead to a better attack result
  95. mnist_inversion_attack(LeNet5_part())

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