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.

hierarchical_occlusion_encap.py 4.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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. """Hierarchical Occlusion encapsulator."""
  16. from mindinsight.datavisual.common.exceptions import TrainJobNotExistError
  17. from mindinsight.explainer.common.enums import ExplanationKeys, ImageQueryTypes
  18. from mindinsight.explainer.encapsulator.explain_data_encap import ExplanationEncap
  19. class HierarchicalOcclusionEncap(ExplanationEncap):
  20. """Hierarchical occlusion encapsulator."""
  21. def query_hierarchical_occlusion(self,
  22. train_id,
  23. labels,
  24. limit,
  25. offset,
  26. sorted_name,
  27. sorted_type,
  28. prediction_types=None,
  29. drop_empty=True,
  30. ):
  31. """
  32. Query hierarchical occlusion results.
  33. Args:
  34. train_id (str): Job ID.
  35. labels (list[str]): Label filter.
  36. limit (int): Maximum number of items to be returned.
  37. offset (int): Page offset.
  38. sorted_name (str): Field to be sorted.
  39. sorted_type (str): Sorting order, 'ascending' or 'descending'.
  40. prediction_types (list[str]): Prediction types filter.
  41. drop_empty (bool): Whether to drop out the data without hoc data. Default: True.
  42. Returns:
  43. tuple[int, list[dict]], total number of samples after filtering and list of sample results.
  44. """
  45. job = self.job_manager.get_job(train_id)
  46. if job is None:
  47. raise TrainJobNotExistError(train_id)
  48. if drop_empty:
  49. samples = self._query_samples(job, labels, sorted_name, sorted_type, prediction_types,
  50. drop_type=ExplanationKeys.HOC.value)
  51. else:
  52. samples = self._query_samples(job, labels, sorted_name, sorted_type, prediction_types)
  53. sample_infos = []
  54. obj_offset = offset * limit
  55. count = len(samples)
  56. end = count
  57. if obj_offset + limit < end:
  58. end = obj_offset + limit
  59. for i in range(obj_offset, end):
  60. sample = samples[i]
  61. sample_infos.append(self._touch_sample(sample, job, drop_empty))
  62. return count, sample_infos
  63. def _touch_sample(self, sample, job, drop_empty):
  64. """
  65. Final edit on single sample info.
  66. Args:
  67. sample (dict): Sample info.
  68. job (ExplainManager): Explain job.
  69. drop_empty (bool): Whether to drop out inferences without HOC explanations.
  70. Returns:
  71. dict, the edited sample info.
  72. """
  73. original = ImageQueryTypes.ORIGINAL.value
  74. outcome = ImageQueryTypes.OUTCOME.value
  75. sample["image"] = self._get_image_url(job.train_id, sample["image"], original)
  76. inferences = sample["inferences"]
  77. i = 0 # init index for while loop
  78. while i < len(inferences):
  79. inference_item = inferences[i]
  80. if drop_empty and not inference_item[ExplanationKeys.HOC.value]:
  81. inferences.pop(i)
  82. continue
  83. new_list = []
  84. for idx, hoc_layer in enumerate(inference_item[ExplanationKeys.HOC.value]):
  85. hoc_layer[outcome] = self._get_image_url(job.train_id,
  86. f"{sample['id']}_{inference_item['label']}_{idx}.jpg",
  87. outcome)
  88. new_list.append(hoc_layer)
  89. inference_item[ExplanationKeys.HOC.value] = new_list
  90. i += 1
  91. return sample