AI Logic

Explainability (XAI)

LIME (Local Interpretable Model-agnostic Explanations)

Updated:

Diagram of LIME. The left side shows the flow: the input is split into superpixels, inputs with some parts removed are created and predicted by the model, a linear model is fitted with weights based on proximity, and its coefficients become the explanation. The right side shows a computation example in which an image of a circle and a triangle is split into 4 superpixels, coefficients are obtained by linear regression from the predictions and weights of the perturbed inputs, and only the circle, which has a positive coefficient, is kept

What is LIME?

LIME (Local Interpretable Model-agnostic Explanations) is a method that approximates a complex model with a simple linear model only in the neighborhood of the single input to be explained, and presents its coefficients as the explanation. Ribeiro, Singh, and Guestrin proposed it in 2016.

The procedure has three stages. First, it creates many variants of the input with some parts removed (superpixels for images, words for text). Next, it feeds each variant to the model and collects the predictions. Finally, it fits a linear model that weights variants closer to the original input more heavily. The coefficients of the linear model explain "which parts pushed the prediction up or down, and by how much".

The model is only given inputs and its outputs observed; gradients and weights are not used. Therefore, the same procedure works for any classifier, not only neural networks but also random forests, support vector machines, and others. This is a major difference from methods that need the model's internals (gradients or feature maps), such as the gradient saliency map and Grad-CAM.

Even though the Earth is round, a flat map of a town is perfectly useful. LIME rests on the same idea: even if the model as a whole is a complex curved surface, it can be well approximated by a flat plane (a linear model) close to the input being explained.

Background: three properties required of explanations

Using the example of a doctor deciding whether to trust a model's prediction of "flu", the paper gives reasons why predictions need explanations. Accuracy on validation data alone cannot reveal data leakage (answer cues mixed only into the training data) or differences between the training data and real-world data.

It then requires explanation methods to have the following three properties.

  • Interpretability: present the explanation in a form people can understand. With hundreds of features, showing all the coefficients would not be understandable, so the number of features shown is limited. The explanation uses a representation people understand (whether a word is present or absent) rather than the features the model itself uses (such as word embeddings).
  • Local fidelity: match the model's behavior in the neighborhood of the input being explained. Even if an explanation faithful to the whole model is hard to build, one faithful only nearby is possible.
  • Model agnosticism: treat the model as a black box so that the method works with any model.

In addition, to judge whether the model as a whole can be trusted, the paper proposes a method that selects a few representative inputs and shows their explanations (SP-LIME).

Computation steps

The explanation follows Section 3 of Ribeiro et al. (2016), who proposed the method. Let ff be the model to be explained (returning a probability for each class) and x∈Rdx \in \mathbb{R}^d the input.

  1. Convert to an interpretable representation: represent the input as a binary vector xβ€²βˆˆ{0,1}dβ€²x' \in \{0, 1\}^{d'} indicating the "presence or absence" of human-understandable components. The components are superpixels (small regions of similarly colored pixels) for images and words for text.
  2. Create variants with some parts removed: uniformly choose some of the 1 entries of xβ€²x' and set them to 0 (the number to remove is also chosen uniformly). Convert the resulting zβ€²z' back to the original representation zz. For images, removed superpixels are painted gray.
  3. Predict with the model: compute f(z)f(z) and use it as the label for zβ€²z'. Repeat this NN times.
  4. Weight by proximity: compute the proximity Ο€x(z)\pi_x(z) to the original input with an exponential kernel of distance DD and width Οƒ\sigma. Cosine distance is used for text and L2 distance for images.
  5. Fit a linear model: find the linear model g(zβ€²)=wgβ‹…zβ€²g(z') = w_g \cdot z' that minimizes the squared error weighted by proximity (Eq. 2). The coefficients wgw_g are the explanation.

The explanation is defined as the model that minimizes the sum of the approximation error LL and the complexity of the explanation Ξ©(g)\Omega(g).

ΞΎ(x)=argmin⁑g∈Gβ€…β€ŠL(f,g,Ο€x)+Ξ©(g)(1)\xi(x) = \underset{g \in G}{\operatorname{argmin}}\; L(f, g, \pi_x) + \Omega(g) \qquad (1)

The approximation error is the squared error weighted by proximity. ZZ is the set of variants created in steps 2 and 3.

L(f,g,Ο€x)=βˆ‘z,zβ€²βˆˆZΟ€x(z)(f(z)βˆ’g(zβ€²))2,Ο€x(z)=exp⁑ ⁣(βˆ’D(x,z)2Οƒ2)(2)L(f, g, \pi_x) = \sum_{z, z' \in Z} \pi_x(z) \big(f(z) - g(z')\big)^2, \qquad \pi_x(z) = \exp\!\left(-\frac{D(x, z)^2}{\sigma^2}\right) \qquad (2)

The complexity Ξ©(g)\Omega(g) becomes infinite when more than KK coefficients are nonzero, limiting the explanation to KK components. Eq. 1 cannot be solved directly under this constraint, so the paper selects KK features using the Lasso regularization path and then computes their coefficients by least squares (K-LASSO).

