当我在Tensorflow 2.0环境中执行命令sess = tf.Session()时,我得到了一个错误消息,如下所示:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'tensorflow' has no attribute 'Session'

系统信息:

操作系统平台及发行版本:Windows 10 Python版本:3.7.1 Tensorflow版本:2.0.0-alpha0(已安装pip)

复制步骤: 安装:

PIP安装——升级PIP PIP install tensorflow==2.0.0-alpha0 PIP安装keras PIP install numpy==1.16.2

执行:

执行命令:import tensorflow as tf 执行命令:sess = tf.Session()


当前回答

使用Anaconda + Spyder (Python 3.7)

(代码)

import tensorflow as tf
valor1 = tf.constant(2)
valor2 = tf.constant(3)
type(valor1)
print(valor1)
soma=valor1+valor2
type(soma)
print(soma)
sess = tf.compat.v1.Session()
with sess:
    print(sess.run(soma))

[控制台]

import tensorflow as tf
valor1 = tf.constant(2)
valor2 = tf.constant(3)
type(valor1)
print(valor1)
soma=valor1+valor2
type(soma)
Tensor("Const_8:0", shape=(), dtype=int32)
Out[18]: tensorflow.python.framework.ops.Tensor

print(soma)
Tensor("add_4:0", shape=(), dtype=int32)

sess = tf.compat.v1.Session()

with sess:
    print(sess.run(soma))
5

其他回答

如果你在做这件事的时候,

from keras.applications.vgg16 import VGG16
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_input
import numpy as np

然后我建议你遵循这些步骤,注意:只适用于TensorFlow2和CPU进程 步骤1:告诉你的代码就像编译器是TF1一样,并禁用TF2行为,使用以下代码:

import tensorflow as tf
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

步骤2:当导入库时,提醒你的代码必须像TF1一样,是的,每一次。

tf.disable_v2_behavior()
from keras.applications.vgg16 import VGG16
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_input
import numpy as np

结论:这应该工作,让我知道如果有什么问题,也如果它是GPU,然后提到添加keras后端代码。此外,TF2不支持会话,对此有单独的理解,TensorFlow上已经提到过,链接是: TensorFlow TF2中使用会话的页面 其他主要的TF2变化已经在这个链接中提到,它很长,但请通过它,使用Ctrl+F协助。链接, Effective TensorFlow 2 Page Link

Tensorflow 2。x支持的热切执行默认情况下,因此会话不支持。

同样的问题也发生在我身上

import tensorflow as tf
hello = tf.constant('Hello World ') 
sess = tf.compat.v1.Session()    *//I got the error on this step when I used 
                                   tf.Session()*
sess.run(hello)

尝试用tf.compact.v1.Session()替换它

TF2在默认情况下运行Eager Execution,从而消除了对session的需求。如果你想运行静态图形,更合适的方法是在TF2中使用tf.function()。虽然在TF2中仍然可以通过tf. compatat .v1.Session()访问Session,但我不鼓励使用它。通过比较hello worlds中的差异可能有助于演示这种差异:

TF1。X你好世界:

import tensorflow as tf
msg = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(msg))

TF2。X你好世界:

import tensorflow as tf
msg = tf.constant('Hello, TensorFlow!')
tf.print(msg)

更多信息请参见Effective TensorFlow 2

import tensorflow as tf
sess = tf.Session()

这段代码在版本2.x上会显示一个属性错误

使用版本1。版本2.x中的X代码

试试这个

import tensorflow.compat.v1 as tf
sess = tf.Session()