使用张量是tensorflow中的字典键

Using tensors are dictionary keys in tensorflow

我已经看到答案了。这不是我要找的。

我在tensorflow2.0上运行这个

我在 TensorFlow 文档中读到以下句子:

With the exception of tf.Variable, the value of a tensor is immutable, which means that in the context of a single execution tensors only have a single value. However, evaluating the same tensor twice can return different values; for example that tensor can be the result of reading data from disk, or generating a random number.

我尝试使用张量作为字典键,但出现以下错误:

Tensor is unhashable if Tensor equality is enabled. Instead, use tensor.experimental_ref() as the key
  1. 这个错误是什么意思?
  2. tf.Variables 也可以哈希吗?他们还定义了计算而不是计算,所以为什么要区分 'With the exception of tf.Variable, the value of a tensor is immutable'

What does this error mean?

我想您可以在源代码中找到第一个问题的答案。

查看 this line 和上面的评论,您必须如下显式启用张量哈希。

tf.compat.v1.disable_tensor_equality()

x = tf.ones(shape=[10,2], dtype=np.float32)
dct = {x: 1} # Works fine

发生的事情是现在 __hash__ returns 一个正确的 ID 而不是引发错误。这允许您将其用作字典中的键。

禁用此功能的不利之处在于您无法再与张量执行逐元素比较。例如,

x = tf.ones(shape=[10,2], dtype=np.float32)
print((x==1.0))

启用平等 returns,

>>> tf.Tensor(
[[ True  True]
 [ True  True]
 ...
 [ True  True]
 [ True  True]], shape=(10, 2), dtype=bool)

禁用平等 returns,

>>> False

Are tf.Variables hashable as well? They also define a computation rather than being the computation, so why the distinction 'With the exception of tf.Variable, the value of a tensor is immutable' is there

是的。如果您查看 __hash__ 函数,它 returns id(self) 在该对象的生命周期内对于该对象将是唯一的(来源:here)。我不太了解如何使用 id 生成哈希 ID。但只要它是独一无二的就应该不是问题。事实上,你也可以在它成为字典中的键后更改变量值。