首页 > 解决方案 > 为什么 tf.divide 不返回张量

问题描述

如果我使用 tf2 运行以下代码

import tensorflow as tf
import math as m

print(tf.add(5, 2))
print(tf.multiply(5, 2))
print(tf.divide(5, 2))
print(tf.multiply(tf.add(3, 2), tf.add(14, 32)))
print(tf.multiply(2.54, tf.divide(8, 2.6)))
print(tf.subtract(6.3, 2.1045))
print(tf.pow(3.6, 2))
print(tf.add(1, tf.pow(2, 2)))
print(tf.sqrt(5.0))
print(tf.cos(m.pi))

我把它作为输出

tf.Tensor(7, shape=(), dtype=int32)
tf.Tensor(10, shape=(), dtype=int32)
2.5
tf.Tensor(230, shape=(), dtype=int32)
tf.Tensor(7.815385, shape=(), dtype=float32)
tf.Tensor(4.1955004, shape=(), dtype=float32)
tf.Tensor(12.959999, shape=(), dtype=float32)
tf.Tensor(5, shape=(), dtype=int32)
tf.Tensor(2.236068, shape=(), dtype=float32)
tf.Tensor(-1.0, shape=(), dtype=float32)

为什么只有 tf.divide 不返回张量?

标签: tensorflow

解决方案


TLDR;这可能是一个错误

如果查看源代码,您将看到该divide()方法返回x/y,而其他算术运算返回结果为 ,gen_math_ops.xx()

这就是为什么当你divide使用 python 变量调用时,你只会得到一个 python 变量。但是,如果您对任何其他功能执行相同操作,您将得到一个正确的tf.Tensor.

例如,您可以通过在 Jupyter 中gen_math_ops运行以下命令(来自this的答案)来查看功能。gen_math_ops是自动生成的,所以你不会在 repo 中找到它。但简而言之,它在适当的 TensorFlow 环境中执行这些操作。

from tensorflow.python.ops import gen_math_ops
gen_math_ops??

的来源tf.dividehere。这可能是一个错误。所以我会让你在 Github 上提出一个问题来解决这个问题。这是一个非常微妙的错误,可能会导致一些难以调试的神秘问题(在我看来)。


推荐阅读