小记
tensorflow的sess有一个分步执行的函数partial_run,此函数的文档说明和具体运行有点差异,留文以记录。
形式1
import tensorflow as tf
a = tf.placeholder(dtype=tf.float32, shape=[])
b = tf.placeholder(dtype=tf.float32, shape=[])
c = tf.placeholder(dtype=tf.float32, shape=[])
e = tf.placeholder(dtype=tf.float32, shape=[])
d = tf.Variable(dtype=tf.float32, initial_value=0)
r1 = tf.add(a, b)
a_0 = tf.assign(d, tf.add(d,c),name='0')
a_1 = tf.assign(d, tf.add(d,e),name='1')
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
h = sess.partial_run_setup([r1, a_0, a_1], [a, b, c, e])
res_1 = sess.partial_run(h, r1, feed_dict={a: 1, b: 2})
res_2 = sess.partial_run(h, a_0, feed_dict={c: res_1})
print(d.eval())
此时,输出 3.0
形式2
import tensorflow as tf
a = tf.placeholder(dtype=tf.float32, shape=[])
b = tf.placeholder(dtype=tf.float32, shape=[])
c = tf.placeholder(dtype=tf.float32, shape=[])
e = tf.placeholder(dtype=tf.float32, shape=[])
d = tf.Variable(dtype=tf.float32, initial_value=0)
r1 = tf.add(a, b)
a_0 = tf.assign(d, tf.add(d,c),name='0')
a_1 = tf.assign(d, tf.add(d,e),name='1')
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
h = sess.partial_run_setup([r1, a_0, a_1], [a, b, c, e])
res_1 = sess.partial_run(h, r1, feed_dict={a: 1, b: 2})
res_2 = sess.partial_run(h, a_0, feed_dict={c: res_1})
print(d.eval())
此时输出 6.0
形式3
import tensorflow as tf
a = tf.placeholder(dtype=tf.float32, shape=[])
b = tf.placeholder(dtype=tf.float32, shape=[])
c = tf.placeholder(dtype=tf.float32, shape=[])
e = tf.placeholder(dtype=tf.float32, shape=[])
d = tf.Variable(dtype=tf.float32, initial_value=0)
r1 = tf.add(a, b)
a_0 = tf.assign(d, tf.add(d,c),name='0')
a_1 = tf.assign(d, tf.add(d,e),name='1')
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
h = sess.partial_run_setup([r1, a_0, a_1], [a, b, c, e])
res_1 = sess.partial_run(h, r1, feed_dict={a: 1, b: 2})
res_2 = sess.partial_run(h, a_0, feed_dict={c: res_1, e: res_1})
print(d.eval())
此时,依然输出 6.0
总结
也就是说无论fetches是否写上,只要feed_dict中给与了相应的placeholder值,fetches中的op就会运行。
更多的现象
import tensorflow as tf
c = tf.placeholder(dtype=tf.float32, shape=[2,2])
e = tf.placeholder(dtype=tf.float32, shape=[2,2])
d = tf.Variable(dtype=tf.float32, initial_value=[[0,1],[2,3]])
a_0 = tf.assign(d, tf.matmul(d,c),name='0')
a_1 = tf.assign(d, tf.matmul(d,e),name='1')
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
h = sess.partial_run_setup([a_0, a_1], [c, e])
res_2 = sess.partial_run(h, [a_1,a_0], feed_dict={c: [[1,0],[0,0]], e: [[0,1],[1,0]]})
print(d.eval())
运行多次,会出现不同的结果。诚然partial运行旨在运行分步的代码,也就是下一步的参数需要是上一步代码的结果,此处不是这种类型,但是在使用时还是要小心。