Python TensorFlow 2.0运行时错误:试图使用关闭的会话

Python TensorFlow 2.0运行时错误:试图使用关闭的会话,python,tensorflow2.0,Python,Tensorflow2.0,我正在安装TensorFlow 2.0,但遇到了session.run问题。每次我使用python对代码执行sess.run时,都会出现运行时错误。代码段: import tensorflow.compat.v1 as tf sess=tf.Session() # verify we can print a string hello=tf.constant("Hello Pluralsight from TensorFlow") print((hello))

我正在安装TensorFlow 2.0,但遇到了session.run问题。每次我使用python对代码执行sess.run时,都会出现运行时错误。代码段:

import tensorflow.compat.v1 as tf
    
sess=tf.Session()
# verify we can print a string
hello=tf.constant("Hello Pluralsight from TensorFlow")
print((hello))
    
a = tf.constant(20)
b = tf.constant(22)
z = (a + b)
    
print('a + b = {0}'.format(sess.run(z)))
终端错误如下:

    python installation_test.py
2020-11-23 22:03:21.575988: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x12c79e790 initialized for platform Host (this does not guarantee that XLA will be used). Devices:
2020-11-23 22:03:21.576019: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): Host, Default Version
Traceback (most recent call last):
  File "installation_test.py", line 11, in <module>
    print(ses.run(c))
  File "/Users/evanwiley/Library/Python/2.7/lib/python/site-packages/tensorflow_core/python/client/session.py", line 960, in run
    run_metadata_ptr)
  File "/Users/evanwiley/Library/Python/2.7/lib/python/site-packages/tensorflow_core/python/client/session.py", line 1106, in _run
    raise RuntimeError('Attempted to use a closed Session.')
RuntimeError: Attempted to use a closed Session.
python安装\u test.py
20201-11-23 22:03: 21.575988:I TysFult/Cys/XLA/Service / Service .CC:168)XLA服务0x12C79E790为平台主机初始化(这不能保证XLA将被使用)。设备:
2020-11-23 22:03:21.576019:I tensorflow/compiler/xla/service/service.cc:176]StreamExecutor设备(0):主机,默认版本
回溯(最近一次呼叫最后一次):
文件“installation_test.py”,第11行,在
打印(ses.run(c))
文件“/Users/evanwiley/Library/Python/2.7/lib/Python/site packages/tensorflow_core/Python/client/session.py”,第960行,正在运行
运行_元数据_ptr)
文件“/Users/evanwiley/Library/Python/2.7/lib/Python/site-packages/tensorflow\u-core/Python/client/session.py”,第1106行,正在运行
raise RUNTIMERROR('试图使用关闭的会话')
RuntimeError:试图使用已关闭的会话。

任何使用tf.Session的内容都必须与Session处于活动状态的名称空间保持一致,在您的情况下,需要进行以下更改:

import tensorflow.compat.v1 as tf
    
with tf.Session() as sess:
    # verify we can print a string
    hello=tf.constant("Hello, TensorFlow")
    print((hello))
    
    a = tf.constant(20)
    b = tf.constant(22)
    z = (a + b)
    
    print('a + b = {0}'.format(sess.run(z)))

当您尝试在范围外执行sess.run时,它会自动关闭会话。

您应该尝试使用较新版本的python。2.7已经到了生命的尽头。谢谢你的帮助!