182

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

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 安装)

重现步骤:

安装:

  1. 点安装——升级点
  2. pip install tensorflow==2.0.0-alpha0
  3. 点安装 keras
  4. pip install numpy==1.16.2

执行:

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

16 回答 16

329

根据TF 1:1 Symbols Map,在 TF 2.0 中,您应该使用tf.compat.v1.Session()而不是tf.Session()

https://docs.google.com/spreadsheets/d/1FLFJLzg7WNP6JHODX5q8BDgptKafq_slHpnHVbJIteQ/edit#gid=0

要在 TF 2.0 中获得类似 TF 1.x 的行为,可以运行

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

但随后无法从 TF 2.0 中的许多改进中受益。有关更多详细信息,请参阅迁移指南 https://www.tensorflow.org/guide/migrate

于 2019-03-13T13:42:08.217 回答
87

TF2 默认运行 Eager Execution,因此不再需要 Session。如果要运行静态图,更合适的方法是tf.function()在 TF2 中使用。虽然 Session 仍然可以tf.compat.v1.Session()在 TF2 中访问,但我不鼓励使用它。通过比较 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)

有关详细信息,请参阅有效的 TensorFlow 2

于 2019-12-04T15:18:49.587 回答
33

我在安装后第一次尝试 python 时遇到了这个问题windows10 + python3.7(64bit) + anacconda3 + jupyter notebook.

我通过参考“ https://vispud.blogspot.com/2019/05/tensorflow200a0-attributeerror-module.html ”解决了这个问题

我同意

我相信“Session()”已经被 TF 2.0 删除了。

我插入了两行。一个是tf.compat.v1.disable_eager_execution()另一个是sess = tf.compat.v1.Session()

我的 Hello.py 如下:

import tensorflow as tf

tf.compat.v1.disable_eager_execution()

hello = tf.constant('Hello, TensorFlow!')

sess = tf.compat.v1.Session()

print(sess.run(hello))
于 2019-10-15T02:51:59.633 回答
6

对于TF2.x,您可以这样做。

import tensorflow as tf
with tf.compat.v1.Session() as sess:
    hello = tf.constant('hello world')
    print(sess.run(hello))

>>> b'hello world

于 2020-01-26T16:15:05.287 回答
4

如果这是您的代码,正确的解决方案是将其重写为 not use Session(),因为在 TensorFlow 2 中不再需要

如果这只是您正在运行的代码,您可以通过运行降级到 TensorFlow 1

pip3 install --upgrade --force-reinstall tensorflow-gpu==1.15.0 

(或任何最新版本的 TensorFlow 1

于 2019-10-23T06:21:57.870 回答
4

Tensorflow 2.x 默认支持 Eager Execution,因此不支持 Session。

于 2020-10-08T15:30:54.140 回答
1
import tensorflow as tf
sess = tf.Session()

此代码将在版本 2.x 上显示属性错误

在 2.x 版中使用 1.x 版代码

试试这个

import tensorflow.compat.v1 as tf
sess = tf.Session()
于 2020-10-14T16:44:41.930 回答
1

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

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

结果,一切顺利

于 2021-03-27T01:42:51.940 回答
1

用这个:

sess = tf.compat.v1.Session()

如果有错误,请使用以下

tf.compat.v1.disable_eager_execution()
sess = tf.compat.v1.Session()
于 2021-04-18T09:41:49.753 回答
1
import tensorflow._api.v2.compat.v1 as tf
tf.disable_v2_behavior()
于 2021-08-12T20:16:41.257 回答
1

对于 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)
于 2021-08-18T10:30:59.283 回答
0

使用 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
于 2020-01-05T14:16:31.350 回答
0

TF v2.0 支持 Eager 模式相对于 v1.0 的 Graph 模式。因此,v2.0 不支持 tf.session()。因此,建议您重写代码以在 Eager 模式下工作。

于 2020-06-29T10:11:53.070 回答
0

我也遇到了同样的问题

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()

于 2021-02-11T16:44:20.923 回答
0

如果你在一些进口喜欢的时候这样做,

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 不支持 session 对此有一个单独的理解,在 TensorFlow 上已经提到,链接是:

TensorFlow Page for using Sessions in TF2

其他主要的 TF2 变化在这个链接中已经提到,很长,但请浏览它,使用 Ctrl+F 寻求帮助。链接,

Effective TensorFlow 2 页面链接

于 2021-05-18T15:20:44.580 回答
0

没有你想的那么容易,在 TF 2.x 环境下运行 TF 1.x 我在网上修复神经元网络的问题时发现了一些错误,需要回顾一些变量的用法。转换为 TF 2.x 是更好的主意。(更容易和适应性)

TF 2.X
while not done:
    next_obs, reward, done, info = env.step(action) 
        env.render()
    img = tf.keras.preprocessing.image.array_to_img(
            img,
            data_format=None,
            scale=True
    )
    img_array = tf.keras.preprocessing.image.img_to_array(img)
    predictions = model_self_1.predict(img_array) ### Prediction

### Training: history_highscores = model_highscores.fit(batched_features, epochs=1 ,validation_data=(dataset.shuffle(10))) # epochs=500 # , callbacks=[cp_callback, tb_callback]    
TF 1.X
with tf.compat.v1.Session() as sess:
    saver = tf.compat.v1.train.Saver()
    saver.restore(sess, tf.train.latest_checkpoint(savedir + '\\invader_001'))
    train_loss, _ = sess.run([loss, training_op], feed_dict={X:o_obs, y:y_batch, X_action:o_act})
    
    for layer in mainQ_outputs: 
                model.add(layer)
        model.add(tf.keras.layers.Flatten() )
        model.add(tf.keras.layers.Dense(6, activation=tf.nn.softmax))
        predictions = model.predict(obs) ### Prediction

    
### Training: summ = sess.run(summaries, feed_dict={X:o_obs, y:y_batch, X_action:o_act})

将 TF 1.X 转换为 TF 2.X 的示例,只有您在示例中看到

于 2022-01-23T02:12:06.800 回答