1

I want to test the type of a Tensor in non-eager mode. In Eager mode, this code works:

tf.enable_eager_execution()
t = tf.random.normal([1, 1])
num_type = t.dtype
print(num_type == tf.float32) # prints `True`

In non-eager mode, the same code does not and the only way I found to test is the ugly str(num_type) == "float32":

sess = tf.Session()

t = sess.run(tf.random.normal([1, 1]))

num_type = t.dtype
print(num_type) # prints `float32`
print(str(num_type) == "float32") # prints `True`
print(num_type == float32) # returns `NameError: name 'float32' is not defined`
print(num_type == tf.float32) # returns `TypeError: data type not understood`

and if I try to grab the type of the Tensor inside the session:

t = tf.random.normal([1, 1])
t_type = t.dtype

num_type = sess.run(t_type)

then I get:

TypeError: Fetch argument tf.float32 has invalid type <class 'tensorflow.python.framework.dtypes.DType'>, must be a string or Tensor. (Can not convert a DType into a Tensor or Operation.)

How can I test for a float32 type in non-eager mode?

miguelmorin
  • 5,025
  • 4
  • 29
  • 64
  • Why would you need something like this? I find it a bit confusing that you want to evaluate the dtype of a tensor inside the computational graph. – gorjan Feb 01 '19 at 15:12
  • I am writing tests for the reproducibility of Tensorflow in eager and non-eager mode. In [this issue](https://stackoverflow.com/questions/54478877/simple-tensorflow-computation-not-reproducible-on-different-systems-macos-cola) I find that TensorFlow on different systems produces different results in the 9th decimal of computations, so I added a test on the floating precision of the dtype. – miguelmorin Feb 01 '19 at 15:45

1 Answers1

1

After the tensor evalution in a session you got a numpy tensor object and not a tf.Tensor object (that you got and use directly in the eager mode)..

Your test should, thus, be:

t.dtype == np.float32
nessuno
  • 26,493
  • 5
  • 83
  • 74