關於在使用tensorflow2.0版本時,出現RuntimeError:tf.placeholder() is not compatible with eager execution.的問題
今天在運行程序:(部分代碼)
import tensorflow as tf
import numpy as np
tf.set_random_seed(777) # for reproducibility
learning_rate = 0.1
x_data = [[0, 0],
[0, 1],
[1, 0],
[1, 1]]
y_data = [[0],
[1],
[1],
[0]]
x_data = np.array(x_data, dtype=np.float32)
y_data = np.array(y_data, dtype=np.float32)
X = tf.placeholder(tf.float32, [None, 2])
Y = tf.placeholder(tf.float32, [None, 1])
遇到的第一個問題是:
AttributeError: module ‘tensorflow’ has no attribute ‘set_random_seed’
由於使用的tensorflow版本爲最新的版本,所以考慮到函數爲低版本下的函數,所以找到2.0版本以下和2.0版本的函數對照表:(鏈接:https://docs.google.com/spreadsheets/d/1FLFJLzg7WNP6JHODX5q8BDgptKafq_slHpnHVbJIteQ/edit#gid=0)
所以把代碼
tf.set_random_seed(777)
改爲
tf.compat.v1.set_random_seed(777)
這個問題解決之後,運行時又出現了其他問題:
raise RuntimeError("tf.placeholder() is not compatible with "
RuntimeError: tf.placeholder() is not compatible with eager execution.
再次查看是否是因爲版本的原因導致的問題:
果然,
再次修改代碼:
X = tf.placeholder(tf.float32, [None, 2])
Y = tf.placeholder(tf.float32, [None, 1])
爲:
X = tf.compat.v1.placeholder(tf.float32, [None, 2])
Y = tf.compat.v1.placeholder(tf.float32, [None, 1])
再次執行程序:
但是問題依然是
raise RuntimeError("tf.placeholder() is not compatible with "
RuntimeError: tf.placeholder() is not compatible with eager execution.
然後查看了底層函數代碼:
@tf_export(v1=["placeholder"])
def placeholder(dtype, shape=None, name=None):
"""Inserts a placeholder for a tensor that will be always fed.
**Important**: This tensor will produce an error if evaluated. Its value must
be fed using the `feed_dict` optional argument to `Session.run()`,
`Tensor.eval()`, or `Operation.run()`.
For example:
```python
x = tf.compat.v1.placeholder(tf.float32, shape=(1024, 1024))
y = tf.matmul(x, x)
with tf.compat.v1.Session() as sess:
print(sess.run(y)) # ERROR: will fail because x was not fed.
rand_array = np.random.rand(1024, 1024)
print(sess.run(y, feed_dict={x: rand_array})) # Will succeed.
@compatibility(eager)
Placeholders are not compatible with eager execution.
@end_compatibility
Args:
dtype: The type of elements in the tensor to be fed.
shape: The shape of the tensor to be fed (optional). If the shape is not
specified, you can feed a tensor of any shape.
name: A name for the operation (optional).
Returns:
A `Tensor` that may be used as a handle for feeding a value, but not
evaluated directly.
Raises:
RuntimeError: if eager execution is enabled
"""
if context.executing_eagerly():
raise RuntimeError("tf.placeholder() is not compatible with "
"eager execution.")
return gen_array_ops.placeholder(dtype=dtype, shape=shape, name=name)
看到一句話:
RuntimeError: if eager execution is enabled
如果啓動了緊急執行,會出錯。
最終查到了一個解決方案,放上鍊接:
https://stackoverflow.com/questions/53429896/how-do-i-disable-tensorflows-eager-execution
在import tensorflow as tf 後加上
tf.compat.v1.disable_eager_execution()
關閉緊急執行。
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
再次運行代碼:
結果:
執行正確。
補充一個圖片:
翻譯過來就是: