Last updated: Apr 10, 2024
Reading time·2 min
The TensorFlow error "RuntimeError: tf.placeholder() is not compatible with eager execution" occurs because placeholders are not executable immediately.
To solve the error, disable eager execution in TensorFlow as it is enabled by default starting TensorFlow version 2.
Here is an example of how the error occurs.
import tensorflow as tf x = tf.compat.v1.placeholder(tf.float32, shape=(1024, 1024)) # ⛔️ RuntimeError: tf.placeholder() is not compatible with eager execution. print(x)
The tf.compat.v1.placeholder()
method inserts a placeholder for a tensor that
will be always fed.
However, placeholders are not executable immediately, so we have to disable eager execution in TensorFlow.
import tensorflow as tf # ✅ Disable eager execution. tf.compat.v1.disable_eager_execution() x = tf.compat.v1.placeholder(tf.float32, shape=(1024, 1024)) print(x)
You only have to add the following line to disable eager execution in TensorFlow.
import tensorflow as tf tf.compat.v1.disable_eager_execution()
The tf.compat.v1.disable_eager_execution()
method disables eager execution.
Make sure to call the method before using tf.compat.v1.placeholder()
.
Eager execution is enabled by default in TensorFlow version 2.
If you use Tensorflow version 1, then eager execution is disabled by default.
Check if you've enabled it somewhere in your code by mistake, e.g. by calling
tf.compat.v1.enable_eager_execution()
.
You can check your tensorflow version
with the pip show tensorflow
command.
pip show tensorflow
In general, TensorFlow placeholder values must be fed using the feed_dict
optional argument to Session.run()
.
In other words, in TensorFlow version 1 placeholders must be fed when a
tf.Session
is created.
In TensorFlow version 2, eager execution is enabled by default, so TensorFlow functions execute operations immediately and return concrete values.
This means that placeholders don't make sense in TensorFlow 2.0+.
You can learn more about the related topics by checking out the following tutorials: