Understanding lime

Thomas Lin Pedersen & Michaël Benesty

2018-03-08

In order to be able to understand the explanations produced by lime it is necessary to have at least some knowledge of how these explanations are achieved. To this end, you are encouraged to read through the article that introduced the lime framework as well as the additional resources linked to from the original Python repository. This vignette will provide an overview to allow you to get up to speed on the framework and let you efficiently understand the output it produces.

How lime explains stuff

Behind the workings of lime lies the (big) assumption that every complex model is linear on a local scale. While this is not justified in the paper it is not difficult to convince yourself that this is generally sound — you usually expect two very similar observations to behave predictably even in a complex model. lime then takes this assumption to its natural conclusion by asserting that it is possible to fit a simple model around a single observation that will mimic how the global model behaves at that locality. The simple model can then be used to explain the predictions of the more complex model locally.

The general approach lime takes to achieving this goal is as follows:

  1. For each prediction to explain, permute the observation n times.
  2. Let the complex model predict the outcome of all permuted observations.
  3. Calculate the distance from all permutations to the original observation.
  4. Convert the distance to a similarity score.
  5. Select m features best describing the complex model outcome from the permuted data.
  6. Fit a simple model to the permuted data, explaining the complex model outcome with the m features from the permuted data weighted by its similarity to the original observation.
  7. Extract the feature weights from the simple model and use these as explanations for the complex models local behavior.

It is clear from the above that there’s much wiggle-room in order to optimize the explanation. Chief among the choices that influence the quality of the explanation is how permutations are created, how permutation similarity is calculated, how, and how many, features are selected, and which model is used as the simple model. Some of these choices are hard-coded into lime, while others can be influenced by the user — all of them will be discussed below.

How to permute an observation

When it comes to permuting an observation, lime depends on the type of input data. Currently two types of inputs are supported: tabular and text

Tabular Data
When dealing with tabular data, the permutations are dependent on the training set. During the creation of the explainer the statistics for each variable are extracted and permutations are then sampled from the variable distributions. This means that permutations are in fact independent from the explained variable making the similarity computation even more important as this is the only thing establishing the locality of the analysis.

Text Data
When the outcome of text predictions are to be explained the permutations are performed by randomly removing words from the original observation. Depending on whether the model uses word location or not, words occurring multiple times will be removed one-by-one or as a whole.

Calculating similarities with permutations

Just as permutations are created differently based on the input data, so the similarities are calculated in different ways. For text data the cosine similarity measure is used, which is the standard in text analysis (it effectively measures the angle difference between the two feature vectors). For tabular data a bit more thought is required and the optimal solution will depend on the type of input data. First, the categorical features will be recoded based on whether or not they are equal to the observation. Second, if continuous features are binned (the default) these features will be recoded based on whether they are in the same bin as the observation. Using the recoded data the distance to the original observation is then calculated based on a user-chosen distance measure (euclidean by default), and converted to a similarity using an exponential kernel of a user defined width (defaults to 0.75 times the square root of the number of features).

Selecting the features to use

Feature selection is a complete sub-field of modelling in itself and lime has no silver bullet for this. Instead, it implements a range of different feature selection approaches that the user is free to choose from. First though, the number of features needs to be chosen. The number must strike a balance between the complexity of the model and the simplicity of the explanation, but try to keep it below 10 (personal opinion). As for selecting the features, lime supports the following algorithms:

Fitting a model to the permuted and feature-reduced data

Once permutations have been created, similarities calculated and features selected it is time to fit a model. If the complex model is a regressor, the simple model will predict the output of the complex model directly. If the complex model is a classifier, the simple model will predict the probability of the chosen class (for classifiers it is possible to either specify the classes to explain, or let lime chose the top k most probable classes).

The only requirement for the simple model is that it can work with weighted input and that it is easy to extract understanding from the resulting fit. While multiple types of models support this, lime uses a ridge regression as the model of choice. In the future this might be expanded to other types of models.

An example - Tabular Data

The following is a simple example which seeks to explain the outcome of a model predicting cancer based on biopsy results:

library(MASS)
library(lime)
data(biopsy)

