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

标签 python tensorflow lambda map-function inverse

使用 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/

相关文章:

python - 递归累积或如何计算 Python 中的递归调用次数?

python - resnet50 迁移学习期间的大量过拟合

python - 使用 Tensorflow 的 top_k 和 scatter_nd

Haskell,用于评估的 lambda 演算

lambda - 具有显式返回类型的 Kotlin lambda

python -/usr/lib/python 和/usr/lib64/python 有什么区别?

python - 我如何将其保存到变量中,以便将其保存到文件中

python - 为什么 get_absolute_url() 定义在 models.py 中?

python - Conda - 从防火墙后面的 .whl 文件安装 tensorflow

angularjs - 如何将 lambda 表达式传递给 AngularJS 指令