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.

spatial_smoothing.py 6.2 kB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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. Spatial-Smoothing detector.
  16. """
  17. import numpy as np
  18. from scipy import ndimage
  19. from mindspore import Model
  20. from mindspore import Tensor
  21. from mindarmour.detectors.detector import Detector
  22. from mindarmour.utils.logger import LogUtil
  23. from mindarmour.utils._check_param import check_model, check_numpy_param, \
  24. check_pair_numpy_param, check_int_positive, check_param_type, \
  25. check_param_in_range, check_equal_shape, check_value_positive
  26. LOGGER = LogUtil.get_instance()
  27. TAG = 'SpatialSmoothing'
  28. def _median_filter_np(inputs, size=2):
  29. """median filter using numpy"""
  30. return ndimage.filters.median_filter(inputs, size=size, mode='reflect')
  31. class SpatialSmoothing(Detector):
  32. """
  33. Detect method based on spatial smoothing.
  34. Args:
  35. model (Model): Target model.
  36. ksize (int): Smooth window size. Default: 3.
  37. is_local_smooth (bool): If True, trigger local smooth. If False, none
  38. local smooth. Default: True.
  39. metric (str): Distance method. Default: 'l1'.
  40. false_positive_ratio (float): False positive rate over
  41. benign samples. Default: 0.05.
  42. Examples:
  43. >>> detector = SpatialSmoothing(model)
  44. >>> detector.fit(Tensor(ori), Tensor(labels))
  45. >>> adv_ids = detector.detect(Tensor(adv))
  46. """
  47. def __init__(self, model, ksize=3, is_local_smooth=True,
  48. metric='l1', false_positive_ratio=0.05):
  49. super(SpatialSmoothing, self).__init__()
  50. self._ksize = check_int_positive('ksize', ksize)
  51. self._is_local_smooth = check_param_type('is_local_smooth',
  52. is_local_smooth,
  53. bool)
  54. self._model = check_model('model', model, Model)
  55. self._metric = metric
  56. self._fpr = check_param_in_range('false_positive_ratio',
  57. false_positive_ratio,
  58. 0, 1)
  59. self._threshold = None
  60. def fit(self, inputs, labels=None):
  61. """
  62. Train detector to decide the threshold. The proper threshold make
  63. sure the actual false positive rate over benign sample is less than
  64. the given value.
  65. Args:
  66. inputs (numpy.ndarray): Benign samples.
  67. labels (numpy.ndarray): Default None.
  68. Returns:
  69. float, threshold, distance larger than which is reported
  70. as positive, i.e. adversarial.
  71. """
  72. inputs = check_numpy_param('inputs', inputs)
  73. raw_pred = self._model.predict(Tensor(inputs))
  74. smoothing_pred = self._model.predict(Tensor(self.transform(inputs)))
  75. dist = self._dist(raw_pred.asnumpy(), smoothing_pred.asnumpy())
  76. index = int(len(dist)*(1 - self._fpr))
  77. threshold = np.sort(dist, axis=None)[index]
  78. self._threshold = threshold
  79. return self._threshold
  80. def detect(self, inputs):
  81. """
  82. Detect if an input sample is an adversarial example.
  83. Args:
  84. inputs (numpy.ndarray): Suspicious samples to be judged.
  85. Returns:
  86. list[int], whether a sample is adversarial. if res[i]=1, then the
  87. input sample with index i is adversarial.
  88. """
  89. inputs = check_numpy_param('inputs', inputs)
  90. raw_pred = self._model.predict(Tensor(inputs))
  91. smoothing_pred = self._model.predict(Tensor(self.transform(inputs)))
  92. dist = self._dist(raw_pred.asnumpy(), smoothing_pred.asnumpy())
  93. res = [0]*len(dist)
  94. for i, elem in enumerate(dist):
  95. if elem > self._threshold:
  96. res[i] = 1
  97. return res
  98. def detect_diff(self, inputs):
  99. """
  100. Return the raw distance value (before apply the threshold) between
  101. the input sample and its smoothed counterpart.
  102. Args:
  103. inputs (numpy.ndarray): Suspicious samples to be judged.
  104. Returns:
  105. float, distance.
  106. """
  107. inputs = check_numpy_param('inputs', inputs)
  108. raw_pred = self._model.predict(Tensor(inputs))
  109. smoothing_pred = self._model.predict(Tensor(self.transform(inputs)))
  110. dist = self._dist(raw_pred.asnumpy(), smoothing_pred.asnumpy())
  111. return dist
  112. def transform(self, inputs):
  113. inputs = check_numpy_param('inputs', inputs)
  114. return _median_filter_np(inputs, self._ksize)
  115. def set_threshold(self, threshold):
  116. """
  117. Set the parameters threshold.
  118. Args:
  119. threshold (float): Detection threshold. Default: None.
  120. """
  121. self._threshold = check_value_positive('threshold', threshold)
  122. def _dist(self, before, after):
  123. """
  124. Calculate the distance between the model outputs of a raw sample and
  125. its smoothed counterpart.
  126. Args:
  127. before (numpy.ndarray): Model output of raw samples.
  128. after (numpy.ndarray): Model output of smoothed counterparts.
  129. Returns:
  130. float, distance based on specified norm.
  131. """
  132. before, after = check_pair_numpy_param('before', before, 'after', after)
  133. before, after = check_equal_shape('before', before, 'after', after)
  134. res = []
  135. diff = after - before
  136. for _, elem in enumerate(diff):
  137. if self._metric == 'l1':
  138. res.append(np.linalg.norm(elem, ord=1))
  139. elif self._metric == 'l2':
  140. res.append(np.linalg.norm(elem, ord=2))
  141. else:
  142. res.append(np.linalg.norm(elem, ord=1))
  143. return res

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