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_loader.py 25 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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. """ExplainLoader."""
  16. import math
  17. import os
  18. import re
  19. from collections import defaultdict
  20. from datetime import datetime
  21. from typing import Dict, Iterable, List, Optional, Union
  22. from mindinsight.explainer.common.enums import ExplainFieldsEnum
  23. from mindinsight.explainer.common.log import logger
  24. from mindinsight.explainer.manager.explain_parser import ExplainParser
  25. from mindinsight.datavisual.data_access.file_handler import FileHandler
  26. from mindinsight.datavisual.common.exceptions import TrainJobNotExistError
  27. from mindinsight.utils.exceptions import ParamValueError, UnknownError
  28. _NAN_CONSTANT = 'NaN'
  29. _NUM_DIGITS = 6
  30. _EXPLAIN_FIELD_NAMES = [
  31. ExplainFieldsEnum.SAMPLE_ID,
  32. ExplainFieldsEnum.BENCHMARK,
  33. ExplainFieldsEnum.METADATA,
  34. ]
  35. _SAMPLE_FIELD_NAMES = [
  36. ExplainFieldsEnum.GROUND_TRUTH_LABEL,
  37. ExplainFieldsEnum.INFERENCE,
  38. ExplainFieldsEnum.EXPLANATION,
  39. ]
  40. def _round(score):
  41. """Take round of a number to given precision."""
  42. try:
  43. return round(score, _NUM_DIGITS)
  44. except TypeError:
  45. return score
  46. class ExplainLoader:
  47. """ExplainLoader which manage the record in the summary file."""
  48. def __init__(self,
  49. loader_id: str,
  50. summary_dir: str):
  51. self._parser = ExplainParser(summary_dir)
  52. self._loader_info = {
  53. 'loader_id': loader_id,
  54. 'summary_dir': summary_dir,
  55. 'create_time': os.stat(summary_dir).st_ctime,
  56. 'update_time': os.stat(summary_dir).st_mtime,
  57. 'query_time': os.stat(summary_dir).st_ctime,
  58. 'uncertainty_enabled': False,
  59. }
  60. self._samples = defaultdict(dict)
  61. self._metadata = {'explainers': [], 'metrics': [], 'labels': []}
  62. self._benchmark = {'explainer_score': defaultdict(dict), 'label_score': defaultdict(dict)}
  63. @property
  64. def all_classes(self) -> List[Dict]:
  65. """
  66. Return a list of detailed label information, including label id, label name and sample count of each label.
  67. Returns:
  68. list[dict], a list of dict, each dict contains:
  69. - id (int): label id
  70. - label (str): label name
  71. - sample_count (int): number of samples for each label
  72. """
  73. sample_count_per_label = defaultdict(int)
  74. samples_copy = self._samples.copy()
  75. for sample in samples_copy.values():
  76. if sample.get('image', False) and sample.get('ground_truth_label', False):
  77. for label in sample['ground_truth_label']:
  78. sample_count_per_label[label] += 1
  79. all_classes_return = []
  80. for label_id, label_name in enumerate(self._metadata['labels']):
  81. single_info = {
  82. 'id': label_id,
  83. 'label': label_name,
  84. 'sample_count': sample_count_per_label[label_id]
  85. }
  86. all_classes_return.append(single_info)
  87. return all_classes_return
  88. @property
  89. def query_time(self) -> float:
  90. """Return query timestamp of explain loader."""
  91. return self._loader_info['query_time']
  92. @query_time.setter
  93. def query_time(self, new_time: Union[datetime, float]):
  94. """
  95. Update the query_time timestamp manually.
  96. Args:
  97. new_time (datetime.datetime or float): Updated query_time for the explain loader.
  98. """
  99. if isinstance(new_time, datetime):
  100. self._loader_info['query_time'] = new_time.timestamp()
  101. elif isinstance(new_time, float):
  102. self._loader_info['query_time'] = new_time
  103. else:
  104. raise TypeError('new_time should have type of datetime.datetime or float, but receive {}'
  105. .format(type(new_time)))
  106. @property
  107. def create_time(self) -> float:
  108. """Return the create timestamp of summary file."""
  109. return self._loader_info['create_time']
  110. @create_time.setter
  111. def create_time(self, new_time: Union[datetime, float]):
  112. """
  113. Update the create_time manually
  114. Args:
  115. new_time (datetime.datetime or float): Updated create_time of summary_file.
  116. """
  117. if isinstance(new_time, datetime):
  118. self._loader_info['create_time'] = new_time.timestamp()
  119. elif isinstance(new_time, float):
  120. self._loader_info['create_time'] = new_time
  121. else:
  122. raise TypeError('new_time should have type of datetime.datetime or float, but receive {}'
  123. .format(type(new_time)))
  124. @property
  125. def explainers(self) -> List[str]:
  126. """Return a list of explainer names recorded in the summary file."""
  127. return self._metadata['explainers']
  128. @property
  129. def explainer_scores(self) -> List[Dict]:
  130. """
  131. Return evaluation results for every explainer.
  132. Returns:
  133. list[dict], A list of evaluation results of each explainer. Each item contains:
  134. - explainer (str): Name of evaluated explainer.
  135. - evaluations (list[dict]): A list of evlauation results by different metrics.
  136. - class_scores (list[dict]): A list of evaluation results on different labels.
  137. Each item in the evaluations contains:
  138. - metric (str): name of metric method
  139. - score (float): evaluation result
  140. Each item in the class_scores contains:
  141. - label (str): Name of label
  142. - evaluations (list[dict]): A list of evalution results on different labels by different metrics.
  143. Each item in evaluations contains:
  144. - metric (str): Name of metric method
  145. - score (float): Evaluation scores of explainer on specific label by the metric.
  146. """
  147. explainer_scores = []
  148. for explainer, explainer_score_on_metric in self._benchmark['explainer_score'].copy().items():
  149. metric_scores = [{'metric': metric, 'score': _round(score)}
  150. for metric, score in explainer_score_on_metric.items()]
  151. label_scores = []
  152. for label, label_score_on_metric in self._benchmark['label_score'][explainer].copy().items():
  153. score_of_single_label = {
  154. 'label': self._metadata['labels'][label],
  155. 'evaluations': [
  156. {'metric': metric, 'score': _round(score)} for metric, score in label_score_on_metric.items()
  157. ],
  158. }
  159. label_scores.append(score_of_single_label)
  160. explainer_scores.append({
  161. 'explainer': explainer,
  162. 'evaluations': metric_scores,
  163. 'class_scores': label_scores,
  164. })
  165. return explainer_scores
  166. @property
  167. def labels(self) -> List[str]:
  168. """Return the label recorded in the summary."""
  169. return self._metadata['labels']
  170. @property
  171. def metrics(self) -> List[str]:
  172. """Return a list of metric names recorded in the summary file."""
  173. return self._metadata['metrics']
  174. @property
  175. def min_confidence(self) -> Optional[float]:
  176. """Return minimum confidence used to filter the predicted labels."""
  177. return None
  178. @property
  179. def sample_count(self) -> int:
  180. """
  181. Return total number of samples in the loader.
  182. Since the loader only return available samples (i.e. with original image data and ground_truth_label loaded in
  183. cache), the returned count only takes the available samples into account.
  184. Return:
  185. int, total number of available samples in the loading job.
  186. """
  187. sample_count = 0
  188. samples_copy = self._samples.copy()
  189. for sample in samples_copy.values():
  190. if sample.get('image', False) and sample.get('ground_truth_label', False):
  191. sample_count += 1
  192. return sample_count
  193. @property
  194. def samples(self) -> List[Dict]:
  195. """Return the information of all samples in the job."""
  196. return self.get_all_samples()
  197. @property
  198. def train_id(self) -> str:
  199. """Return ID of explain loader."""
  200. return self._loader_info['loader_id']
  201. @property
  202. def uncertainty_enabled(self):
  203. """Whethter uncertainty is enabled."""
  204. return self._loader_info['uncertainty_enabled']
  205. @property
  206. def update_time(self) -> float:
  207. """Return latest modification timestamp of summary file."""
  208. return self._loader_info['update_time']
  209. @update_time.setter
  210. def update_time(self, new_time: Union[datetime, float]):
  211. """
  212. Update the update_time manually.
  213. Args:
  214. new_time stamp (datetime.datetime or float): Updated time for the summary file.
  215. """
  216. if isinstance(new_time, datetime):
  217. self._loader_info['update_time'] = new_time.timestamp()
  218. elif isinstance(new_time, float):
  219. self._loader_info['update_time'] = new_time
  220. else:
  221. raise TypeError('new_time should have type of datetime.datetime or float, but receive {}'
  222. .format(type(new_time)))
  223. def load(self):
  224. """Start loading data from the latest summary file to the loader."""
  225. filenames = []
  226. for filename in FileHandler.list_dir(self._loader_info['summary_dir']):
  227. if FileHandler.is_file(FileHandler.join(self._loader_info['summary_dir'], filename)):
  228. filenames.append(filename)
  229. filenames = ExplainLoader._filter_files(filenames)
  230. if not filenames:
  231. raise TrainJobNotExistError('No summary file found in %s, explain job will be delete.'
  232. % self._loader_info['summary_dir'])
  233. is_end = False
  234. while not is_end:
  235. is_clean, is_end, event_dict = self._parser.parse_explain(filenames)
  236. if is_clean:
  237. logger.info('Summary file in %s update, reload the data in the summary.',
  238. self._loader_info['summary_dir'])
  239. self._clear_job()
  240. if event_dict:
  241. self._import_data_from_event(event_dict)
  242. def get_all_samples(self) -> List[Dict]:
  243. """
  244. Return a list of sample information cachced in the explain job
  245. Returns:
  246. sample_list (List[SampleObj]): a list of sample objects, each object
  247. consists of:
  248. - id (int): sample id
  249. - name (str): basename of image
  250. - labels (list[str]): list of labels
  251. - inferences list[dict])
  252. """
  253. returned_samples = []
  254. samples_copy = self._samples.copy()
  255. for sample_id, sample_info in samples_copy.items():
  256. if not sample_info.get('image', False) and not sample_info.get('ground_truth_label', False):
  257. continue
  258. returned_sample = {
  259. 'id': sample_id,
  260. 'name': str(sample_id),
  261. 'image': sample_info['image'],
  262. 'labels': [self._metadata['labels'][i] for i in sample_info['ground_truth_label']],
  263. }
  264. # Check whether the sample has valid label-prob pairs.
  265. if not ExplainLoader._is_inference_valid(sample_info):
  266. continue
  267. inferences = {}
  268. for label, prob in zip(sample_info['ground_truth_label'] + sample_info['predicted_label'],
  269. sample_info['ground_truth_prob'] + sample_info['predicted_prob']):
  270. inferences[label] = {
  271. 'label': self._metadata['labels'][label],
  272. 'confidence': _round(prob),
  273. 'saliency_maps': []
  274. }
  275. if sample_info['ground_truth_prob_sd'] or sample_info['predicted_prob_sd']:
  276. for label, std, low, high in zip(
  277. sample_info['ground_truth_label'] + sample_info['predicted_label'],
  278. sample_info['ground_truth_prob_sd'] + sample_info['predicted_prob_sd'],
  279. sample_info['ground_truth_prob_itl95_low'] + sample_info['predicted_prob_itl95_low'],
  280. sample_info['ground_truth_prob_itl95_hi'] + sample_info['predicted_prob_itl95_hi']
  281. ):
  282. inferences[label]['confidence_sd'] = _round(std)
  283. inferences[label]['confidence_itl95'] = [_round(low), _round(high)]
  284. for explainer, label_heatmap_path_dict in sample_info['explanation'].items():
  285. for label, heatmap_path in label_heatmap_path_dict.items():
  286. if label in inferences:
  287. inferences[label]['saliency_maps'].append({'explainer': explainer, 'overlay': heatmap_path})
  288. returned_sample['inferences'] = list(inferences.values())
  289. returned_samples.append(returned_sample)
  290. return returned_samples
  291. def _import_data_from_event(self, event_dict: Dict):
  292. """Parse and import data from the event data."""
  293. if 'metadata' not in event_dict and self._is_metadata_empty():
  294. raise ParamValueError('metadata is imcomplete, should write metadata first in the summary.')
  295. for tag, event in event_dict.items():
  296. if tag == ExplainFieldsEnum.METADATA.value:
  297. self._import_metadata_from_event(event.metadata)
  298. elif tag == ExplainFieldsEnum.BENCHMARK.value:
  299. self._import_benchmark_from_event(event.benchmark)
  300. elif tag == ExplainFieldsEnum.SAMPLE_ID.value:
  301. self._import_sample_from_event(event)
  302. else:
  303. logger.info('Unknown ExplainField: %s.', tag)
  304. def _is_metadata_empty(self):
  305. """Check whether metadata is completely loaded first."""
  306. if not self._metadata['labels']:
  307. return True
  308. return False
  309. def _import_metadata_from_event(self, metadata_event):
  310. """Import the metadata from event into loader."""
  311. def take_union(existed_list, imported_data):
  312. """Take union of existed_list and imported_data."""
  313. if isinstance(imported_data, Iterable):
  314. for sample in imported_data:
  315. if sample not in existed_list:
  316. existed_list.append(sample)
  317. take_union(self._metadata['explainers'], metadata_event.explain_method)
  318. take_union(self._metadata['metrics'], metadata_event.benchmark_method)
  319. take_union(self._metadata['labels'], metadata_event.label)
  320. def _import_benchmark_from_event(self, benchmarks):
  321. """
  322. Parse the benchmark event.
  323. Benchmark data are separeted into 'explainer_score' and 'label_score'. 'explainer_score' contains overall
  324. evaluation results of each explainer by different metrics, while 'label_score' additionally devides the results
  325. w.r.t different labels.
  326. The structure of self._benchmark['explainer_score'] demonstrates below:
  327. {
  328. explainer_1: {metric_name_1: score_1, ...},
  329. explainer_2: {metric_name_1: score_1, ...},
  330. ...
  331. }
  332. The structure of self._benchmark['label_score'] is:
  333. {
  334. explainer_1: {label_id: {metric_1: score_1, metric_2: score_2, ...}, ...},
  335. explainer_2: {label_id: {metric_1: score_1, metric_2: score_2, ...}, ...},
  336. ...
  337. }
  338. Args:
  339. benchmarks (benchmark_container): Parsed benchmarks data from summary file.
  340. """
  341. explainer_score = self._benchmark['explainer_score']
  342. label_score = self._benchmark['label_score']
  343. for benchmark in benchmarks:
  344. explainer = benchmark.explain_method
  345. metric = benchmark.benchmark_method
  346. metric_score = benchmark.total_score
  347. label_score_event = benchmark.label_score
  348. explainer_score[explainer][metric] = _NAN_CONSTANT if math.isnan(metric_score) else metric_score
  349. new_label_score_dict = ExplainLoader._score_event_to_dict(label_score_event, metric)
  350. for label, scores_of_metric in new_label_score_dict.items():
  351. if label not in label_score[explainer]:
  352. label_score[explainer][label] = {}
  353. label_score[explainer][label].update(scores_of_metric)
  354. def _import_sample_from_event(self, sample):
  355. """
  356. Parse the sample event.
  357. Detailed data of each sample are store in self._samples, identified by sample_id. Each sample data are stored
  358. in the following structure.
  359. - ground_truth_labels (list[int]): A list of ground truth labels of the sample.
  360. - ground_truth_probs (list[float]): A list of confidences of ground-truth label from black-box model.
  361. - predicted_labels (list[int]): A list of predicted labels from the black-box model.
  362. - predicted_probs (list[int]): A list of confidences w.r.t the predicted labels.
  363. - explanations (dict): Explanations is a dictionary where the each explainer name mapping to a dictionary
  364. of saliency maps. The structure of explanations demonstrates below:
  365. {
  366. explainer_name_1: {label_1: saliency_id_1, label_2: saliency_id_2, ...},
  367. explainer_name_2: {label_1: saliency_id_1, label_2: saliency_id_2, ...},
  368. ...
  369. }
  370. """
  371. if getattr(sample, 'sample_id', None) is None:
  372. raise ParamValueError('sample_event has no sample_id')
  373. sample_id = sample.sample_id
  374. samples_copy = self._samples.copy()
  375. if sample_id not in samples_copy:
  376. self._samples[sample_id] = {
  377. 'ground_truth_label': [],
  378. 'ground_truth_prob': [],
  379. 'ground_truth_prob_sd': [],
  380. 'ground_truth_prob_itl95_low': [],
  381. 'ground_truth_prob_itl95_hi': [],
  382. 'predicted_label': [],
  383. 'predicted_prob': [],
  384. 'predicted_prob_sd': [],
  385. 'predicted_prob_itl95_low': [],
  386. 'predicted_prob_itl95_hi': [],
  387. 'explanation': defaultdict(dict)
  388. }
  389. if sample.image_path:
  390. self._samples[sample_id]['image'] = sample.image_path
  391. for tag in _SAMPLE_FIELD_NAMES:
  392. try:
  393. if tag == ExplainFieldsEnum.GROUND_TRUTH_LABEL:
  394. self._samples[sample_id]['ground_truth_label'].extend(list(sample.ground_truth_label))
  395. elif tag == ExplainFieldsEnum.INFERENCE:
  396. self._import_inference_from_event(sample, sample_id)
  397. else:
  398. self._import_explanation_from_event(sample, sample_id)
  399. except UnknownError as ex:
  400. logger.warning("Parse %s data failed within image related data, detail: %r", tag, str(ex))
  401. def _import_inference_from_event(self, event, sample_id):
  402. """Parse the inference event."""
  403. inference = event.inference
  404. self._samples[sample_id]['ground_truth_prob'].extend(list(inference.ground_truth_prob))
  405. self._samples[sample_id]['ground_truth_prob_sd'].extend(list(inference.ground_truth_prob_sd))
  406. self._samples[sample_id]['ground_truth_prob_itl95_low'].extend(list(inference.ground_truth_prob_itl95_low))
  407. self._samples[sample_id]['ground_truth_prob_itl95_hi'].extend(list(inference.ground_truth_prob_itl95_hi))
  408. self._samples[sample_id]['predicted_label'].extend(list(inference.predicted_label))
  409. self._samples[sample_id]['predicted_prob'].extend(list(inference.predicted_prob))
  410. self._samples[sample_id]['predicted_prob_sd'].extend(list(inference.predicted_prob_sd))
  411. self._samples[sample_id]['predicted_prob_itl95_low'].extend(list(inference.predicted_prob_itl95_low))
  412. self._samples[sample_id]['predicted_prob_itl95_hi'].extend(list(inference.predicted_prob_itl95_hi))
  413. if self._samples[sample_id]['ground_truth_prob_sd'] or self._samples[sample_id]['predicted_prob_sd']:
  414. self._loader_info['uncertainty_enabled'] = True
  415. def _import_explanation_from_event(self, event, sample_id):
  416. """Parse the explanation event."""
  417. if self._samples[sample_id]['explanation'] is None:
  418. self._samples[sample_id]['explanation'] = defaultdict(dict)
  419. sample_explanation = self._samples[sample_id]['explanation']
  420. for explanation_item in event.explanation:
  421. explainer = explanation_item.explain_method
  422. label = explanation_item.label
  423. sample_explanation[explainer][label] = explanation_item.heatmap_path
  424. def _clear_job(self):
  425. """Clear the cached data and update the time info of the loader."""
  426. self._samples.clear()
  427. self._loader_info['create_time'] = os.stat(self._loader_info['summary_dir']).st_ctime
  428. self._loader_info['update_time'] = os.stat(self._loader_info['summary_dir']).st_mtime
  429. self._loader_info['query_time'] = max(self._loader_info['update_time'], self._loader_info['query_time'])
  430. def clear_inner_dict(outer_dict):
  431. """Clear the inner structured data of the given dict."""
  432. for item in outer_dict.values():
  433. item.clear()
  434. map(clear_inner_dict, [self._metadata, self._benchmark])
  435. @staticmethod
  436. def _filter_files(filenames):
  437. """
  438. Gets a list of summary files.
  439. Args:
  440. filenames (list[str]): File name list, like [filename1, filename2].
  441. Returns:
  442. list[str], filename list.
  443. """
  444. return list(filter(
  445. lambda filename: (re.search(r'summary\.\d+', filename) and filename.endswith("_explain")), filenames))
  446. @staticmethod
  447. def _is_inference_valid(sample):
  448. """
  449. Check whether the inference data is empty or have the same length.
  450. If probs have different length with the labels, it can be confusing when assigning each prob to label.
  451. '_is_inference_valid' returns True only when the data size of match to each other. Note that prob data could be
  452. empty, so empty prob will pass the check.
  453. """
  454. ground_truth_len = len(sample['ground_truth_label'])
  455. for name in ['ground_truth_prob', 'ground_truth_prob_sd',
  456. 'ground_truth_prob_itl95_low', 'ground_truth_prob_itl95_hi']:
  457. if sample[name] and len(sample[name]) != ground_truth_len:
  458. logger.info('Length of %s not match the ground_truth_label. Length of ground_truth_label: %d,'
  459. 'length of %s: %d', name, ground_truth_len, name, len(sample[name]))
  460. return False
  461. predicted_len = len(sample['predicted_label'])
  462. for name in ['predicted_prob', 'predicted_prob_sd',
  463. 'predicted_prob_itl95_low', 'predicted_prob_itl95_hi']:
  464. if sample[name] and len(sample[name]) != predicted_len:
  465. logger.info('Length of %s not match the predicted_labels. Length of predicted_label: %d,'
  466. 'length of %s: %d', name, predicted_len, name, len(sample[name]))
  467. return False
  468. return True
  469. @staticmethod
  470. def _score_event_to_dict(label_score_event, metric) -> Dict:
  471. """Transfer metric scores per label to pre-defined structure."""
  472. new_label_score_dict = defaultdict(dict)
  473. for label_id, label_score in enumerate(label_score_event):
  474. new_label_score_dict[label_id][metric] = _NAN_CONSTANT if math.isnan(label_score) else label_score
  475. return new_label_score_dict