A class for running TensorFlow operations.
这是一个类,执行 tensorflow
中的 op
。它里面定义了 run()
、extend()
、close()
、__init__()
等方法。
简而言之,就是 用户使用tensorflow时交互的接口。
通过类内定义的方法 如 extend()
创建新的边和节点,以创建新的图;通过 run()
执行。
Tensorflow以Session接口类这个C API为边界,将系统分为 前端 和 后端 两个 子系统。后端 = sess.run(前端)
。
前端: 支持多语言的编程环境,能够提供计算图的编程模型。通过Session接口为桥梁,连接tensorflow后端的运行时
, 并启动计算图的执行过程。
后端: 根据Session().run()中的fetches参数,从计算图中反向遍历,找到所依赖的最小子图,将子图分裂成“子图片段”,分发给worker们(如gpu_0、gpu_1、cpu_0等)。所有worker按流程执行子图片段。
若创建 Session
时没有指定Graph,则会加载默认的Graph。
若 一个进程 中有多个图,我们就需要定义创建不同的 Session
来加载不同的图;对于同一个 Graph
可以加载不同的 Session
。
sess = tf.Session()
,此时 sess
成了 Session
类的实例。
Session 可能拥有的资源,如 tf.Variable,tf.QueueBase和tf.ReaderBase。在不再需要这些资源时,重要的是释放这些资源,即调用 Session类 中的 tf.Session.close,也可以在with所创造的上下文管理器中直接run,结束的时候不需要 close Session
的额外操作。以下两个例子是等效的:
# 正常流程
sess = tf.Session()
sess.run(...)
sess.close() # 记得要有这句,否则不会释放。
# 使用上下文管理器
with tf.Session() as sess:
sess.run(...)
tf.Session.init(target=”, graph=None, config=None)
tf.Session.run(fetches, feed_dict=None, options=None, run_metadata=None)
初始化时就已经赋值过了:
import tensorflow as tf
node1 = tf.constant(value=[1, 2], dtype=tf.int32)
node2 = tf.constant(value=[3, 4], dtype=tf.int32)
c = tf.multiply(node1, node2)
tf.global_variables_initializer()
print (node1, node2, c)
print (tf.Session().run(c))
print (tf.Session().run(fetches=node1), tf.Session().run(fetches=node2), tf.Session().run(fetches=c))
tf.Session().close()
(<tf.Tensor 'Const:0' shape=(2,) dtype=int32>, <tf.Tensor 'Const_1:0' shape=(2,) dtype=int32>, <tf.Tensor 'Mul:0' shape=(2,) dtype=int32>)
[3 8]
(array([1, 2], dtype=int32), array([3, 4], dtype=int32), array([3, 8], dtype=int32))
后期执行 run()
时,通过 feed_dict参数
进行赋值:
import tensorflow as tf
node1 = tf.placeholder(dtype=tf.int32, shape=(2,))
node2 = tf.placeholder(dtype=tf.int32, shape=(2,))
c = tf.multiply(node1, node2)
tf.global_variables_initializer()
print (node1, node2, c)
print (tf.Session().run(fetches=c, feed_dict={node1:[1, 2], node2:[3, 4]}))
print (tf.Session().run(fetches=node1, feed_dict={node1:[1, 2]}),
tf.Session().run(fetches=node2, feed_dict={node2:[3, 4]}),
tf.Session().run(fetches=c, feed_dict={node1:[1, 2], node2:[3, 4]}))
tf.Session().close()
(<tf.Tensor 'Const:0' shape=(2,) dtype=int32>, <tf.Tensor 'Const_1:0' shape=(2,) dtype=int32>, <tf.Tensor 'Mul:0' shape=(2,) dtype=int32>)
[3 8]
(array([1, 2], dtype=int32), array([3, 4], dtype=int32), array([3, 8], dtype=int32))
第一种 eval()
用法:
import tensorflow as tf
sess = tf.InteractiveSession() ###
a = tf.constant(5)
b = tf.constant(6)
c = a * b
# 通过使用 'c.eval()' 可以免去 'sess'
print(c.eval()) ###
sess.close() ###
30
第二种 eval()
用法:
import tensorflow as tf
a = tf.constant(5)
b = tf.constant(6)
c = a * b
with tf.Session(): ###
# 这里 tf.Session() 不可替换为 tf.InteractiveSession(), 具体原因我也不知道,以后再探究
print(c.eval()) ###
30