Skip to content

Instantly share code, notes, and snippets.

@thistleknot
Created May 2, 2021 17:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thistleknot/b59ae900cf57cbd74d7d7aa007770b93 to your computer and use it in GitHub Desktop.
Save thistleknot/b59ae900cf57cbd74d7d7aa007770b93 to your computer and use it in GitHub Desktop.
Python shap values
import sklearn
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
import numpy as np
import shap
shap.initjs()
# select a set of background examples to take an expectation over
background = np.array(data)
#[np.random.choice(X_train.shape[0],100,replace=False)]
model = sklearn.linear_model.LinearRegression()
model.fit(data.iloc[:,1:], data.iloc[:,0])
# explain predictions of the model on four images
e = shap.LinearExplainer(model, data.iloc[:,1:])
#explainer = shap.KernelExplainer(model, X_train, link="logit")
shap_values = e.shap_values(np.array(data.iloc[:,1:]))
shap.summary_plot(shap_values, -np.array(data.iloc[:,1:]))
explainer = shap.Explainer(model, data.iloc[:,1:])
shap.plots.heatmap(explainer(data.iloc[:,1:]))
@thistleknot
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment