normlime_base.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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 numpy as np
  16. import glob
  17. from paddlex.interpret.as_data_reader.readers import read_image
  18. import paddlex.utils.logging as logging
  19. from . import lime_base
  20. from ._session_preparation import compute_features_for_kmeans, h_pre_models_kmeans
  21. def load_kmeans_model(fname):
  22. import pickle
  23. with open(fname, 'rb') as f:
  24. kmeans_model = pickle.load(f)
  25. return kmeans_model
  26. def combine_normlime_and_lime(lime_weights, g_weights):
  27. pred_labels = lime_weights.keys()
  28. combined_weights = {y: [] for y in pred_labels}
  29. for y in pred_labels:
  30. normlized_lime_weights_y = lime_weights[y]
  31. lime_weights_dict = {tuple_w[0]: tuple_w[1] for tuple_w in normlized_lime_weights_y}
  32. normlized_g_weight_y = g_weights[y]
  33. normlime_weights_dict = {tuple_w[0]: tuple_w[1] for tuple_w in normlized_g_weight_y}
  34. combined_weights[y] = [
  35. (seg_k, lime_weights_dict[seg_k] * normlime_weights_dict[seg_k])
  36. for seg_k in lime_weights_dict.keys()
  37. ]
  38. combined_weights[y] = sorted(combined_weights[y],
  39. key=lambda x: np.abs(x[1]), reverse=True)
  40. return combined_weights
  41. def avg_using_superpixels(features, segments):
  42. one_list = np.zeros((len(np.unique(segments)), features.shape[2]))
  43. for x in np.unique(segments):
  44. one_list[x] = np.mean(features[segments == x], axis=0)
  45. return one_list
  46. def centroid_using_superpixels(features, segments):
  47. from skimage.measure import regionprops
  48. regions = regionprops(segments + 1)
  49. one_list = np.zeros((len(np.unique(segments)), features.shape[2]))
  50. for i, r in enumerate(regions):
  51. one_list[i] = features[int(r.centroid[0] + 0.5), int(r.centroid[1] + 0.5), :]
  52. # print(one_list.shape)
  53. return one_list
  54. def get_feature_for_kmeans(feature_map, segments):
  55. from sklearn.preprocessing import normalize
  56. centroid_feature = centroid_using_superpixels(feature_map, segments)
  57. avg_feature = avg_using_superpixels(feature_map, segments)
  58. x = np.concatenate((centroid_feature, avg_feature), axis=-1)
  59. x = normalize(x)
  60. return x
  61. def precompute_normlime_weights(list_data_, predict_fn, num_samples=3000, batch_size=50, save_dir='./tmp'):
  62. # save lime weights and kmeans cluster labels
  63. precompute_lime_weights(list_data_, predict_fn, num_samples, batch_size, save_dir)
  64. # load precomputed results, compute normlime weights and save.
  65. fname_list = glob.glob(os.path.join(save_dir, f'lime_weights_s{num_samples}*.npy'))
  66. return compute_normlime_weights(fname_list, save_dir, num_samples)
  67. def save_one_lime_predict_and_kmean_labels(lime_all_weights, image_pred_labels, cluster_labels, save_path):
  68. lime_weights = {}
  69. for label in image_pred_labels:
  70. lime_weights[label] = lime_all_weights[label]
  71. for_normlime_weights = {
  72. 'lime_weights': lime_weights, # a dict: class_label: (seg_label, weight)
  73. 'cluster': cluster_labels # a list with segments as indices.
  74. }
  75. np.save(save_path, for_normlime_weights)
  76. def precompute_lime_weights(list_data_, predict_fn, num_samples, batch_size, save_dir):
  77. kmeans_model = load_kmeans_model(h_pre_models_kmeans)
  78. for data_index, each_data_ in enumerate(list_data_):
  79. if isinstance(each_data_, str):
  80. save_path = f"lime_weights_s{num_samples}_{each_data_.split('/')[-1].split('.')[0]}.npy"
  81. save_path = os.path.join(save_dir, save_path)
  82. else:
  83. save_path = f"lime_weights_s{num_samples}_{data_index}.npy"
  84. save_path = os.path.join(save_dir, save_path)
  85. if os.path.exists(save_path):
  86. logging.info(save_path + ' exists, not computing this one.', use_color=True)
  87. continue
  88. logging.info('processing'+each_data_ if isinstance(each_data_, str) else data_index + \
  89. f'+{data_index}/{len(list_data_)}', use_color=True)
  90. image_show = read_image(each_data_)
  91. result = predict_fn(image_show)
  92. result = result[0] # only one image here.
  93. if abs(np.sum(result) - 1.0) > 1e-4:
  94. # softmax
  95. exp_result = np.exp(result)
  96. probability = exp_result / np.sum(exp_result)
  97. else:
  98. probability = result
  99. pred_label = np.argsort(probability)[::-1]
  100. # top_k = argmin(top_n) > threshold
  101. threshold = 0.05
  102. top_k = 0
  103. for l in pred_label:
  104. if probability[l] < threshold or top_k == 5:
  105. break
  106. top_k += 1
  107. if top_k == 0:
  108. top_k = 1
  109. pred_label = pred_label[:top_k]
  110. algo = lime_base.LimeImageInterpreter()
  111. interpreter = algo.interpret_instance(image_show[0], predict_fn, pred_label, 0,
  112. num_samples=num_samples, batch_size=batch_size)
  113. X = get_feature_for_kmeans(compute_features_for_kmeans(image_show).transpose((1, 2, 0)), interpreter.segments)
  114. try:
  115. cluster_labels = kmeans_model.predict(X)
  116. except AttributeError:
  117. from sklearn.metrics import pairwise_distances_argmin_min
  118. cluster_labels, _ = pairwise_distances_argmin_min(X, kmeans_model.cluster_centers_)
  119. save_one_lime_predict_and_kmean_labels(
  120. interpreter.local_weights, pred_label,
  121. cluster_labels,
  122. save_path
  123. )
  124. def compute_normlime_weights(a_list_lime_fnames, save_dir, lime_num_samples):
  125. normlime_weights_all_labels = {}
  126. for f in a_list_lime_fnames:
  127. try:
  128. lime_weights_and_cluster = np.load(f, allow_pickle=True).item()
  129. lime_weights = lime_weights_and_cluster['lime_weights']
  130. cluster = lime_weights_and_cluster['cluster']
  131. except:
  132. print('When loading precomputed LIME result, skipping', f)
  133. continue
  134. print('Loading precomputed LIME result,', f)
  135. pred_labels = lime_weights.keys()
  136. for y in pred_labels:
  137. normlime_weights = normlime_weights_all_labels.get(y, {})
  138. w_f_y = [abs(w[1]) for w in lime_weights[y]]
  139. w_f_y_l1norm = sum(w_f_y)
  140. for w in lime_weights[y]:
  141. seg_label = w[0]
  142. weight = w[1] * w[1] / w_f_y_l1norm
  143. a = normlime_weights.get(cluster[seg_label], [])
  144. a.append(weight)
  145. normlime_weights[cluster[seg_label]] = a
  146. normlime_weights_all_labels[y] = normlime_weights
  147. # compute normlime
  148. for y in normlime_weights_all_labels:
  149. normlime_weights = normlime_weights_all_labels.get(y, {})
  150. for k in normlime_weights:
  151. normlime_weights[k] = sum(normlime_weights[k]) / len(normlime_weights[k])
  152. # check normlime
  153. if len(normlime_weights_all_labels.keys()) < max(normlime_weights_all_labels.keys()) + 1:
  154. print(
  155. "\n"
  156. "Warning: !!! \n"
  157. f"There are at least {max(normlime_weights_all_labels.keys()) + 1} classes, "
  158. f"but the NormLIME has results of only {len(normlime_weights_all_labels.keys())} classes. \n"
  159. "It may have cause unstable results in the later computation"
  160. " but can be improved by computing more test samples."
  161. "\n"
  162. )
  163. n = 0
  164. f_out = f'normlime_weights_s{lime_num_samples}_samples_{len(a_list_lime_fnames)}-{n}.npy'
  165. while os.path.exists(
  166. os.path.join(save_dir, f_out)
  167. ):
  168. n += 1
  169. f_out = f'normlime_weights_s{lime_num_samples}_samples_{len(a_list_lime_fnames)}-{n}.npy'
  170. continue
  171. np.save(
  172. os.path.join(save_dir, f_out),
  173. normlime_weights_all_labels
  174. )
  175. return os.path.join(save_dir, f_out)