lime_base.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. """
  2. Copyright (c) 2016, Marco Tulio Correia Ribeiro
  3. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions are met:
  6. * Redistributions of source code must retain the above copyright notice, this
  7. list of conditions and the following disclaimer.
  8. * Redistributions in binary form must reproduce the above copyright notice,
  9. this list of conditions and the following disclaimer in the documentation
  10. and/or other materials provided with the distribution.
  11. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  12. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  13. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  14. DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  15. FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  16. DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  17. SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  18. CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  19. OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  20. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  21. """
  22. """
  23. The code in this file (lime_base.py) is modified from https://github.com/marcotcr/lime.
  24. """
  25. import numpy as np
  26. import scipy as sp
  27. import tqdm
  28. import copy
  29. from functools import partial
  30. import paddlex.utils.logging as logging
  31. class LimeBase(object):
  32. """Class for learning a locally linear sparse model from perturbed data"""
  33. def __init__(self,
  34. kernel_fn,
  35. verbose=False,
  36. random_state=None):
  37. """Init function
  38. Args:
  39. kernel_fn: function that transforms an array of distances into an
  40. array of proximity values (floats).
  41. verbose: if true, print local prediction values from linear model.
  42. random_state: an integer or numpy.RandomState that will be used to
  43. generate random numbers. If None, the random state will be
  44. initialized using the internal numpy seed.
  45. """
  46. from sklearn.utils import check_random_state
  47. self.kernel_fn = kernel_fn
  48. self.verbose = verbose
  49. self.random_state = check_random_state(random_state)
  50. @staticmethod
  51. def generate_lars_path(weighted_data, weighted_labels):
  52. """Generates the lars path for weighted data.
  53. Args:
  54. weighted_data: data that has been weighted by kernel
  55. weighted_label: labels, weighted by kernel
  56. Returns:
  57. (alphas, coefs), both are arrays corresponding to the
  58. regularization parameter and coefficients, respectively
  59. """
  60. from sklearn.linear_model import lars_path
  61. x_vector = weighted_data
  62. alphas, _, coefs = lars_path(x_vector,
  63. weighted_labels,
  64. method='lasso',
  65. verbose=False)
  66. return alphas, coefs
  67. def forward_selection(self, data, labels, weights, num_features):
  68. """Iteratively adds features to the model"""
  69. clf = Ridge(alpha=0, fit_intercept=True, random_state=self.random_state)
  70. used_features = []
  71. for _ in range(min(num_features, data.shape[1])):
  72. max_ = -100000000
  73. best = 0
  74. for feature in range(data.shape[1]):
  75. if feature in used_features:
  76. continue
  77. clf.fit(data[:, used_features + [feature]], labels,
  78. sample_weight=weights)
  79. score = clf.score(data[:, used_features + [feature]],
  80. labels,
  81. sample_weight=weights)
  82. if score > max_:
  83. best = feature
  84. max_ = score
  85. used_features.append(best)
  86. return np.array(used_features)
  87. def feature_selection(self, data, labels, weights, num_features, method):
  88. """Selects features for the model. see interpret_instance_with_data to
  89. understand the parameters."""
  90. from sklearn.linear_model import Ridge
  91. if method == 'none':
  92. return np.array(range(data.shape[1]))
  93. elif method == 'forward_selection':
  94. return self.forward_selection(data, labels, weights, num_features)
  95. elif method == 'highest_weights':
  96. clf = Ridge(alpha=0.01, fit_intercept=True,
  97. random_state=self.random_state)
  98. clf.fit(data, labels, sample_weight=weights)
  99. coef = clf.coef_
  100. if sp.sparse.issparse(data):
  101. coef = sp.sparse.csr_matrix(clf.coef_)
  102. weighted_data = coef.multiply(data[0])
  103. # Note: most efficient to slice the data before reversing
  104. sdata = len(weighted_data.data)
  105. argsort_data = np.abs(weighted_data.data).argsort()
  106. # Edge case where data is more sparse than requested number of feature importances
  107. # In that case, we just pad with zero-valued features
  108. if sdata < num_features:
  109. nnz_indexes = argsort_data[::-1]
  110. indices = weighted_data.indices[nnz_indexes]
  111. num_to_pad = num_features - sdata
  112. indices = np.concatenate((indices, np.zeros(num_to_pad, dtype=indices.dtype)))
  113. indices_set = set(indices)
  114. pad_counter = 0
  115. for i in range(data.shape[1]):
  116. if i not in indices_set:
  117. indices[pad_counter + sdata] = i
  118. pad_counter += 1
  119. if pad_counter >= num_to_pad:
  120. break
  121. else:
  122. nnz_indexes = argsort_data[sdata - num_features:sdata][::-1]
  123. indices = weighted_data.indices[nnz_indexes]
  124. return indices
  125. else:
  126. weighted_data = coef * data[0]
  127. feature_weights = sorted(
  128. zip(range(data.shape[1]), weighted_data),
  129. key=lambda x: np.abs(x[1]),
  130. reverse=True)
  131. return np.array([x[0] for x in feature_weights[:num_features]])
  132. elif method == 'lasso_path':
  133. weighted_data = ((data - np.average(data, axis=0, weights=weights))
  134. * np.sqrt(weights[:, np.newaxis]))
  135. weighted_labels = ((labels - np.average(labels, weights=weights))
  136. * np.sqrt(weights))
  137. nonzero = range(weighted_data.shape[1])
  138. _, coefs = self.generate_lars_path(weighted_data,
  139. weighted_labels)
  140. for i in range(len(coefs.T) - 1, 0, -1):
  141. nonzero = coefs.T[i].nonzero()[0]
  142. if len(nonzero) <= num_features:
  143. break
  144. used_features = nonzero
  145. return used_features
  146. elif method == 'auto':
  147. if num_features <= 6:
  148. n_method = 'forward_selection'
  149. else:
  150. n_method = 'highest_weights'
  151. return self.feature_selection(data, labels, weights,
  152. num_features, n_method)
  153. def interpret_instance_with_data(self,
  154. neighborhood_data,
  155. neighborhood_labels,
  156. distances,
  157. label,
  158. num_features,
  159. feature_selection='auto',
  160. model_regressor=None):
  161. """Takes perturbed data, labels and distances, returns interpretation.
  162. Args:
  163. neighborhood_data: perturbed data, 2d array. first element is
  164. assumed to be the original data point.
  165. neighborhood_labels: corresponding perturbed labels. should have as
  166. many columns as the number of possible labels.
  167. distances: distances to original data point.
  168. label: label for which we want an interpretation
  169. num_features: maximum number of features in interpretation
  170. feature_selection: how to select num_features. options are:
  171. 'forward_selection': iteratively add features to the model.
  172. This is costly when num_features is high
  173. 'highest_weights': selects the features that have the highest
  174. product of absolute weight * original data point when
  175. learning with all the features
  176. 'lasso_path': chooses features based on the lasso
  177. regularization path
  178. 'none': uses all features, ignores num_features
  179. 'auto': uses forward_selection if num_features <= 6, and
  180. 'highest_weights' otherwise.
  181. model_regressor: sklearn regressor to use in interpretation.
  182. Defaults to Ridge regression if None. Must have
  183. model_regressor.coef_ and 'sample_weight' as a parameter
  184. to model_regressor.fit()
  185. Returns:
  186. (intercept, exp, score, local_pred):
  187. intercept is a float.
  188. exp is a sorted list of tuples, where each tuple (x,y) corresponds
  189. to the feature id (x) and the local weight (y). The list is sorted
  190. by decreasing absolute value of y.
  191. score is the R^2 value of the returned interpretation
  192. local_pred is the prediction of the interpretation model on the original instance
  193. """
  194. from sklearn.linear_model import Ridge
  195. weights = self.kernel_fn(distances)
  196. labels_column = neighborhood_labels[:, label]
  197. used_features = self.feature_selection(neighborhood_data,
  198. labels_column,
  199. weights,
  200. num_features,
  201. feature_selection)
  202. if model_regressor is None:
  203. model_regressor = Ridge(alpha=1, fit_intercept=True,
  204. random_state=self.random_state)
  205. easy_model = model_regressor
  206. easy_model.fit(neighborhood_data[:, used_features],
  207. labels_column, sample_weight=weights)
  208. prediction_score = easy_model.score(
  209. neighborhood_data[:, used_features],
  210. labels_column, sample_weight=weights)
  211. local_pred = easy_model.predict(neighborhood_data[0, used_features].reshape(1, -1))
  212. if self.verbose:
  213. logging.info('Intercept' + str(easy_model.intercept_))
  214. logging.info('Prediction_local' + str(local_pred))
  215. logging.info('Right:' + str(neighborhood_labels[0, label]))
  216. return (easy_model.intercept_,
  217. sorted(zip(used_features, easy_model.coef_),
  218. key=lambda x: np.abs(x[1]), reverse=True),
  219. prediction_score, local_pred)
  220. class ImageInterpretation(object):
  221. def __init__(self, image, segments):
  222. """Init function.
  223. Args:
  224. image: 3d numpy array
  225. segments: 2d numpy array, with the output from skimage.segmentation
  226. """
  227. self.image = image
  228. self.segments = segments
  229. self.intercept = {}
  230. self.local_weights = {}
  231. self.local_pred = None
  232. def get_image_and_mask(self, label, positive_only=True, negative_only=False, hide_rest=False,
  233. num_features=5, min_weight=0.):
  234. """Init function.
  235. Args:
  236. label: label to interpret
  237. positive_only: if True, only take superpixels that positively contribute to
  238. the prediction of the label.
  239. negative_only: if True, only take superpixels that negatively contribute to
  240. the prediction of the label. If false, and so is positive_only, then both
  241. negativey and positively contributions will be taken.
  242. Both can't be True at the same time
  243. hide_rest: if True, make the non-interpretation part of the return
  244. image gray
  245. num_features: number of superpixels to include in interpretation
  246. min_weight: minimum weight of the superpixels to include in interpretation
  247. Returns:
  248. (image, mask), where image is a 3d numpy array and mask is a 2d
  249. numpy array that can be used with
  250. skimage.segmentation.mark_boundaries
  251. """
  252. if label not in self.local_weights:
  253. raise KeyError('Label not in interpretation')
  254. if positive_only & negative_only:
  255. raise ValueError("Positive_only and negative_only cannot be true at the same time.")
  256. segments = self.segments
  257. image = self.image
  258. local_weights_label = self.local_weights[label]
  259. mask = np.zeros(segments.shape, segments.dtype)
  260. if hide_rest:
  261. temp = np.zeros(self.image.shape)
  262. else:
  263. temp = self.image.copy()
  264. if positive_only:
  265. fs = [x[0] for x in local_weights_label
  266. if x[1] > 0 and x[1] > min_weight][:num_features]
  267. if negative_only:
  268. fs = [x[0] for x in local_weights_label
  269. if x[1] < 0 and abs(x[1]) > min_weight][:num_features]
  270. if positive_only or negative_only:
  271. for f in fs:
  272. temp[segments == f] = image[segments == f].copy()
  273. mask[segments == f] = 1
  274. return temp, mask
  275. else:
  276. for f, w in local_weights_label[:num_features]:
  277. if np.abs(w) < min_weight:
  278. continue
  279. c = 0 if w < 0 else 1
  280. mask[segments == f] = -1 if w < 0 else 1
  281. temp[segments == f] = image[segments == f].copy()
  282. temp[segments == f, c] = np.max(image)
  283. return temp, mask
  284. def get_rendered_image(self, label, min_weight=0.005):
  285. """
  286. Args:
  287. label: label to interpret
  288. min_weight:
  289. Returns:
  290. image, is a 3d numpy array
  291. """
  292. if label not in self.local_weights:
  293. raise KeyError('Label not in interpretation')
  294. from matplotlib import cm
  295. segments = self.segments
  296. image = self.image
  297. local_weights_label = self.local_weights[label]
  298. temp = np.zeros_like(image)
  299. weight_max = abs(local_weights_label[0][1])
  300. local_weights_label = [(f, w/weight_max) for f, w in local_weights_label]
  301. local_weights_label = sorted(local_weights_label, key=lambda x: x[1], reverse=True) # negatives are at last.
  302. cmaps = cm.get_cmap('Spectral')
  303. colors = cmaps(np.linspace(0, 1, len(local_weights_label)))
  304. colors = colors[:, :3]
  305. for i, (f, w) in enumerate(local_weights_label):
  306. if np.abs(w) < min_weight:
  307. continue
  308. temp[segments == f] = image[segments == f].copy()
  309. temp[segments == f] = colors[i] * 255
  310. return temp
  311. class LimeImageInterpreter(object):
  312. """Interpres predictions on Image (i.e. matrix) data.
  313. For numerical features, perturb them by sampling from a Normal(0,1) and
  314. doing the inverse operation of mean-centering and scaling, according to the
  315. means and stds in the training data. For categorical features, perturb by
  316. sampling according to the training distribution, and making a binary
  317. feature that is 1 when the value is the same as the instance being
  318. interpreted."""
  319. def __init__(self, kernel_width=.25, kernel=None, verbose=False,
  320. feature_selection='auto', random_state=None):
  321. """Init function.
  322. Args:
  323. kernel_width: kernel width for the exponential kernel.
  324. If None, defaults to sqrt(number of columns) * 0.75.
  325. kernel: similarity kernel that takes euclidean distances and kernel
  326. width as input and outputs weights in (0,1). If None, defaults to
  327. an exponential kernel.
  328. verbose: if true, print local prediction values from linear model
  329. feature_selection: feature selection method. can be
  330. 'forward_selection', 'lasso_path', 'none' or 'auto'.
  331. See function 'einterpret_instance_with_data' in lime_base.py for
  332. details on what each of the options does.
  333. random_state: an integer or numpy.RandomState that will be used to
  334. generate random numbers. If None, the random state will be
  335. initialized using the internal numpy seed.
  336. """
  337. from sklearn.utils import check_random_state
  338. kernel_width = float(kernel_width)
  339. if kernel is None:
  340. def kernel(d, kernel_width):
  341. return np.sqrt(np.exp(-(d ** 2) / kernel_width ** 2))
  342. kernel_fn = partial(kernel, kernel_width=kernel_width)
  343. self.random_state = check_random_state(random_state)
  344. self.feature_selection = feature_selection
  345. self.base = LimeBase(kernel_fn, verbose, random_state=self.random_state)
  346. def interpret_instance(self, image, classifier_fn, labels=(1,),
  347. hide_color=None,
  348. num_features=100000, num_samples=1000,
  349. batch_size=10,
  350. distance_metric='cosine',
  351. model_regressor=None
  352. ):
  353. """Generates interpretations for a prediction.
  354. First, we generate neighborhood data by randomly perturbing features
  355. from the instance (see __data_inverse). We then learn locally weighted
  356. linear models on this neighborhood data to interpret each of the classes
  357. in an interpretable way (see lime_base.py).
  358. Args:
  359. image: 3 dimension RGB image. If this is only two dimensional,
  360. we will assume it's a grayscale image and call gray2rgb.
  361. classifier_fn: classifier prediction probability function, which
  362. takes a numpy array and outputs prediction probabilities. For
  363. ScikitClassifiers , this is classifier.predict_proba.
  364. labels: iterable with labels to be interpreted.
  365. hide_color: TODO
  366. num_features: maximum number of features present in interpretation
  367. num_samples: size of the neighborhood to learn the linear model
  368. batch_size: TODO
  369. distance_metric: the distance metric to use for weights.
  370. model_regressor: sklearn regressor to use in interpretation. Defaults
  371. to Ridge regression in LimeBase. Must have model_regressor.coef_
  372. and 'sample_weight' as a parameter to model_regressor.fit()
  373. Returns:
  374. An ImageIinterpretation object (see lime_image.py) with the corresponding
  375. interpretations.
  376. """
  377. import sklearn
  378. from skimage.measure import regionprops
  379. from skimage.segmentation import quickshift
  380. from skimage.color import gray2rgb
  381. if len(image.shape) == 2:
  382. image = gray2rgb(image)
  383. try:
  384. segments = quickshift(image, sigma=1)
  385. except ValueError as e:
  386. raise e
  387. self.segments = segments
  388. fudged_image = image.copy()
  389. if hide_color is None:
  390. # if no hide_color, use the mean
  391. for x in np.unique(segments):
  392. mx = np.mean(image[segments == x], axis=0)
  393. fudged_image[segments == x] = mx
  394. elif hide_color == 'avg_from_neighbor':
  395. from scipy.spatial.distance import cdist
  396. n_features = np.unique(segments).shape[0]
  397. regions = regionprops(segments + 1)
  398. centroids = np.zeros((n_features, 2))
  399. for i, x in enumerate(regions):
  400. centroids[i] = np.array(x.centroid)
  401. d = cdist(centroids, centroids, 'sqeuclidean')
  402. for x in np.unique(segments):
  403. a = [image[segments == i] for i in np.argsort(d[x])[1:6]]
  404. mx = np.mean(np.concatenate(a), axis=0)
  405. fudged_image[segments == x] = mx
  406. else:
  407. fudged_image[:] = 0
  408. top = labels
  409. data, labels = self.data_labels(image, fudged_image, segments,
  410. classifier_fn, num_samples,
  411. batch_size=batch_size)
  412. distances = sklearn.metrics.pairwise_distances(
  413. data,
  414. data[0].reshape(1, -1),
  415. metric=distance_metric
  416. ).ravel()
  417. interpretation_image = ImageInterpretation(image, segments)
  418. for label in top:
  419. (interpretation_image.intercept[label],
  420. interpretation_image.local_weights[label],
  421. interpretation_image.score, interpretation_image.local_pred) = self.base.interpret_instance_with_data(
  422. data, labels, distances, label, num_features,
  423. model_regressor=model_regressor,
  424. feature_selection=self.feature_selection)
  425. return interpretation_image
  426. def data_labels(self,
  427. image,
  428. fudged_image,
  429. segments,
  430. classifier_fn,
  431. num_samples,
  432. batch_size=10):
  433. """Generates images and predictions in the neighborhood of this image.
  434. Args:
  435. image: 3d numpy array, the image
  436. fudged_image: 3d numpy array, image to replace original image when
  437. superpixel is turned off
  438. segments: segmentation of the image
  439. classifier_fn: function that takes a list of images and returns a
  440. matrix of prediction probabilities
  441. num_samples: size of the neighborhood to learn the linear model
  442. batch_size: classifier_fn will be called on batches of this size.
  443. Returns:
  444. A tuple (data, labels), where:
  445. data: dense num_samples * num_superpixels
  446. labels: prediction probabilities matrix
  447. """
  448. n_features = np.unique(segments).shape[0]
  449. data = self.random_state.randint(0, 2, num_samples * n_features) \
  450. .reshape((num_samples, n_features))
  451. labels = []
  452. data[0, :] = 1
  453. imgs = []
  454. for row in tqdm.tqdm(data):
  455. temp = copy.deepcopy(image)
  456. zeros = np.where(row == 0)[0]
  457. mask = np.zeros(segments.shape).astype(bool)
  458. for z in zeros:
  459. mask[segments == z] = True
  460. temp[mask] = fudged_image[mask]
  461. imgs.append(temp)
  462. if len(imgs) == batch_size:
  463. preds = classifier_fn(np.array(imgs))
  464. labels.extend(preds)
  465. imgs = []
  466. if len(imgs) > 0:
  467. preds = classifier_fn(np.array(imgs))
  468. labels.extend(preds)
  469. return data, np.array(labels)