Tensorflow 2.0 - AttributeError: module 'tensorflow' has no attribute 'Session'

Tensorflow 2.0 - AttributeError: module 'tensorflow' has no attribute 'Session'

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

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

System Information:

Steps to reproduce:

Installation:

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

Execution:

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

根据 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 1.x 类似 TF 2.0 中的行为,可以 运行

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

但是人们无法从 TF 2.0 中做出的许多改进中获益。有关详细信息,请参阅迁移指南 https://www.tensorflow.org/guide/migrate

我在安装 windows10 + python3.7(64bit) + anacconda3 + jupyter notebook.

后第一次尝试 python 时遇到了这个问题

我参考“https://vispud.blogspot.com/2019/05/tensorflow200a0-attributeerror-module.html

解决了这个问题

我同意

I believe "Session()" has been removed with 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))

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

如果这只是您 运行 的代码,您可以通过 运行

降级到 TensorFlow 1
pip3 install --upgrade --force-reinstall tensorflow-gpu==1.15.0 

(或者 latest version of TensorFlow 1 是什么)

TF2 运行s Eager Execution 默认情况下,因此不需要会话。如果你想运行静态图,比较合适的方法是在TF2中使用tf.function()。虽然在 TF2 中仍然可以通过 tf.compat.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

使用 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

对于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

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

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

import tensorflow as tf
sess = tf.Session()

此代码将在版本 2.x

上显示属性错误

在版本 2.x

中使用版本 1.x 的代码

试试这个

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

我遇到了同样的问题

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

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

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

结果一切顺利

使用这个:

sess = tf.compat.v1.Session()

如果有错误,使用下面的

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

如果你在做一些像这样的导入时,

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上已经提到,link是:

TensorFlow Page for using Sessions in TF2

link 中提到了 TF2 的其他主要更改,虽然很长,但请仔细阅读,使用 Ctrl+F 寻求帮助。 Link,

Effective TensorFlow 2 Page Link

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

对于 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)

这并不像你想象的那么容易,运行 TF 1.x with TF 2.x environment 我发现了一些错误,当我修复问题时需要回顾一些变量的使用互联网上的神经元网络。转换为 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})