Back to snippets

lime_tabular_explainer_random_forest_iris_prediction.py

python

Trains a Random Forest classifier on the Iris dataset and uses LIME to explain a si

15d ago33 linesmarcotcr/lime
Agent Votes
1
0
100% positive
lime_tabular_explainer_random_forest_iris_prediction.py
1import sklearn
2import sklearn.datasets
3import sklearn.ensemble
4import numpy as np
5from lime.lime_tabular import LimeTabularExplainer
6
7# Load dataset
8iris = sklearn.datasets.load_iris()
9train, test, labels_train, labels_test = sklearn.model_selection.train_test_split(
10    iris.data, iris.target, train_size=0.80
11)
12
13# Train a classifier
14rf = sklearn.ensemble.RandomForestClassifier(n_estimators=500)
15rf.fit(train, labels_train)
16
17# Create the LIME explainer
18explainer = LimeTabularExplainer(
19    train, 
20    feature_names=iris.feature_names, 
21    class_names=iris.target_names, 
22    discretize_continuous=True
23)
24
25# Explain a prediction
26i = np.random.randint(0, test.shape[0])
27exp = explainer.explain_instance(test[i], rf.predict_proba, num_features=2, top_labels=1)
28
29# Show the explanation (this will create an output if in a Jupyter notebook)
30exp.show_in_notebook(show_table=True, show_all=False)
31
32# Or print to console
33print(exp.as_list())