A beginner-friendly guide to Local Interpretable Model-agnostic Explanations with a practical Python example
Imagine a machine learning model flags a transaction as fraudulent.
Or perhaps a model analyzes a medical image and predicts that something looks risky.
The obvious next question is:
Why?
If the only answer is "because the model predicted it," it becomes difficult to trust the model, debug it, or communicate its decision to other people.
This is the problem that LIME tries to solve.
LIME stands for Local Interpretable Model-agnostic Explanations Despite the complicated name, its basic idea is surprisingly simple:
Take one prediction, make small changes around it, and observe how the model reacts.
In this article, we will break down what LIME means, understand how it works step by step, and use it to explain a real machine learning model in Python.
What Does LIME Mean?
Each word in LIME describes an important part of the method.
Local
LIME explains one prediction at a time rather than attempting to explain the entire model.
Interpretable
LIME uses a simple model, such as a linear model, to create an explanation that people can understand.
Model-Agnostic
LIME treats the original machine learning model as a black box.
It does not need to know how the model works internally. It simply provides inputs and observes the predictions.
This means LIME can be used with models such as:
Random forests
Neural networks
Support vector machines
Other black-box models
Explanations
The result is a list of features and their estimated influence on the prediction.
The Core Idea: Zoom In
A complex machine learning model can create a very complicated decision boundary.
Trying to describe the entire model using one simple rule may be extremely difficult.
But what happens if we focus on only a small region around one particular prediction?
A complicated curve can look almost like a straight line when viewed closely.
Think about the Earth. The Earth is round, but a small patch of ground looks flat when you stand on it.
LIME uses a similar idea.
It creates a simple model around the specific prediction and uses that local model to explain what the original model is doing nearby.
How Does LIME Work?
Suppose we want to explain one particular data point, which we call x.
LIME follows several steps.
Step 1: Perturb the Data
LIME creates many slightly modified versions of the original input.
For tabular data, it may change feature values.
For text, it can remove or modify words.
For images, it can switch off regions of pixels.
Step 2: Ask the Original Model
Each modified example is sent to the original black-box model.
LIME records the predictions produced by the model.
Step 3: Give More Importance to Nearby Examples
Not every generated example is equally useful.
Examples that are very similar to the original input receive a higher weight.
Examples farther away receive a lower weight.
This is what keeps the explanation local.
Step 4: Fit a Simple Model
LIME then trains an interpretable model—usually a sparse linear model—using the generated samples.
The goal is for this simple model to imitate the original black-box model around the prediction we are explaining.
Step 5: Read the Coefficients
The coefficients of the simple model become the explanation.
A positive weight means a feature pushes the prediction toward the class being explained.
A negative weight means it pushes the prediction in the opposite direction.
In simplified form, LIME tries to solve:
text
Explanation(x) =
argmin [ L(f, g, πx) + Ω(g) ]
Here:
f = original black-box model
g = simple interpretable model
πx = weighting based on closeness to the original example
L = how poorly the simple model imitates the original model
Ω(g) = penalty for making the explanation too complicated
In plain English:
Find the simplest model that behaves like the black-box model around this particular prediction.
Hands-On: Explaining a Random Forest with LIME
Let's train a random forest classifier using scikit-learn's built-in breast cancer dataset and then use LIME to explain one prediction.
This dataset is used only for demonstration and should not be used for real medical decisions.
Install the required libraries:
bash
pip install lime scikit-learn matplotlib
Then use:
python
import numpy as np
from lime.lime_tabular import LimeTabularExplainer
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
data = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(
data.data,
data.target,
test_size=0.2,
random_state=42
)
model = RandomForestClassifier(
n_estimators=200,
random_state=42
)
model.fit(X_train, y_train)
print("Test accuracy:", round(model.score(X_test, y_test), 3))
explainer = LimeTabularExplainer(
training_data=X_train,
feature_names=data.feature_names,
class_names=data.target_names,
mode="classification",
random_state=42
)
i = 0
exp = explainer.explain_instance(
X_test[i],
model.predict_proba,
num_features=6,
num_samples=5000
)
proba = model.predict_proba(X_test[[i]])[0]
print("Model says:",
dict(zip(data.target_names, proba.round(3))))
print("Local fit R²:", round(exp.score, 3))
for rule, weight in exp.as_list():
print(f"{rule:45s} {weight:+.3f}")
Example Result
One run produces results similar to:
text
Test accuracy: 0.965
Model says:
{'malignant': 0.045, 'benign': 0.955}
Local fit R²: 0.107
516.45 < worst area <= 686.60 +0.069
84.25 < worst perimeter <= 97.67 +0.063
13.05 < worst radius <= 14.97 +0.038
0.23 < worst concavity <= 0.39 -0.026
420.30 < mean area <= 551.70 +0.023
0.10 < worst concave points <= 0.16 +0.020
How Do We Read This?
The model predicts that the sample is 95.5% likely to belong to the benign class.
LIME then provides a list of feature conditions and weights.
For example:
text
516.45 < worst area <= 686.60
has a positive weight of approximately +0.069, meaning this condition pushes the explanation toward the predicted class.
Meanwhile:
text
0.23 < worst concavity <= 0.39
has a negative weight of approximately −0.026, meaning it pushes in the opposite direction.
Notice that LIME converts continuous numerical features into ranges.
Instead of simply displaying a value such as:
text
worst area = 600
it may produce:
text
516.45 < worst area <= 686.60
These ranges can be easier for people to interpret.
Visualizing a LIME Explanation
LIME can also generate a chart showing which features support or oppose the prediction.
python
fig = exp.as_pyplot_figure()
fig.savefig("lime_chart.png", bbox_inches="tight")
The chart provides a quick visual summary of the explanation.
An Important Number: Local Fit R²
One of the most important things to check when using LIME is the local fit score.
Our example gives:
text
Local fit R²: 0.107
The score indicates how well LIME's simple model imitates the original black-box model around the selected data point.
Generally:
Near 1 → the local explanation fits the model well
Near 0 → the simple explanation does not represent the model very well
In this example, the score is relatively low.
That means we should treat this particular explanation as a rough indication, rather than assuming it perfectly represents the original model.
This is an important lesson:
Do not look only at the LIME feature weights. Check how well the local model actually fits.
Is LIME Stable?
LIME uses random sampling to create perturbed examples.
Because of this, two runs can sometimes produce different explanations.
One useful practice is to run LIME multiple times using different random seeds and compare the important features.
If the same features repeatedly appear near the top, that gives you more confidence in the explanation.
For important applications, you should not rely on a single LIME run.
Useful LIME Parameters
Several parameters can affect the explanation.
| Parameter | What It Controls |
| num_samples | Number of perturbed samples generated |
| num_features | Number of features shown in the explanation |
| kernel_width | Size of the local neighbourhood |
| discretize_
continuous | Whether numerical values are converted into
ranges |
| random_state | Makes the random sampling reproducible
num_samples
More samples can produce more stable explanations but may take longer.
num_features
Controls how many features appear in the final explanation. Keeping this number small makes the result easier to understand.
kernel_width
Controls how broadly LIME considers the neighbourhood around the prediction.
random_state
Fixing the random seed helps reproduce the same result.
LIME Is Not Only for Tabular Data
One of LIME's strengths is its flexibility.
It can also be applied to other types of machine learning problems.
Text
LimeTextExplainer can identify words that influenced a text classification.
Images
LimeImageExplainer can identify image regions that influenced a prediction.
This makes LIME useful when working with different types of machine learning models and data.
Limitations of LIME
LIME is useful, but it has several limitations.
1. Instability
Because LIME relies on random sampling, explanations can change between runs.
Using a fixed seed and repeating the experiment can help.
2. Choosing the Neighbourhood
LIME must decide what counts as "near" the original data point.
Changing the kernel width can change the explanation.
3. Unrealistic Perturbations
LIME can perturb features independently.
This may sometimes produce combinations of feature values that are unrealistic or that never appeared in the training data.
4. It Is Local
An explanation for one data point does not automatically explain another data point.
LIME focuses on the specific prediction being analyzed.
5. The Simple Model May Not Fit
If the original model is highly nonlinear even within the local region, a simple linear model may not approximate it well.
The local R² score can help reveal this problem.
A practical approach is to consider SHAP for tree-based models and global feature analysis, while LIME can be useful when you need a local explanation for an unusual black-box model or for text and image inputs.
If both methods tell a similar story about a prediction, that can provide additional confidence in the explanation.
Final Thoughts
LIME provides a simple way to understand what a complex machine learning model is doing around a particular prediction.
You do not need to inspect the internal structure of the black-box model.
Instead, LIME:
1. Creates small variations of the input.
2. Gets predictions from the original model.
3. Gives more importance to nearby examples.
4. Fits a simple interpretable model.
5. Uses that model to explain the prediction.
The most important thing to remember is that LIME provides a local approximation, not a complete description of the original model.
So when using LIME, pay attention to both the feature weights and the local fit score, and consider repeating the explanation to check its stability.
Have you used LIME on your own machine learning model? What did it reveal? Share your experience in the comments.
Top comments (0)