Introduction
Model interpretability helps us understand why a machine learning model makes certain decisions. It makes the model's predictions clear and trustworthy.
import shap import lime from lime import lime_tabular # For SHAP explainer = shap.Explainer(model, data) shap_values = explainer(data_to_explain) # For LIME explainer = lime_tabular.LimeTabularExplainer(training_data, feature_names=features, class_names=classes, mode='classification') exp = explainer.explain_instance(instance_to_explain, model.predict_proba)
import shap explainer = shap.Explainer(model, X_train) shap_values = explainer(X_test[0:1]) shap.plots.waterfall(shap_values[0])
from lime import lime_tabular explainer = lime_tabular.LimeTabularExplainer(X_train, feature_names=feature_names, class_names=class_names, mode='classification') exp = explainer.explain_instance(X_test[0], model.predict_proba) exp.show_in_notebook()
import numpy as np from sklearn.datasets import load_iris from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import train_test_split import shap from lime import lime_tabular # Load data iris = load_iris() X, y = iris.data, iris.target feature_names = iris.feature_names class_names = iris.target_names # Split data X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42) # Train model model = RandomForestClassifier(random_state=42) model.fit(X_train, y_train) # SHAP explanation explainer_shap = shap.Explainer(model, X_train) shap_values = explainer_shap(X_test[0:1]) # Print SHAP values for first test sample print('SHAP values for first test sample:') for name, val in zip(feature_names, shap_values.values[0]): print(f'{name}: {val:.4f}') # LIME explanation explainer_lime = lime_tabular.LimeTabularExplainer(X_train, feature_names=feature_names, class_names=class_names, mode='classification') exp = explainer_lime.explain_instance(X_test[0], model.predict_proba) print('\nLIME explanation for first test sample:') for feature, weight in exp.as_list(): print(f'{feature}: {weight:.4f}')
exp.as_list() return?import lime.lime_tabular explainer = lime.lime_tabular.LimeTabularExplainer(training_data, feature_names=features) exp = explainer.explain_instance(test_instance, model.predict_proba) print(exp.as_list())
explain_instance method returns an explanation object. Calling as_list() gives feature importance as a list of (feature, weight) tuples.as_list() does not return. The training data used to build the explainer is training data, unrelated here. A plot object visualizing the model's decision is a plot, which requires a different method.AttributeError: 'TreeExplainer' object has no attribute 'shap_values'. What is the likely cause?Pass the test and this pattern moves unknown