gpt4 book ai didi

python - 使用 tf.map_fn 计算张量的逆

转载 作者:太空宇宙 更新时间:2023-11-03 20:20:23 24 4
gpt4 key购买 nike

使用 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_fnMap_fn将在第一维上分割张量并将这些单独的张量传递给其内部提供的函数。此功能不会给您带来任何问题。接下来是tf.condtf.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_alltf.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.condtrue_fnfalse_fn没有能力按元素进行处理。

希望您能够了解代码中存在的各种问题。

关于python - 使用 tf.map_fn 计算张量的逆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58198538/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com