Tensorflow 2.0 Cannot convert tensor to numpy array when using tf.compat.v1.disable_eager_execution()

Viewed 2547

I build a network which returns numpy arrays of the same size as the input. However this network is really slow and needs more than 10 seconds to process 12 images.

When I use tf.compat.v1.disable_eager_execution() the same network processes 12 images in less than 0.1 seconds. Now, however, the network returns tensors that I can not convert to numpy arrays. This is the output of the network when I do print(output):

Tensor("mul_20:0", shape=(12, 224, 224, 3), dtype=float32)

I tried output.numpy() and get the following error:

AttributeError: 'Tensor' object has no attribute 'numpy'

What can I do to solve this problem?

1 Answers

You can only use tf.Tensor.numpy when you are using eager execution. When eager execution is disabled, all of your operations are just constructing a graph. You need to use a Session to actually run it and get the result.

with tf.compat.v1.Session() as sess:
    result = sess.run(output)
    print(result)  # result is a numpy array

See https://www.tensorflow.org/api_docs/python/tf/compat/v1/Session

Related