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


当前回答

运行TF 1并不像你想的那么容易。x和TF 2。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})

其他回答

TF2。X,你可以这样做。

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

>>>你好世界

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

tf.compat.v1.disable_eager_execution () sess = tf. compatat .v1. session ()

结果,一切都很顺利

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

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

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

(或者TensorFlow 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)

Tensorflow 2。x支持的热切执行默认情况下,因此会话不支持。