tensorflow使用Session模块时报错:AttributeError: module ‘tensorflow‘ has no attribute ‘Session‘,已解决

安装好tensorflow2.0之后,当使用Session时,报错AttributeError: module ‘tensorflow’ has no attribute ‘Session’:

源代码:

import tensorflow as tf
import os
os.environ["CUDA_VISIBLE_DEVICES"]="0"
a=tf.constant(2)
b=tf.constant(3)
with tf.Session() as sess:
    print("a:%i" % sess.run(a),"b:%i" % sess.run(b))
    print("Addition with constants: %i" % sess.run(a+b))
    print("Multiplication with constant:%i" % sess.run(a*b))

错误信息:
在这里插入图片描述
错误的意思是tensortflow模块没有Session属性,后来查阅资料发现,tensorflow2.0版本中的确没有Session这个属性,如果安装的是tensorflow2.0版本又想利用Session属性,可以将tf.Session()更改为:

tf.compat.v1.Session()

这个方法可以解决此类问题,不仅仅适用于Session属性。

再次运行时,程序又报了另一个错误:

查阅资料发现,原因是2.0与1.0版本不兼容,在程序开始部分添加以下代码:

tf.compat.v1.disable_eager_execution()

就可以正常运行了。

tensorflow的官网对disable_eager_execution()方法是这样解释的:

This function can only be called before any Graphs, Ops, or Tensors have been created. <br data-filtered="filtered">It can be used at the beginning of the program for complex migration projects from TensorFlow 1.x to 2.x.

翻译过来为:此函数只能在创建任何图、运算或张量之前调用。它可以用于从TensorFlow 1.x到2.x的复杂迁移项目的程序开头。

更新:

找到了一个更简单的方法,在引用tensorflow时,直接用:

import tensorflow.compat.v1 as tf

一劳永逸的方法。

原文链接

  • 24
    点赞
  • 94
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值