tensorflow2 AttributeError: module 'tensorflow' has no attribute 'Session'

出现问题:

AttributeError: module ‘tensorflow’ has no attribute ‘Session’

原因:

tensorflow2删除了 tf.Session()

解决方法:

tf.Session() 将改为tf.compat.v1.Session()
或者版本降级:pip install tensorflow==1.4

注意事项

tf.compat.v1.Session() 前加上tf.compat.v1.disable_eager_execution()。

tensorflow经典的方式是需要构建计算图,启动会话后,张量在图中流动进行计算。在tf 2.0最大的特色之一就在于eager execution,大大简化了之前这个繁琐的定义和计算过程。

eager execution有两个模式tf.compat.v1.enable_eager_execution()和tf.compat.v1.disable_eager_execution()。默认第一种,因此要改过来。

eg.

import tensorflow as tf #引入模块
tf.compat.v1.disable_eager_execution()
x = tf.constant([[1.0, 2.0]]) #定义一个 2 阶张量等于[[1.0,2.0]]
w = tf.constant([[3.0], [4.0]]) #定义一个 2 阶张量等于[[3.0],[4.0]]
y = tf.matmul(x, w) #实现 xw 矩阵乘法
print (y) #打印出结果
# 初始化所有变量,也就是上面定义的a/b两个变量
#tf.compat.v1.Session() as session
with tf.compat.v1.Session() as sess:
    print (sess.run(y))

猜你喜欢

转载自blog.csdn.net/qq_40575024/article/details/105862550