lime_base.py 23 KB

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