TensorFlow 运算符重载 [英] TensorFlow operator overloading

查看:36
本文介绍了TensorFlow 运算符重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

   tf.add(x, y)

   x + y

在 TensorFlow 中?当您使用 + 而不是 tf.add() 构建图表时,您的计算图表会有什么不同?

in TensorFlow? What would be different in your computation graph when you construct your graph with + instead of tf.add()?

更一般地说,+ 或其他操作是否对张量重载?

More generally, are + or other operations overloaded for tensors?

推荐答案

如果 xy 中的至少一个是 tf.Tensor 对象,表达式 tf.add(x, y)x + y 是等价的.您可能使用 tf.add() 的主要原因是指定一个显式的 name 用于创建操作的关键字参数,这对于重载的运算符版本是不可能的.

If at least one of x or y is a tf.Tensor object, the expressions tf.add(x, y) and x + y are equivalent. The main reason you might use tf.add() is to specify an explicit name keyword argument for the created op, which is not possible with the overloaded operator version.

请注意,如果 xy 都不是 tf.Tensor—例如如果它们是 NumPy 数组—那么 x + y 不会创建 TensorFlow 操作.tf.add() 总是创建一个 TensorFlow op 并将其参数转换为 tf.Tensor 对象.因此,如果您正在编写一个可能同时接受张量和 NumPy 数组的库函数,您可能更喜欢使用 tf.add().

Note that if neither x nor y is a tf.Tensor—for example if they are NumPy arrays—then x + y will not create a TensorFlow op. tf.add() always creates a TensorFlow op and converts its arguments to tf.Tensor objects. Therefore, if you are writing a library function that might accept both tensors and NumPy arrays, you might prefer to use tf.add().

TensorFlow Python API 中重载了以下运算符:

The following operators are overloaded in the TensorFlow Python API:

  • __neg__ (一元 -)
  • __abs__ (abs())
  • __invert__ (一元 ~)
  • __add__(二进制+)
  • __sub__(二进制-)
  • __mul__(二进制元素*)
  • __div__(Python 2 中的二进制 /)
  • __floordiv__(Python 3 中的二进制 //)
  • __truediv__(Python 3 中的二进制 /)
  • __mod__(二进制%)
  • __pow__(二进制**)
  • __and__(二进制&)
  • __or__(二进制|)
  • __xor__(二进制^)
  • __lt__(二进制<)
  • __le__(二进制<=)
  • __gt__(二进制>)
  • __ge__(二进制>=)
  • __neg__ (unary -)
  • __abs__ (abs())
  • __invert__ (unary ~)
  • __add__ (binary +)
  • __sub__ (binary -)
  • __mul__ (binary elementwise *)
  • __div__ (binary / in Python 2)
  • __floordiv__ (binary // in Python 3)
  • __truediv__ (binary / in Python 3)
  • __mod__ (binary %)
  • __pow__ (binary **)
  • __and__ (binary &)
  • __or__ (binary |)
  • __xor__ (binary ^)
  • __lt__ (binary <)
  • __le__ (binary <=)
  • __gt__ (binary >)
  • __ge__ (binary >=)

请注意,__eq__(二进制 ==)重载.x == y 将简单地返回一个 Python 布尔值,无论 xy 是否引用相同的张量.您需要明确使用 tf.equal()检查元素方面的相等性.不相等也一样,__ne__(二进制!=).

Please note, __eq__ ( binary == ) is not overloaded. x == y will simply return a Python boolean whether x and y refer to the same tensor. You need to use tf.equal() explicitly to check for element-wise equality. Same goes for not equal, __ne__ ( binary != ).

这篇关于TensorFlow 运算符重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