当我在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()


当前回答

用这个:

sess = tf.compat.v1.Session()

如果出现错误,请使用以下方法

tf.compat.v1.disable_eager_execution()
sess = tf.compat.v1.Session()

其他回答

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

我在更新Windows 10后第一次尝试谷歌Colab时也遇到了同样的问题。然后我改了一下,插入了两行,

tf.compat.v1.disable_eager_execution () sess = tf. compatat .v1. session ()

结果,一切都很顺利

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

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

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()替换它

对于Tensorflow 2.0及以后版本,试试这个。

import tensorflow as tf

tf.compat.v1.disable_eager_execution()

a = tf.constant(5)
b = tf.constant(6)
c = tf.constant(7)
d = tf.multiply(a,b)
e = tf.add(c,d)
f = tf.subtract(a,c)

with tf.compat.v1.Session() as sess:
  outs = sess.run(f)
  print(outs)