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.

test_nad.py 2.1 kB

5 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. """
  15. Natural adversarial defense test.
  16. """
  17. import numpy as np
  18. import pytest
  19. import logging
  20. from mindspore import nn
  21. from mindspore import context
  22. from mindspore.nn.optim.momentum import Momentum
  23. from mindarmour.defenses.natural_adversarial_defense import \
  24. NaturalAdversarialDefense
  25. from mindarmour.utils.logger import LogUtil
  26. from mock_net import Net
  27. LOGGER = LogUtil.get_instance()
  28. TAG = 'Nad_Test'
  29. @pytest.mark.level0
  30. @pytest.mark.platform_arm_ascend_training
  31. @pytest.mark.platform_x86_ascend_training
  32. @pytest.mark.env_card
  33. @pytest.mark.component_mindarmour
  34. def test_nad():
  35. """UT for natural adversarial defense."""
  36. num_classes = 10
  37. batch_size = 16
  38. sparse = False
  39. context.set_context(mode=context.GRAPH_MODE)
  40. context.set_context(device_target='Ascend')
  41. # create test data
  42. inputs = np.random.rand(batch_size, 1, 32, 32).astype(np.float32)
  43. labels = np.random.randint(num_classes, size=batch_size).astype(np.int32)
  44. if not sparse:
  45. labels = np.eye(num_classes)[labels].astype(np.float32)
  46. net = Net()
  47. loss_fn = nn.SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=sparse)
  48. optimizer = Momentum(net.trainable_params(), 0.001, 0.9)
  49. # defense
  50. nad = NaturalAdversarialDefense(net, loss_fn=loss_fn, optimizer=optimizer)
  51. LOGGER.set_level(logging.DEBUG)
  52. LOGGER.debug(TAG, '---start natural adversarial defense--')
  53. loss = nad.defense(inputs, labels)
  54. LOGGER.debug(TAG, '---end natural adversarial defense--')
  55. assert np.any(loss >= 0.0)

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