lime_base.py 23 KB

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