由于Deepexplainer尚不兼容Inception-ResNet V2模型,因此我想使用GradientExplainer计算SHAP值。但是我在map2layer函数中确实收到以下错误:
TypeError: Tensor is unhashable. Instead, use tensor.ref() as the key.
有人知道如何使GradientExplainer或DeepExplainer与Inception-ResNet V2模型一起使用吗? 请在下面找到我的GradientExplainer代码。
import numpy as np
import cv2
import keras
from keras import optimizers
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.models import Model, load_model
from keras import applications
from keras.callbacks import ReduceLROnPlateau
from keras.layers.normalization import BatchNormalization
from keras.metrics import categorical_accuracy
from keras.preprocessing.image import ImageDataGenerator
from keras.callbacks import ModelCheckpoint
from keras import backend as K
from keras.applications.inception_resnet_v2 import preprocess_input
import shap
import tensorflow
tf.compat.v1.Session()
print('Calculating SHAP value for image')
# Import Inception-ResNet V2 model
model = applications.InceptionResNetV2(include_top=True,
weights='imagenet',
pooling='avg',
input_shape=(299, 299, 3))
# Function to read image
def read_img(img_path, size):
img = cv2.imread(str(img_path))
img = cv2.resize(img, (size[0], size[1]))
return img
# Read image
img = read_img(img_path, (299,299))
img = np.array([img], np.float32) / 255
print(img.shape) # (1, 299, 299, 3)
# 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 tf.compat.v1.Session().run(model.layers[layer].input, feed_dict)
e = shap.GradientExplainer(
(model.layers[7].input, model.layers[-1].output),
map2layer(img, 7),
local_smoothing=0 # std dev of smoothing noise
)
shap_values,indexes = e.shap_values(map2layer(img, 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, img)