EPLE tensorflow runtime_error ai_generated true

RuntimeError: tf.placeholder() is not compatible with eager execution. Use tf.keras.Input() instead.

ID: tensorflow/graph-mode-placeholder-in-eager

Also available as: JSON · Markdown · 中文
90%Fix Rate
90%Confidence
1Evidence
2023-05-10First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.0 active
2.1 active
2.2 active
2.3 active

Root Cause

TensorFlow 2.x runs in eager mode by default, but the code uses tf.placeholder which is a graph-mode API removed in TF2.

generic

中文

TensorFlow 2.x 默认以急切模式运行,但代码使用了 tf.placeholder,这是 TF2 中已移除的图模式 API。

Official Documentation

https://www.tensorflow.org/guide/eager

Workarounds

  1. 95% success Replace all tf.placeholder calls with tf.keras.Input(shape=..., dtype=...) and rebuild the model using the Keras Functional API.
    Replace all tf.placeholder calls with tf.keras.Input(shape=..., dtype=...) and rebuild the model using the Keras Functional API.
  2. 70% success If you must use graph mode, wrap the code in a @tf.function decorator and use tf.compat.v1.placeholder inside a tf.compat.v1.Graph() context, but this is not future-proof.
    If you must use graph mode, wrap the code in a @tf.function decorator and use tf.compat.v1.placeholder inside a tf.compat.v1.Graph() context, but this is not future-proof.

中文步骤

  1. Replace all tf.placeholder calls with tf.keras.Input(shape=..., dtype=...) and rebuild the model using the Keras Functional API.
  2. If you must use graph mode, wrap the code in a @tf.function decorator and use tf.compat.v1.placeholder inside a tf.compat.v1.Graph() context, but this is not future-proof.

Dead Ends

Common approaches that don't work:

  1. Disable eager execution with tf.compat.v1.disable_eager_execution() 70% fail

    Disabling eager execution may cause other TF2 features to break, and is not recommended for new code.

  2. Replace placeholder with tf.Variable 80% fail

    tf.Variable is for model parameters, not for input tensors; it will change the model semantics.