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_runner.py 7.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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. """Tests on mindspore.explainer.ImageClassificationRunner."""
  16. import os
  17. import shutil
  18. from random import random
  19. from unittest.mock import patch
  20. import numpy as np
  21. import pytest
  22. from PIL import Image
  23. from mindspore import context
  24. import mindspore as ms
  25. import mindspore.nn as nn
  26. from mindspore.dataset import GeneratorDataset
  27. from mindspore.explainer import ImageClassificationRunner
  28. from mindspore.explainer._image_classification_runner import _normalize
  29. from mindspore.explainer.benchmark import Faithfulness
  30. from mindspore.explainer.explanation import Gradient
  31. from mindspore.train.summary import SummaryRecord
  32. CONST = random()
  33. NUMDATA = 2
  34. context.set_context(mode=context.PYNATIVE_MODE)
  35. def image_label_bbox_generator():
  36. for i in range(NUMDATA):
  37. image = np.arange(i, i + 16 * 3).reshape((3, 4, 4)) / 50
  38. label = np.array(i)
  39. bbox = np.array([1, 1, 2, 2])
  40. yield (image, label, bbox)
  41. class SimpleNet(nn.Cell):
  42. """
  43. Simple model for the unit test.
  44. """
  45. def __init__(self):
  46. super(SimpleNet, self).__init__()
  47. self.reshape = ms.ops.operations.Reshape()
  48. def construct(self, x):
  49. prob = ms.Tensor([0.1, 0.9], ms.float32)
  50. prob = self.reshape(prob, (1, 2))
  51. return prob
  52. class ActivationFn(nn.Cell):
  53. """
  54. Simple activation function for unit test.
  55. """
  56. def __init__(self):
  57. super(ActivationFn, self).__init__()
  58. def construct(self, x):
  59. return x
  60. def mock_gradient_call(_, inputs, targets):
  61. return inputs[:, 0:1, :, :]
  62. def mock_faithfulness_evaluate(_, explainer, inputs, targets, saliency):
  63. return CONST * targets
  64. def mock_make_rgba(array):
  65. return array.asnumpy()
  66. class TestRunner:
  67. """Test on Runner."""
  68. def setup_method(self):
  69. self.dataset = GeneratorDataset(image_label_bbox_generator, ["image", "label", "bbox"])
  70. self.labels = ["label_{}".format(i) for i in range(2)]
  71. self.network = SimpleNet()
  72. self.summary_dir = "summary_test_temp"
  73. self.explainer = [Gradient(self.network)]
  74. self.activation_fn = ActivationFn()
  75. self.benchmarkers = [Faithfulness(num_labels=len(self.labels),
  76. metric="NaiveFaithfulness",
  77. activation_fn=self.activation_fn)]
  78. @pytest.mark.level0
  79. @pytest.mark.platform_arm_ascend_training
  80. @pytest.mark.platform_x86_ascend_training
  81. @pytest.mark.env_onecard
  82. def test_run_saliency_no_benchmark(self):
  83. """Test case when argument benchmarkers is not parsed."""
  84. res = []
  85. runner = ImageClassificationRunner(summary_dir=self.summary_dir, data=(self.dataset, self.labels),
  86. network=self.network, activation_fn=self.activation_fn)
  87. def mock_summary_add_value(_, plugin, name, value):
  88. res.append((plugin, name, value))
  89. with patch.object(SummaryRecord, "add_value", mock_summary_add_value), \
  90. patch.object(Gradient, "__call__", mock_gradient_call):
  91. runner.register_saliency(self.explainer)
  92. runner.run()
  93. # test on meta data
  94. idx = 0
  95. assert res[idx][0] == "explainer"
  96. assert res[idx][1] == "metadata"
  97. assert res[idx][2].metadata.label == self.labels
  98. assert res[idx][2].metadata.explain_method == ["Gradient"]
  99. # test on inference data
  100. for i in range(NUMDATA):
  101. idx += 1
  102. data_np = np.arange(i, i + 3 * 16).reshape((3, 4, 4)) / 50
  103. assert res[idx][0] == "explainer"
  104. assert res[idx][1] == "sample"
  105. assert res[idx][2].sample_id == i
  106. original_path = os.path.join(self.summary_dir, res[idx][2].image_path)
  107. with open(original_path, "rb") as f:
  108. image_data = np.asarray(Image.open(f)) / 255.0
  109. original_image = _normalize(np.transpose(data_np, [1, 2, 0]))
  110. assert np.allclose(image_data, original_image, rtol=3e-2, atol=3e-2)
  111. idx += 1
  112. assert res[idx][0] == "explainer"
  113. assert res[idx][1] == "inference"
  114. assert res[idx][2].sample_id == i
  115. assert res[idx][2].ground_truth_label == [i]
  116. diff = np.array(res[idx][2].inference.ground_truth_prob) - np.array([[0.1, 0.9][i]])
  117. assert np.max(np.abs(diff)) < 1e-6
  118. assert res[idx][2].inference.predicted_label == [1]
  119. diff = np.array(res[idx][2].inference.predicted_prob) - np.array([0.9])
  120. assert np.max(np.abs(diff)) < 1e-6
  121. # test on explanation data
  122. for i in range(NUMDATA):
  123. idx += 1
  124. data_np = np.arange(i, i + 3 * 16).reshape((3, 4, 4)) / 50
  125. saliency_np = data_np[0, :, :]
  126. assert res[idx][0] == "explainer"
  127. assert res[idx][1] == "explanation"
  128. assert res[idx][2].sample_id == i
  129. assert res[idx][2].explanation[0].explain_method == "Gradient"
  130. assert res[idx][2].explanation[0].label in [i, 1]
  131. heatmap_path = os.path.join(self.summary_dir, res[idx][2].explanation[0].heatmap_path)
  132. assert os.path.exists(heatmap_path)
  133. with open(heatmap_path, "rb") as f:
  134. heatmap_data = np.asarray(Image.open(f)) / 255.0
  135. heatmap_image = _normalize(saliency_np)
  136. assert np.allclose(heatmap_data, heatmap_image, atol=3e-2, rtol=3e-2)
  137. @pytest.mark.level0
  138. @pytest.mark.platform_arm_ascend_training
  139. @pytest.mark.platform_x86_ascend_training
  140. @pytest.mark.env_onecard
  141. def test_run_saliency_with_benchmark(self):
  142. """Test case when argument benchmarkers is parsed."""
  143. res = []
  144. def mock_summary_add_value(_, plugin, name, value):
  145. res.append((plugin, name, value))
  146. runner = ImageClassificationRunner(summary_dir=self.summary_dir, data=(self.dataset, self.labels),
  147. network=self.network, activation_fn=self.activation_fn)
  148. with patch.object(SummaryRecord, "add_value", mock_summary_add_value), \
  149. patch.object(Gradient, "__call__", mock_gradient_call), \
  150. patch.object(Faithfulness, "evaluate", mock_faithfulness_evaluate):
  151. runner.register_saliency(self.explainer, self.benchmarkers)
  152. runner.run()
  153. idx = 3 * NUMDATA + 1 # start index of benchmark data
  154. assert res[idx][0] == "explainer"
  155. assert res[idx][1] == "benchmark"
  156. assert abs(res[idx][2].benchmark[0].total_score - 2 / 3 * CONST) < 1e-6
  157. diff = np.array(res[idx][2].benchmark[0].label_score) - np.array([i * CONST for i in range(NUMDATA)])
  158. assert np.max(np.abs(diff)) < 1e-6
  159. def teardown_method(self):
  160. shutil.rmtree(self.summary_dir)