(我不想学tensorflow,真的不想学,没办法,别人开源的代码一个tensorflow版本一个MatConvNet版本。。。)
主要出处:http://blog.csdn.net/xierhacker/article/details/53860379
Sess与Graph
1,在tensorflow中,你一旦开始你的任务,就已经有一个默认的图(Graph)已经创建好了,Session是Graph和执行者之间的媒介,Session.run()实际上将graph、fetches、feed_dict序列化到字节数组中;
2,Sess存在的意义就是使得graph定义的计算生效:
import tensorflow as tf
#build graph
a=tf.constant(2.)
b=tf.constant(5.)
c=a*b
#construct session
sess=tf.Session()
#Evaluate the tensor `c`
print(sess.run(c))
#close session
sess.close()
如果结合上下文管理器,会更加简单:
# Using the `close()` method.
sess = tf.Session()
sess.run(...)
sess.close()
# Using the context manager.
with tf.Session() as sess:
sess.run(...)
3,我们在编写代码的时候,总是要先定义好整个图,然后才调用sess.run()去执行这个定义好的图,但是!并不是执行sess.run()后图中定义的计算全被执行,只有为了得到sess.run()输入需要计算的部分才被计算;
例子:
import tensorflow as tf
x = tf.Variable(0.0,dtype=tf.float32)
y = tf.constant(1.0,dtype=tf.float32)
z_1 = tf.add(x, y)
z_2 = tf.assign(x, z_1) % 被执行
z_3 = tf.assign(x, 100) % 不被执行(因为要得到最终的输出z_2,不需要计算z_3)
init = tf.initialize_all_variables()
with tf.Session() as sess:
sess.run(init)
print sess.run(z_2)
输出结果:1.0
4,feed_dict还可以这么用!
一般来说,feed_dict的作用是给使用placeholder创建出来的tensor赋值,feed_dict还可以提供作为数据参数提供给 run() 调用,此时feed_dict只在调用它的方法内有效, 方法结束, feed_dict就会消失;
import tensorflow as tf
x = tf.Variable(1)
y = tf.identity(x)
with tf.Session() as sess:
tf.global_variables_initializer().run()
print(sess.run(y,feed_dict={x:3})) % 输出3
print(sess.run(b)) % 输出1
5,基于Graph.as_default() 的上下文管理器,它能够在这个上下文里面覆盖默认的图;
两种典型用法:
# 1. Using Graph.as_default():
g = tf.Graph()
with g.as_default():
c = tf.constant(5.0)
assert c.graph is g
# 2. Constructing and making default:
with tf.Graph().as_default() as g:
c = tf.constant(5.0)
assert c.graph is g
上面的例子里面创创建了一个新的图g,然后把g设为默认,那么接下来的操作不是在默认的图中,而是在g中了。你也可以认为现在g这个图就是新的默认的图了。
6,Graph中指定创建的图在特定设备上运行:
g = tf.Graph()
with g.device('/gpu:0'):
# All operations constructed in this context will be placed
# on GPU 0.
with g.device(None):
# All operations constructed in this context will have no
# assigned device.
7,Graph中的finalize():
结束这个graph,使得他只读(read-only).调用 g.finalize()之后,新的操作就不能够添加到g里面去了。