【问题标题】:Unable to use SHAP GradientExplainer due to Tensorflow error (tensors are unhashable)由于 Tensorflow 错误(张量不可散列),无法使用 SHAP GradientExplainer
【发布时间】:2021-05-06 06:49:38
【问题描述】:

我被这个错误困扰了很长时间,有没有办法在不降级我的 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, model.layers[-1].output), map2layer(preprocess_input(X.copy()), 7))
      2 shap_values, indexes = e.shap_values(map2layer(to_predict, 7), 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, 224, 3), dtype=tf.float32, name='input_1'), name='input_1', description="created by layer 'input_1'"))Instead, use tensor.ref() as the key.

【问题讨论】:

  • 你能显示更多的堆栈跟踪吗?
  • 谢谢。如果您在主要问题中跳过它,可能会更容易阅读

标签: python tensorflow keras vgg-net shap


【解决方案1】:

您似乎正在将 TensorKerasTensor 输入到您的 feed_dict 中。 Python 尝试对字典键进行哈希处理(python 字典是哈希映射),这会引发您看到的错误。原因是张量不可散列(这意味着它们没有__hash__ 方法的实现)。

要解决此问题,请确保 feed_dict 键是占位符或 keras.Input 对象。

【讨论】:

  • 抱歉,这是我第一次使用 VGG 或进行图像处理,我将如何检查 feed_dict 键是否为 keras.Input 对象,如果它们不是我如何将它们转换为那种类型的?
  • 只需检查您正在创建的 feed_dict 对象。也许解决方案是遵循错误消息中的建议,即使用tensor.ref() 作为您的密钥。
  • 我个人已经有一段时间没用过tensorflow/keras了,所以我可能错了
猜你喜欢
  • 2017-07-24
  • 1970-01-01
  • 1970-01-01
  • 2018-04-24
  • 1970-01-01
  • 2018-04-07
  • 1970-01-01
  • 1970-01-01
  • 2021-06-23
相关资源
最近更新 更多