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