| feature_desc | feature_weight | model_r2 |
|---|---|---|
| 0.0166 < x <= 0.5060 | -0.0534219 | 0.002533 |
| -0.48171 < y <= 0.00701 | 0.0087073 | 0.002533 |
5 kumquat: A simpler lime
6 Introduction
Machine learning models are increasingly used because they capture complex relationships in data and achieve high predictive accuracy. This accuracy often comes at the cost of interpretability, and prediction accuracy alone is not sufficient when users need to understand the decision process behind a prediction. Together with regulations that give people a right to meaningful information about automated decisions made about them (European Parliament and Council of the European Union 2016; Goodman and Flaxman 2017), this has driven the development of explainable AI (XAI) methods (Molnar 2022). XAI methods examine different facets of a model, such as feature importances and feature contributions. Global methods describe the model over the whole dataset. Local methods describe the prediction for a single observation. Because predictions are made about individuals, understanding how features influence the prediction for a specific observation is particularly important.
Local Interpretable Model-agnostic Explanations (LIME) (Ribeiro et al. 2016) is a widely used local, model-agnostic XAI method that answers the question “Which features were most important in making the prediction for this observation?”. For a given observation, LIME (i) generates perturbations in the local neighbourhood of the observation, (ii) passes them through the black-box model and records the predictions, (iii) weights the perturbations by their proximity to the observation, and (iv) fits a simple interpretable surrogate model to these weighted predictions. The coefficients of the surrogate are then reported as the contributions of each feature to the black-box prediction. In R, LIME is implemented in lime (Hvitfeldt et al. 2025), and related local surrogate explanations are available in iml (Molnar et al. 2018) and through DALEX (Biecek 2018; Staniak and Biecek 2018).
While lime provides a robust implementation of the method, it returns the feature weights together with only a summary of the surrogate fit (its R^2, intercept and prediction for the observation). The perturbations, their weights and the fitted surrogate model itself are discarded. Thereby users of lime cannot check how faithfully the surrogate approximates the black-box model, nor visualise the local decision boundary that the explanation is based on. Similarly, existing tools for visualising local surrogate explanations, such as plot_features() and plot_explanations() in lime (Hvitfeldt et al. 2025) and the plot() methods for local models in iml (Molnar et al. 2018) and DALEX (Biecek 2018), display the importance values produced by the explainer as bar charts or heatmaps, rather than the data and models that produced them.
These limitations also affect how XAI methods are taught and evaluated. Because methods such as LIME combine several components, it can be daunting for beginners to understand how an importance value is obtained. On real datasets the true decision boundary is unknown, so neither learners nor practitioners can tell whether an explanation is correct. Small datasets with known boundaries, where the important feature in each region is visually identifiable, allow educators to show each step of the pipeline and how it shapes the final importances, and allow practitioners to check that an explainer recovers the expected importances before applying it to real problems.
The kumquat package (Wanniarachchi 2026) presented in this paper provides a simplified and transparent implementation of LIME in R. Each step of the LIME pipeline is implemented as its own function that can be swapped for a user-written alternative, and every intermediate object is returned to the user. Models of any class are supported through a user-supplied prediction function and the bundle package (Silge et al. 2025).
Our contributions include a modular reimplementation of LIME in which the perturbations, weights, surrogate model and its predictions are exposed for inspection and visualisation. In addition we provide four synthetic benchmark datasets with known decision boundaries and identifiable feature importances, designed for teaching LIME and for checking whether a local explainer behaves as expected.
The paper is structured as follows. Section 8.1 introduces the notation used throughout, Chapter 8 defines LIME mathematically, and Chapter 9 motivates the need for a reimplementation by illustrating the limitations of lime on a simple dataset. Chapter 10 describes the design of kumquat, and Chapter 11 introduces the benchmark datasets. Chapter 12 uses one of these datasets to demonstrate what kumquat offers beyond lime: access to the output of every step of the pipeline, and the ability to swap any step for an alternative. Finally, Chapter 13 discusses future improvements and the need for transparent and understandable explainers.
8 Preliminary
8.1 Notations
We consider a binary classification problem with p continuous predictors and classes A and B. The training data consist of n observations \boldsymbol{x}_i = (x_{i1}, \dots, x_{ip})^\top \in \mathbb{R}^p with class labels c_i \in \{A, B\}, i = 1, \dots, n. The black-box model is a classifier f : \mathbb{R}^p \to \{A, B\}. The observation to be explained, the point of interest, is \boldsymbol{x}_0 = (x_{01}, \dots, x_{0p})^\top, which need not be one of the training observations. kumquat uses \boldsymbol{x}_0 only to centre and weight the neighbourhood, and the training data only to check the predictor names, so any point of the feature space can be explained (the example in Chapter 9 uses \boldsymbol{x}_0 = (0.28, 0)^\top, which is not in d_vertical). Its neighbourhood is represented by N perturbations \boldsymbol{z}_k = (z_{k1}, \dots, z_{kp})^\top, k = 1, \dots, N. Throughout, the subscripts i, k and j index training observations, perturbations and predictors respectively, and \boldsymbol{x} without a subscript denotes a generic point of the feature space.
8.2 A brief introduction to LIME
Given a black-box model f and a point of interest \boldsymbol{x}_0, LIME (Ribeiro et al. 2016) produces the explanation
\xi(\boldsymbol{x}_0) = \underset{g \in \mathcal{G}}{\arg\min} \; \mathcal{L}(f, g, \pi_{\boldsymbol{x}_0}) + \Omega(g),
where \mathcal{G} is a class of interpretable models, \mathcal{L} is a loss that measures the disagreement between the predictions of g and those of f on points near \boldsymbol{x}_0, with each point weighted by its proximity to \boldsymbol{x}_0 through the kernel \pi_{\boldsymbol{x}_0}, and \Omega penalises the complexity of g. A small value of \mathcal{L} means that g reproduces the behaviour of f closely around \boldsymbol{x}_0.
The original formulation defines g on an interpretable representation \boldsymbol{z}' \in \{0,1\}^p, which indicates whether each feature of a perturbation agrees with the point of interest. For tabular data, lime constructs it by discretising continuous features into quantile bins. kumquat instead uses the features on their original scale, so that g is defined on \mathbb{R}^p and its coefficients describe the local decision boundary directly.
In kumquat, \mathcal{G} is the class of logistic regression models. Given the perturbations \boldsymbol{z}_1, \dots, \boldsymbol{z}_N with black-box labels y_k = \mathbb{1}\{f(\boldsymbol{z}_k) = B\} and weights w_k = \pi_{\boldsymbol{x}_0}(\boldsymbol{z}_k), the loss and complexity terms are the weighted binomial deviance and the lasso penalty,
\mathcal{L}(f, g, \pi_{\boldsymbol{x}_0}) = -\frac{1}{N}\sum_{k=1}^{N} w_k \left[ y_k \eta_k - \log\left(1 + e^{\eta_k}\right) \right], \qquad \Omega(g) = \lambda \sum_{j=1}^{p} |\beta_j|,
where \eta_k = \beta_0 + \boldsymbol{\beta}^\top \boldsymbol{z}_k. The penalty \lambda is chosen by K-fold cross-validation with glmnet::cv.glmnet() (Friedman et al. 2010). The perturbations are randomly split into K folds (K = 50 by default in kumquat(), set by nfolds). For a decreasing sequence of \lambda values, the model is fitted to K - 1 folds and the weighted binomial deviance is computed on the remaining fold. The \lambda with the smallest deviance averaged over the folds (lambda.min) is used, and the model is refitted to all perturbations with that value. Because the folds are random, the coefficients can vary slightly between runs unless a seed is set. Features with \beta_j = 0 are considered unimportant. The explanation is therefore
\xi(\boldsymbol{x}_0) = \underset{\beta_0, \boldsymbol{\beta}}{\arg\min} \; -\frac{1}{N}\sum_{k=1}^{N} w_k \left[ y_k \eta_k - \log\left(1 + e^{\eta_k}\right) \right] + \lambda \sum_{j=1}^{p} |\beta_j| .
Compared with the original formulation and its implementation in lime, this changes four parts of the problem.
- Representation: g is defined on \boldsymbol{z}_k \in \mathbb{R}^p on the original scale of the features, not on the binary vector \boldsymbol{z}' \in \{0,1\}^p.
- Neighbourhood: the perturbations are evenly spaced points on a regular grid centred on the point of interest, reaching a distance r on either side of it along every feature (Chapter 10). The same point of interest always gives the same perturbations, whereas lime draws them at random from the distribution of the training data.
- Kernel: by default w_k = 1 for every perturbation, so the box acts as a uniform kernel. The exponential kernel of LIME is used only when requested.
- Loss and complexity: y_k are the predicted class labels of f and g is a lasso logistic regression, whereas lime fits a ridge regression to the predicted class probabilities and controls \Omega by limiting the number of selected features.
9 The need for a reimplementation
9.1 The lime package
lime (Hvitfeldt et al. 2025) is a port of the Python reference implementation. It uses a two-step interface. lime() takes the training data and a model and returns an explainer object, which stores summary statistics of the training data. explain() then takes the observations to be explained together with the explainer and returns a data frame with one row per observation, class label and selected feature. Supported model classes are handled through the S3 generics model_type() and predict_model(), and users can register new classes by writing methods for both. The results can be visualised with plot_features() and plot_explanations(), which display the feature weights as bar charts and heatmaps respectively.
9.2 Limitations illustrated on a simple boundary
Consider d_vertical, where the class changes at x_1 = 0.3 and x_2 is irrelevant (Chapter 11). We fit a random forest and explain a point just to the left of the boundary, \boldsymbol{x}_0 = (0.28, 0)^\top, with lime using its default settings. The quartile bins of x_1 are approximately [-1, -0.5), [-0.5, 0), [0, 0.5) and [0.5, 1], so the boundary lies inside the bin that contains \boldsymbol{x}_0. Being inside the bin is not a problem in itself. The problem is that the class changes within the bin. The binary feature z'_1 only records whether a perturbation falls in the same bin as \boldsymbol{x}_0, so a perturbation at x_1 = 0.1 (class B) and one at x_1 = 0.4 (class A) both have z'_1 = 1. Outside the bin, perturbations in [0.5, 1] are class A and those in [-1, 0) are class B, so z'_1 = 0 also mixes both classes. z'_1 is therefore only weakly associated with the prediction, and the surrogate has no way to express that the class changes at x_1 = 0.3. In the explanation below, the weight of x_1 is -0.053 and the weight of x_2 is 0.009, with R^2 = 0.003. Because only the weights and model_r2 are returned, the user cannot see that the surrogate was fitted to a representation in which the true boundary is invisible.
d_vertical, coloured by the random forest prediction. Left: perturbations sampled by lime, with the quartile bin edges (dashed) and the bin containing \boldsymbol{x}_0 (solid). The boundary at x_1 = 0.3 lies inside this bin. Right: the kumquat perturbations with the boundary of the local surrogate.
10 Package overview and Implementation
10.1 Design
kumquat implements each step of the LIME algorithm as a separate function (Table 10.1). Each function corresponds to one component of the LIME objective. generate_perturbations() defines the neighbourhood in which \mathcal{L} is evaluated, kernel_weights() implements the proximity kernel \pi_{\boldsymbol{x}_0}, and fit_local_model() minimises \mathcal{L} + \Omega over \mathcal{G}. kumquat() chains these functions, and each can be replaced through an argument of kumquat() (Table 10.2). Each step is called with named arguments, and a replacement only needs to accept the ones it uses, so a perturbation scheme that depends only on the point of interest and the radius can be written as function(poi, radius, predictor_vars). The output of each step is checked before it is passed on, so a replacement that returns the wrong shape fails with an informative error rather than further down the pipeline. Pre-computed neighbourhoods can also be supplied directly through the perturbations argument. An example of replacing a step is given in Section 12.3.
| Function | Purpose |
|---|---|
generate_perturbations() |
Regular grid of perturbations in a box of half-width radius around the point of interest. |
kernel_weights() |
LIME exponential-kernel weights based on Euclidean or Manhattan distance. |
fit_local_model() |
Weighted, cross-validated lasso logistic regression on the perturbations. |
kumquat() |
Full pipeline for one or more points of interest, with replaceable steps; returns every intermediate object. |
pinch_importance() |
Collects the local coefficients of several explanations into one data frame. |
plot_interest() |
Plots perturbations, training data and the point of interest for two-dimensional data, with a configurable class palette. |
kumquat(). Each step function receives the listed inputs by name and must return the listed output.
| Argument | Default | Inputs | Output |
|---|---|---|---|
perturb_fun |
generate_perturbations() |
data, poi, radius, step, predictor_vars
|
Data frame with one column per predictor and one row per perturbation |
weight_fun |
kernel_weights() if weighted = TRUE, otherwise equal weights |
perturbations, poi, predictor_vars, kernel_width, dist_fun
|
Non-negative numeric vector with one weight per perturbation |
surrogate_fun |
fit_local_model() |
perturbations, predictor_vars, nfolds, alpha, class_names, weights
|
List; glm_predictions and importances are needed by plot_interest() and pinch_importance()
|
The design choices behind the kumquat package are defined as follows.
Perturbations
Let r be the radius and \delta the step size. For each predictor j, generate_perturbations() forms the grid G_j = \{x_{0j} - r,\; x_{0j} - r + \delta,\; \dots,\; x_{0j} + r\} of 2r/\delta + 1 equally spaced values centred on the point of interest. The perturbations are all combinations of these values, \boldsymbol{z}_k \in G_1 \times \dots \times G_p, built with tidyr::expand_grid() (Wickham et al. 2025), giving N = (2r/\delta + 1)^p perturbations. The neighbourhood is deterministic and expressed in the units of the data. With the defaults r = 0.1 and \delta = 0.01 a two-dimensional problem yields N = 21^2 = 441 perturbations. Users who prefer random sampling, or who need a neighbourhood shaped differently, can supply their own generator through perturb_fun, or pass pre-computed perturbations through the perturbations argument. Figure 10.1 illustrates the construction for two predictors.
Weights
By default all perturbations within the box receive equal weight (w_k = 1 for all k), so the box itself acts as a uniform kernel. Setting weighted = TRUE in kumquat() instead applies kernel_weights(), which implements the kernel used in LIME. Any other kernel can be supplied through weight_fun; supplying one always weights the perturbations, whatever the value of weighted.
Feature representation
Continuous predictors are used on their original scale. The fitted coefficients therefore have the interpretation of a change in log-odds per unit change in the predictor, and their ratios describe the orientation of the model’s decision boundary near the point of interest.
Surrogate model
fit_local_model() fits a lasso (Tibshirani 1996) logistic regression with glmnet::cv.glmnet() (Friedman et al. 2010), choosing the penalty \lambda that minimises cross-validated deviance (lambda.min). The elastic net mixing parameter alpha and the number of folds nfolds can be changed. The surrogate is fitted to the predicted class labels y_k of the black-box model, so it approximates the model’s decision boundary rather than its probability surface. If every perturbation receives the same predicted class there is no local boundary to describe; in that case no model is fitted, the model element of the result is NULL, and a constant placeholder importance of 0.5 is returned for every feature. A different class of surrogate, such as a decision tree or an unpenalised logistic regression, can be used through surrogate_fun.
10.2 Model interface
kumquat makes no assumptions about the class of the model. The user supplies a prediction function through predict_func, which must take the model and a data frame and return a factor of predicted classes; the default is stats::predict(). The model itself is passed as a bundle object (Silge et al. 2025). Bundling serialises models that hold references to external memory, such as those fitted by xgboost or keras, so that the explanation pipeline can be run in a fresh R session or in parallel workers, and costs nothing for models that are ordinary R objects.
10.3 Output
For each point of interest kumquat() returns a list with four elements:
-
perturbations: the perturbations together with the black-box predictions in a columnpred; -
local_model: the list returned by the surrogate step. With the defaultfit_local_model(), it holds the surrogate’s predictions (glm_predictions), the coefficients (importancesandcoef_mat), the observation weights (weights) and the fittedcv.glmnetobject (model); -
point_of_interest: the observation being explained; -
train_data: the training data with the black-box predictions added.
Because the perturbations, weights and surrogate predictions are all returned, the fidelity of an explanation can be checked directly, for example by comparing glm_predictions with pred.
11 Benchmark datasets
In kumquat, we introduce four different datasets with known decision boundaries to evaluate whether the explainer has extracted the correct feature importances.
These datasets contain two numeric variables (x, y) and a categorical variable (class) with two classes named A and B. Following Section 8.1, we write x_1 and x_2 for the variables x and y. These datasets are limited to two classes as extending to multiclass classification can be set as one class against others if needed and also provides an easier foundation to understand how LIME works. The decision boundary for each dataset is specified below.
Each dataset consists of n = 5000 observations \boldsymbol{x}_i = (x_{i1}, x_{i2})^\top, i = 1, \dots, n, whose coordinates are drawn independently from the uniform distribution on [-1, 1]. The class of each observation, c_i = c(\boldsymbol{x}_i), is assigned deterministically by a labelling function c : [-1, 1]^2 \to \{A, B\}, so that the true decision boundary is known exactly and there is no label noise.
d_vertical separates the classes with the vertical line x_1 = 0.3,
c_{\text{vertical}}(\boldsymbol{x}) = \begin{cases} A & \text{if } x_1 > 0.3, \\ B & \text{otherwise.} \end{cases}
d_oblique separates the classes with the line x_2 = 0.1 + 1.4x_1,
c_{\text{oblique}}(\boldsymbol{x}) = \begin{cases} A & \text{if } x_2 > 0.1 + 1.4x_1, \\ B & \text{otherwise.} \end{cases}
d_multi uses a boundary made up of three linear segments. Define the piecewise linear function
h(x_1) = \begin{cases} -0.3 & \text{if } x_1 < -0.5, \\ 0.1 + 0.8x_1 & \text{if } -0.5 \le x_1 < 0.4, \\ +\infty & \text{if } x_1 \ge 0.4, \end{cases}
which is continuous at x_1 = -0.5 (where 0.1 + 0.8x_1 = -0.3) and jumps to +\infty at x_1 = 0.4, so that the boundary is the vertical line x_1 = 0.4 for x_2 \ge 0.42. The labelling function is then
c_{\text{multi}}(\boldsymbol{x}) = \begin{cases} A & \text{if } x_2 < h(x_1), \\ B & \text{otherwise.} \end{cases}
d_multitwo extends d_multi with a fourth boundary, the line x_2 = -1 + 0.8x_1, which assigns the lower-right corner of the square back to class B,
c_{\text{multitwo}}(\boldsymbol{x}) = \begin{cases} A & \text{if } -1 + 0.8x_1 \le x_2 < h(x_1), \\ B & \text{otherwise.} \end{cases}
Since -1 + 0.8x_1 < -1 for x_1 < 0, the additional boundary only affects points with x_1 > 0, and it runs parallel to the middle segment of h.
The purpose of the boundaries behind each dataset is based on the identifiable feature importances.
- d_vertical: The dataset contains a vertical boundary. The decision boundary is determined by x_1 alone and does not divide its range equally. For a point near the boundary, x_1 should therefore be more important than x_2. This gives a clear benchmark to see if the XAI method can identify the baseline.
- d_oblique: A slanted decision boundary (x_2 = 0.1 + 1.4x_1) was used. The values were set such that the range of x_1 is not divided equally (i.e. the intercept is set to 0.1), and the importances of the two features are not equal (i.e. the slope is set to 1.4).
- d_multi: The decision boundary is made of three linear segments, and the important features change depending on where a point lies along the boundary. For x_1 < -0.5 the boundary is horizontal (x_2 = -0.3), so only x_2 should be important. For -0.5 \le x_1 < 0.4 the boundary is slanted (x_2 = 0.1 + 0.8x_1), so both features should be important, with x_2 slightly more important than x_1 because the slope is less than 1. This is the reverse of d_oblique, where the slope of 1.4 makes x_1 more important. For x_1 \ge 0.4 the boundary is vertical, so only x_1 should be important. Because the boundary bends, the correct importances depend on where the point lies, and a single global linear model can only capture an average direction. A logistic regression fitted to the whole of d_multi misclassifies about 7% of the points, mostly near the bends. A local explanation method should therefore give different feature importances to points in each region, and its explanations should change near the corners at (-0.5, -0.3) and (0.4, 0.42), where the boundary changes direction. This gives a benchmark for whether the XAI method is truly local, and how sensitive it is to the size of the neighbourhood (e.g. the kernel width in LIME).
- d_multitwo: The dataset adds a fourth boundary (x_2 = -1 + 0.8x_1) to d_multi, which puts the lower-right corner of the square back into class B. This new boundary is parallel to the slanted segment of d_multi, so class A in the region 0 < x_1 < 0.4 becomes a band between two parallel lines. Points near either line should get the same relative importances for x_1 and x_2, but with opposite signs, because crossing each line changes the class in opposite directions. Class B is also split into two separate regions (upper-left and lower-right), which tests whether the XAI method can explain the same prediction coming from different parts of the feature space. Finally, the new boundary meets the vertical segment at (0.4, -0.68), which adds another corner where both features are important.
The constants were chosen according to three principles. First, no boundary passes through the origin or divides the square symmetrically (the offsets x_1 = 0.3 and 0.1, and the corner at x_1 = 0.4). An explainer that relies on the global centre of the data, such as one using quantile bins centred at zero, would therefore give visibly wrong answers. Second, no slope equals one (1.4 and 0.8), so the two features always have different importances wherever both matter. The two slopes lie on opposite sides of one, so x_1 dominates in d_oblique and x_2 dominates in the slanted segment of d_multi. Third, every linear segment and corner lies well inside [-1, 1]^2, so that a neighbourhood of the default radius r = 0.1 around a point near the boundary is entirely within the support of the data. With n = 5000 observations, the square is sampled densely enough (about one point per 0.03 \times 0.03 cell) for flexible models such as random forests to recover the boundaries closely.
The visual appearance of each dataset is shown in Figure 11.1.
12 Inspecting and swapping the steps that lime hides
lime and kumquat carry out the same steps: generate perturbations, weight them, and fit a surrogate. The difference lies in what the user can reach. In lime the steps are internal to explain(). Their behaviour can be tuned through arguments such as n_permutations, kernel_width, dist_fun and feature_select, but the steps themselves cannot be replaced, and their outputs are discarded once the feature weights have been computed. kumquat returns the output of every step and accepts a user-written replacement for any of them. Table 12.1 summarises these differences step by step.
| Step | lime returns | lime lets the user change | kumquat returns | kumquat lets the user change |
|---|---|---|---|---|
| Perturbations | Not returned | Tuning only: n_permutations, bin_continuous, n_bins, quantile_bins, use_density
|
Every perturbation with its black-box prediction (perturbations) |
radius, step; replace with perturb_fun or supply perturbations
|
| Weights | Not returned | Tuning only: kernel_width, dist_fun
|
One weight per perturbation (local_model$weights) |
weighted, kernel_width, dist_fun; replace with weight_fun
|
| Surrogate | Feature weights, intercept, R^2 and prediction at \boldsymbol{x}_0 | Tuning only: n_features, feature_select; ridge regression is fixed |
Fitted cv.glmnet object, coefficients and predictions on every perturbation |
alpha, nfolds; replace with surrogate_fun
|
| Black-box model | Prediction at \boldsymbol{x}_0 | S3 methods model_type() and predict_model()
|
Predictions on the training data (train_data) |
Any class, through predict_func and bundle
|
The rest of this section demonstrates these differences on d_vertical. We first run the pipeline (Section 12.1), then inspect the pieces that lime discards (Section 12.2), and finally swap one of them for an alternative (Section 12.3).
12.1 Running the pipeline
We construct a simple classification model using the randomForest package on d_vertical. The workflow has four steps. First, the d_vertical dataset is loaded and a random forest is trained to predict class from the two features x and y. Second, the fitted model is wrapped with bundle() from the bundle package, so that it can be serialised and moved safely to wherever the explanation is computed. Third, the points of interest (POIs) are selected. Here we use two observations of d_vertical that lie close to the boundary x_1 = 0.3, one on each side. Finally, kumquat() runs the complete local interpretation pipeline. It takes the bundled model, the training data, the POIs, the names of the predictor variables and the class labels. The pois argument is not limited to a single observation: any number of rows can be passed, and kumquat() returns a list with one explanation for each point of interest.
library(randomForest)
library(bundle)
library(kumquat)
# 1. Load data and train black-box model
set.seed(1)
data(d_vertical)
rfmodel <- randomForest(
class ~ x + y,
data = d_vertical
)
# 2. Bundle the model for safe transport
rfmodel_bundled <- bundle(rfmodel)
# 3. Select points of interest (POIs) near the boundary x = 0.3
pois <- d_vertical[c(799, 1905), ]
# 4. Run the complete local interpretation pipeline
ks <- kumquat(
model_bundle = rfmodel_bundled,
data = d_vertical,
pois = pois,
predictor_vars = c("x", "y"),
class_names = levels(d_vertical$class)
)Unlike lime, no S3 methods have to be registered for randomForest objects: the default predict_func, stats::predict(), already returns predicted classes, and a model of any other class only needs a prediction function.
12.2 Inspecting the pieces lime discards
The explanation returned by lime in Chapter 9 is a data frame describing only the surrogate:
names(lime_exp) [1] "model_type" "case" "label" "label_prob"
[5] "model_r2" "model_intercept" "model_prediction" "feature"
[9] "feature_value" "feature_weight" "feature_desc" "data"
[13] "prediction"
The data and prediction columns hold the point of interest and its black-box prediction, not the neighbourhood. To draw Figure 9.1 we had to regenerate the perturbations by calling the internal function lime:::permute_cases(), and the weights and the fitted surrogate cannot be recovered at all. Each explanation returned by kumquat, by contrast, contains every intermediate object:
names(ks[[1]])[1] "perturbations" "local_model" "point_of_interest"
[4] "train_data"
names(ks[[1]]$local_model)[1] "glm_predictions" "importances" "coef_mat" "weights"
[5] "model"
Because ks contains the actual perturbations and the fitted local model, users can visualise the local neighbourhood directly. kumquat includes the plot_interest() function, which uses these exposed internals.
# Extract the first explanation list
explanation <- ks[[1]]
# View the actual perturbations generated
head(explanation$perturbations)# A tibble: 6 × 3
x y pred
<dbl> <dbl> <fct>
1 0.200 -0.258 B
2 0.200 -0.248 B
3 0.200 -0.238 B
4 0.200 -0.228 B
5 0.200 -0.218 B
6 0.200 -0.208 B
# Visualize the neighbourhood of each point of interest:
# full view (top) and zoomed in on each neighbourhood (bottom)
plots <- plot_interest(ks)
zoomed <- Map(
\(p, k) p + ggplot2::coord_equal(
xlim = k$point_of_interest$x + c(-0.25, 0.25),
ylim = k$point_of_interest$y + c(-0.25, 0.25)
),
plots, ks
)
patchwork::wrap_plots(
c(lapply(plots, \(p) p + ggplot2::coord_equal()), zoomed),
ncol = 2, guides = "collect"
)
The plot_interest() function (included in the package) utilizes the exposed perturbations, local_model and train_data to generate one ggplot2 scatter plot per point of interest, using the same class colours as Figure 11.1 by default. Each plot shows the perturbations around the point of interest, coloured by the local surrogate’s predictions, overlaid on the training data coloured by the black-box model’s predictions. Other palettes can be passed through the colours argument. Since the surrogate’s predictions sit alongside the black-box predictions on the same perturbations, the fidelity of the explanation can be seen in the plot and computed directly, which is not possible from the output of lime.
12.3 Swapping a step
In lime, changing how the neighbourhood is sampled means modifying the package itself, as limeaid (Goode and Hofmann 2021) had to do to obtain the perturbations. In kumquat, each step of the pipeline can be replaced without modifying the package. As an example, we replace the regular grid with LIME-style random sampling: 441 points drawn uniformly in the same box around each point of interest, matching the size of the default grid. The function only uses three of the inputs that kumquat() provides, so it only declares those three.
random_box <- function(poi, radius, predictor_vars) {
n <- 441
as.data.frame(lapply(
setNames(predictor_vars, predictor_vars),
\(v) runif(n, poi[[v]] - radius, poi[[v]] + radius)
))
}
set.seed(2026)
ks_random <- kumquat(
model_bundle = rfmodel_bundled,
data = d_vertical,
pois = pois,
predictor_vars = c("x", "y"),
class_names = levels(d_vertical$class),
perturb_fun = random_box
)Table 12.2 compares the local coefficients obtained from the default grid with those from random sampling, for both points of interest.
d_vertical, using the default regular grid and uniform random sampling in the same box. Coefficients are on the log-odds scale of class B.
| Neighbourhood |
Local surrogate
|
|
|---|---|---|
| Coefficient of x1 | Coefficient of x2 | |
| (0.300, -0.158) | ||
| Regular grid | −1,001.3 | 0.0 |
| Random sampling | −2,060.7 | −14.1 |
| (0.331, 0.489) | ||
| Regular grid | −1,011.3 | 0.0 |
| Random sampling | −1,595.1 | −17.7 |
Both neighbourhoods give the same qualitative explanation. x_1 receives a large negative coefficient, because moving to the right across x_1 = 0.3 changes the prediction from B to A, and the coefficient of x_2 is zero or close to zero, matching the known boundary of d_vertical. The size of the x_1 coefficient reflects how sharply the classes change at the boundary rather than an effect size: the black-box labels switch abruptly, so the logistic regression is close to perfectly separating them. The two neighbourhoods differ in the details. On the regular grid every value of x_2 is paired with exactly the same set of x_1 values, so x_2 is uncorrelated with the black-box labels and the lasso sets its coefficient exactly to zero. With random sampling this balance holds only approximately, and chance correlations between x_2 and the labels let a small nonzero coefficient through.
The rest of the pipeline, including pinch_importance() and plot_interest(), works unchanged on the result. In the same way, weight_fun can be used to try a different proximity kernel, and surrogate_fun to fit a different class of interpretable model.