RuntimeError: tf.placeholder() is not compatible with eager execution.
时间: 2023-12-29 12:12:28 浏览: 27
这个错误通常是因为你正在使用 TensorFlow 2.0 的 Eager Execution 模式,而 placeholder 是 TensorFlow 1.x 的概念,不支持 Eager Execution 模式。你可以使用 tf.data.Dataset API 代替 placeholder,或者禁用 Eager Execution 模式。
如果你想禁用 Eager Execution 模式,可以在代码开头添加以下代码:
```python
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
```
这会将 TensorFlow 切换回到 1.x 版本的 Graph Execution 模式,从而可以使用 placeholder。
如果你想使用 tf.data.Dataset API 代替 placeholder,可以使用以下示例代码:
```python
import tensorflow as tf
# 定义输入数据
input_data = tf.data.Dataset.from_tensor_slices(input_placeholder)
label_data = tf.data.Dataset.from_tensor_slices(label_placeholder)
# 定义批次大小和迭代器
batch_size = 32
iterator = tf.compat.v1.data.Iterator.from_structure(input_data.output_types, input_data.output_shapes)
input_batch, label_batch = iterator.get_next()
input_batch.set_shape([batch_size] + list(input_data.output_shapes))
label_batch.set_shape([batch_size] + list(label_data.output_shapes))
# 定义其他操作
# ...
# 初始化迭代器
train_init_op = iterator.make_initializer(input_data)
sess.run(train_init_op, feed_dict={input_placeholder: input_data, label_placeholder: label_data})
```
其中,input_placeholder 和 label_placeholder 分别是输入数据和标签的占位符,input_data 和 label_data 是输入数据和标签的 tf.data.Dataset 对象。通过 tf.compat.v1.data.Iterator.from_structure() 创建一个迭代器,然后通过 iterator.get_next() 获取批次数据。最后,通过 iterator.make_initializer() 初始化迭代器,并通过 feed_dict 传入数据。