attributeerror: tensor object has no attribute numpy error occurs because of a parameter run_eagerly value if it is set as False. Actually, 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. Still in some cases of Tensorflow 2. o we need to set this parameter to true explicitly.
Well in this article, We will explore the root cause for this error in more detail with practical syntax. So let’s start.
Attributeerror: tensor object has no attribute numpy ( Solution ) –
Actually numpy arrays or equivalent to tensors. Also, Tensors are most computationally optimized than numpy arrays. Hence for achieving high performance while model training and prediction, Tensorflow internally converts NumPy arrays to Tensors. Sometimes, this explicit conversion causes the above error.
Let’s drill through it with different levels of solutions.
Solution 1 : Enable eager_execution ( Only for Tenorflow 1.x ) –
If we are using TensorFlow 1. x, we need to explicitly invoke eager_execution.
tf.enable_eager_execution(config=None, device_policy=None, execution_mode=None)
The above code will enable eager_execution.
Solution 2 : invoke run_functions_eagerly ( For Tensorflow 2.x ) –
Typically with Tensorflow the above property is by default True. But still, in some cases, we have to explicitly set it as True. Please refer to the below syntax for this.
As I told you already this error occurs because of using NumPy in the place of tensors in TensorFlow. To avoid such performance TensorFlow avoids using NumPy. Typically the above two solutions will work to fix this issue. But if you want to opt for them, we can manage by passing it at the function level. Just take an example-
Here model. compile by default does not allow numpy. But we can parameterize and fix this issue. This is the smart way to do tradeoff the effort in syntax fixing and performance downgrade.
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.