interpretation_algorithms.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. #copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
  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. import os
  15. import os.path as osp
  16. import numpy as np
  17. import time
  18. from . import lime_base
  19. from ._session_preparation import paddle_get_fc_weights, compute_features_for_kmeans, gen_user_home
  20. from .normlime_base import combine_normlime_and_lime, get_feature_for_kmeans, load_kmeans_model
  21. from paddlex.interpret.as_data_reader.readers import read_image
  22. import paddlex.utils.logging as logging
  23. import cv2
  24. class CAM(object):
  25. def __init__(self, predict_fn, label_names):
  26. """
  27. Args:
  28. predict_fn: input: images_show [N, H, W, 3], RGB range(0, 255)
  29. output: [
  30. logits [N, num_classes],
  31. feature map before global average pooling [N, num_channels, h_, w_]
  32. ]
  33. """
  34. self.predict_fn = predict_fn
  35. self.label_names = label_names
  36. def preparation_cam(self, data_):
  37. image_show = read_image(data_)
  38. result = self.predict_fn(image_show)
  39. logit = result[0][0]
  40. if abs(np.sum(logit) - 1.0) > 1e-4:
  41. # softmax
  42. logit = logit - np.max(logit)
  43. exp_result = np.exp(logit)
  44. probability = exp_result / np.sum(exp_result)
  45. else:
  46. probability = logit
  47. # only interpret top 1
  48. pred_label = np.argsort(probability)
  49. pred_label = pred_label[-1:]
  50. self.predicted_label = pred_label[0]
  51. self.predicted_probability = probability[pred_label[0]]
  52. self.image = image_show[0]
  53. self.labels = pred_label
  54. fc_weights = paddle_get_fc_weights()
  55. feature_maps = result[1]
  56. l = pred_label[0]
  57. ln = l
  58. if self.label_names is not None:
  59. ln = self.label_names[l]
  60. prob_str = "%.3f" % (probability[pred_label[0]])
  61. logging.info("predicted result: {} with probability {}.".format(
  62. ln, prob_str))
  63. return feature_maps, fc_weights
  64. def interpret(self, data_, visualization=True, save_outdir=None):
  65. feature_maps, fc_weights = self.preparation_cam(data_)
  66. cam = get_cam(self.image, feature_maps, fc_weights,
  67. self.predicted_label)
  68. if visualization or save_outdir is not None:
  69. import matplotlib.pyplot as plt
  70. from skimage.segmentation import mark_boundaries
  71. l = self.labels[0]
  72. ln = l
  73. if self.label_names is not None:
  74. ln = self.label_names[l]
  75. psize = 5
  76. nrows = 1
  77. ncols = 2
  78. plt.close()
  79. f, axes = plt.subplots(
  80. nrows, ncols, figsize=(psize * ncols, psize * nrows))
  81. for ax in axes.ravel():
  82. ax.axis("off")
  83. axes = axes.ravel()
  84. axes[0].imshow(self.image)
  85. prob_str = "{%.3f}" % (self.predicted_probability)
  86. axes[0].set_title("label {}, proba: {}".format(ln, prob_str))
  87. axes[1].imshow(cam)
  88. axes[1].set_title("CAM")
  89. if save_outdir is not None:
  90. save_fig(data_, save_outdir, 'cam')
  91. if visualization:
  92. plt.show()
  93. return
  94. class LIME(object):
  95. def __init__(self,
  96. predict_fn,
  97. label_names,
  98. num_samples=3000,
  99. batch_size=50):
  100. """
  101. LIME wrapper. See lime_base.py for the detailed LIME implementation.
  102. Args:
  103. predict_fn: from image [N, H, W, 3] to logits [N, num_classes], this is necessary for computing LIME.
  104. num_samples: the number of samples that LIME takes for fitting.
  105. batch_size: batch size for model inference each time.
  106. """
  107. self.num_samples = num_samples
  108. self.batch_size = batch_size
  109. self.predict_fn = predict_fn
  110. self.labels = None
  111. self.image = None
  112. self.lime_interpreter = None
  113. self.label_names = label_names
  114. def preparation_lime(self, data_):
  115. image_show = read_image(data_)
  116. result = self.predict_fn(image_show)
  117. result = result[0] # only one image here.
  118. if abs(np.sum(result) - 1.0) > 1e-4:
  119. # softmax
  120. result = result - np.max(result)
  121. exp_result = np.exp(result)
  122. probability = exp_result / np.sum(exp_result)
  123. else:
  124. probability = result
  125. # only interpret top 1
  126. pred_label = np.argsort(probability)
  127. pred_label = pred_label[-1:]
  128. self.predicted_label = pred_label[0]
  129. self.predicted_probability = probability[pred_label[0]]
  130. self.image = image_show[0]
  131. self.labels = pred_label
  132. l = pred_label[0]
  133. ln = l
  134. if self.label_names is not None:
  135. ln = self.label_names[l]
  136. prob_str = "%.3f" % (probability[pred_label[0]])
  137. logging.info("predicted result: {} with probability {}.".format(
  138. ln, prob_str))
  139. end = time.time()
  140. algo = lime_base.LimeImageInterpreter()
  141. interpreter = algo.interpret_instance(
  142. self.image,
  143. self.predict_fn,
  144. self.labels,
  145. 0,
  146. num_samples=self.num_samples,
  147. batch_size=self.batch_size)
  148. self.lime_interpreter = interpreter
  149. logging.info('lime time: ' + str(time.time() - end) + 's.')
  150. def interpret(self, data_, visualization=True, save_outdir=None):
  151. if self.lime_interpreter is None:
  152. self.preparation_lime(data_)
  153. if visualization or save_outdir is not None:
  154. import matplotlib.pyplot as plt
  155. from skimage.segmentation import mark_boundaries
  156. l = self.labels[0]
  157. ln = l
  158. if self.label_names is not None:
  159. ln = self.label_names[l]
  160. psize = 5
  161. nrows = 2
  162. weights_choices = [0.6, 0.7, 0.75, 0.8, 0.85]
  163. ncols = len(weights_choices)
  164. plt.close()
  165. f, axes = plt.subplots(
  166. nrows, ncols, figsize=(psize * ncols, psize * nrows))
  167. for ax in axes.ravel():
  168. ax.axis("off")
  169. axes = axes.ravel()
  170. axes[0].imshow(self.image)
  171. prob_str = "{%.3f}" % (self.predicted_probability)
  172. axes[0].set_title("label {}, proba: {}".format(ln, prob_str))
  173. axes[1].imshow(
  174. mark_boundaries(self.image, self.lime_interpreter.segments))
  175. axes[1].set_title("superpixel segmentation")
  176. # LIME visualization
  177. for i, w in enumerate(weights_choices):
  178. num_to_show = auto_choose_num_features_to_show(
  179. self.lime_interpreter, l, w)
  180. temp, mask = self.lime_interpreter.get_image_and_mask(
  181. l,
  182. positive_only=True,
  183. hide_rest=False,
  184. num_features=num_to_show)
  185. axes[ncols + i].imshow(mark_boundaries(temp, mask))
  186. axes[ncols + i].set_title(
  187. "label {}, first {} superpixels".format(ln, num_to_show))
  188. if save_outdir is not None:
  189. save_fig(data_, save_outdir, 'lime', self.num_samples)
  190. if visualization:
  191. plt.show()
  192. return
  193. class NormLIMEStandard(object):
  194. def __init__(self,
  195. predict_fn,
  196. label_names,
  197. num_samples=3000,
  198. batch_size=50,
  199. kmeans_model_for_normlime=None,
  200. normlime_weights=None):
  201. root_path = gen_user_home()
  202. root_path = osp.join(root_path, '.paddlex')
  203. h_pre_models = osp.join(root_path, "pre_models")
  204. if not osp.exists(h_pre_models):
  205. if not osp.exists(root_path):
  206. os.makedirs(root_path)
  207. url = "https://bj.bcebos.com/paddlex/interpret/pre_models.tar.gz"
  208. pdx.utils.download_and_decompress(url, path=root_path)
  209. h_pre_models_kmeans = osp.join(h_pre_models, "kmeans_model.pkl")
  210. if kmeans_model_for_normlime is None:
  211. try:
  212. self.kmeans_model = load_kmeans_model(h_pre_models_kmeans)
  213. except:
  214. raise ValueError(
  215. "NormLIME needs the KMeans model, where we provided a default one in "
  216. "pre_models/kmeans_model.pkl.")
  217. else:
  218. logging.debug("Warning: It is *strongly* suggested to use the \
  219. default KMeans model in pre_models/kmeans_model.pkl. \
  220. Use another one will change the final result.")
  221. self.kmeans_model = load_kmeans_model(kmeans_model_for_normlime)
  222. self.num_samples = num_samples
  223. self.batch_size = batch_size
  224. try:
  225. self.normlime_weights = np.load(
  226. normlime_weights, allow_pickle=True).item()
  227. except:
  228. self.normlime_weights = None
  229. logging.debug(
  230. "Warning: not find the correct precomputed Normlime result.")
  231. self.predict_fn = predict_fn
  232. self.labels = None
  233. self.image = None
  234. self.label_names = label_names
  235. def predict_cluster_labels(self, feature_map, segments):
  236. X = get_feature_for_kmeans(feature_map, segments)
  237. try:
  238. cluster_labels = self.kmeans_model.predict(X)
  239. except AttributeError:
  240. from sklearn.metrics import pairwise_distances_argmin_min
  241. cluster_labels, _ = pairwise_distances_argmin_min(
  242. X, self.kmeans_model.cluster_centers_)
  243. return cluster_labels
  244. def predict_using_normlime_weights(self, pred_labels,
  245. predicted_cluster_labels):
  246. # global weights
  247. g_weights = {y: [] for y in pred_labels}
  248. for y in pred_labels:
  249. cluster_weights_y = self.normlime_weights.get(y, {})
  250. g_weights[y] = [(i, cluster_weights_y.get(k, 0.0))
  251. for i, k in enumerate(predicted_cluster_labels)]
  252. g_weights[y] = sorted(
  253. g_weights[y], key=lambda x: np.abs(x[1]), reverse=True)
  254. return g_weights
  255. def preparation_normlime(self, data_):
  256. self._lime = LIME(self.predict_fn, self.label_names, self.num_samples,
  257. self.batch_size)
  258. self._lime.preparation_lime(data_)
  259. image_show = read_image(data_)
  260. self.predicted_label = self._lime.predicted_label
  261. self.predicted_probability = self._lime.predicted_probability
  262. self.image = image_show[0]
  263. self.labels = self._lime.labels
  264. logging.info('performing NormLIME operations ...')
  265. cluster_labels = self.predict_cluster_labels(
  266. compute_features_for_kmeans(image_show).transpose((1, 2, 0)),
  267. self._lime.lime_interpreter.segments)
  268. g_weights = self.predict_using_normlime_weights(self.labels,
  269. cluster_labels)
  270. return g_weights
  271. def interpret(self, data_, visualization=True, save_outdir=None):
  272. if self.normlime_weights is None:
  273. raise ValueError(
  274. "Not find the correct precomputed NormLIME result. \n"
  275. "\t Try to call compute_normlime_weights() first or load the correct path."
  276. )
  277. g_weights = self.preparation_normlime(data_)
  278. lime_weights = self._lime.lime_interpreter.local_weights
  279. if visualization or save_outdir is not None:
  280. import matplotlib.pyplot as plt
  281. from skimage.segmentation import mark_boundaries
  282. l = self.labels[0]
  283. ln = l
  284. if self.label_names is not None:
  285. ln = self.label_names[l]
  286. psize = 5
  287. nrows = 4
  288. weights_choices = [0.6, 0.7, 0.75, 0.8, 0.85]
  289. nums_to_show = []
  290. ncols = len(weights_choices)
  291. plt.close()
  292. f, axes = plt.subplots(
  293. nrows, ncols, figsize=(psize * ncols, psize * nrows))
  294. for ax in axes.ravel():
  295. ax.axis("off")
  296. axes = axes.ravel()
  297. axes[0].imshow(self.image)
  298. prob_str = "{%.3f}" % (self.predicted_probability)
  299. axes[0].set_title("label {}, proba: {}".format(ln, prob_str))
  300. axes[1].imshow(
  301. mark_boundaries(self.image,
  302. self._lime.lime_interpreter.segments))
  303. axes[1].set_title("superpixel segmentation")
  304. # LIME visualization
  305. for i, w in enumerate(weights_choices):
  306. num_to_show = auto_choose_num_features_to_show(
  307. self._lime.lime_interpreter, l, w)
  308. nums_to_show.append(num_to_show)
  309. temp, mask = self._lime.lime_interpreter.get_image_and_mask(
  310. l,
  311. positive_only=False,
  312. hide_rest=False,
  313. num_features=num_to_show)
  314. axes[ncols + i].imshow(mark_boundaries(temp, mask))
  315. axes[ncols + i].set_title("LIME: first {} superpixels".format(
  316. num_to_show))
  317. # NormLIME visualization
  318. self._lime.lime_interpreter.local_weights = g_weights
  319. for i, num_to_show in enumerate(nums_to_show):
  320. temp, mask = self._lime.lime_interpreter.get_image_and_mask(
  321. l,
  322. positive_only=False,
  323. hide_rest=False,
  324. num_features=num_to_show)
  325. axes[ncols * 2 + i].imshow(mark_boundaries(temp, mask))
  326. axes[ncols * 2 + i].set_title(
  327. "NormLIME: first {} superpixels".format(num_to_show))
  328. # NormLIME*LIME visualization
  329. combined_weights = combine_normlime_and_lime(lime_weights,
  330. g_weights)
  331. self._lime.lime_interpreter.local_weights = combined_weights
  332. for i, num_to_show in enumerate(nums_to_show):
  333. temp, mask = self._lime.lime_interpreter.get_image_and_mask(
  334. l,
  335. positive_only=False,
  336. hide_rest=False,
  337. num_features=num_to_show)
  338. axes[ncols * 3 + i].imshow(mark_boundaries(temp, mask))
  339. axes[ncols * 3 + i].set_title(
  340. "Combined: first {} superpixels".format(num_to_show))
  341. self._lime.lime_interpreter.local_weights = lime_weights
  342. if save_outdir is not None:
  343. save_fig(data_, save_outdir, 'normlime', self.num_samples)
  344. if visualization:
  345. plt.show()
  346. class NormLIME(object):
  347. def __init__(self,
  348. predict_fn,
  349. label_names,
  350. num_samples=3000,
  351. batch_size=50,
  352. kmeans_model_for_normlime=None,
  353. normlime_weights=None):
  354. root_path = gen_user_home()
  355. root_path = osp.join(root_path, '.paddlex')
  356. h_pre_models = osp.join(root_path, "pre_models")
  357. if not osp.exists(h_pre_models):
  358. if not osp.exists(root_path):
  359. os.makedirs(root_path)
  360. url = "https://bj.bcebos.com/paddlex/interpret/pre_models.tar.gz"
  361. pdx.utils.download_and_decompress(url, path=root_path)
  362. h_pre_models_kmeans = osp.join(h_pre_models, "kmeans_model.pkl")
  363. if kmeans_model_for_normlime is None:
  364. try:
  365. self.kmeans_model = load_kmeans_model(h_pre_models_kmeans)
  366. except:
  367. raise ValueError(
  368. "NormLIME needs the KMeans model, where we provided a default one in "
  369. "pre_models/kmeans_model.pkl.")
  370. else:
  371. logging.debug("Warning: It is *strongly* suggested to use the \
  372. default KMeans model in pre_models/kmeans_model.pkl. \
  373. Use another one will change the final result.")
  374. self.kmeans_model = load_kmeans_model(kmeans_model_for_normlime)
  375. self.num_samples = num_samples
  376. self.batch_size = batch_size
  377. try:
  378. self.normlime_weights = np.load(
  379. normlime_weights, allow_pickle=True).item()
  380. except:
  381. self.normlime_weights = None
  382. logging.debug(
  383. "Warning: not find the correct precomputed Normlime result.")
  384. self.predict_fn = predict_fn
  385. self.labels = None
  386. self.image = None
  387. self.label_names = label_names
  388. def predict_cluster_labels(self, feature_map, segments):
  389. X = get_feature_for_kmeans(feature_map, segments)
  390. try:
  391. cluster_labels = self.kmeans_model.predict(X)
  392. except AttributeError:
  393. from sklearn.metrics import pairwise_distances_argmin_min
  394. cluster_labels, _ = pairwise_distances_argmin_min(
  395. X, self.kmeans_model.cluster_centers_)
  396. return cluster_labels
  397. def predict_using_normlime_weights(self, pred_labels,
  398. predicted_cluster_labels):
  399. # global weights
  400. g_weights = {y: [] for y in pred_labels}
  401. for y in pred_labels:
  402. cluster_weights_y = self.normlime_weights.get(y, {})
  403. g_weights[y] = [(i, cluster_weights_y.get(k, 0.0))
  404. for i, k in enumerate(predicted_cluster_labels)]
  405. g_weights[y] = sorted(
  406. g_weights[y], key=lambda x: np.abs(x[1]), reverse=True)
  407. return g_weights
  408. def preparation_normlime(self, data_):
  409. self._lime = LIME(self.predict_fn, self.label_names, self.num_samples,
  410. self.batch_size)
  411. self._lime.preparation_lime(data_)
  412. image_show = read_image(data_)
  413. self.predicted_label = self._lime.predicted_label
  414. self.predicted_probability = self._lime.predicted_probability
  415. self.image = image_show[0]
  416. self.labels = self._lime.labels
  417. logging.info('performing NormLIME operations ...')
  418. cluster_labels = self.predict_cluster_labels(
  419. compute_features_for_kmeans(image_show).transpose((1, 2, 0)),
  420. self._lime.lime_interpreter.segments)
  421. g_weights = self.predict_using_normlime_weights(self.labels,
  422. cluster_labels)
  423. return g_weights
  424. def interpret(self, data_, visualization=True, save_outdir=None):
  425. if self.normlime_weights is None:
  426. raise ValueError(
  427. "Not find the correct precomputed NormLIME result. \n"
  428. "\t Try to call compute_normlime_weights() first or load the correct path."
  429. )
  430. g_weights = self.preparation_normlime(data_)
  431. lime_weights = self._lime.lime_interpreter.local_weights
  432. if visualization or save_outdir is not None:
  433. import matplotlib.pyplot as plt
  434. from skimage.segmentation import mark_boundaries
  435. l = self.labels[0]
  436. ln = l
  437. if self.label_names is not None:
  438. ln = self.label_names[l]
  439. psize = 5
  440. nrows = 4
  441. weights_choices = [0.6, 0.7, 0.75, 0.8, 0.85]
  442. nums_to_show = []
  443. ncols = len(weights_choices)
  444. plt.close()
  445. f, axes = plt.subplots(
  446. nrows, ncols, figsize=(psize * ncols, psize * nrows))
  447. for ax in axes.ravel():
  448. ax.axis("off")
  449. axes = axes.ravel()
  450. axes[0].imshow(self.image)
  451. prob_str = "{%.3f}" % (self.predicted_probability)
  452. axes[0].set_title("label {}, proba: {}".format(ln, prob_str))
  453. axes[1].imshow(
  454. mark_boundaries(self.image,
  455. self._lime.lime_interpreter.segments))
  456. axes[1].set_title("superpixel segmentation")
  457. # LIME visualization
  458. for i, w in enumerate(weights_choices):
  459. num_to_show = auto_choose_num_features_to_show(
  460. self._lime.lime_interpreter, l, w)
  461. nums_to_show.append(num_to_show)
  462. temp, mask = self._lime.lime_interpreter.get_image_and_mask(
  463. l,
  464. positive_only=True,
  465. hide_rest=False,
  466. num_features=num_to_show)
  467. axes[ncols + i].imshow(mark_boundaries(temp, mask))
  468. axes[ncols + i].set_title("LIME: first {} superpixels".format(
  469. num_to_show))
  470. # NormLIME visualization
  471. self._lime.lime_interpreter.local_weights = g_weights
  472. for i, num_to_show in enumerate(nums_to_show):
  473. temp, mask = self._lime.lime_interpreter.get_image_and_mask(
  474. l,
  475. positive_only=True,
  476. hide_rest=False,
  477. num_features=num_to_show)
  478. axes[ncols * 2 + i].imshow(mark_boundaries(temp, mask))
  479. axes[ncols * 2 + i].set_title(
  480. "NormLIME: first {} superpixels".format(num_to_show))
  481. # NormLIME*LIME visualization
  482. combined_weights = combine_normlime_and_lime(lime_weights,
  483. g_weights)
  484. self._lime.lime_interpreter.local_weights = combined_weights
  485. for i, num_to_show in enumerate(nums_to_show):
  486. temp, mask = self._lime.lime_interpreter.get_image_and_mask(
  487. l,
  488. positive_only=True,
  489. hide_rest=False,
  490. num_features=num_to_show)
  491. axes[ncols * 3 + i].imshow(mark_boundaries(temp, mask))
  492. axes[ncols * 3 + i].set_title(
  493. "Combined: first {} superpixels".format(num_to_show))
  494. self._lime.lime_interpreter.local_weights = lime_weights
  495. if save_outdir is not None:
  496. save_fig(data_, save_outdir, 'normlime', self.num_samples)
  497. if visualization:
  498. plt.show()
  499. def auto_choose_num_features_to_show(lime_interpreter, label,
  500. percentage_to_show):
  501. segments = lime_interpreter.segments
  502. lime_weights = lime_interpreter.local_weights[label]
  503. num_pixels_threshold_in_a_sp = segments.shape[0] * segments.shape[
  504. 1] // len(np.unique(segments)) // 8
  505. # l1 norm with filtered weights.
  506. used_weights = [(tuple_w[0], tuple_w[1])
  507. for i, tuple_w in enumerate(lime_weights)
  508. if tuple_w[1] > 0]
  509. norm = np.sum([tuple_w[1] for i, tuple_w in enumerate(used_weights)])
  510. normalized_weights = [(tuple_w[0], tuple_w[1] / norm)
  511. for i, tuple_w in enumerate(lime_weights)]
  512. a = 0.0
  513. n = 0
  514. for i, tuple_w in enumerate(normalized_weights):
  515. if tuple_w[1] < 0:
  516. continue
  517. if len(np.where(segments == tuple_w[0])[
  518. 0]) < num_pixels_threshold_in_a_sp:
  519. continue
  520. a += tuple_w[1]
  521. if a > percentage_to_show:
  522. n = i + 1
  523. break
  524. if percentage_to_show <= 0.0:
  525. return 5
  526. if n == 0:
  527. return auto_choose_num_features_to_show(lime_interpreter, label,
  528. percentage_to_show - 0.1)
  529. return n
  530. def get_cam(image_show,
  531. feature_maps,
  532. fc_weights,
  533. label_index,
  534. cam_min=None,
  535. cam_max=None):
  536. _, nc, h, w = feature_maps.shape
  537. cam = feature_maps * fc_weights[:, label_index].reshape(1, nc, 1, 1)
  538. cam = cam.sum((0, 1))
  539. if cam_min is None:
  540. cam_min = np.min(cam)
  541. if cam_max is None:
  542. cam_max = np.max(cam)
  543. cam = cam - cam_min
  544. cam = cam / cam_max
  545. cam = np.uint8(255 * cam)
  546. cam_img = cv2.resize(
  547. cam, image_show.shape[0:2], interpolation=cv2.INTER_LINEAR)
  548. heatmap = cv2.applyColorMap(np.uint8(255 * cam_img), cv2.COLORMAP_JET)
  549. heatmap = np.float32(heatmap)
  550. cam = heatmap + np.float32(image_show)
  551. cam = cam / np.max(cam)
  552. return cam
  553. def save_fig(data_, save_outdir, algorithm_name, num_samples=3000):
  554. import matplotlib.pyplot as plt
  555. if algorithm_name == 'cam':
  556. f_out = "{}_{}.png".format(algorithm_name, data_.split('/')[-1])
  557. else:
  558. f_out = "{}_{}_s{}.png".format(save_outdir, algorithm_name,
  559. num_samples)
  560. plt.savefig(f_out)
  561. logging.info('The image of intrepretation result save in {}'.format(f_out))