首页 > 技术文章 > tensorflow报错:AttributeError: module ‘tensorflow._api.v2.compat.v1‘ has no attribute ‘Sessions‘,亲测有效

wsj-create 2021-04-14 16:14 原文

在用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()

运行结果如下:
在这里插入图片描述

参考链接:https://www.cnblogs.com/123456www/p/12584427.html

推荐阅读