# First we'll clean up the data a bit
biopsy$ID <- NULL
biopsy <- na.omit(biopsy)
names(biopsy) <- c('clump thickness', 'uniformity of cell size', 
                   'uniformity of cell shape', 'marginal adhesion',
                   'single epithelial cell size', 'bare nuclei', 
                   'bland chromatin', 'normal nucleoli', 'mitoses',
                   'class')

# Now we'll fit a linear discriminant model on all but 4 cases
set.seed(4)
test_set <- sample(seq_len(nrow(biopsy)), 4)
prediction <- biopsy$class
biopsy$class <- NULL
model <- lda(biopsy[-test_set, ], prediction[-test_set])

If we use the model to predict the 4 remaining cases we get some pretty solid predictions:

predict(model, biopsy[test_set, ])
## $class
## [1] benign    benign    malignant benign   
## Levels: benign malignant
## 
## $posterior
##           benign    malignant
## 416 9.943635e-01 5.636486e-03
## 7   9.527375e-01 4.726245e-02
## 207 1.456491e-05 9.999854e-01
## 195 9.999977e-01 2.300862e-06
## 
## $x
##            LD1
## 416 -0.2070616
## 7    0.2382330
## 207  3.1409787
## 195 -1.8101622

But lets see how these predictions came to be, using lime.

explainer <- lime(biopsy[-test_set,], model, bin_continuous = TRUE, quantile_bins = FALSE)
explanation <- explain(biopsy[test_set, ], explainer, n_labels = 1, n_features = 4)
# Only showing part of output for better printing
explanation[, 2:9]
##    case     label label_prob  model_r2 model_intercept model_prediction
## 1   416    benign  0.9943635 0.5432439       0.1298920        1.0137381
## 2   416    benign  0.9943635 0.5432439       0.1298920        1.0137381
## 3   416    benign  0.9943635 0.5432439       0.1298920        1.0137381
## 4   416    benign  0.9943635 0.5432439       0.1298920        1.0137381
## 5     7    benign  0.9527375 0.6586789       0.6779101        0.3433356
## 6     7    benign  0.9527375 0.6586789       0.6779101        0.3433356
## 7     7    benign  0.9527375 0.6586789       0.6779101        0.3433356
## 8     7    benign  0.9527375 0.6586789       0.6779101        0.3433356
## 9   207 malignant  0.9999854 0.1566576       0.3125322        0.6982489
## 10  207 malignant  0.9999854 0.1566576       0.3125322        0.6982489
## 11  207 malignant  0.9999854 0.1566576       0.3125322        0.6982489
## 12  207 malignant  0.9999854 0.1566576       0.3125322        0.6982489
## 13  195    benign  0.9999977 0.5377909       0.1133910        1.0411376
## 14  195    benign  0.9999977 0.5377909       0.1133910        1.0411376
## 15  195    benign  0.9999977 0.5377909       0.1133910        1.0411376
## 16  195    benign  0.9999977 0.5377909       0.1133910        1.0411376
##                    feature feature_value
## 1        marginal adhesion             6
## 2              bare nuclei             3
## 3          clump thickness             3
## 4  uniformity of cell size             3
## 5                  mitoses             1
## 6              bare nuclei            10
## 7          clump thickness             1
## 8  uniformity of cell size             1
## 9              bare nuclei             5
## 10         clump thickness            10
## 11 uniformity of cell size            10
## 12         bland chromatin             3
## 13                 mitoses             1
## 14             bare nuclei             1
## 15         clump thickness             3
## 16 uniformity of cell size             1

We can see that all the explanations for a benign outcome have chosen the same features, strongly indicating that these are both locally and globally important features. Unfortunately we can see that the simple model-fit is not very good (the model_r2 column) leading to less trust in the explanation. We can try to improve on this by decreasing the kernel width, thus making the fit more local.

