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.

explain_job.py 14 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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. """ExplainJob."""
  16. import os
  17. from collections import defaultdict
  18. from datetime import datetime
  19. from typing import Union
  20. from mindinsight.explainer.common.enums import PluginNameEnum
  21. from mindinsight.explainer.common.log import logger
  22. from mindinsight.explainer.manager.explain_parser import _ExplainParser
  23. from mindinsight.explainer.manager.event_parse import EventParser
  24. from mindinsight.datavisual.data_access.file_handler import FileHandler
  25. from mindinsight.datavisual.common.exceptions import TrainJobNotExistError
  26. _NUM_DIGIT = 7
  27. class ExplainJob:
  28. """ExplainJob which manage the record in the summary file."""
  29. def __init__(self,
  30. job_id: str,
  31. summary_dir: str,
  32. create_time: float,
  33. latest_update_time: float):
  34. self._job_id = job_id
  35. self._summary_dir = summary_dir
  36. self._parser = _ExplainParser(summary_dir)
  37. self._event_parser = EventParser(self)
  38. self._latest_update_time = latest_update_time
  39. self._create_time = create_time
  40. self._uncertainty_enabled = False
  41. self._labels = []
  42. self._metrics = []
  43. self._explainers = []
  44. self._samples_info = {}
  45. self._labels_info = {}
  46. self._explainer_score_dict = defaultdict(list)
  47. self._label_score_dict = defaultdict(dict)
  48. @property
  49. def all_classes(self):
  50. """
  51. Return a list of label info
  52. Returns:
  53. class_objs (List[ClassObj]): a list of class_objects, each object
  54. contains:
  55. - id (int): label id
  56. - label (str): label name
  57. - sample_count (int): number of samples for each label
  58. """
  59. all_classes_return = []
  60. for label_id, label_info in self._labels_info.items():
  61. single_info = {
  62. 'id': label_id,
  63. 'label': label_info['label'],
  64. 'sample_count': len(label_info['sample_ids'])}
  65. all_classes_return.append(single_info)
  66. return all_classes_return
  67. @property
  68. def explainers(self):
  69. """
  70. Return a list of explainer names
  71. Returns:
  72. list(str), explainer names
  73. """
  74. return self._explainers
  75. @property
  76. def explainer_scores(self):
  77. """Return evaluation results for every explainer."""
  78. merged_scores = []
  79. for explainer, explainer_score_on_metric in self._explainer_score_dict.items():
  80. label_scores = []
  81. for label, label_score_on_metric in self._label_score_dict[explainer].items():
  82. score_single_label = {
  83. 'label': self._labels[label],
  84. 'evaluations': label_score_on_metric,
  85. }
  86. label_scores.append(score_single_label)
  87. merged_scores.append({
  88. 'explainer': explainer,
  89. 'evaluations': explainer_score_on_metric,
  90. 'class_scores': label_scores,
  91. })
  92. return merged_scores
  93. @property
  94. def sample_count(self):
  95. """
  96. Return total number of samples in the job.
  97. Return:
  98. int, total number of samples
  99. """
  100. return len(self._samples_info)
  101. @property
  102. def train_id(self):
  103. """
  104. Return ID of explain job
  105. Returns:
  106. str, id of ExplainJob object
  107. """
  108. return self._job_id
  109. @property
  110. def metrics(self):
  111. """
  112. Return a list of metric names
  113. Returns:
  114. list(str), metric names
  115. """
  116. return self._metrics
  117. @property
  118. def min_confidence(self):
  119. """
  120. Return minimum confidence
  121. Returns:
  122. min_confidence (float):
  123. """
  124. return None
  125. @property
  126. def uncertainty_enabled(self):
  127. return self._uncertainty_enabled
  128. @property
  129. def create_time(self):
  130. """
  131. Return the create time of summary file
  132. Returns:
  133. creation timestamp (float)
  134. """
  135. return self._create_time
  136. @property
  137. def labels(self):
  138. """Return the label contained in the job."""
  139. return self._labels
  140. @property
  141. def latest_update_time(self):
  142. """
  143. Return last modification time stamp of summary file.
  144. Returns:
  145. float, last_modification_time stamp
  146. """
  147. return self._latest_update_time
  148. @latest_update_time.setter
  149. def latest_update_time(self, new_time: Union[float, datetime]):
  150. """
  151. Update the latest_update_time timestamp manually.
  152. Args:
  153. new_time stamp (union[float, datetime]): updated time for the job
  154. """
  155. if isinstance(new_time, datetime):
  156. self._latest_update_time = new_time.timestamp()
  157. elif isinstance(new_time, float):
  158. self._latest_update_time = new_time
  159. else:
  160. raise TypeError('new_time should have type of float or datetime')
  161. @property
  162. def loader_id(self):
  163. """Return the job id."""
  164. return self._job_id
  165. @property
  166. def samples(self):
  167. """Return the information of all samples in the job."""
  168. return self._samples_info
  169. @staticmethod
  170. def get_create_time(file_path: str) -> float:
  171. """Return timestamp of create time of specific path."""
  172. create_time = os.stat(file_path).st_ctime
  173. return create_time
  174. @staticmethod
  175. def get_update_time(file_path: str) -> float:
  176. """Return timestamp of update time of specific path."""
  177. update_time = os.stat(file_path).st_mtime
  178. return update_time
  179. def _initialize_labels_info(self):
  180. """Initialize a dict for labels in the job."""
  181. if self._labels is None:
  182. logger.warning('No labels is provided in job %s', self._job_id)
  183. return
  184. for label_id, label in enumerate(self._labels):
  185. self._labels_info[label_id] = {'label': label,
  186. 'sample_ids': set()}
  187. def _explanation_to_dict(self, explanation):
  188. """Transfer the explanation from event to dict storage."""
  189. explain_info = {
  190. 'explainer': explanation.explain_method,
  191. 'overlay': explanation.heatmap_path,
  192. }
  193. return explain_info
  194. def _image_container_to_dict(self, sample_data):
  195. """Transfer the image container to dict storage."""
  196. has_uncertainty = False
  197. sample_id = sample_data.sample_id
  198. sample_info = {
  199. 'id': sample_id,
  200. 'image': sample_data.image_path,
  201. 'name': str(sample_id),
  202. 'labels': [self._labels_info[x]['label']
  203. for x in sample_data.ground_truth_label],
  204. 'inferences': []}
  205. ground_truth_labels = list(sample_data.ground_truth_label)
  206. ground_truth_probs = list(sample_data.inference.ground_truth_prob)
  207. predicted_labels = list(sample_data.inference.predicted_label)
  208. predicted_probs = list(sample_data.inference.predicted_prob)
  209. if sample_data.inference.predicted_prob_sd or sample_data.inference.ground_truth_prob_sd:
  210. ground_truth_prob_sds = list(sample_data.inference.ground_truth_prob_sd)
  211. ground_truth_prob_lows = list(sample_data.inference.ground_truth_prob_itl95_low)
  212. ground_truth_prob_his = list(sample_data.inference.ground_truth_prob_itl95_hi)
  213. predicted_prob_sds = list(sample_data.inference.predicted_prob_sd)
  214. predicted_prob_lows = list(sample_data.inference.predicted_prob_itl95_low)
  215. predicted_prob_his = list(sample_data.inference.predicted_prob_itl95_hi)
  216. has_uncertainty = True
  217. else:
  218. ground_truth_prob_sds = ground_truth_prob_lows = ground_truth_prob_his = None
  219. predicted_prob_sds = predicted_prob_lows = predicted_prob_his = None
  220. inference_info = {}
  221. for label, prob in zip(
  222. ground_truth_labels + predicted_labels,
  223. ground_truth_probs + predicted_probs):
  224. inference_info[label] = {
  225. 'label': self._labels_info[label]['label'],
  226. 'confidence': round(prob, _NUM_DIGIT),
  227. 'saliency_maps': []}
  228. if ground_truth_prob_sds or predicted_prob_sds:
  229. for label, sd, low, hi in zip(
  230. ground_truth_labels + predicted_labels,
  231. ground_truth_prob_sds + predicted_prob_sds,
  232. ground_truth_prob_lows + predicted_prob_lows,
  233. ground_truth_prob_his + predicted_prob_his):
  234. inference_info[label]['confidence_sd'] = sd
  235. inference_info[label]['confidence_itl95'] = [low, hi]
  236. if EventParser.is_attr_ready(sample_data, 'explanation'):
  237. for explanation in sample_data.explanation:
  238. explanation_dict = self._explanation_to_dict(explanation)
  239. inference_info[explanation.label]['saliency_maps'].append(explanation_dict)
  240. sample_info['inferences'] = list(inference_info.values())
  241. return sample_info, has_uncertainty
  242. def _import_sample(self, sample):
  243. """Add sample object of given sample id."""
  244. for label_id in sample.ground_truth_label:
  245. self._labels_info[label_id]['sample_ids'].add(sample.sample_id)
  246. sample_info, has_uncertainty = self._image_container_to_dict(sample)
  247. self._samples_info.update({sample_info['id']: sample_info})
  248. self._uncertainty_enabled |= has_uncertainty
  249. def get_all_samples(self):
  250. """
  251. Return a list of sample information cachced in the explain job
  252. Returns:
  253. sample_list (List[SampleObj]): a list of sample objects, each object
  254. consists of:
  255. - id (int): sample id
  256. - name (str): basename of image
  257. - labels (list[str]): list of labels
  258. - inferences list[dict])
  259. """
  260. samples_in_list = list(self._samples_info.values())
  261. return samples_in_list
  262. def _is_metadata_empty(self):
  263. """Check whether metadata is loaded first."""
  264. if not self._explainers or not self._metrics or not self._labels:
  265. return True
  266. return False
  267. def _import_data_from_event(self, event):
  268. """Parse and import data from the event data."""
  269. tags = {
  270. 'sample_id': PluginNameEnum.SAMPLE_ID,
  271. 'benchmark': PluginNameEnum.BENCHMARK,
  272. 'metadata': PluginNameEnum.METADATA
  273. }
  274. if 'metadata' not in event and self._is_metadata_empty():
  275. raise ValueError('metadata is empty, should write metadata first in the summary.')
  276. for tag in tags:
  277. if tag not in event:
  278. continue
  279. if tag == PluginNameEnum.SAMPLE_ID.value:
  280. sample_event = event[tag]
  281. sample_data = self._event_parser.parse_sample(sample_event)
  282. if sample_data is not None:
  283. self._import_sample(sample_data)
  284. continue
  285. if tag == PluginNameEnum.BENCHMARK.value:
  286. benchmark_event = event[tag].benchmark
  287. explain_score_dict, label_score_dict = EventParser.parse_benchmark(benchmark_event)
  288. self._update_benchmark(explain_score_dict, label_score_dict)
  289. elif tag == PluginNameEnum.METADATA.value:
  290. metadata_event = event[tag].metadata
  291. metadata = EventParser.parse_metadata(metadata_event)
  292. self._explainers, self._metrics, self._labels = metadata
  293. self._initialize_labels_info()
  294. def load(self):
  295. """
  296. Start loading data from parser.
  297. """
  298. valid_file_names = []
  299. for filename in FileHandler.list_dir(self._summary_dir):
  300. if FileHandler.is_file(
  301. FileHandler.join(self._summary_dir, filename)):
  302. valid_file_names.append(filename)
  303. if not valid_file_names:
  304. raise TrainJobNotExistError('No summary file found in %s, explain job will be delete.' % self._summary_dir)
  305. is_end = False
  306. while not is_end:
  307. is_clean, is_end, event = self._parser.parse_explain(valid_file_names)
  308. if is_clean:
  309. logger.info('Summary file in %s update, reload the clean the loaded data.', self._summary_dir)
  310. self._clean_job()
  311. if event:
  312. self._import_data_from_event(event)
  313. def _clean_job(self):
  314. """Clean the cached data in job."""
  315. self._latest_update_time = ExplainJob.get_update_time(self._summary_dir)
  316. self._create_time = ExplainJob.get_update_time(self._summary_dir)
  317. self._labels.clear()
  318. self._metrics.clear()
  319. self._explainers.clear()
  320. self._samples_info.clear()
  321. self._labels_info.clear()
  322. self._explainer_score_dict.clear()
  323. self._label_score_dict.clear()
  324. self._event_parser.clear()
  325. def _update_benchmark(self, explainer_score_dict, labels_score_dict):
  326. """Update the benchmark info."""
  327. for explainer, score in explainer_score_dict.items():
  328. self._explainer_score_dict[explainer].extend(score)
  329. for explainer, score in labels_score_dict.items():
  330. for label, score_of_label in score.items():
  331. self._label_score_dict[explainer][label] = (self._label_score_dict[explainer].get(label, [])
  332. + score_of_label)