如何解决由于 Tensorflow 错误,无法使用 SHAP GradientExplainer张量不可散列
我已经被这个错误困扰了很长时间,有没有办法在不降级我的 tensorflow 版本的情况下解决它?到目前为止,我发现的所有解决方案都建议使用 TF
我正在尝试将 SHAP GradientExplainer 与 VGG 16 模型结合使用,以查看特定层如何影响预测。
代码是:
e = shap.GradientExplainer((model.layers[7].input,model.layers[-1].output),map2layer(preprocess_input(X.copy()),7))
shap_values,indexes = e.shap_values(map2layer(to_predict,7),ranked_outputs=2)
index_names = np.vectorize(lambda x: class_names[str(x)][1])(indexes)
index_names
错误是:
TypeError Traceback (most recent call last)
<ipython-input-13-b3a265bc3cde> in <module>()
----> 1 e = shap.GradientExplainer((model.layers[7].input,7))
2 shap_values,ranked_outputs=2)
3 index_names = np.vectorize(lambda x: class_names[str(x)][1])(indexes)
4 index_names
<ipython-input-11-f110beabf449> in map2layer(x,layer)
1 def map2layer(x,layer):
----> 2 feed_dict = dict(zip([model.layers[0].input],[preprocess_input(x.copy())]))
3 return K.get_session().run(model.layers[layer].input,feed_dict)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/keras_tensor.py in __hash__(self)
259 def __hash__(self):
260 raise TypeError('Tensors are unhashable. (%s)'
--> 261 'Instead,use tensor.ref() as the key.' % self)
262
263 # Note: This enables the KerasTensor's overloaded "right" binary
TypeError: Tensors are unhashable. (KerasTensor(type_spec=TensorSpec(shape=(None,224,3),dtype=tf.float32,name='input_1'),name='input_1',description="created by layer 'input_1'"))Instead,use tensor.ref() as the key.
解决方法
看起来您正在将 "ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE","TEN"
或 Tensor
输入您的 feed_dict。 Python 尝试散列字典键(python dict 是一个散列映射),这会引发您看到的错误。原因是张量不可哈希(意味着它们没有 KerasTensor
方法的实现)。
要解决此问题,请确保 feed_dict 键是占位符或 keras.Input
对象。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。