The right side of the top figure is an example in which an image of a circle and a triangle is split into 4 superpixels. Removing the circle greatly lowers the probability of class c, and removing the triangle raises it slightly, so the circle's coefficient is positive and the triangle's is negative. As in the paper's image examples, only the superpixels with positive coefficients are kept, and the rest are shown in gray.

Distant variants are not discarded; their weight is merely reduced by the proximity Ο€x\pi_x. The paper states that this weighting makes the method fairly robust to sampling noise.

Checking the whole model: SP-LIME

Explaining a single prediction does not tell whether the model as a whole can be trusted. Yet the number of explanations a person can look at is limited. The paper proposes a method (Submodular Pick, SP-LIME) that fixes the number of explanations to view at BB and selects inputs that cover as many important features as possible without overlap.

  1. Explain each of the nn inputs with LIME and build the explanation matrix WW (Wij=∣wgij∣W_{ij} = |w_{g_i j}|).
  2. Define the global importance of feature jj as Ij=βˆ‘i=1nWijI_j = \sqrt{\sum_{i=1}^{n} W_{ij}} (for text). Features that appear in the explanations of many inputs get larger values.
  3. Select BB inputs so as to maximize the total importance of the features that appear in the explanation of at least one input in the selected set VV (the coverage cc).
c(V,W,I)=βˆ‘j=1dβ€²1[βˆƒi∈V:Wij>0] Ij(3)c(V, W, I) = \sum_{j=1}^{d'} \mathbb{1}\big[\exists i \in V : W_{ij} > 0\big]\, I_j \qquad (3)

This maximization is NP-hard, but because the coverage is submodular (the gain shrinks as more items are added), a greedy algorithm that adds the input with the largest gain one at a time is guaranteed to reach at least 1βˆ’1/e1 - 1/e of the optimal value.

Experiments in the paper

The paper verifies the method's effectiveness both with simulated users and in experiments with human subjects.

Are the explanations faithful to the model? On binary classification of book reviews and DVD reviews (2000 each), the paper explained models that are themselves interpretable, trained to use at most 10 features per prediction, and measured how well each method recovered the features the model actually used (recall). K=10K = 10 and N=15000N = 15000.

DataModelRandomparzenGreedyLIME
BooksSparse logistic regression17.4%72.8%64.3%92.1%
BooksDecision tree20.6%78.9%37.0%97.0%
DVDsSparse logistic regression19.2%60.8%63.4%90.2%
DVDsDecision tree17.4%80.6%47.6%97.8%

parzen approximates the whole model with Parzen windows and explains it with gradients; greedy removes the most influential feature one at a time until the prediction changes. With decision trees, removing features one at a time often did not change the prediction, so the greedy method's recall dropped.

Can people choose the better model by looking at explanations? Using SVMs that separate "Christianity" and "Atheism" documents in 20 Newsgroups, the paper compared one trained on the original data with one trained on data from which non-generalizing features (headers and author names) had been removed by hand. Accuracy on the original test data was 94.0% and 88.6%, higher for the original, but on separately collected religion web pages it was 57.3% and 69.0%, the reverse. The fraction of users (100 per setting) who picked the better model after viewing 6 explanations was 75.0% (randomly chosen inputs) and 89.0% (inputs chosen by SP-LIME) with LIME explanations, compared with 68.0% and 80.0% with the greedy method's explanations.

Can explanations reveal a flawed model? The paper tested a deliberately built model that predicts wolf if there is a snowy background and husky otherwise.

27 people who took a graduate machine learning courseBefore seeing explanationsAfter seeing explanations
Trusted this model103
Named snow as a cue for the prediction1225

As for computation time, explaining a random forest of 1000 trees with N=5000N = 5000 took under 3 seconds on a laptop, and explaining a single prediction of GoogLeNet (Inception) took about 10 minutes.

Caveats in practice

LIME explanations change with how "removal" is represented, the width Οƒ\sigma of the proximity kernel, and the number of samples NN. The paper chooses these heuristically. The SHAP paper (Lundberg and Lee 2017) shows that, with these heuristic choices, LIME does not satisfy the property that the coefficients sum to the prediction, nor the property that explanations move in the same direction as changes in the model (consistency). Explanations of the same input can change with a different random seed, so compute them several times to check.

Keep the following points in mind as well.

  • Behavior that cannot be expressed in the interpretable representation cannot be explained: in the paper's example, a model that predicts "retro" for sepia-toned images cannot be explained by the presence or absence of superpixels.
  • Strong nonlinearity even nearby leads to unfaithful explanations: this is because the model is approximated with a linear model. The paper recommends estimating the fidelity of the approximation on the generated variants ZZ and showing it to users.
  • It depends on how superpixels are segmented: the unit of explanation is the superpixel, so coarse segmentation cannot show fine details.
  • It takes time to compute: the model's prediction is repeated NN times (5000 to 15000 in the paper). For large image models, explaining a single prediction takes several minutes.

Comparison with other explanation methods

The table compares LIME with explanation methods it is often compared with, from the same viewpoints.

MethodWhat it usesNeeds model internalsUnit of explanationContributions sum to the predictionAmount of computation
LIMEPredictions on partially removed inputs and weighted linear regressionNoSuperpixels, wordsNoThousands of predictions
SHAP (Kernel SHAP)Solves a regression of the same form as LIME with weights that yield Shapley valuesNoSuperpixels, words, featuresYesThousands of predictions
Gradient saliency mapGradient at the inputYes (gradients)PixelsNo1 backward pass
Integrated GradientsIntegral of gradients from the baseline to the inputYes (gradients)PixelsYes20 to 300 backward passes
Grad-CAMFeature maps and gradients of the last convolutional layerYes (intermediate CNN layers)Coarse cells of the feature mapNo1 backward pass

Rough guidelines for choosing:

  • To explain models without gradients (such as tree ensembles) or models behind external APIs: use LIME or SHAP.
  • To make the contributions sum to the prediction, with theoretical backing: use SHAP.
  • To quickly obtain per-pixel contributions for a neural network: use the gradient saliency map, Integrated Gradients, or DeepLIFT.

PyTorch example

Show code
python
import torch

'''
A small implementation of LIME (Ribeiro et al. 2016): represent the presence of superpixels as a binary vector,
predict partially removed images with the model, and use the coefficients of a proximity-weighted linear model as the explanation (Eqs. 1 and 2, Algorithm 1)
'''


@torch.no_grad()
def lime_image(model, image, segments, target, num_samples=1000, sigma=0.25, k=5, fill=0.5):
  # image: [3, H, W], segments: [H, W] superpixel indices (0..d'-1, created beforehand with SLIC or similar)
  model.eval()                                       # predict with inference-time behavior
  d = int(segments.max()) + 1
  # step 2: choose the number to remove uniformly, then uniformly choose that many superpixels and set them to 0
  z = torch.ones(num_samples, d)
  for n in range(1, num_samples):                    # the first sample is the original input (nothing removed)
    m = int(torch.randint(1, d + 1, ()))
    z[n, torch.randperm(d)[:m]] = 0
  # convert z' back to images: paint superpixels with 0 in gray (fill)
  keep = z[:, segments]                              # [N, H, W]
  batch = image * keep[:, None] + fill * (1 - keep[:, None])
  # step 3: predict with the model and use the probability of class target as the label
  y = torch.cat([model(b).softmax(dim=1)[:, target] for b in batch.split(64)])
  # step 4: proximity Ο€_x(z) = exp(βˆ’DΒ² / σ²). Here D is the cosine distance of z'
  cos = z.sum(dim=1) / (d ** 0.5 * z.norm(dim=1).clamp_min(1e-8))
  pi = torch.exp(-((1 - cos) ** 2) / sigma ** 2)
  # step 5: weighted least squares (a simplified version that, instead of K-LASSO, picks the K largest coefficients and refits)
  X = torch.cat([z, torch.ones(num_samples, 1)], dim=1)   # also fit an intercept
  sw = pi.sqrt()[:, None]
  w = torch.linalg.lstsq(X * sw, y[:, None] * sw).solution[:-1, 0]
  top = w.abs().topk(min(k, d)).indices
  Xk = torch.cat([z[:, top], torch.ones(num_samples, 1)], dim=1)
  wk = torch.linalg.lstsq(Xk * sw, y[:, None] * sw).solution[:-1, 0]
  weights = torch.zeros(d)
  weights[top] = wk
  return weights                                     # coefficient per superpixel (positive: supports target)


# Usage example
# weights = lime_image(model, image, segments, target=pred_class, num_samples=1000, k=10)
# mask = (weights > 0)[segments]   # display only the superpixels with positive coefficients

FAQ

Q. How many samples $N$ should be used?
A.

The paper uses N=15000N = 15000 in the text experiments and N=5000N = 5000 in the random forest computation-time example. With too few samples, explanations vary more with the random seed, so compute several times on the same input and increase NN until the top features stop changing places.

Q. How do LIME and SHAP differ?
A.

Both "fit a weighted linear model to predictions on partially removed inputs". They differ in how the weights are determined. LIME sets the proximity kernel Ο€x\pi_x and the limit on the number of features heuristically. Kernel SHAP in SHAP derives the weights (the Shapley kernel) from theory so that the coefficients become Shapley values, and the coefficients sum to the difference between the prediction and the base value.

Q. Can it be used with data other than images?
A.

Yes. The paper represents text by the "presence or absence" of words and explains the predictions of SVMs and random forests. For tabular data too, the same procedure works if each feature is represented as a binary choice between "original value" and "replaced with another value".

References

  1. M. T. Ribeiro, S. Singh, and C. Guestrin, "\"Why Should I Trust You?\": Explaining the Predictions of Any Classifier," Proceedings of the 22nd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining (KDD), pp. 1135–1144, 2016(arXiv:1602.04938).
  2. S. M. Lundberg and S.-I. Lee, "A Unified Approach to Interpreting Model Predictions," Advances in Neural Information Processing Systems 30 (NIPS), 2017(arXiv:1705.07874).