A local explanation of a single prediction with LIME

BeginnerInterpretability & Explainable AIModel interpretability

Goal: Finding out why the model classified a particular sample.

Python — example.py
from lime.lime_tabular import LimeTabularExplainer
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier

data = load_breast_cancer()
clf = RandomForestClassifier(n_estimators=100, random_state=0).fit(data.data, data.target)
exp = LimeTabularExplainer(data.data, feature_names=list(data.feature_names),
                           class_names=list(data.target_names), random_state=0)
e = exp.explain_instance(data.data[0], clf.predict_proba, num_features=3)
print("Predicted class:", data.target_names[clf.predict(data.data[:1])[0]])
for cond, w in e.as_list():
    print(f"{w:+.3f}  {cond}")

Code explanation

LIME creates perturbed samples around the sample, observes how the prediction changes, then fits a simple local linear model. The weights express the effect of each condition on the decision for this sample only. The explanation changes slightly between runs because of random sampling, so we fixed random_state.

Requirements

Shell
pip install lime scikit-learn

How to run

Save the code in a file example.py then run it:

Shell
python example.py

Output recorded during testing

Predicted class: malignant
-0.128  worst perimeter > 125.40
-0.122  worst concave points > 0.16
-0.119  worst radius > 18.79

This example was actually run and tested on 21 November 2026 on a CPU — lime 0.2.0.1, scikit-learn 1.9.1, python 3.13.18

Libraries used

Related examples

AdvancedCaptumRun and tested

Integrated Gradients for a PyTorch network

Attributing the network's prediction to input features and checking the completeness axiom.

Interpretability & Explainable AI · Explaining networks