【问题标题】:reusing part of tensorflow graph重用张量流图的一部分
【发布时间】:2017-04-15 05:00:57
【问题描述】:

我有一些起始值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 中造成混乱时,创建这样的图表需要一些时间。

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    在计算中“重用”同一图的最简单方法是将foo() 放入tf.while_loop() 的主体中。例如,以下代码等价于您的基于 for-loop 的代码,并且生成的图形要小得多,仍然可以区分:

    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})
    

    【讨论】:

      猜你喜欢
      • 2022-06-14
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 2017-12-05
      • 2018-04-18
      • 2020-10-13
      • 2018-07-31
      • 1970-01-01
      相关资源
      最近更新 更多