tf.placeholder() is not compatible with eager execution.解决方法

我用的是tf 2版本,出现这个错误的原因分析如下:
在tf 1 版本中,placeholder可以这么用,placeholder相当于一个占位符
with是开启这个会话,等到有feed_dict喂入时,placeholder代表的参数才会真正地进入会话之中,运算开始进行。

tf.placeholder() is meant to be fed to the session that when run recieve the values from feed dict and perform the required operation. Generally you would create a Session() with ‘with’ keyword and run it.But this might not favour all situations due to which you would require immediate execution.This is called eager execution. Example:

generally this is the procedure to run a Session:

import tensorflow as tf

def square(num):
    return tf.square(num) 

p = tf.placeholder(tf.float32)
q = square(num)

with tf.Session() as sess:
    print(sess.run(q, feed_dict={num: 10})

但是在tf 2中,已经用eager来替代了session,使代码更加简洁
But when we run with eager execution we run it as:

import tensorflow as tf

tf.enable_eager_execution()

def square(num):
   return tf.square(num)

print(square(10)) 

Therefore we need not run it inside a session explicitely and can be more intuitive in most of the cases.
更多关于eager
如果想要在tf 2的情况下使用tf 1的placeholder,那么就要先将eager关掉,可以加一个语句如下:

tf.compat.v1.disable_eager_execution()

回过头来,我们再看这个错误,说的其实就是placeholder和eager execution不兼容,所以将tf 2.0中的eager execution暂时关闭是很自然的解决方法。

你可能感兴趣的:(机器学习)