pythonintermediate

LIME Local Model Explanation

Generate local interpretable explanations for any black-box classifier using LIME.

python
from lime import lime_tabular
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris
import numpy as np

X, y = load_iris(return_X_y=True)
feature_names = ['sepal_length','sepal_width','petal_length','petal_width']
class_names   = ['setosa','versicolor','virginica']

model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X, y)

explainer = lime_tabular.LimeTabularExplainer(
    training_data=X,
    feature_names=feature_names,
    class_names=class_names,
    mode='classification',
)

# Explain a single prediction
instance = X[50]
exp = explainer.explain_instance(instance, model.predict_proba, num_features=4, top_labels=1)
print('Prediction:', class_names[model.predict([instance])[0]])
for feat, weight in exp.as_list():
    print(f'  {feat}: {weight:+.4f}')

Use Cases

  • black-box explanation
  • feature attribution
  • model auditing

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.