Tensorflow 2.0-AttributeError:模块'tensorflow'没有属性'Session'

Atu*_*ble 29 python keras tensorflow tensorflow2.0

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

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

系统信息:

  • 操作系统平台和发行版:Windows 10
  • python版本:3.7.1
  • Tensorflow版本:2.0.0-alpha0(随pip一起安装)

重现步骤:

安装:

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

执行:

  1. 执行命令:将tensorflow导入为tf
  2. 执行命令:sess = tf.Session()

Wes*_*Wes 75

TF2 默认运行 Eager Execution,因此不需要会话。如果要运行静态图,更合适的方法是tf.function()在TF2中使用。虽然 Session 仍然可以通过tf.compat.v1.Session()TF2访问,但我不鼓励使用它。通过比较 hello world 中的差异来证明这种差异可能会有所帮助:

TF1.x 你好世界:

import tensorflow as tf
msg = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(msg))
Run Code Online (Sandbox Code Playgroud)

TF2.x 你好世界:

import tensorflow as tf
msg = tf.constant('Hello, TensorFlow!')
tf.print(msg)
Run Code Online (Sandbox Code Playgroud)

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


MPę*_*ski 50

根据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()
Run Code Online (Sandbox Code Playgroud)

但后来人们无法受益于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'` (6认同)

小智 9

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

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

我同意

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

我插入了两行。一个是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))
Run Code Online (Sandbox Code Playgroud)


Ban*_*nta 5

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

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

>>> b'hello world