2017-04-14 31 views
1

的一部分,我有一些起始值s_in,我想它執行一些操作幾次:重用tensorflow圖

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

所以,首先我把數據作爲一個佔位符,然後再使用已定義的OPS作爲輸入。

現在的問題是:foo的圖可以創建一次,然後以某種方式重新使用而不用評估兩者之間的值(我需要計算一個漸變)?當step_count很大而foo很複雜並且在TensorBoard中弄得一團糟時,創建這樣的圖形需要一些時間。

回答

0

在計算中「重複使用」同一圖形的最簡單方法是將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})