tf.Session()是Tensorflow中控制输出内容的一个api。通过运行session.run()可以获得你要得知的运算结果,将运算结果作为可视化变量进行显示。
用代码来举个简单的例子方便更好的理解
import tensorflow as tf
matrix1 = tf.constant([[3,3]])
matrix2 = tf.constant([[2],
[2]])
product = tf.matmul(matrix1,matrix2)
这里创建两个矩阵并进行运算,通过运行可知,输出product的值并无法直接进行观察。
然后就可以使用session.run()对其进行可视化,改进后的代码如下:
import tensorflow as tf
matrix1 = tf.constant([[3,3]])
matrix2 = tf.constant([[2],
[2]])
product = tf.matmul(matrix1,matrix2)
#加入session
sess = tf.Session()
result = sess.run(product)
print(result)
sess.close()
此时就可以在变量区看到result是个具体值。
Tip:有时候直接运行上面代码会报错AttributeError: module 'tensorflow' has no attribute 'Session',别慌,这是因为TF版本1.0与2.0部分API不同所致,只需要加上下面的代码即可
import tensorflow.compat.v1 as tf
tf.disable_eager_execution()
这样就可以顺利实现目的啦