ChatGPT解决这个技术问题 Extra ChatGPT

Tensorflow 2.0 - AttributeError:模块'tensorflow'没有属性'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'

系统信息:

操作系统平台和发行版:Windows 10

Python版本:3.7.1

Tensorflow 版本:2.0.0-alpha0(用 pip 安装)

重现步骤: 安装:

pip install --upgrade pip pip install tensorflow==2.0.0-alpha0 pip install keras pip install numpy==1.16.2

执行:

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

诡异的。我认为不是TF版本的原因,而是完整的TF安装坏了。请参阅github.com/tensorflow/tensorflow/issues/…
TensorFlow 2.0 围绕 functions, not sessions 工作。我认为最初的想法是至少在最初保留 tf.Session,但看看 the docs,它似乎终于被完全刮掉了。
哦,看来您仍然可以通过 tf.compat.v1.Session 访问它。
@DmytroPrylipko 我在创建这个问题之前尝试过。它对我不起作用。

M
MPękalski

根据 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


使用 import tensorflow.compat.v1 as tf tf.disable_v2_behavior() 给我一个错误 AttributeError: module 'tensorflow_core.compat.v1' has no attribute 'contrib'
在 TF 2.0 迁移文档 It is still possible to run 1.X code, unmodified (except for contrib), in TensorFlow 2.0 中找到了这个
当您收到 tensorflow_core has no attribute 错误时,您使用的是哪个 TF 版本?
我已经下载了一些笔记本,我正面临着这些问题,如答案中提到的在顶部导入语句帮助我摆脱了恼人的错误。
那么如何评估 TF2 中的静态 .pb 图?只能通过使用像 tf.compat.v1.Session() 这样的 tf1-feature。在 TF2 中,您应该始终使用渴望模式而不使用 .pb
W
Wes

TF2 默认运行 Eager Execution,因此不再需要 Session。如果要运行静态图,更合适的方法是在 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


TF2有非eager模式吗?还是急切模式只是建议的执行模式?如果我想在 TF2 中有静态 .pb 文件怎么办?可能吗?那么如何在 TF2 中评估它?
K
Kavitha Karunakaran

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

我通过参考“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))

我宁愿说在 TF 2.0 中 Session() 已被移动而不是被删除。 需要使用 Session() 已被删除。
B
Bandham Manikanta

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


B
BlueRaja - Danny Pflughoeft

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

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

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

(或任何 latest version of TensorFlow 1


1.15.x 之后应该没有其他 1.x 版本的 TF,除非会出现一些补丁,但没有改进。
D
DataCrusade1999

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


d
decorator-factory

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

a
azad1701
import tensorflow as tf
sess = tf.Session()

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

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

尝试这个

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

P
Pawara Siriwardhane

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

tf.compat.v1.disable_eager_execution()

sess = tf.compat.v1.Session()

结果,一切顺利


A
Abu Bakar Siddik

用这个:

sess = tf.compat.v1.Session()

如果有错误,请使用以下

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

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

B
Bruno

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

a
aksingh2411

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


TF2 是否完全支持非急切模式?还是非急切只是 tf1 功能?那么如何评估 tf2 中的 .pb 图表?
E
EMiller

我也遇到了同样的问题

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


P
Param rathod

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

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 Page Link


J
Jirayu Kaewprateep

没有你想的那么容易,在 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})

https://i.stack.imgur.com/sVMts.png


关注公众号,不定期副业成功案例分享
关注公众号

不定期副业成功案例分享

领先一步获取最新的外包任务吗?

立即订阅