学习tensorflow2.0遇到的问题记录–AttributeError: module ‘tensorflow’ has no attribute ‘Session’
今天在测试自己的电脑上的tensorflow是否能用时,就照着书上敲了以下代码:
01 import tensorflow as tf
02 txt_tf=tf.constant("hello tensorflow!",dtype=tf.string,name="input")
03 with tf.Session() as sess:
04 txt=sess.run(txt_tf)
05 print(txt.decode())
运行之后,报错:AttributeError: module ‘tensorflow’ has no attribute 'Session’
网上查了下资料,原来tf.Session()是tensorflow1的写法,而我装的是tensorflow2,因此报了错,需要将tf.Session()改为tf.compat.v1.Session()。纠正之后,再次运行,又遇到了另一个问题:
RuntimeError: The Session graph is empty. Add operations to the graph before calling run().
原来也是1.0和2.0不兼容的问题,需要加一行:tf.compat.v1.disable_eager_execution()
即最终代码为:
import tensorflow as tf
tf.compat.v1.disable_eager_execution()#保证sess.run()能够正常运行
txt_tf=tf.constant("hello tensorflow!",dtype=tf.string,name="input")
with tf.compat.v1.Session() as sess:
txt=sess.run(txt_tf)
print(txt.decode())
再次运行,结果如下:
成功解决!