Created
November 9, 2020 23:54
-
-
Save cicorias/cac937556563615ccb1b7c837f576db3 to your computer and use it in GitHub Desktop.
Shap shit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from keras.applications.vgg16 import VGG16 | |
from keras.applications.vgg16 import preprocess_input | |
import keras.backend as K | |
import numpy as np | |
import json | |
import shap | |
# load pre-trained model and choose two images to explain | |
model = VGG16(weights='imagenet', include_top=True) | |
X,y = shap.datasets.imagenet50() | |
to_explain = X[[39,41]] | |
# load the ImageNet class names | |
url = "https://s3.amazonaws.com/deep-learning-models/image-models/imagenet_class_index.json" | |
fname = shap.datasets.cache(url) | |
with open(fname) as f: | |
class_names = json.load(f) | |
# explain how the input to the 7th layer of the model explains the top two classes | |
def map2layer(x, layer): | |
feed_dict = dict(zip([model.layers[0].input], [preprocess_input(x.copy())])) | |
return K.get_session().run(model.layers[layer].input, feed_dict) | |
e = shap.GradientExplainer( | |
(model.layers[7].input, model.layers[-1].output), | |
map2layer(X, 7), | |
local_smoothing=0 # std dev of smoothing noise | |
) | |
shap_values,indexes = e.shap_values(map2layer(to_explain, 7), ranked_outputs=2) | |
# get the names for the classes | |
index_names = np.vectorize(lambda x: class_names[str(x)][1])(indexes) | |
# plot the explanations | |
shap.image_plot(shap_values, to_explain, index_names) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment