转自:huahuanzhu
1
函数参数
run( fetches, feed_dict=None, options=None, run_metadata=None)
tf.Session.run() 执行 fetches 中的操作,计算 fetches 中的张量值。
这个函数执行一步 TensorFlow 运算,通过运行必要的图块来执行每一个操作,并且计算每一个 fetches 中的张量的值,用相关的输入变量替换 feed_dict 中的值。
fetches 参数可能是一个单一图元素,或者任意嵌套列表,元组,namedtuple,字典,或者有序字典在叶子中包含图元素。
tf.Session.run()函数返回值为fetches的执行结果。如果fetches是一个元素就返回一个值;若fetches是一个list,则返回list的值,若fetches是一个字典类型,则返回和fetches同keys的字典。
(Either a single valueif `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).)
2
session.run([fetch1, fetch2])
关于 session.run([fetch1, fetch2]),请看http://stackoverflow.com/questions/42407611/how-tensorflow-handle-the-computional-graph-when-executing-sess-run/42408368?noredirect=1#comment71994086_42408368
执行sess.run()时,tensorflow是否计算了整个图
我们在编写代码的时候,总是要先定义好整个图,然后才调用sess.run()。那么调用sess.run()的时候,程序是否执行了整个图
import tensorflow as tf
state = tf.Variable(0.0,dtype=tf.float32)
one = tf.constant(1.0,dtype=tf.float32)
new_val = tf.add(state, one)
update = tf.assign(state, new_val) #返回tensor, 值为new_val
update2 = tf.assign(state, 10000) #没有fetch,便没有执行
init = tf.initialize_all_variables()
with tf.Session() as sess:
sess.run(init)
for _ in range(3):
print sess.run(update)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
和上个程序差不多,但我们这次仅仅是fetch “update”,输出是1.0 , 2.0, 3.0,可以看出,tensorflow并没有计算整个图,只是计算了与想要fetch 的值相关的部分
sess.run() 中的feed_dict
我们都知道feed_dict的作用是给使用placeholder创建出来的tensor赋值。其实,他的作用更加广泛:feed 使用一个 值临时替换一个 op 的输出结果. 你可以提供 feed 数据作为 run() 调用的参数. feed 只在调用它的方法内有效, 方法结束, feed 就会消失.
import tensorflow as tf
y = tf.Variable(1)
b = tf.identity(y)
with tf.Session() as sess:
tf.global_variables_initializer().run()
print(sess.run(b,feed_dict={y:3})) #使用3 替换掉
#tf.Variable(1)的输出结果,所以打印出来3
#feed_dict{y.name:3} 和上面写法等价
print(sess.run(b)) #由于feed只在调用他的方法范围内有效,所以这个打印的结果是 1
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
输出是3 1
参考文献:
[1] tensorflow whitepaper