sess = tf.Session() module 'tensorflow' has no attribute 'Session'
时间: 2023-10-29 12:07:29 浏览: 31
在 TensorFlow 2.0 及以上版本中,`tf.Session()` 被弃用了,取而代之的是使用 `tf.compat.v1.Session()`。如果您正在使用 TensorFlow 2.0 及以上版本,请改为使用 `tf.compat.v1.Session()`。如果您在使用 TensorFlow 1.x 版本,则可以继续使用 `tf.Session()`。
相关问题
sess = tf.Session() AttributeError: module 'tensorflow' has no attribute 'Session'
在TensorFlow 2.0版本中,tf.Session()被删除了,所以在使用时会出现"AttributeError: module 'tensorflow' has no attribute 'Session'"的错误。你可以将tf.Session()更改为tf.compat.v1.Session(),这样就可以在TensorFlow 2.0版本中使用Session属性了。
源代码的修改后版本如下:
import tensorflow as tf
import os
os.environ["CUDA_VISIBLE_DEVICES"]="0"
a = tf.constant(2)
b = tf.constant(3)
with tf.compat.v1.Session() as sess:
print("a:%i" % sess.run(a),"b:%i" % sess.run(b))
print("Addition with constants: %i" % sess.run(a+b))
print("Multiplication with constant:%i" % sess.run(a*b))
with tf.Session() as sess: AttributeError: module tensorflow has no attribute Session
在 TensorFlow 2.x 版本中,`Session` 已经被弃用。相反,您需要使用 `tf.compat.v1.Session()` 方法。
下面是一个示例代码:
```python
import tensorflow as tf
# 创建一个常量张量
a = tf.constant(3)
b = tf.constant(4)
# 创建一个 TensorFlow 会话
with tf.compat.v1.Session() as sess:
# 计算 a 和 b 的和
result = sess.run(a + b)
print(result)
```
您还可以将以下代码添加到文件的开头,以避免在代码中使用 `tf.compat.v1.Session()`:
```python
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
```
这将禁用 TensorFlow 2.x 版本的行为,并允许您继续使用 `tf.Session()`。