How to Fix AttributeError: ‘Tensor’ object has no attribute ‘numpy’

AttributeError: ‘Tensor’ object has no attribute ‘numpy’ errors because a parameter run_eagerly value is set as False. There are two versions of the TensorFlow module, Tensorflow 1. x and Tensorflow 2. x. In Tensorflow 1. x, we have to manually set this parameter, but in Tensorflow 2.0, it is, by default, True.

Solution  1 : Enable eager_execution (Only for Tenorflow 1.x)

If you are using TensorFlow 1. x, we need to explicitly invoke eager_execution.

tf.enable_eager_execution(config=None, device_policy=None, 
                          execution_mode=None)

Solution 2 : invoke run_functions_eagerly (For Tensorflow 2.x)

Set the tf.enable_eager_execution() function to True.

tf.config.run_functions_eagerly(run_eagerly)

Solution 3

Another solution to fix the AttributeError: ‘Tensor’ object has no attribute ‘numpy’ error, convert a Tensor to a NumPy array using the .numpy() method of the Tensor object.

import tensorflow as tf

tensor = tf.constant([[11, 21], [19, 46]])
array = tensor.numpy()

print(array)

Output

[[11, 21], [19, 46]]

In this code, first, we imported the tensorflow library and defined a tensor using the tf.constant() method.

To convert a tensor to a numpy array, we used the tensor.numpy() function.

If you run the above code, we won’t get any error, instead, it will return this output: '[[11, 21], [19, 46]]'.

That’s pretty much it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.