zoukankan      html  css  js  c++  java
  • 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. 
    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
    

    一劳永逸的方法。

  • 相关阅读:
    vue表单:输入身份证号码则自动获取对应的年龄和性别,,若不输入身份证号则自己填写年龄和性别
    el-input 电话号码输入时加上空格(344)
    vue图片上传---融合裁剪功能
    shell 基本编程
    virtualbox 安装centos ,运行shell 脚本
    js 检测变量类型
    js deepCopy
    python 安装requests库
    python 识别文件 文件夹
    python 删除非空文件夹
  • 原文地址:https://www.cnblogs.com/123456www/p/12584427.html
Copyright © 2011-2022 走看看