explanation <- explain(biopsy[test_set, ], explainer, n_labels = 1, n_features = 4, kernel_width = 0.5)
explanation[, 2:9]
##    case     label label_prob  model_r2 model_intercept model_prediction
## 1   416    benign  0.9943635 0.5448504       0.1208588        1.0374223
## 2   416    benign  0.9943635 0.5448504       0.1208588        1.0374223
## 3   416    benign  0.9943635 0.5448504       0.1208588        1.0374223
## 4   416    benign  0.9943635 0.5448504       0.1208588        1.0374223
## 5     7    benign  0.9527375 0.6382741       0.6202056        0.3729293
## 6     7    benign  0.9527375 0.6382741       0.6202056        0.3729293
## 7     7    benign  0.9527375 0.6382741       0.6202056        0.3729293
## 8     7    benign  0.9527375 0.6382741       0.6202056        0.3729293
## 9   207 malignant  0.9999854 0.1630723       0.3332637        0.7002596
## 10  207 malignant  0.9999854 0.1630723       0.3332637        0.7002596
## 11  207 malignant  0.9999854 0.1630723       0.3332637        0.7002596
## 12  207 malignant  0.9999854 0.1630723       0.3332637        0.7002596
## 13  195    benign  0.9999977 0.5637476       0.1120103        1.0433130
## 14  195    benign  0.9999977 0.5637476       0.1120103        1.0433130
## 15  195    benign  0.9999977 0.5637476       0.1120103        1.0433130
## 16  195    benign  0.9999977 0.5637476       0.1120103        1.0433130
##                    feature feature_value
## 1                  mitoses             1
## 2              bare nuclei             3
## 3          clump thickness             3
## 4  uniformity of cell size             3
## 5                  mitoses             1
## 6              bare nuclei            10
## 7          clump thickness             1
## 8  uniformity of cell size             1
## 9              bare nuclei             5
## 10         clump thickness            10
## 11 uniformity of cell size            10
## 12         bland chromatin             3
## 13                 mitoses             1
## 14             bare nuclei             1
## 15         clump thickness             3
## 16 uniformity of cell size             1

This improved it somewhat, especially for the malignant case. In order to get a more intuitive representation, we can use the provided plot_features() to get a visual overview of the explanations.

plot_features(explanation, ncol = 1)

In this overview it is clear to see how case 195 and 416 behave alike, while the third benign case (7) has an unusual large bare nuclei which are detracting from its status as benign without affecting the final prediction (indicating that the values of its other features are making up for this odd one). To no surprise it is clear that high values in the measurements are indicative of a malignant tumor.

An example - text data

The following is a simple example which seeks to explain the outcome of a model classifying sentences from 30 scientific papers as being about (or not) the author’s own work, e.g. methods, results or conclusions.

Most of the things written for data.frame can be applied to textual data.

library(lime)
library(xgboost) # the classifier
library(text2vec) # used to build the BoW matrix

# load data
data(train_sentences)
data(test_sentences)

# Data are stored in a 2 columns data.frame, one for the sentences, one for the 
# labels.
print(str(train_sentences))
## 'data.frame':    2517 obs. of  2 variables:
##  $ class.text: chr  "MISC" "MISC" "AIMX" "OWNX" ...
##  $ text      : chr  "although the internet as level topology has been extensively studied over the past few years  little is known a"| __truncated__ "an as  node  can represent a wide variety of organizations  e g   large isp  or small private business  univers"| __truncated__ "in this paper  we introduce a radically new approach based on machine learning techniques to map all the ases i"| __truncated__ "we believe that this dataset will serve as an invaluable addition to further understanding of the structure and"| __truncated__ ...
## NULL
# The list of possible classes for a sentence
# We are only interested in the class "OWNX"
print(unique(train_sentences$class.text))
##  [1] "MISC"                "AIMX"                "OWNX"               
##  [4] "BASE"                "CONT"                "MISC--the"          
##  [7] "AIMX--on"            "OWNX--after"         "MISC--in"           
## [10] "MISC--specifically," "MISC--on"            "MISC--several"      
## [13] "CONT--these"         "OWNX--we"            "MISC--for"
# Tokenize data
get_matrix <- function(text) {
  it <- itoken(text, progressbar = FALSE)
  create_dtm(it, vectorizer = hash_vectorizer())
}

# BoW matrix generation
dtm_train = get_matrix(train_sentences$text)
dtm_test = get_matrix(test_sentences$text)

# Create boosting model for binary classification (-> logistic loss)
# Other parameters are quite standard
param <- list(max_depth = 7, 
              eta = 0.1, 
              objective = "binary:logistic", 
              eval_metric = "error", 
              nthread = 1)

xgb_model <- xgb.train(
  param, 
  xgb.DMatrix(dtm_train, label = train_sentences$class.text == "OWNX"),
  nrounds = 50
)

