Attributeerror: module tensorflow has no attribute placeholder occurs because of the incompatibility conflict between Tensorflow version 1. x and 2. x. Actually, the attribute ‘placeholder’ does not exist in Tesnorflow 2. x version. When we install the tensorflow using pip or conda. Typically it by default install the latest version which is 2. x. Apart from this, there is so many other situations where we encounter this error. Like some time we search for some code on the code community regarding tensorflow. There we found the solution which is related to the 1. x series and we try to apply the same in our codebase.
These all situations end up at this AttributeError. In this article, we will explore the best way to fix this TensorFlow error.
The best solution for any incompatibility error is to make either side compatible.
The Tensorflow 2.x provide the option to disable v2_behavior behavior. Here you need to import tensorflow.compat.v1 and then disable v2_behavior in the code. You need to add two lines in the code. But make sure the other part of the code which you write or use should be of TensorFlow 1. x.
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
Since Tensorflow 2. x is more advance than TensorFlow 1. x hence if the placeholder is removed then we have a variable in that place. Here is how we can use the same.
incorrect –
self._states = tf.placeholder(shape=[None, self._num_states], dtype=tf.float32)
correct –
self._states = tf.Variable(tf.ones(shape=[None, self._num_states]), dtype=tf.float32)
Since your interpreter has installed the version for TensorFlow is 2. x and you want to run 1. x supportive code on the same. Hence you are getting this attributeerror. If we convert our code from 1. x to 2. x then there will be no error. Don’t worry it is easy because the compatibility script is provided in TensorFlow 2. x. use the below command.
tf_upgrade_v2 \
--intree code/ \
--outtree code_v2/ \
--reportfile log.txt
Simple you can downgrade the existing version of tensorflow to 1. x. Here is the command.
pip install tensorflow==1.15.5
Thanks
Data Science Learner Team