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


当前回答

TF2。X,你可以这样做。

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

>>>你好世界

其他回答

用这个:

sess = tf.compat.v1.Session()

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

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

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

import tensorflow as tf
sess = tf.Session()

这段代码在版本2.x上会显示一个属性错误

使用版本1。版本2.x中的X代码

试试这个

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

根据TF 1:1符号映射,在TF 2.0中您应该使用TF . compatat .v1. session()而不是TF . session ()

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

得到TF 1。在TF 2.0中可以运行类似x的行为

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笔记本电脑后第一次尝试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))