We will test our model on test data.

# We use a (standard) threshold of 0.5
predictions <- predict(xgb_model, dtm_test) > 0.5
test_labels <- test_sentences$class.text == "OWNX"

# Accuracy
print(mean(predictions == test_labels))
## [1] 0.8433333

Now we are sure that the model works, we may want to understand what are the most important words for the predictions.

# We select 10 sentences from the label OWNX
sentence_to_explain <- head(test_sentences[test_labels,]$text, 5)
explainer <- lime(sentence_to_explain, model = xgb_model, 
                  preprocess = get_matrix)
explanation <- explain(sentence_to_explain, explainer, n_labels = 1, 
                       n_features = 2)

# Most of the words choosen by Lime
# are related to the team (we, our)
# or part of the paper (Section, in)
explanation[, 2:9]
##          case label label_prob  model_r2 model_intercept model_prediction
## in          1     1  0.6418385 0.9879333       0.3326710        0.6436784
## we          1     1  0.6418385 0.9879333       0.3326710        0.6436784
## in1         2     1  0.8022363 0.8685332       0.3211022        0.7412829
## We          2     1  0.8022363 0.8685332       0.3211022        0.7412829
## those       3     0  0.5432571 0.8829248       0.6906814        0.4991896
## we1         3     0  0.5432571 0.8829248       0.6906814        0.4991896
## in2         4     1  0.8719526 0.6727718       0.4898704        0.8398251
## Section     4     1  0.8719526 0.6727718       0.4898704        0.8398251
## CITATION    5     1  0.7316587 0.4646800       0.4378562        0.6101550
## our         5     1  0.7316587 0.4646800       0.4378562        0.6101550
##           feature feature_value
## in             in            in
## we             we            we
## in1            in            in
## We             We            We
## those       those         those
## we1            we            we
## in2            in            in
## Section   Section       Section
## CITATION CITATION      CITATION
## our           our           our
# Another more graphical view of the same information (2 first sentences only)
plot_features(explanation)

The graph view gives lots of detailed information about the selected words. Another approach to explain a text classification model is to see the most important words in their context.

plot_text_explanations(explanation)

For some sentences, the prediction is wrong. For instance, look at the third sentence. The word we is in red and the predicted label is 0 (with a low probability), meaning the model thinks it’s not a sentence from the category OWNX, mainly because of the presence of the word those but the word we in red doesn’t support this (false) prediction.

Interactive text model explanations

Text explanations are also available through shine to explore interactively the model.

After loading the application, both text and parameters can be modified. Prediction and selected words are updated in real time.

# Launching the application is done in one command
interactive_text_explanations(explainer)
Interactive text explanations

Interactive text explanations

Session Info

