why tf.divide does not return a tensor

Viewed 183

If I run the following code using 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))

I get this as an ouput

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)

Why only tf.divide does not return a tensor?

2 Answers

TLDR; It's probably a bug

If you look at the source, you will see that the divide() method returns x/y, where the other arithmetic operations return the result as, gen_math_ops.xx().

This is why when you call divide with python variables, you just get a python variable. However if you do the same with any other function, you get a proper tf.Tensor.

You can see what gen_math_ops does by running the following (answer from this) in Jupyter for example. gen_math_ops is auto-generated so you won't find it in the repo. But in short, it executes these operations in a proper TensorFlow environment.

from tensorflow.python.ops import gen_math_ops
gen_math_ops??

The source for tf.divide is here. It is probably a mistake. So I'll leave it up to you to raise an issue on Github to fix that. This is a very subtle bug, and can lead to some cryptic difficult-to-debug issues (in my opinion).

Related