RuntimeError: tf.placeholder() is not compatible with eager execution

avatar
Borislav Hadzhiev

Last updated: Apr 10, 2024
2 min

banner

# RuntimeError: tf.placeholder() is not compatible with eager execution

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.

main.py
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)

runtime error tf placeholder is not compatible with eager execution

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.

main.py
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.

main.py
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.

When eager execution is enabled, TensorFlow functions execute operations immediately (as opposed to adding to a graph to be executed later in a TensorFlow Session) and return concrete values (as opposed to symbolic references to a node in a computational graph).

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.

shell
pip show tensorflow

check tensorflow version

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+.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.