提问人:Daniel S. 提问时间:9/5/2023 最后编辑:Daniel S. 更新时间:9/5/2023 访问量:50
可以对 tensorflow 张量使用 python 运算符吗?
Is it okay to use python operators for tensorflow tensors?
问:
TL的;DR:在优化和性能方面
是等价的吗?( 并且是 TensorFlow 张量)(a and b)
tf.logical_and(a, b)
a
b
细节:
我将python与tensorflow一起使用。我的首要任务是让代码快速运行,第二要务是让它可读。我有工作和快速的代码,就我个人的感觉而言,看起来很丑:
@tf.function
# @tf.function(jit_compile=True)
def my_tf_func():
# ...
a = ... # some tensorflow tensor
b = ... # another tensorflow tensor
# currently ugly: prefix notation with tf.logical_and
c = tf.math.count_nonzero(tf.logical_and(a, b))
# more readable alternative: infix notation:
c = tf.math.count_nonzero(a and b)
# ...
使用前缀表示法的代码工作且运行速度快,但我认为由于前缀表示法(它被称为前缀表示法,因为操作的名称在操作数和 之前)的可读性不是很强。logical_and
a
b
我是否可以使用中缀表示法,即上述代码末尾的替代方法,以及常用的 python 运算符,如 、 、 或 ,并且仍然可以在 GPU 上获得 tensorflow 的所有好处并在 XLA 支持下编译它?它会编译成相同的结果吗?and
+
-
==
同样的问题也适用于一元运算符,例如 vs. 。not
tf.logical_not(...)
这个问题在 https://software.codidact.com/posts/289588 交叉发布。
答:
一般来说,没有。
这取决于具体的运营商。如您所知,Python 的数据模型允许通过重新定义类的特殊方法来覆盖运算符的行为。Tensorflow 为其类重新定义了其中的大部分(如果不是全部),值得庆幸的是,它们还记录了它们的行为,因此您可以轻松查看 tf 的文档。张量
。Tensor
某些操作员可能会按照您的预期行事。例如,与 或 相同。tensor_a + tensor_b
tensor_a.__add__(tensor_b)
tf.math.add(tensor_a, tensor_b)
他们中的一些人可能不会。例如,将引发异常,因为 的方法是专门设计用于避免误用,并在每次将张量用作布尔值时引发异常。另一方面,如果 t
是布尔张量(它是布尔),则对非布尔张量执行按位否定(源)。因此,在使用运算符而不是显式方法时必须小心。if not some_tensor: ...
__bool__
tf.Tensor
x = not t
tf.logical_not(t)
dtype
在您的示例中,可以按照 tf.logical_and()
的文档编写。由于与上述相同的原因,该表达式将引发异常,因为在 Python 中,您无法覆盖逻辑和运算符(请参阅此处),并且将被调用。tf.logical_and(a, b)
a & b
a and b
and
or
__bool__
评论
and
首先,做不同的事情。 是元素逻辑的 AND 如果 和 都是张量,而 is unless 是空的,否则(因为仅由 控制,你不能重载自定义类的运算符,并且它的形状不是零元组,AFAIC)。因为这不应该给性能带来损失。tf.logical_and
tf.logical_and(a, b)
a
b
a and b
a
a
b
and
__bool__
and
tf.Tensor
+