Tensorflow 中 Session 会话控制

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/nanhuaibeian/article/details/100585899

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)

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/nanhuaibeian/article/details/100585899