计算机视觉交流群:677855967,欢迎大家加入交流。
一直对tensorflow中的session的原理搞不清楚,只知道傻傻的用,今天有空去看了一下源码,把一些的粗浅的认识记录在这里,分享给大家,不正之处,多拍板转。
在tensorflow中,大家一般这样使用session:with tf.Session() as sess: 或者sess=tf.Sessions();为了便于理解,中间参数先使用默认参数。
先看一段代码:和session相关的两个关键语句 with tf.Session() as sess:和sess.run()
with tf.Graph().as_default() as graph:
x = tf.placeholder(tf.string, None)
img=tf.image.decode_jpeg(x)
with tf.Session() as sess:
sess.run(img,feed_dict={x:imgdata})
其实在执行tf.Session()这个语句时,在源码session.py中我们可以看到,我们初始化了一个session object。
初始化参数可以选择设备,哪个图,还有配置文件,比如GPU指定资源使用率等
这是tf.Session()的执行过程。
首先明确一点,一个session必然是要和一个graph连接的,如果没有显示指定,session会选择当前默认graph。
下面讲解sess.run():由源码可知,session()这个object继承于class BaseSession(SessionInterface),其中run这个函数位于BaseSession()中,源码如下:限于篇幅,去了部分注释。
def run(self, fetches, feed_dict=None, options=None, run_metadata=None):
Args:
fetches: A single graph element, a list of graph elements,
or a dictionary whose values are graph elements or lists of graph
elements (described above).
feed_dict: A dictionary that maps graph elements to values
(described above).
options: A [`RunOptions`] protocol buffer
run_metadata: A [`RunMetadata`] protocol buffer
Returns:
Either a single value if `fetches` is a single graph element, or
a list of values if `fetches` is a list, or a dictionary with the
same keys as `fetches` if that is a dictionary (described above).
Order in which `fetches` operations are evaluated inside the call
is undefined.
Raises:
RuntimeError: If this `Session` is in an invalid state (e.g. has been
closed).
TypeError: If `fetches` or `feed_dict` keys are of an inappropriate type.
ValueError: If `fetches` or `feed_dict` keys are invalid or refer to a
`Tensor` that doesn't exist.
"""
options_ptr = tf_session.TF_NewBufferFromString(
compat.as_bytes(options.SerializeToString())) if options else None
run_metadata_ptr = tf_session.TF_NewBuffer() if run_metadata else None
try:
result = self._run(None, fetches, feed_dict, options_ptr,
run_metadata_ptr)
if run_metadata:
proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)
run_metadata.ParseFromString(compat.as_bytes(proto_data))
finally:
if run_metadata_ptr:
tf_session.TF_DeleteBuffer(run_metadata_ptr)
if options:
tf_session.TF_DeleteBuffer(options_ptr)
return result
关于options,run_metadata目前只看到在timeline()做性能分析时用到,有兴趣的话可以看看这个这篇文章。
从源码看出sess.run()调用了 self._run(None, fetches, feed_dict, options_ptr,run_metadata_ptr):