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

Solution 1:

I suspect the place where you copied the code from had eager execution enabled, i.e. had invoked tf.enable_eager_execution() at the start of the program.

You could do the same. Hope that helps.

UPDATE: Note that eager execution is enabled by default in TensorFlow 2.0. So the answer above applies only to TensorFlow 1.x

Solution 2:

Since the accepted answer did not solve the problem for me so I thought it might be helpful for some people who face the problem and that already have tensorflow version >= 2.2.0 and eager execution enabled.

The issue seems to be that for certain functions during the fitting model.fit() the @tf.function decorator prohibits the execution of functions like tensor.numpy() for performance reasons.

The solution for me was to pass the flag run_eagerly=True to the model.compile() like this:

model.compile(..., run_eagerly=True)

Solution 3:

This can also happen in TF2.0 if your code is wrapped in a @tf.function or inside a Keras layer. Both of those run in graph mode. There's a lot of secretly broken code out of there because behavior differs between eager and graph modes and people are not aware that they're switching contexts, so be careful!

Solution 4:

Tensorflow 2 has a config option to run functions "eagerly" which will enable getting Tensor values via .numpy() method. To enable eager execution, use following command:

tf.config.run_functions_eagerly(True)

Note that this is useful mainly for debugging.

See also: https://www.tensorflow.org/api_docs/python/tf/config/run_functions_eagerly