重用张量流图的一部分

时间:2017-04-14 20:15:37

标签: python tensorflow

我有一些起始值s_in,我想多次执行一些操作:

import tensorflow as tf

s_in_pl = tf.placeholder(tf.float32)
s_current = s_in_pl
def foo(a):
    return tf.exp(s_in_pl)

step_count = 1000
for i in range(step_count):
    s_current = foo(s_current)

s_in = [1,2,3]
with tf.Session():
    print s_current.eval(feed_dict={s_in_pl: s_in})

所以首先我将数据作为占位符,然后再次使用已定义的操作作为输入。

问题是:foo的图形是否可以创建一次然后以某种方式重用而不用评估其间的值(我需要计算一个渐变)?当step_count很大而且foo很复杂并且在TensorBoard中造成混乱时,创建这样的图需要一些时间。

1 个答案:

答案 0 :(得分:0)

重用"最简单的方法。计算中的相同图表是将foo()放在tf.while_loop()的正文中。例如,以下代码等同于基于for - 循环的代码,并生成了一个更小的图表,仍然可以区分:

import tensorflow as tf

s_in_pl = tf.placeholder(tf.float32)
def foo(a):
    return tf.exp(s_in_pl)

step_count = 1000

# Ignore the first return value (which will be the final value of the iteration
# counter, `i`).
_, s_final = tf.while_loop(lambda i, _: i < step_count,
                           lambda i, s_current: [i + 1, foo(s_current)],
                           [0, s_in_pl])

s_in = [1,2,3]
with tf.Session():
    print s_final.eval(feed_dict={s_in_pl: s_in})
相关问题