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.

saliency_encap.py 6.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  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. """Saliency map encapsulator."""
  16. import copy
  17. from mindinsight.utils.exceptions import ParamValueError
  18. from mindinsight.explainer.encapsulator.explain_data_encap import ExplainDataEncap
  19. def _sort_key_min_confidence(sample):
  20. """Samples sort key by the min. confidence."""
  21. min_confidence = float("+inf")
  22. for inference in sample["inferences"]:
  23. if inference["confidence"] < min_confidence:
  24. min_confidence = inference["confidence"]
  25. return min_confidence
  26. def _sort_key_max_confidence(sample):
  27. """Samples sort key by the max. confidence."""
  28. max_confidence = float("-inf")
  29. for inference in sample["inferences"]:
  30. if inference["confidence"] > max_confidence:
  31. max_confidence = inference["confidence"]
  32. return max_confidence
  33. def _sort_key_min_confidence_sd(sample):
  34. """Samples sort key by the min. confidence_sd."""
  35. min_confidence_sd = float("+inf")
  36. for inference in sample["inferences"]:
  37. confidence_sd = inference.get("confidence_sd", float("+inf"))
  38. if confidence_sd < min_confidence_sd:
  39. min_confidence_sd = confidence_sd
  40. return min_confidence_sd
  41. def _sort_key_max_confidence_sd(sample):
  42. """Samples sort key by the max. confidence_sd."""
  43. max_confidence_sd = float("-inf")
  44. for inference in sample["inferences"]:
  45. confidence_sd = inference.get("confidence_sd", float("-inf"))
  46. if confidence_sd > max_confidence_sd:
  47. max_confidence_sd = confidence_sd
  48. return max_confidence_sd
  49. class SaliencyEncap(ExplainDataEncap):
  50. """Saliency map encapsulator."""
  51. def __init__(self, image_url_formatter, *args, **kwargs):
  52. super().__init__(*args, **kwargs)
  53. self._image_url_formatter = image_url_formatter
  54. def query_saliency_maps(self,
  55. train_id,
  56. labels,
  57. explainers,
  58. limit,
  59. offset,
  60. sorted_name,
  61. sorted_type):
  62. """
  63. Query saliency maps.
  64. Args:
  65. train_id (str): Job ID.
  66. labels (list[str]): Label filter.
  67. explainers (list[str]): Explainers of saliency maps to be shown.
  68. limit (int): Max. no. of items to be returned.
  69. offset (int): Page offset.
  70. sorted_name (str): Field to be sorted.
  71. sorted_type (str): Sorting order, 'ascending' or 'descending'.
  72. Returns:
  73. tuple[int, list[dict]], total no. of samples after filtering and
  74. list of sample result.
  75. """
  76. job = self.job_manager.get_job(train_id)
  77. if job is None:
  78. return 0, None
  79. samples = copy.deepcopy(job.get_all_samples())
  80. if labels:
  81. filtered = []
  82. for sample in samples:
  83. has_label = False
  84. for label in sample["labels"]:
  85. if label in labels:
  86. has_label = True
  87. break
  88. if has_label:
  89. filtered.append(sample)
  90. samples = filtered
  91. reverse = sorted_type == "descending"
  92. if sorted_name == "confidence":
  93. if reverse:
  94. samples.sort(key=_sort_key_max_confidence, reverse=reverse)
  95. else:
  96. samples.sort(key=_sort_key_min_confidence, reverse=reverse)
  97. elif sorted_name == "uncertainty":
  98. if not job.uncertainty_enabled:
  99. raise ParamValueError("Uncertainty is not enabled, sorted_name cannot be 'uncertainty'")
  100. if reverse:
  101. samples.sort(key=_sort_key_max_confidence_sd, reverse=reverse)
  102. else:
  103. samples.sort(key=_sort_key_min_confidence_sd, reverse=reverse)
  104. elif sorted_name != "":
  105. raise ParamValueError("sorted_name")
  106. sample_infos = []
  107. obj_offset = offset*limit
  108. count = len(samples)
  109. end = count
  110. if obj_offset + limit < end:
  111. end = obj_offset + limit
  112. for i in range(obj_offset, end):
  113. sample = samples[i]
  114. sample_infos.append(self._touch_sample(sample, job, explainers))
  115. return count, sample_infos
  116. def _touch_sample(self, sample, job, explainers):
  117. """
  118. Final editing the sample info.
  119. Args:
  120. sample (dict): Sample info.
  121. job (ExplainJob): Explain job.
  122. explainers (list[str]): Explainer names.
  123. Returns:
  124. dict, the edited sample info.
  125. """
  126. sample["image"] = self._get_image_url(job.train_id, sample['image'], "original")
  127. for inference in sample["inferences"]:
  128. new_list = []
  129. for saliency_map in inference["saliency_maps"]:
  130. if explainers and saliency_map["explainer"] not in explainers:
  131. continue
  132. saliency_map["overlay"] = self._get_image_url(job.train_id, saliency_map['overlay'], "overlay")
  133. new_list.append(saliency_map)
  134. inference["saliency_maps"] = new_list
  135. return sample
  136. def _get_image_url(self, train_id, image_path, image_type):
  137. """Returns image's url."""
  138. if self._image_url_formatter is None:
  139. return image_path
  140. return self._image_url_formatter(train_id, image_path, image_type)