## Session info -------------------------------------------------------------
##  setting  value                       
##  version  R version 3.4.3 (2017-11-30)
##  system   x86_64, darwin15.6.0        
##  ui       X11                         
##  language (EN)                        
##  collate  C                           
##  tz       Europe/Copenhagen           
##  date     2018-03-08
## Packages -----------------------------------------------------------------
##  package        * version    date       source                          
##  assertthat       0.2.0      2017-04-11 CRAN (R 3.4.0)                  
##  backports        1.1.2      2017-12-13 CRAN (R 3.4.3)                  
##  base           * 3.4.3      2017-12-07 local                           
##  codetools        0.2-15     2016-10-05 CRAN (R 3.4.3)                  
##  colorspace       1.3-2      2016-12-14 CRAN (R 3.4.0)                  
##  compiler         3.4.3      2017-12-07 local                           
##  data.table       1.10.4-3   2017-10-27 CRAN (R 3.4.2)                  
##  datasets       * 3.4.3      2017-12-07 local                           
##  devtools         1.13.4     2017-11-09 CRAN (R 3.4.2)                  
##  digest           0.6.15     2018-01-28 CRAN (R 3.4.3)                  
##  evaluate         0.10.1     2017-06-24 CRAN (R 3.4.1)                  
##  foreach          1.4.4      2017-12-12 CRAN (R 3.4.3)                  
##  futile.logger    1.4.3      2016-07-10 CRAN (R 3.4.0)                  
##  futile.options   1.0.0      2010-04-06 CRAN (R 3.4.0)                  
##  ggplot2          2.2.1.9000 2018-01-22 local                           
##  glmnet           2.0-13     2017-09-22 CRAN (R 3.4.2)                  
##  gower            0.1.2      2017-02-23 CRAN (R 3.4.0)                  
##  graphics       * 3.4.3      2017-12-07 local                           
##  grDevices      * 3.4.3      2017-12-07 local                           
##  grid             3.4.3      2017-12-07 local                           
##  gtable           0.2.0      2016-02-26 CRAN (R 3.4.0)                  
##  htmltools        0.3.6      2017-04-28 CRAN (R 3.4.0)                  
##  htmlwidgets      1.0        2018-01-20 CRAN (R 3.4.3)                  
##  httpuv           1.3.5      2017-07-04 CRAN (R 3.4.1)                  
##  iterators        1.0.9      2017-12-12 CRAN (R 3.4.3)                  
##  jsonlite         1.5        2017-06-01 CRAN (R 3.4.0)                  
##  knitr            1.19       2018-01-29 CRAN (R 3.4.3)                  
##  labeling         0.3        2014-08-23 CRAN (R 3.4.0)                  
##  lambda.r         1.2        2017-09-16 CRAN (R 3.4.1)                  
##  lattice          0.20-35    2017-03-25 CRAN (R 3.4.3)                  
##  lazyeval         0.2.1      2017-10-29 CRAN (R 3.4.2)                  
##  lime           * 0.4.0      2018-03-08 local                           
##  magick           1.6        2017-12-01 CRAN (R 3.4.3)                  
##  magrittr         1.5        2014-11-22 CRAN (R 3.4.0)                  
##  MASS           * 7.3-48     2017-12-25 CRAN (R 3.4.3)                  
##  Matrix           1.2-12     2017-11-20 CRAN (R 3.4.3)                  
##  memoise          1.1.0      2017-04-21 CRAN (R 3.4.0)                  
##  methods        * 3.4.3      2017-12-07 local                           
##  mime             0.5        2016-07-07 CRAN (R 3.4.0)                  
##  mlapi            0.1.0      2017-12-17 CRAN (R 3.4.3)                  
##  munsell          0.4.3      2016-02-13 CRAN (R 3.4.0)                  
##  parallel         3.4.3      2017-12-07 local                           
##  pillar           1.1.0      2018-01-14 CRAN (R 3.4.3)                  
##  plyr             1.8.4      2016-06-08 CRAN (R 3.4.0)                  
##  R6               2.2.2      2017-06-17 CRAN (R 3.4.0)                  
##  Rcpp             0.12.15    2018-01-20 CRAN (R 3.4.3)                  
##  RcppParallel     4.3.20     2016-08-16 CRAN (R 3.4.0)                  
##  rlang            0.1.6.9003 2018-01-17 Github (tidyverse/rlang@c56b0ae)
##  rmarkdown        1.8        2017-11-17 CRAN (R 3.4.2)                  
##  rprojroot        1.3-2      2018-01-03 CRAN (R 3.4.3)                  
##  scales           0.5.0.9000 2017-10-09 Github (hadley/scales@d767915)  
##  shiny            1.0.5      2017-08-23 CRAN (R 3.4.1)                  
##  shinythemes      1.1.1      2016-10-12 CRAN (R 3.4.0)                  
##  stats          * 3.4.3      2017-12-07 local                           
##  stringdist       0.9.4.6    2017-07-31 CRAN (R 3.4.1)                  
##  stringi          1.1.6      2017-11-17 CRAN (R 3.4.2)                  
##  stringr          1.2.0      2017-02-18 CRAN (R 3.4.0)                  
##  text2vec       * 0.5.1      2018-01-11 CRAN (R 3.4.3)                  
##  tibble           1.4.2      2018-01-22 CRAN (R 3.4.3)                  
##  tools            3.4.3      2017-12-07 local                           
##  utils          * 3.4.3      2017-12-07 local                           
##  withr            2.1.1.9000 2018-01-04 Github (jimhester/withr@df18523)
##  xgboost        * 0.6.4.1    2018-01-23 CRAN (R 3.4.3)                  
##  xtable           1.8-2      2016-02-05 CRAN (R 3.4.0)                  
##  yaml             2.1.16     2017-12-12 CRAN (R 3.4.3)