在讨论TensorFlow 2.0 AutoGraphs 之后,我一直在玩,并注意到不等式比较如>和<是直接指定的,而等式比较使用tf.equal.
这里有一个例子来演示。此函数使用>运算符并在调用时运行良好:
@tf.function
def greater_than_zero(value):
return value > 0
greater_than_zero(tf.constant(1))
# <tf.Tensor: id=1377, shape=(), dtype=bool, numpy=True>
greater_than_zero(tf.constant(-1))
# <tf.Tensor: id=1380, shape=(), dtype=bool, numpy=False>
Run Code Online (Sandbox Code Playgroud)
这是另一个使用相等比较的函数,但不起作用:
@tf.function
def equal_to_zero(value):
return value == 0
equal_to_zero(tf.constant(1))
# <tf.Tensor: id=1389, shape=(), dtype=bool, numpy=False> # OK...
equal_to_zero(tf.constant(0))
# <tf.Tensor: id=1392, shape=(), dtype=bool, numpy=False> # WHAT?
Run Code Online (Sandbox Code Playgroud)
如果我将==相等比较更改为tf.equal,它将起作用。
@tf.function
def equal_to_zero2(value):
return tf.equal(value, 0)
equal_to_zero2(tf.constant(0))
# <tf.Tensor: …Run Code Online (Sandbox Code Playgroud)