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.

class_sensitivity.py 4.0 kB

5 years ago
5 years ago
5 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. # Copyright 2020 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. """Class Sensitivity."""
  16. import numpy as np
  17. from mindspore.explainer.explanation import RISE
  18. from .metric import LabelAgnosticMetric
  19. from ... import _operators as ops
  20. from ..._utils import calc_correlation
  21. class ClassSensitivity(LabelAgnosticMetric):
  22. """
  23. Class sensitivity metric used to evaluate attribution-based explanations.
  24. Reasonable atrribution-based explainers are expected to generate distinct saliency maps for different labels,
  25. especially for labels of highest confidence and low confidence. ClassSensitivity evaluates the explainer through
  26. computing the correlation between saliency maps of highest-confidence and lowest-confidence labels. Explainer with
  27. better class sensitivity will receive lower correlation score. To make the evaluation results intuitive, the
  28. returned score will take negative on correlation and normalize.
  29. """
  30. def evaluate(self, explainer, inputs):
  31. """
  32. Evaluate class sensitivity on a single data sample.
  33. Args:
  34. explainer (Explanation): The explainer to be evaluated, see `mindspore.explainer.explanation`.
  35. inputs (Tensor): A data sample, a 4D tensor of shape :math:`(N, C, H, W)`.
  36. Returns:
  37. numpy.ndarray, 1D array of shape :math:`(N,)`, result of class sensitivity evaluated on `explainer`.
  38. Examples:
  39. >>> import mindspore as ms
  40. >>> from mindspore.explainer.benchmark import ClassSensitivity
  41. >>> from mindspore.explainer.explanation import Gradient
  42. >>> from mindspore.train.serialization import load_checkpoint, load_param_into_net
  43. >>> # prepare your network and load the trained checkpoint file, e.g., resnet50.
  44. >>> network = resnet50(10)
  45. >>> param_dict = load_checkpoint("resnet50.ckpt")
  46. >>> load_param_into_net(network, param_dict)
  47. >>> # prepare your explainer to be evaluated, e.g., Gradient.
  48. >>> gradient = Gradient(network)
  49. >>> input_x = ms.Tensor(np.random.rand(1, 3, 224, 224), ms.float32)
  50. >>> class_sensitivity = ClassSensitivity()
  51. >>> res = class_sensitivity.evaluate(gradient, input_x)
  52. """
  53. self._check_evaluate_param(explainer, inputs)
  54. outputs = explainer.network(inputs)
  55. max_confidence_label = ops.argmax(outputs)
  56. min_confidence_label = ops.argmin(outputs)
  57. if isinstance(explainer, RISE):
  58. labels = ops.stack([max_confidence_label, min_confidence_label], axis=1)
  59. full_saliency = explainer(inputs, labels)
  60. max_confidence_saliency = full_saliency[:, max_confidence_label].asnumpy()
  61. min_confidence_saliency = full_saliency[:, min_confidence_label].asnumpy()
  62. else:
  63. max_confidence_saliency = explainer(inputs, max_confidence_label).asnumpy()
  64. min_confidence_saliency = explainer(inputs, min_confidence_label).asnumpy()
  65. correlations = []
  66. for i in range(inputs.shape[0]):
  67. correlation = calc_correlation(max_confidence_saliency[i].reshape(-1),
  68. min_confidence_saliency[i].reshape(-1))
  69. normalized_correlation = (-correlation + 1) / 2
  70. correlations.append(normalized_correlation)
  71. return np.array(correlations, np.float)