AttributeError: 'Tensor' object has no attribute 'numpy'
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!
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.
UPDATE: Note that eager execution is enabled by default in TensorFlow 2.0. So the answer above applies only to TensorFlow 1.x
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:
Note that this is useful mainly for debugging.
See also: https://www.tensorflow.org/api_docs/python/tf/config/run_functions_eagerly
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
@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: