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.

_image_classification_runner.py 46 kB

5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978
  1. # Copyright 2020-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. """Image Classification Runner."""
  16. import os
  17. import re
  18. import json
  19. from time import time
  20. import numpy as np
  21. from scipy.stats import beta
  22. from PIL import Image
  23. import mindspore as ms
  24. from mindspore import context
  25. from mindspore import log
  26. import mindspore.dataset as ds
  27. from mindspore.dataset import Dataset
  28. from mindspore.nn import Cell, SequentialCell
  29. from mindspore.ops.operations import ExpandDims
  30. from mindspore.train._utils import check_value_type
  31. from mindspore.train.summary._summary_adapter import _convert_image_format
  32. from mindspore.train.summary.summary_record import SummaryRecord
  33. from mindspore.train.summary_pb2 import Explain
  34. from mindspore.nn.probability.toolbox.uncertainty_evaluation import UncertaintyEvaluation
  35. from mindspore.explainer.benchmark import Localization
  36. from mindspore.explainer.benchmark._attribution.metric import AttributionMetric
  37. from mindspore.explainer.benchmark._attribution.metric import LabelSensitiveMetric
  38. from mindspore.explainer.benchmark._attribution.metric import LabelAgnosticMetric
  39. from mindspore.explainer.explanation import RISE
  40. from mindspore.explainer.explanation._attribution.attribution import Attribution
  41. from mindspore.explainer.explanation._counterfactual import hierarchical_occlusion as hoc
  42. _EXPAND_DIMS = ExpandDims()
  43. def _normalize(img_np):
  44. """Normalize the numpy image to the range of [0, 1]. """
  45. max_ = img_np.max()
  46. min_ = img_np.min()
  47. normed = (img_np - min_) / (max_ - min_).clip(min=1e-10)
  48. return normed
  49. def _np_to_image(img_np, mode):
  50. """Convert numpy array to PIL image."""
  51. return Image.fromarray(np.uint8(img_np * 255), mode=mode)
  52. class ImageClassificationRunner:
  53. """
  54. A high-level API for users to generate and store results of the explanation methods and the evaluation methods.
  55. Update in 2020.11: Adjust the storage structure and format of the data. Summary files generated by previous version
  56. will be deprecated and will not be supported in MindInsight of current version.
  57. Args:
  58. summary_dir (str): The directory path to save the summary files which store the generated results.
  59. data (tuple[Dataset, list[str]]): Tuple of dataset and the corresponding class label list. The dataset
  60. should provides [images], [images, labels] or [images, labels, bboxes] as columns. The label list must
  61. share the exact same length and order of the network outputs.
  62. network (Cell): The network(with logit outputs) to be explained.
  63. activation_fn (Cell): The activation layer that transforms logits to prediction probabilities. For
  64. single label classification tasks, `nn.Softmax` is usually applied. As for multi-label classification tasks,
  65. `nn.Sigmoid` is usually be applied. Users can also pass their own customized `activation_fn` as long as
  66. when combining this function with network, the final output is the probability of the input.
  67. Examples:
  68. >>> from mindspore.explainer import ImageClassificationRunner
  69. >>> from mindspore.explainer.explanation import GuidedBackprop, Gradient
  70. >>> from mindspore.explainer.benchmark import Faithfulness
  71. >>> from mindspore.nn import Softmax
  72. >>> from mindspore.train.serialization import load_checkpoint, load_param_into_net
  73. >>> # Prepare the dataset for explaining and evaluation, e.g., Cifar10
  74. >>> dataset = get_dataset('/path/to/Cifar10_dataset')
  75. >>> labels = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
  76. >>> # load checkpoint to a network, e.g. checkpoint of resnet50 trained on Cifar10
  77. >>> param_dict = load_checkpoint("checkpoint.ckpt")
  78. >>> net = resnet50(len(labels))
  79. >>> activation_fn = Softmax()
  80. >>> load_param_into_net(net, param_dict)
  81. >>> gbp = GuidedBackprop(net)
  82. >>> gradient = Gradient(net)
  83. >>> explainers = [gbp, gradient]
  84. >>> faithfulness = Faithfulness(len(labels), activation_fn, "NaiveFaithfulness")
  85. >>> benchmarkers = [faithfulness]
  86. >>> runner = ImageClassificationRunner("./summary_dir", (dataset, labels), net, activation_fn)
  87. >>> runner.register_saliency(explainers=explainers, benchmarkers=benchmarkers)
  88. >>> runner.run()
  89. """
  90. # datafile directory names
  91. _DATAFILE_DIRNAME_PREFIX = "_explain_"
  92. _ORIGINAL_IMAGE_DIRNAME = "origin_images"
  93. _HEATMAP_DIRNAME = "heatmap"
  94. # specfial filenames
  95. _MANIFEST_FILENAME = "manifest.json"
  96. # max. no. of sample per directory
  97. _SAMPLE_PER_DIR = 1000
  98. # seed for fixing the iterating order of the dataset
  99. _DATASET_SEED = 58
  100. # printing spacer
  101. _SPACER = "{:120}\r"
  102. # datafile directory's permission
  103. _DIR_MODE = 0o750
  104. # datafile's permission
  105. _FILE_MODE = 0o600
  106. def __init__(self,
  107. summary_dir,
  108. data,
  109. network,
  110. activation_fn):
  111. check_value_type("data", data, tuple)
  112. if len(data) != 2:
  113. raise ValueError("Argument data is not a tuple with 2 elements")
  114. check_value_type("data[0]", data[0], Dataset)
  115. check_value_type("data[1]", data[1], list)
  116. if not all(isinstance(ele, str) for ele in data[1]):
  117. raise ValueError("Argument data[1] is not list of str.")
  118. check_value_type("summary_dir", summary_dir, str)
  119. check_value_type("network", network, Cell)
  120. check_value_type("activation_fn", activation_fn, Cell)
  121. self._summary_dir = summary_dir
  122. self._dataset = data[0]
  123. self._labels = data[1]
  124. self._network = network
  125. self._explainers = None
  126. self._benchmarkers = None
  127. self._uncertainty = None
  128. self._hoc_searcher = None
  129. self._summary_timestamp = None
  130. self._sample_index = -1
  131. self._full_network = SequentialCell([self._network, activation_fn])
  132. self._full_network.set_train(False)
  133. self._manifest = None
  134. self._verify_data_n_settings(check_data_n_network=True,
  135. check_environment=True)
  136. def register_saliency(self,
  137. explainers,
  138. benchmarkers=None):
  139. """
  140. Register saliency explanation instances.
  141. Note:
  142. This function can not be invoked more than once on each runner.
  143. Args:
  144. explainers (list[Attribution]): The explainers to be evaluated,
  145. see `mindspore.explainer.explanation`. All explainers' class must be distinct and their network
  146. must be the exact same instance of the runner's network.
  147. benchmarkers (list[AttributionMetric], optional): The benchmarkers for scoring the explainers,
  148. see `mindspore.explainer.benchmark`. All benchmarkers' class must be distinct.
  149. Raises:
  150. ValueError: Be raised for any data or settings' value problem.
  151. TypeError: Be raised for any data or settings' type problem.
  152. RuntimeError: Be raised if this function was invoked before.
  153. """
  154. check_value_type("explainers", explainers, list)
  155. if not all(isinstance(ele, Attribution) for ele in explainers):
  156. raise TypeError("Argument explainers is not list of mindspore.explainer.explanation .")
  157. if not explainers:
  158. raise ValueError("Argument explainers is empty.")
  159. if benchmarkers is not None:
  160. check_value_type("benchmarkers", benchmarkers, list)
  161. if not all(isinstance(ele, AttributionMetric) for ele in benchmarkers):
  162. raise TypeError("Argument benchmarkers is not list of mindspore.explainer.benchmark .")
  163. if self._explainers is not None:
  164. raise RuntimeError("Function register_saliency() was invoked already.")
  165. self._explainers = explainers
  166. self._benchmarkers = benchmarkers
  167. try:
  168. self._verify_data_n_settings(check_saliency=True, check_environment=True)
  169. except (ValueError, TypeError):
  170. self._explainers = None
  171. self._benchmarkers = None
  172. raise
  173. def register_hierarchical_occlusion(self):
  174. """
  175. Register hierarchical occlusion instances.
  176. Notes:
  177. Input images are required to be in 3 channels formats and the length of side short must be equals to or
  178. greater than 56 pixels. This function can not be invoked more than once on each runner.
  179. Raises:
  180. ValueError: Be raised for any data or settings' value problem.
  181. RuntimeError: Be raised if the function was called already.
  182. """
  183. if self._hoc_searcher is not None:
  184. raise RuntimeError("Function register_hierarchical_occlusion() was invoked already.")
  185. self._hoc_searcher = hoc.Searcher(self._full_network)
  186. try:
  187. self._verify_data_n_settings(check_hoc=True, check_environment=True)
  188. except ValueError:
  189. self._hoc_searcher = None
  190. raise
  191. def register_uncertainty(self):
  192. """
  193. Register uncertainty instance to compute the epistemic uncertainty base on the Bayes' theorem.
  194. Notes:
  195. Please refer to the documentation of mindspore.nn.probability.toolbox.uncertainty_evaluation for the
  196. details. The actual output is standard deviation of the classification predictions and the corresponding
  197. 95% confidence intervals. Users have to invoke register_saliency() as well for the uncertainty results are
  198. going to be shown on the saliency map page in MindInsight. This function can not be invoked more then once
  199. on each runner.
  200. Raises:
  201. RuntimeError: Be raised if the function was called already.
  202. """
  203. if self._uncertainty is not None:
  204. raise RuntimeError("Function register_uncertainty() was invoked already.")
  205. self._uncertainty = UncertaintyEvaluation(model=self._full_network,
  206. train_dataset=None,
  207. task_type='classification',
  208. num_classes=len(self._labels))
  209. def run(self):
  210. """
  211. Run the explain job and save the result as a summary in summary_dir.
  212. Note:
  213. User should call register_saliency() once before running this function.
  214. Raises:
  215. ValueError: Be raised for any data or settings' value problem.
  216. TypeError: Be raised for any data or settings' type problem.
  217. RuntimeError: Be raised for any runtime problem.
  218. """
  219. self._verify_data_n_settings(check_all=True)
  220. self._manifest = {"saliency_map": False,
  221. "benchmark": False,
  222. "uncertainty": False,
  223. "hierarchical_occlusion": False}
  224. with SummaryRecord(self._summary_dir, raise_exception=True) as summary:
  225. print("Start running and writing......")
  226. begin = time()
  227. self._summary_timestamp = self._extract_timestamp(summary.event_file_name)
  228. if self._summary_timestamp is None:
  229. raise RuntimeError("Cannot extract timestamp from summary filename!"
  230. " It should contains a timestamp after 'summary.' .")
  231. self._save_metadata(summary)
  232. imageid_labels = self._run_inference(summary)
  233. sample_count = self._sample_index
  234. if self._is_saliency_registered:
  235. self._run_saliency(summary, imageid_labels)
  236. if not self._manifest["saliency_map"]:
  237. raise RuntimeError(
  238. f"No saliency map was generated in {sample_count} samples. "
  239. f"Please make sure the dataset, labels, activation function and network are properly trained "
  240. f"and configured.")
  241. if self._is_hoc_registered and not self._manifest["hierarchical_occlusion"]:
  242. raise RuntimeError(
  243. f"No Hierarchical Occlusion result was found in {sample_count} samples. "
  244. f"Please make sure the dataset, labels, activation function and network are properly trained "
  245. f"and configured.")
  246. self._save_manifest()
  247. print("Finish running and writing. Total time elapsed: {:.3f} s".format(time() - begin))
  248. @property
  249. def _is_hoc_registered(self):
  250. """Check if HOC module is registered."""
  251. return self._hoc_searcher is not None
  252. @property
  253. def _is_saliency_registered(self):
  254. """Check if saliency module is registered."""
  255. return bool(self._explainers)
  256. @property
  257. def _is_uncertainty_registered(self):
  258. """Check if uncertainty module is registered."""
  259. return self._uncertainty is not None
  260. def _save_metadata(self, summary):
  261. """Save metadata of the explain job to summary."""
  262. print("Start writing metadata......")
  263. explain = Explain()
  264. explain.metadata.label.extend(self._labels)
  265. if self._is_saliency_registered:
  266. exp_names = [exp.__class__.__name__ for exp in self._explainers]
  267. explain.metadata.explain_method.extend(exp_names)
  268. if self._benchmarkers is not None:
  269. bench_names = [bench.__class__.__name__ for bench in self._benchmarkers]
  270. explain.metadata.benchmark_method.extend(bench_names)
  271. summary.add_value("explainer", "metadata", explain)
  272. summary.record(1)
  273. print("Finish writing metadata.")
  274. def _run_inference(self, summary, threshold=0.5):
  275. """
  276. Run inference for the dataset and write the inference related data into summary.
  277. Args:
  278. summary (SummaryRecord): The summary object to store the data.
  279. threshold (float): The threshold for prediction.
  280. Returns:
  281. dict, The map of sample d to the union of its ground truth and predicted labels.
  282. """
  283. has_uncertainty_rec = False
  284. sample_id_labels = {}
  285. self._sample_index = 0
  286. ds.config.set_seed(self._DATASET_SEED)
  287. for j, next_element in enumerate(self._dataset):
  288. now = time()
  289. inputs, labels, _ = self._unpack_next_element(next_element)
  290. prob = self._full_network(inputs).asnumpy()
  291. if self._uncertainty is not None:
  292. prob_var = self._uncertainty.eval_epistemic_uncertainty(inputs)
  293. else:
  294. prob_var = None
  295. for idx, inp in enumerate(inputs):
  296. gt_labels = labels[idx]
  297. gt_probs = [float(prob[idx][i]) for i in gt_labels]
  298. if prob_var is not None:
  299. gt_prob_vars = [float(prob_var[idx][i]) for i in gt_labels]
  300. gt_itl_lows, gt_itl_his, gt_prob_sds = \
  301. self._calc_beta_intervals(gt_probs, gt_prob_vars)
  302. data_np = _convert_image_format(np.expand_dims(inp.asnumpy(), 0), 'NCHW')
  303. original_image = _np_to_image(_normalize(data_np), mode='RGB')
  304. original_image_path = self._save_original_image(self._sample_index, original_image)
  305. predicted_labels = [int(i) for i in (prob[idx] > threshold).nonzero()[0]]
  306. predicted_probs = [float(prob[idx][i]) for i in predicted_labels]
  307. if prob_var is not None:
  308. predicted_prob_vars = [float(prob_var[idx][i]) for i in predicted_labels]
  309. predicted_itl_lows, predicted_itl_his, predicted_prob_sds = \
  310. self._calc_beta_intervals(predicted_probs, predicted_prob_vars)
  311. union_labs = list(set(gt_labels + predicted_labels))
  312. sample_id_labels[str(self._sample_index)] = union_labs
  313. explain = Explain()
  314. explain.sample_id = self._sample_index
  315. explain.image_path = original_image_path
  316. summary.add_value("explainer", "sample", explain)
  317. explain = Explain()
  318. explain.sample_id = self._sample_index
  319. explain.ground_truth_label.extend(gt_labels)
  320. explain.inference.ground_truth_prob.extend(gt_probs)
  321. explain.inference.predicted_label.extend(predicted_labels)
  322. explain.inference.predicted_prob.extend(predicted_probs)
  323. if prob_var is not None:
  324. explain.inference.ground_truth_prob_sd.extend(gt_prob_sds)
  325. explain.inference.ground_truth_prob_itl95_low.extend(gt_itl_lows)
  326. explain.inference.ground_truth_prob_itl95_hi.extend(gt_itl_his)
  327. explain.inference.predicted_prob_sd.extend(predicted_prob_sds)
  328. explain.inference.predicted_prob_itl95_low.extend(predicted_itl_lows)
  329. explain.inference.predicted_prob_itl95_hi.extend(predicted_itl_his)
  330. has_uncertainty_rec = True
  331. summary.add_value("explainer", "inference", explain)
  332. summary.record(1)
  333. if self._is_hoc_registered:
  334. self._run_hoc(summary, self._sample_index, inputs[idx], prob[idx])
  335. self._sample_index += 1
  336. self._spaced_print("Finish running and writing {}-th batch inference data."
  337. " Time elapsed: {:.3f} s".format(j, time() - now))
  338. if has_uncertainty_rec:
  339. self._manifest["uncertainty"] = True
  340. return sample_id_labels
  341. def _run_saliency(self, summary, sample_id_labels):
  342. """Run the saliency explanations."""
  343. if self._benchmarkers is None or not self._benchmarkers:
  344. for exp in self._explainers:
  345. start = time()
  346. print("Start running and writing explanation data for {}......".format(exp.__class__.__name__))
  347. self._sample_index = 0
  348. ds.config.set_seed(self._DATASET_SEED)
  349. for idx, next_element in enumerate(self._dataset):
  350. now = time()
  351. self._spaced_print("Start running {}-th explanation data for {}......".format(
  352. idx, exp.__class__.__name__))
  353. self._run_exp_step(next_element, exp, sample_id_labels, summary)
  354. self._spaced_print("Finish writing {}-th explanation data for {}. Time elapsed: "
  355. "{:.3f} s".format(idx, exp.__class__.__name__, time() - now))
  356. self._spaced_print(
  357. "Finish running and writing explanation data for {}. Time elapsed: {:.3f} s".format(
  358. exp.__class__.__name__, time() - start))
  359. else:
  360. for exp in self._explainers:
  361. explain = Explain()
  362. for bench in self._benchmarkers:
  363. bench.reset()
  364. print(f"Start running and writing explanation and "
  365. f"benchmark data for {exp.__class__.__name__}......")
  366. self._sample_index = 0
  367. start = time()
  368. ds.config.set_seed(self._DATASET_SEED)
  369. for idx, next_element in enumerate(self._dataset):
  370. now = time()
  371. self._spaced_print("Start running {}-th explanation data for {}......".format(
  372. idx, exp.__class__.__name__))
  373. saliency_dict_lst = self._run_exp_step(next_element, exp, sample_id_labels, summary)
  374. self._spaced_print(
  375. "Finish writing {}-th batch explanation data for {}. Time elapsed: {:.3f} s".format(
  376. idx, exp.__class__.__name__, time() - now))
  377. for bench in self._benchmarkers:
  378. now = time()
  379. self._spaced_print(
  380. "Start running {}-th batch {} data for {}......".format(
  381. idx, bench.__class__.__name__, exp.__class__.__name__))
  382. self._run_exp_benchmark_step(next_element, exp, bench, saliency_dict_lst)
  383. self._spaced_print(
  384. "Finish running {}-th batch {} data for {}. Time elapsed: {:.3f} s".format(
  385. idx, bench.__class__.__name__, exp.__class__.__name__, time() - now))
  386. for bench in self._benchmarkers:
  387. benchmark = explain.benchmark.add()
  388. benchmark.explain_method = exp.__class__.__name__
  389. benchmark.benchmark_method = bench.__class__.__name__
  390. benchmark.total_score = bench.performance
  391. if isinstance(bench, LabelSensitiveMetric):
  392. benchmark.label_score.extend(bench.class_performances)
  393. self._spaced_print("Finish running and writing explanation and benchmark data for {}. "
  394. "Time elapsed: {:.3f} s".format(exp.__class__.__name__, time() - start))
  395. summary.add_value('explainer', 'benchmark', explain)
  396. summary.record(1)
  397. def _run_hoc(self, summary, sample_id, sample_input, prob):
  398. """
  399. Run HOC search for a sample image, and then save the result to summary.
  400. Args:
  401. summary (SummaryRecord): The summary object to store the data.
  402. sample_id (int): The sample ID.
  403. sample_input (Union[Tensor, np.ndarray]): Sample image tensor in CHW or NCWH(N=1).
  404. prob (Union[Tensor, np.ndarray]): List of sample's classification prediction output, HOC will run for
  405. labels with prediction output strictly larger then HOC searcher's threshold(0.5 by default).
  406. """
  407. if isinstance(sample_input, ms.Tensor):
  408. sample_input = sample_input.asnumpy()
  409. if len(sample_input.shape) == 3:
  410. sample_input = np.expand_dims(sample_input, axis=0)
  411. has_rec = False
  412. explain = Explain()
  413. explain.sample_id = sample_id
  414. str_mask = hoc.auto_str_mask(sample_input)
  415. compiled_mask = None
  416. for label_idx, label_prob in enumerate(prob):
  417. if label_prob > self._hoc_searcher.threshold:
  418. if compiled_mask is None:
  419. compiled_mask = hoc.compile_mask(str_mask, sample_input)
  420. try:
  421. edit_tree, layer_outputs = self._hoc_searcher.search(sample_input, label_idx, compiled_mask)
  422. except hoc.NoValidResultError:
  423. log.warning(f"No Hierarchical Occlusion result was found in sample#{sample_id} "
  424. f"label:{self._labels[label_idx]}, skipped.")
  425. continue
  426. has_rec = True
  427. hoc_rec = explain.hoc.add()
  428. hoc_rec.label = label_idx
  429. hoc_rec.mask = str_mask
  430. layer_count = edit_tree.max_layer + 1
  431. for layer in range(layer_count):
  432. steps = edit_tree.get_layer_or_leaf_steps(layer)
  433. layer_output = layer_outputs[layer]
  434. hoc_layer = hoc_rec.layer.add()
  435. hoc_layer.prob = layer_output
  436. for step in steps:
  437. hoc_layer.box.extend(list(step.box))
  438. if has_rec:
  439. summary.add_value("explainer", "hoc", explain)
  440. summary.record(1)
  441. self._manifest['hierarchical_occlusion'] = True
  442. def _run_exp_step(self, next_element, explainer, sample_id_labels, summary):
  443. """
  444. Run the explanation for each step and write explanation results into summary.
  445. Args:
  446. next_element (Tuple): Data of one step
  447. explainer (_Attribution): An Attribution object to generate saliency maps.
  448. sample_id_labels (dict): A dict that maps the sample id and its union labels.
  449. summary (SummaryRecord): The summary object to store the data.
  450. Returns:
  451. list, List of dict that maps label to its corresponding saliency map.
  452. """
  453. has_saliency_rec = False
  454. inputs, labels, _ = self._unpack_next_element(next_element)
  455. sample_index = self._sample_index
  456. unions = []
  457. for _ in range(len(labels)):
  458. unions_labels = sample_id_labels[str(sample_index)]
  459. unions.append(unions_labels)
  460. sample_index += 1
  461. batch_unions = self._make_label_batch(unions)
  462. saliency_dict_lst = []
  463. if isinstance(explainer, RISE):
  464. batch_saliency_full = explainer(inputs, batch_unions)
  465. else:
  466. batch_saliency_full = []
  467. for i in range(len(batch_unions[0])):
  468. batch_saliency = explainer(inputs, batch_unions[:, i])
  469. batch_saliency_full.append(batch_saliency)
  470. concat = ms.ops.operations.Concat(1)
  471. batch_saliency_full = concat(tuple(batch_saliency_full))
  472. for idx, union in enumerate(unions):
  473. saliency_dict = {}
  474. explain = Explain()
  475. explain.sample_id = self._sample_index
  476. for k, lab in enumerate(union):
  477. saliency = batch_saliency_full[idx:idx + 1, k:k + 1]
  478. saliency_dict[lab] = saliency
  479. saliency_np = _normalize(saliency.asnumpy().squeeze())
  480. saliency_image = _np_to_image(saliency_np, mode='L')
  481. heatmap_path = self._save_heatmap(explainer.__class__.__name__, lab, self._sample_index, saliency_image)
  482. explanation = explain.explanation.add()
  483. explanation.explain_method = explainer.__class__.__name__
  484. explanation.heatmap_path = heatmap_path
  485. explanation.label = lab
  486. has_saliency_rec = True
  487. summary.add_value("explainer", "explanation", explain)
  488. summary.record(1)
  489. self._sample_index += 1
  490. saliency_dict_lst.append(saliency_dict)
  491. if has_saliency_rec:
  492. self._manifest['saliency_map'] = True
  493. return saliency_dict_lst
  494. def _run_exp_benchmark_step(self, next_element, explainer, benchmarker, saliency_dict_lst):
  495. """Run the explanation and evaluation for each step and write explanation results into summary."""
  496. inputs, labels, _ = self._unpack_next_element(next_element)
  497. for idx, inp in enumerate(inputs):
  498. inp = _EXPAND_DIMS(inp, 0)
  499. if isinstance(benchmarker, LabelAgnosticMetric):
  500. res = benchmarker.evaluate(explainer, inp)
  501. benchmarker.aggregate(res)
  502. else:
  503. saliency_dict = saliency_dict_lst[idx]
  504. for label, saliency in saliency_dict.items():
  505. if isinstance(benchmarker, Localization):
  506. _, _, bboxes = self._unpack_next_element(next_element, True)
  507. if label in labels[idx]:
  508. res = benchmarker.evaluate(explainer, inp, targets=label, mask=bboxes[idx][label],
  509. saliency=saliency)
  510. benchmarker.aggregate(res, label)
  511. elif isinstance(benchmarker, LabelSensitiveMetric):
  512. res = benchmarker.evaluate(explainer, inp, targets=label, saliency=saliency)
  513. benchmarker.aggregate(res, label)
  514. else:
  515. raise TypeError('Benchmarker must be one of LabelSensitiveMetric or LabelAgnosticMetric, but'
  516. 'receive {}'.format(type(benchmarker)))
  517. self._manifest['benchmark'] = True
  518. @staticmethod
  519. def _calc_beta_intervals(means, variances, prob=0.95):
  520. """Calculate confidence interval of beta distributions."""
  521. if not isinstance(means, np.ndarray):
  522. means = np.array(means)
  523. if not isinstance(variances, np.ndarray):
  524. variances = np.array(variances)
  525. with np.errstate(divide='ignore'):
  526. coef_a = ((means ** 2) * (1 - means) / variances) - means
  527. coef_b = (coef_a * (1 - means)) / means
  528. itl_lows, itl_his = beta.interval(prob, coef_a, coef_b)
  529. sds = np.sqrt(variances)
  530. for i in range(itl_lows.shape[0]):
  531. if not np.isfinite(sds[i]) or not np.isfinite(itl_lows[i]) or not np.isfinite(itl_his[i]):
  532. itl_lows[i] = means[i]
  533. itl_his[i] = means[i]
  534. sds[i] = 0
  535. return itl_lows, itl_his, sds
  536. def _verify_labels(self):
  537. """Verify labels."""
  538. label_set = set()
  539. if not self._labels:
  540. raise ValueError(f"The label list provided is empty.")
  541. for i, label in enumerate(self._labels):
  542. if label.strip() == "":
  543. raise ValueError(f"Label [{i}] is all whitespaces or empty. Please make sure there is "
  544. f"no empty label.")
  545. if label in label_set:
  546. raise ValueError(f"Duplicated label:{label}! Please make sure all labels are unique.")
  547. label_set.add(label)
  548. def _verify_ds_sample(self, sample):
  549. """Verify a dataset sample."""
  550. if len(sample) not in [1, 2, 3]:
  551. raise ValueError("The dataset should provide [images] or [images, labels], [images, labels, bboxes]"
  552. " as columns.")
  553. if len(sample) == 3:
  554. inputs, labels, bboxes = sample
  555. if bboxes.shape[-1] != 4:
  556. raise ValueError("The third element of dataset should be bounding boxes with shape of "
  557. "[batch_size, num_ground_truth, 4].")
  558. else:
  559. if self._benchmarkers is not None:
  560. if any([isinstance(bench, Localization) for bench in self._benchmarkers]):
  561. raise ValueError("The dataset must provide bboxes if Localization is to be computed.")
  562. if len(sample) == 2:
  563. inputs, labels = sample
  564. if len(sample) == 1:
  565. inputs = sample[0]
  566. if len(inputs.shape) > 4 or len(inputs.shape) < 3 or inputs.shape[-3] not in [1, 3, 4]:
  567. raise ValueError(
  568. "Image shape {} is unrecognizable: the dimension of image can only be CHW or NCHW.".format(
  569. inputs.shape))
  570. if len(inputs.shape) == 3:
  571. log.warning(
  572. "Image shape {} is 3-dimensional. All the data will be automatically unsqueezed at the 0-th"
  573. " dimension as batch data.".format(inputs.shape))
  574. if len(sample) > 1:
  575. if len(labels.shape) > 2 and (np.array(labels.shape[1:]) > 1).sum() > 1:
  576. raise ValueError(
  577. "Labels shape {} is unrecognizable: outputs should not have more than two dimensions"
  578. " with length greater than 1.".format(labels.shape))
  579. if self._is_hoc_registered:
  580. if inputs.shape[-3] != 3:
  581. raise ValueError(
  582. "Hierarchical occlusion is registered, images must be in 3 channels format, but "
  583. "{} channel(s) is(are) encountered.".format(inputs.shape[-3]))
  584. short_side = min(inputs.shape[-2:])
  585. if short_side < hoc.AUTO_IMAGE_SHORT_SIDE_MIN:
  586. raise ValueError(
  587. "Hierarchical occlusion is registered, images' short side must be equals to or greater then "
  588. "{}, but {} is encountered.".format(hoc.AUTO_IMAGE_SHORT_SIDE_MIN, short_side))
  589. def _verify_data(self):
  590. """Verify dataset and labels."""
  591. self._verify_labels()
  592. try:
  593. sample = next(self._dataset.create_tuple_iterator())
  594. except StopIteration:
  595. raise ValueError("The dataset provided is empty.")
  596. self._verify_ds_sample(sample)
  597. def _verify_network(self):
  598. """Verify the network."""
  599. next_element = next(self._dataset.create_tuple_iterator())
  600. inputs, _, _ = self._unpack_next_element(next_element)
  601. prop_test = self._full_network(inputs)
  602. check_value_type("output of network in explainer", prop_test, ms.Tensor)
  603. if prop_test.shape[1] != len(self._labels):
  604. raise ValueError("The dimension of network output does not match the no. of classes. Please "
  605. "check labels or the network in the explainer again.")
  606. def _verify_saliency(self):
  607. """Verify the saliency settings."""
  608. if self._explainers:
  609. explainer_classes = []
  610. for explainer in self._explainers:
  611. if explainer.__class__ in explainer_classes:
  612. raise ValueError(f"Repeated {explainer.__class__.__name__} explainer! "
  613. "Please make sure all explainers' class is distinct.")
  614. if explainer.network is not self._network:
  615. raise ValueError(f"The network of {explainer.__class__.__name__} explainer is different "
  616. "instance from network of runner. Please make sure they are the same "
  617. "instance.")
  618. explainer_classes.append(explainer.__class__)
  619. if self._benchmarkers:
  620. benchmarker_classes = []
  621. for benchmarker in self._benchmarkers:
  622. if benchmarker.__class__ in benchmarker_classes:
  623. raise ValueError(f"Repeated {benchmarker.__class__.__name__} benchmarker! "
  624. "Please make sure all benchmarkers' class is distinct.")
  625. if isinstance(benchmarker, LabelSensitiveMetric) and benchmarker.num_labels != len(self._labels):
  626. raise ValueError(f"The num_labels of {benchmarker.__class__.__name__} benchmarker is different "
  627. "from no. of labels of runner. Please make them are the same.")
  628. benchmarker_classes.append(benchmarker.__class__)
  629. def _verify_data_n_settings(self,
  630. check_all=False,
  631. check_registration=False,
  632. check_data_n_network=False,
  633. check_saliency=False,
  634. check_hoc=False,
  635. check_environment=False):
  636. """
  637. Verify the validity of dataset and other settings.
  638. Args:
  639. check_all (bool): Set it True for checking everything.
  640. check_registration (bool): Set it True for checking registrations, check if it is enough to invoke run().
  641. check_data_n_network (bool): Set it True for checking data and network.
  642. check_saliency (bool): Set it True for checking saliency related settings.
  643. check_hoc (bool): Set it True for checking HOC related settings.
  644. check_environment (bool): Set it True for checking environment conditions.
  645. Raises:
  646. ValueError: Be raised for any data or settings' value problem.
  647. TypeError: Be raised for any data or settings' type problem.
  648. RuntimeError: Be raised for any runtime problem.
  649. """
  650. if check_all:
  651. check_registration = True
  652. check_data_n_network = True
  653. check_saliency = True
  654. check_hoc = True
  655. check_environment = True
  656. if check_environment:
  657. device_target = context.get_context('device_target')
  658. if device_target not in ("Ascend", "GPU"):
  659. raise RuntimeError(f"Unsupported device_target: '{device_target}', "
  660. f"only 'Ascend' or 'GPU' is supported. "
  661. f"Please call context.set_context(device_target='Ascend') or "
  662. f"context.set_context(device_target='GPU').")
  663. if check_environment or check_saliency:
  664. if self._is_saliency_registered:
  665. mode = context.get_context('mode')
  666. if mode != context.PYNATIVE_MODE:
  667. raise RuntimeError("Context mode: GRAPH_MODE is not supported, "
  668. "please call context.set_context(mode=context.PYNATIVE_MODE).")
  669. if check_registration:
  670. if self._is_uncertainty_registered and not self._is_saliency_registered:
  671. raise ValueError("Function register_uncertainty() is called but register_saliency() is not.")
  672. if not self._is_saliency_registered and not self._is_hoc_registered:
  673. raise ValueError("No explanation module was registered, user should at least call register_saliency() "
  674. "or register_hierarchical_occlusion() once with proper arguments.")
  675. if check_data_n_network or check_saliency or check_hoc:
  676. self._verify_data()
  677. if check_data_n_network:
  678. self._verify_network()
  679. if check_saliency:
  680. self._verify_saliency()
  681. def _transform_data(self, inputs, labels, bboxes, ifbbox):
  682. """
  683. Transform the data from one iteration of dataset to a unifying form for the follow-up operations.
  684. Args:
  685. inputs (Tensor): the image data
  686. labels (Tensor): the labels
  687. bboxes (Tensor): the boudnding boxes data
  688. ifbbox (bool): whether to preprocess bboxes. If True, a dictionary that indicates bounding boxes w.r.t
  689. label id will be returned. If False, the returned bboxes is the the parsed bboxes.
  690. Returns:
  691. inputs (Tensor): the image data, unified to a 4D Tensor.
  692. labels (list[list[int]]): the ground truth labels.
  693. bboxes (Union[list[dict], None, Tensor]): the bounding boxes
  694. """
  695. inputs = ms.Tensor(inputs, ms.float32)
  696. if len(inputs.shape) == 3:
  697. inputs = _EXPAND_DIMS(inputs, 0)
  698. if isinstance(labels, ms.Tensor):
  699. labels = ms.Tensor(labels, ms.int32)
  700. labels = _EXPAND_DIMS(labels, 0)
  701. if isinstance(bboxes, ms.Tensor):
  702. bboxes = ms.Tensor(bboxes, ms.int32)
  703. bboxes = _EXPAND_DIMS(bboxes, 0)
  704. input_len = len(inputs)
  705. if bboxes is not None and ifbbox:
  706. bboxes = ms.Tensor(bboxes, ms.int32)
  707. masks_lst = []
  708. labels = labels.asnumpy().reshape([input_len, -1])
  709. bboxes = bboxes.asnumpy().reshape([input_len, -1, 4])
  710. for idx, label in enumerate(labels):
  711. height, width = inputs[idx].shape[-2], inputs[idx].shape[-1]
  712. masks = {}
  713. for j, label_item in enumerate(label):
  714. target = int(label_item)
  715. if -1 < target < len(self._labels):
  716. if target not in masks:
  717. mask = np.zeros((1, 1, height, width))
  718. else:
  719. mask = masks[target]
  720. x_min, y_min, x_len, y_len = bboxes[idx][j].astype(int)
  721. mask[:, :, x_min:x_min + x_len, y_min:y_min + y_len] = 1
  722. masks[target] = mask
  723. masks_lst.append(masks)
  724. bboxes = masks_lst
  725. labels = ms.Tensor(labels, ms.int32)
  726. if len(labels.shape) == 1:
  727. labels_lst = [[int(i)] for i in labels.asnumpy()]
  728. else:
  729. labels = labels.asnumpy().reshape([input_len, -1])
  730. labels_lst = []
  731. for item in labels:
  732. labels_lst.append(list(set(int(i) for i in item if -1 < int(i) < len(self._labels))))
  733. labels = labels_lst
  734. return inputs, labels, bboxes
  735. def _unpack_next_element(self, next_element, ifbbox=False):
  736. """
  737. Unpack a single iteration of dataset.
  738. Args:
  739. next_element (Tuple): a single element iterated from dataset object.
  740. ifbbox (bool): whether to preprocess bboxes in self._transform_data.
  741. Returns:
  742. tuple, a unified Tuple contains image_data, labels, and bounding boxes.
  743. """
  744. if len(next_element) == 3:
  745. inputs, labels, bboxes = next_element
  746. elif len(next_element) == 2:
  747. inputs, labels = next_element
  748. bboxes = None
  749. else:
  750. inputs = next_element[0]
  751. labels = [[] for _ in inputs]
  752. bboxes = None
  753. inputs, labels, bboxes = self._transform_data(inputs, labels, bboxes, ifbbox)
  754. return inputs, labels, bboxes
  755. @staticmethod
  756. def _make_label_batch(labels):
  757. """
  758. Unify a List of List of labels to be a 2D Tensor with shape (b, m), where b = len(labels) and m is the max
  759. length of all the rows in labels.
  760. Args:
  761. labels (List[List]): the union labels of a data batch.
  762. Returns:
  763. 2D Tensor.
  764. """
  765. max_len = max([len(label) for label in labels])
  766. batch_labels = np.zeros((len(labels), max_len))
  767. for idx, _ in enumerate(batch_labels):
  768. length = len(labels[idx])
  769. batch_labels[idx, :length] = np.array(labels[idx])
  770. return ms.Tensor(batch_labels, ms.int32)
  771. def _save_manifest(self):
  772. """Save manifest.json underneath datafile directory."""
  773. if self._manifest is None:
  774. raise RuntimeError("Manifest not yet be initialized.")
  775. path_tokens = [self._summary_dir,
  776. self._DATAFILE_DIRNAME_PREFIX + str(self._summary_timestamp)]
  777. abs_dir_path = self._create_subdir(*path_tokens)
  778. save_path = os.path.join(abs_dir_path, self._MANIFEST_FILENAME)
  779. with open(save_path, 'w') as file:
  780. json.dump(self._manifest, file, indent=4)
  781. os.chmod(save_path, self._FILE_MODE)
  782. def _save_original_image(self, sample_id, image):
  783. """Save an image to summary directory."""
  784. id_dirname = self._get_sample_dirname(sample_id)
  785. path_tokens = [self._summary_dir,
  786. self._DATAFILE_DIRNAME_PREFIX + str(self._summary_timestamp),
  787. self._ORIGINAL_IMAGE_DIRNAME,
  788. id_dirname]
  789. abs_dir_path = self._create_subdir(*path_tokens)
  790. filename = f"{sample_id}.jpg"
  791. save_path = os.path.join(abs_dir_path, filename)
  792. image.save(save_path)
  793. os.chmod(save_path, self._FILE_MODE)
  794. return os.path.join(*path_tokens[1:], filename)
  795. def _save_heatmap(self, explain_method, class_id, sample_id, image):
  796. """Save heatmap image to summary directory."""
  797. id_dirname = self._get_sample_dirname(sample_id)
  798. path_tokens = [self._summary_dir,
  799. self._DATAFILE_DIRNAME_PREFIX + str(self._summary_timestamp),
  800. self._HEATMAP_DIRNAME,
  801. explain_method,
  802. id_dirname]
  803. abs_dir_path = self._create_subdir(*path_tokens)
  804. filename = f"{sample_id}_{class_id}.jpg"
  805. save_path = os.path.join(abs_dir_path, filename)
  806. image.save(save_path, optimize=True)
  807. os.chmod(save_path, self._FILE_MODE)
  808. return os.path.join(*path_tokens[1:], filename)
  809. def _create_subdir(self, *args):
  810. """Recursively create subdirectories."""
  811. abs_path = None
  812. for token in args:
  813. if abs_path is None:
  814. abs_path = os.path.realpath(token)
  815. else:
  816. abs_path = os.path.join(abs_path, token)
  817. # os.makedirs() don't set intermediate dir permission properly, we mkdir() one by one
  818. try:
  819. os.mkdir(abs_path, mode=self._DIR_MODE)
  820. # In some platform, mode may be ignored in os.mkdir(), we have to chmod() again to make sure
  821. os.chmod(abs_path, mode=self._DIR_MODE)
  822. except FileExistsError:
  823. pass
  824. return abs_path
  825. @classmethod
  826. def _get_sample_dirname(cls, sample_id):
  827. """Get the name of parent directory of the image id."""
  828. return str(int(sample_id / cls._SAMPLE_PER_DIR) * cls._SAMPLE_PER_DIR)
  829. @staticmethod
  830. def _extract_timestamp(filename):
  831. """Extract timestamp from summary filename."""
  832. matched = re.search(r"summary\.(\d+)", filename)
  833. if matched:
  834. return int(matched.group(1))
  835. return None
  836. @classmethod
  837. def _spaced_print(cls, message):
  838. """Spaced message printing."""
  839. # workaround to print logs starting new line in case line width mismatch.
  840. print(cls._SPACER.format(message))