explanation.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. from .explanation_algorithms import CAM, LIME, NormLIME
  15. class Explanation(object):
  16. """
  17. Base class for all explanation algorithms.
  18. """
  19. def __init__(self, explanation_algorithm_name, predict_fn, **kwargs):
  20. supported_algorithms = {
  21. 'cam': CAM,
  22. 'lime': LIME,
  23. 'normlime': NormLIME
  24. }
  25. self.algorithm_name = explanation_algorithm_name.lower()
  26. assert self.algorithm_name in supported_algorithms.keys()
  27. self.predict_fn = predict_fn
  28. # initialization for the explanation algorithm.
  29. self.explain_algorithm = supported_algorithms[self.algorithm_name](
  30. self.predict_fn, **kwargs
  31. )
  32. def explain(self, data_, visualization=True, save_to_disk=True, save_dir='./tmp'):
  33. """
  34. Args:
  35. data_: data_ can be a path or numpy.ndarray.
  36. visualization: whether to show using matplotlib.
  37. save_to_disk: whether to save the figure in local disk.
  38. save_dir: dir to save figure if save_to_disk is True.
  39. Returns:
  40. """
  41. return self.explain_algorithm.explain(data_, visualization, save_to_disk, save_dir)