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 4.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  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.explainer.encapsulator.explain_data_encap import ExplainDataEncap
  18. def _sort_key_confidence(sample):
  19. """Samples sort key by the max. confidence."""
  20. max_confid = None
  21. for inference in sample["inferences"]:
  22. if max_confid is None or inference["confidence"] > max_confid:
  23. max_confid = inference["confidence"]
  24. return max_confid
  25. class SaliencyEncap(ExplainDataEncap):
  26. """Saliency map encapsulator."""
  27. def __init__(self, image_url_formatter, *args, **kwargs):
  28. super().__init__(*args, **kwargs)
  29. self._image_url_formatter = image_url_formatter
  30. def query_saliency_maps(self,
  31. train_id,
  32. labels,
  33. explainers,
  34. limit,
  35. offset,
  36. sorted_name,
  37. sorted_type):
  38. """
  39. Query saliency maps.
  40. Args:
  41. train_id (str): Job ID.
  42. labels (List[str]): Label filter.
  43. explainers (List[str]): Explainers of saliency maps to be shown.
  44. limit (int): Max. no. of items to be returned.
  45. offset (int): Page offset.
  46. sorted_name (str): Field to be sorted.
  47. sorted_type (str): Sorting order, 'ascending' or 'descending'.
  48. Returns:
  49. Tuple[int, List[dict]], total no. of samples after filtering and
  50. list of sample result.
  51. """
  52. job = self.job_manager.get_job(train_id)
  53. if job is None:
  54. return 0, None
  55. samples = copy.deepcopy(job.get_all_samples())
  56. if labels:
  57. filtered = []
  58. for sample in samples:
  59. has_label = False
  60. for label in sample["labels"]:
  61. if label in labels:
  62. has_label = True
  63. break
  64. if has_label:
  65. filtered.append(sample)
  66. samples = filtered
  67. reverse = sorted_type == "descending"
  68. if sorted_name == "confidence":
  69. samples.sort(key=_sort_key_confidence, reverse=reverse)
  70. sample_infos = []
  71. obj_offset = offset*limit
  72. count = len(samples)
  73. end = count
  74. if obj_offset + limit < end:
  75. end = obj_offset + limit
  76. for i in range(obj_offset, end):
  77. sample = samples[i]
  78. sample_infos.append(self._touch_sample(sample, job, explainers))
  79. return count, sample_infos
  80. def _touch_sample(self, sample, job, explainers):
  81. """
  82. Final editing the sample info.
  83. Args:
  84. sample (dict): Sample info.
  85. job (ExplainJob): Explain job.
  86. explainers (List[str]): Explainer names.
  87. Returns:
  88. Dict, the edited sample info.
  89. """
  90. sample["image"] = self._get_image_url(job.train_id, sample["id"], "original")
  91. for inference in sample["inferences"]:
  92. new_list = []
  93. for saliency_map in inference["saliency_maps"]:
  94. if explainers and saliency_map["explainer"] not in explainers:
  95. continue
  96. saliency_map["overlay"] = self._get_image_url(job.train_id,
  97. saliency_map["overlay"],
  98. "overlay")
  99. new_list.append(saliency_map)
  100. inference["saliency_maps"] = new_list
  101. return sample
  102. def _get_image_url(self, train_id, image_id, image_type):
  103. """Returns image's url."""
  104. if self._image_url_formatter is None:
  105. return image_id
  106. return self._image_url_formatter(train_id, image_id, image_type)