使用 Tensorflow 1.4 我想使用映射函数计算张量的元素逆 (x --> 1/x)。如果张量中某个元素的值为零,我希望输出为零。
以 tensor: [[0, 1, 0], [0.5, 0.5, 0.3]]
为例,我想要output: [[0,1,0], [2, 2, 3.333]]
。
我知道我可以使用 tf2.0
中的 tf.math.reciprocal_no_nan() 轻松获得所需的输出和tf.math.divide_no_nan()
在tf 1.4
,但我想知道为什么下面的代码不起作用:
tensor = tf.constant([[0, 1, 0], [0.5, 0.5, 0.3]], tf.float32)
tensor_inverse = tf.map_fn(lambda x: tf.cond(tf.math.not_equal(x, 0.0), lambda x: 1/x, lambda: 0) , tensor)
我收到此错误:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
最佳答案
让我们分解您的代码示例:
您使用的第一个函数是map_fn
。 Map_fn
将在第一维上分割张量并将这些单独的张量传递给其内部提供的函数。此功能不会给您带来任何问题。
接下来是tf.cond
。 tf.cond
期望其谓词中有一个标量值。分割:
tensor = tf.constant([[0, 1, 0], [0.5, 0.5, 0.3]], tf.float32)
cond_val1 = tf.math.not_equal(tensor, 0.0)
print(cond_val1.shape) # Shape (2, 3)
cond_val1
上面的例子显然是一个张量。您必须使用 tf.reduce_all
或tf.reduce_any
将其转换为标量。然后您将获得 tf.cond
所需的标量。例如:
cond_val2 = tf.reduce_all(tf.math.not_equal(tensor, 0.0))
print(cond_val2.shape) # Shape ()
现在这将使得 tf.cond
工作。但您还遇到了另一个问题。您已经失去了按元素处理张量的能力。
其次,通过map_fn
您正在第一维传递整个张量分割,在您的情况下将是 [0, 1, 0]
和[0.5, 0.5, 0.3]
。但问题是你的tf.cond
的true_fn
和false_fn
没有能力按元素进行处理。
希望您能够了解代码中存在的各种问题。
关于python - 使用 tf.map_fn 计算张量的逆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58198538/