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.2 kB

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