Session 是 TensorFlow 为了控制和输出文件的执行语句,运行 Session.run() 可以获得你想要的运算结果
一、示例 1
import tensorflow as tf
# 建立一个一行两列的矩阵
matrix1 = tf.constant([3,3])
# 建立一个两行一列的矩阵
matrix2 = tf.constant([[2],
[2]])
# 执行两个矩阵的乘法
product = tf.matmul(matrix1,matrix2)
# 这里 product 是直接计算的步骤,所以使用 Session 来激活 product
sess = tf.Session()
result = sess.run(product)
sess.close()
二、示例 2
由于 Session 是一个对象,使用完需要 close
在编程的时候,往往会忘记 close() ,所以我们可以使用 with 更加简洁的语句来实现
Python 中 with 的作用:
(1)使用with后不管with中的代码出现什么错误,都会进行对当前对象进行清理工作。例如file的file.close()方法,无论with中出现任何错误,都会执行file.close()方法
(2)with只有在特定场合下才能使用。这个特定场合指的是那些支持了上下文管理器的对象。
import tensorflow as tf
# 建立一个一行两列的矩阵
matrix1 = tf.constant([3,3])
# 建立一个两行一列的矩阵
matrix2 = tf.constant([[2],
[2]])
# 执行两个矩阵的乘法
product = tf.matmul(matrix1,matrix2)
# 这里 product 是直接计算的步骤,所以使用 Session 来激活 product
with tf.Session() as sess:
result = sess.run(product)
print(result)