LIME: Local Interpretable Model-Agnostic Explanations

0.2.0.1 · active · verified Tue Apr 14

LIME (Local Interpretable Model-agnostic Explanations) is a Python library designed to explain individual predictions of machine learning classifiers and regressors. It works for tabular, text, and image data by building local, interpretable surrogate models around the instance to be explained. The current version is 0.2.0.1 and the library is actively maintained.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `LimeTabularExplainer` to explain an individual prediction from a scikit-learn RandomForestClassifier on the Iris dataset. It covers data preparation, model training, explainer initialization, and generating/displaying the explanation.

import numpy as np
import sklearn
import sklearn.ensemble
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

import lime
import lime.lime_tabular

# 1. Prepare Data and Model
iris = load_iris()
X = iris.data
y = iris.target
feature_names = iris.feature_names
class_names = iris.target_names

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

model = sklearn.ensemble.RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)

# 2. Create a LIME Explainer for Tabular Data
explainer = lime.lime_tabular.LimeTabularExplainer(
    training_data=X_train, 
    feature_names=feature_names, 
    class_names=class_names, 
    mode='classification'
)

# 3. Choose an instance to explain
i = np.random.randint(0, X_test.shape[0])
instance_to_explain = X_test[i]

# 4. Generate the explanation
explanation = explainer.explain_instance(
    data_row=instance_to_explain, 
    predict_fn=model.predict_proba, 
    num_features=2
)

# 5. Print the explanation
print(f"Explaining instance: {instance_to_explain}")
print(f"Predicted class: {iris.target_names[model.predict(instance_to_explain.reshape(1, -1))[0]]}")
print("--- Local Explanation ---")
print(explanation.as_list())

# For visualization in a Jupyter Notebook:
# explanation.show_in_notebook(show_table=True)

view raw JSON →