normlime_base.py 7.9 KB

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