RuntimeError: tf.placeholder() is not compatible with eager execution.和沒有placeholder函式解決方法
阿新 • • 發佈:2021-01-27
在新版本tensorflow (1.15.0,2.0及以上) 中由於沒有tf.placeholder佔位符,函式呼叫應為:
a = tf.compat.v1.placeholder(dtype=tf.float32)
但這樣placeholder在執行時會被立刻執行發生報錯,為了讓它只作為一個定義而不被立刻執行,等到session部分再執行,應在前面加上:
tf.compat.v1.disable_eager_execution() # 使placeholder只被定義,防止placeholder立刻被執行
整體程式為(以相加為例):
# 使用佔位符構建計算
tf.compat.v1.disable_eager_execution() # 使placeholder只被定義,防止placeholder立刻被執行
a = tf.compat.v1.placeholder(dtype=tf.float32)
b = tf.compat.v1.placeholder(dtype=tf.float32) # 建立兩個佔位節點
adder = a + b
print(a)
print(b)
print(adder)
tf.compat.v1.disable_eager_execution() # 無法直接呼叫tf.Session
sess = tf.compat.v1.Session()
print(sess.run(adder, {a: 3, b: 4}))
print(sess.run(adder, {a: [1,3], b: [2,3]}))
執行結果為:
Tensor("Placeholder:0", dtype=float32)
Tensor("Placeholder_1:0", dtype=float32)
Tensor("add:0", dtype=float32)
7.0
[3. 6.]