tensorflow报错:AttributeError: module ‘tensorflow._api.v2.compat.v1‘ has no attribute ‘Sessions‘,亲测有效
原创
©著作权归作者所有:来自51CTO博客作者秃头小苏的原创作品,请联系作者获取转载授权,否则将追究法律责任
在用tensorflow的session模块报下面错误:
AttributeError: module ‘tensorflow._api.v2.compat.v1’ has no attribute
‘Sessions’
import tensorflow as tf
matrix1 = tf.constant([[3, 3]])
matrix2 = tf.constant([[2],
[2]])
product = tf.matmul(matrix1, matrix2) # matrix multiply np.dot(m1, m2)
# method 1
sess = tf.Session()
result = sess.run(product)
print(result)
sess.close()
查找资料得知是tensorflow版本更新导致的,解决方法如下:
step1 将sess = tf.Session()改成sess = tf.compat.v1.Session()
step2 在程序开始部分添加以下代码:
tf.compat.v1.disable_eager_execution()
修改后的完整代码如下:
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
matrix1 = tf.constant([[3, 3]])
matrix2 = tf.constant([[2],
[3]])
product = tf.matmul(matrix1, matrix2) # matrix multiply np.dot(m1, m2)
# method 1
sess = tf.compat.v1.Session()
result = sess.run(product)
print(result)
sess.close()
运行结果如下: