visualize.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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 cv2
  16. import copy
  17. import os.path as osp
  18. import numpy as np
  19. import paddlex as pdx
  20. from .interpretation_predict import interpretation_predict
  21. from .core.interpretation import Interpretation
  22. from .core.normlime_base import precompute_normlime_weights
  23. def gen_user_home():
  24. if "HOME" in os.environ:
  25. home_path = os.environ["HOME"]
  26. if os.path.exists(home_path) and os.path.isdir(home_path):
  27. return home_path
  28. return os.path.expanduser('~')
  29. def visualize(img_file,
  30. model,
  31. dataset=None,
  32. algo='lime',
  33. num_samples=3000,
  34. batch_size=50,
  35. save_dir='./'):
  36. """可解释性可视化。
  37. Args:
  38. img_file (str): 预测图像路径。
  39. model (paddlex.cv.models): paddlex中的模型。
  40. dataset (paddlex.datasets): 数据集读取器,默认为None。
  41. algo (str): 可解释性方式,当前可选'lime'和'normlime'。
  42. num_samples (int): LIME用于学习线性模型的采样数,默认为3000。
  43. batch_size (int): 预测数据batch大小,默认为50。
  44. save_dir (str): 可解释性可视化结果(保存为png格式文件)和中间文件存储路径。
  45. """
  46. assert model.model_type == 'classifier', \
  47. 'Now the interpretation visualize only be supported in classifier!'
  48. if model.status != 'Normal':
  49. raise Exception('The interpretation only can deal with the Normal model')
  50. if not osp.exists(save_dir):
  51. os.makedirs(save_dir)
  52. model.arrange_transforms(
  53. transforms=model.test_transforms, mode='test')
  54. tmp_transforms = copy.deepcopy(model.test_transforms)
  55. tmp_transforms.transforms = tmp_transforms.transforms[:-2]
  56. img = tmp_transforms(img_file)[0]
  57. img = np.around(img).astype('uint8')
  58. img = np.expand_dims(img, axis=0)
  59. interpreter = None
  60. if algo == 'lime':
  61. interpreter = get_lime_interpreter(img, model, dataset, num_samples=num_samples, batch_size=batch_size)
  62. elif algo == 'normlime':
  63. if dataset is None:
  64. raise Exception('The dataset is None. Cannot implement this kind of interpretation')
  65. interpreter = get_normlime_interpreter(img, model, dataset,
  66. num_samples=num_samples, batch_size=batch_size,
  67. save_dir=save_dir)
  68. else:
  69. raise Exception('The {} interpretation method is not supported yet!'.format(algo))
  70. img_name = osp.splitext(osp.split(img_file)[-1])[0]
  71. interpreter.interpret(img, save_dir=save_dir)
  72. def get_lime_interpreter(img, model, dataset, num_samples=3000, batch_size=50):
  73. def predict_func(image):
  74. image = image.astype('float32')
  75. for i in range(image.shape[0]):
  76. image[i] = cv2.cvtColor(image[i], cv2.COLOR_RGB2BGR)
  77. tmp_transforms = copy.deepcopy(model.test_transforms.transforms)
  78. model.test_transforms.transforms = model.test_transforms.transforms[-2:]
  79. out = interpretation_predict(model, image)
  80. model.test_transforms.transforms = tmp_transforms
  81. return out[0]
  82. labels_name = None
  83. if dataset is not None:
  84. labels_name = dataset.labels
  85. interpreter = Interpretation('lime',
  86. predict_func,
  87. labels_name,
  88. num_samples=num_samples,
  89. batch_size=batch_size)
  90. return interpreter
  91. def get_normlime_interpreter(img, model, dataset, num_samples=3000, batch_size=50, save_dir='./'):
  92. def precompute_predict_func(image):
  93. image = image.astype('float32')
  94. tmp_transforms = copy.deepcopy(model.test_transforms.transforms)
  95. model.test_transforms.transforms = model.test_transforms.transforms[-2:]
  96. out = interpretation_predict(model, image)
  97. model.test_transforms.transforms = tmp_transforms
  98. return out[0]
  99. def predict_func(image):
  100. image = image.astype('float32')
  101. for i in range(image.shape[0]):
  102. image[i] = cv2.cvtColor(image[i], cv2.COLOR_RGB2BGR)
  103. tmp_transforms = copy.deepcopy(model.test_transforms.transforms)
  104. model.test_transforms.transforms = model.test_transforms.transforms[-2:]
  105. out = interpretation_predict(model, image)
  106. model.test_transforms.transforms = tmp_transforms
  107. return out[0]
  108. labels_name = None
  109. if dataset is not None:
  110. labels_name = dataset.labels
  111. root_path = gen_user_home()
  112. root_path = osp.join(root_path, '.paddlex')
  113. pre_models_path = osp.join(root_path, "pre_models")
  114. if not osp.exists(pre_models_path):
  115. if not osp.exists(root_path):
  116. os.makedirs(root_path)
  117. url = "https://bj.bcebos.com/paddlex/interpret/pre_models.tar.gz"
  118. pdx.utils.download_and_decompress(url, path=root_path)
  119. npy_dir = precompute_for_normlime(precompute_predict_func,
  120. dataset,
  121. num_samples=num_samples,
  122. batch_size=batch_size,
  123. save_dir=save_dir)
  124. interpreter = Interpretation('normlime',
  125. predict_func,
  126. labels_name,
  127. num_samples=num_samples,
  128. batch_size=batch_size,
  129. normlime_weights=npy_dir)
  130. return interpreter
  131. def precompute_for_normlime(predict_func, dataset, num_samples=3000, batch_size=50, save_dir='./'):
  132. image_list = []
  133. for item in dataset.file_list:
  134. image_list.append(item[0])
  135. return precompute_normlime_weights(
  136. image_list,
  137. predict_func,
  138. num_samples=num_samples,
  139. batch_size=batch_size,
  140. save_dir=save_dir)