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.
Attributeerror: module tensorflow has no attribute placeholder ( Solution ) –
The best solution for any incompatibility error is to make either side compatible.
Solution 1: Disabling Tensorflow 2. x behavior –
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
Solution 2: Using placeholder alternative of tensorflow 2.0 ( Variable) –
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.
self._states = tf.placeholder(shape=[None, self._num_states], dtype=tf.float32)
self._states = tf.Variable(tf.ones(shape=[None, self._num_states]), dtype=tf.float32)
Solution 3: Complete code conversion from 1. x to 2. x
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.
--intree code/ \
--outtree code_v2/ \
Solution 4: Downgrade TensorFlow version
Simple you can downgrade the existing version of tensorflow to 1. x. Here is the command.
pip install tensorflow==1.15.5
Related Error –
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.