pythonintermediate
LIME Local Model Explanation
Generate local interpretable explanations for any black-box classifier using LIME.
pythonPress ⌘/Ctrl + Shift + C to copy
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.
pythonintermediate
SHAP Model Explainability in Python
Explain ML model predictions globally and locally using SHAP values with tree-based models.
Best for: model interpretability
#shap#explainability
typescriptintermediate
AI Text Classification with Prompts
Classify text into categories using structured prompting with confidence scores and explanations.
Best for: Automated support ticket routing
#classification#prompt-engineering
pythonintermediate
Text Classification with Hugging Face
Fine-tune or use pre-trained Hugging Face models for text classification.
Best for: Sentiment analysis
#ai#huggingface
pythonbeginner
Zero-Shot Text Classification
Classify text into custom categories using zero-shot NLI models without training data.
Best for: content categorization
#huggingface#zero-shot