在执行下面代码时,报错:AttributeError: module 'tensorflow' has no attribute 'Session'
原因:tensorflow为2.0以上版本,不支持Session
import tensorflow as tf
a = tf.constant(11.0)
b = tf.constant(20.0)
c = tf.add(a, b)
#指定一个会话运行tensorflow程序
with tf.Session() as sess:
c_res = sess.run(c)
print(c_res)
修改代码如下:
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
a = tf.constant(11.0)
b = tf.constant(20.0)
c = tf.add(a, b)
#指定一个会话运行tensorflow程序
with tf.compat.v1.Session() as sess:
c_res = sess.run(c)
print(c_res)
或者可以选择卸载重装1.几版本的tensorflow。
更新:
我发现这样改不太好,因为这样下面要调用的不匹配代码就都得改。可以直接开头的代码import tensorflow as tf 改成
import tensorflow.compat.v1 as tf