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