AttributeError: module ‘tensorflow‘ has no attribute ‘Session‘

刚开始学习使用tensorflow,遇到的一个问题


前言

<
刚开始学习使用tensorflow,遇到的一个问题,通过tensorflow实现加法

一、原本代码

import tensorflow as tf

a = tf.constant(11.0)
b = tf.constant(12.0)
c = tf.add(a, b)

with tf.Session() as sess:
    c_res = sess.run(c)
    print(c_res)

结果出现下面错误

Traceback (most recent call last):
  File "C:/Users/lbb/Desktop/demo/demo.py", line 7, in <module>
    with tf.Session() as sess:
AttributeError: module 'tensorflow' has no attribute 'Session'

二更改后代码

在网上查询得知是tensorflow2对之前的tensorflow1不兼容,tensorflow2中没有session这个模块,需要将其中的

with tf.Session() as sess:

改为

with tf.compat.v1.Session() as sess:

运行之后还是报错,解决方法,在前面加一行代码

tf.compat.v1.disable_eager_execution()#保证sess.run能够运行

完整代码

import tensorflow as tf
tf.compat.v1.disable_eager_execution()#保证sess.run能够运行
a = tf.constant(11.0)
b = tf.constant(12.0)
c = tf.add(a, b)

with tf.compat.v1.Session() as sess:
    c_res = sess.run(c)
    print(c_res)

程序运行结果:

23.0

总结

参考这个博主的[https://blog.csdn.net/weixin_38410551/article/details/103631977]
有时运行时会出现一堆警告,虽然不影响程序运行,但是影响心情。在代码最上方加上

import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'

就能获得清爽的界面了

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值