学习tensorflow遇到的问题记录--AttributeError: module ‘tensorflow‘ has no attribute ‘Session‘

学习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())

再次运行,结果如下:
在这里插入图片描述
成功解决!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值