Solve AttributeError – ‘Tensor’ object has no attribute ‘numpy’

Solve AttributeError – ‘Tensor’ object has no attribute ‘numpy’ is an error which occurs with TensorFlow when your code was copied from a place which had eager execution enabled.

In this article I am going to explain what happens when you get this AttributeError and how you can solve it with a main solution and with other solutions which we will explore and that can possibly solve the issue.

Explaining AttributeError – ‘Tensor’ object has no attribute ‘numpy’

The problem happens when you use TensorFlow and when your copy code from a source which had eager execution enabled.

The error message should look like the error in the example bellow.

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

Copying from an eager execution enabled source means using tf.enable_eager_execution() at the beginning of your script.

Bellow is a number of tested solutions which I have tried and have worked for me.

Solution 1 : Add eager execution

The first solution is simple just duplicate what the source of your code has done and add the eager execution to the beginning of your script. In order to do that, you can just add tf.enable_eager_execution().

Follow this link provided by TensorFlow to know how to enable eager execution: https://www.tensorflow.org/api_docs/python/tf/compat/v1/enable_eager_execution

Enabling this option will get TensorFlow to execute operations immediately on tensors. 

If that did not work, try using the solution bellow.

Solution 2 : edit model.compile

Sometimes, using eager execution does not do the trick.

The main reason is that for performance reasons the @tf.function decorator prohibits the execution of tensor.numpy() for example.

The solution is to edit model.compile from this

                                                                       #
model.compile(...)
                                                                       #

To this.

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

Passing run_eagerly=True will do the trick, exactly like we did above.

This should be enough to get rid of the error for good. I wish you good luck.

Summing-up

This is the end of our article, this error could be confusing but with a little bit of investigating the error could be solved easily by renaming your files, thank you for reading.

To support us consider donating to our Kofi account above. Keep coding, keep learning and cheers. If you want to learn more about Python, please check out the Python Documentation : https://docs.python.org/3/