2016-01-15 69 views
1

我很感興趣如何在控制流程語句中使用張量(沒有會話)。在控制流程和條件語句中使用張量


一個例子就是我的意思是:

myTensor = tf.where(myOtherTensor) # shape == [None, 2] 
numLoops = tf.shape(myTensor)[0] # Results in tensor of shape [1] 
for i in xrange(numLoops): 
    # ... 

我可以通過numLoops(張量)來XRANGE()?如果沒有,是否有另一種方法來做到這一點?


另一個例子是:

myTensor = tf.in_top_k(myOtherTensor1, myOtherTensor2, 5) # Tensor of bools 
myCondition = myTensor[0] # Results in tensor of shape [1] of type bool 
if myCondition: 
    # ... 

我的問題:能張量(不含特定的會話)將在上文所述的方式使用?

如果我有一個會話,我可以簡單地評估這些單元張量然後使用它們。如果直到運行時才知道具體的值,則必須使用這些值。

問題,我可以預見:也許循環會使生成圖表不可能的,因爲你不知道所包含的業務將有多少次被執行?但是,在運行時,存儲循環的操作似乎並不重要,只需將它們應用於正確的次數即可。

如果有什麼不明確的地方,讓我知道,我會提供更多的細節。

回答

2

TensorFlow包含對the tensorflow.python.ops.control_flow_ops module中的圖中控制流程的實驗性支持。 (NB這些OPS的接口有可能發生變化!在您自擔風險使用!)


有條件的支持(你的第二個案例)將出現在下一版本,並於近期加入到公共API (如果你從源代碼構建)。它目前用於TensorFlow附帶的一些庫中,例如RNN cell(用於在序列長度已知時提前停止)。

tf.cond()運算符采用布爾Tensor作爲謂詞和兩個lambda表達式;並返回一個或多個值。

你的程序將類似於:

if_true = lambda: ... # Value to return if `myCondition` is true 
if_false = lambda: ... # Value to return if `myCondition` is false 

result = tf.cond(myCondition, if_true, if_false) 

迭代(你的第一種情況),可以使用While()高階經營者進行處理。從本質上講,你會寫程序的(僞代碼):

i = 0 
while i < tf.rank(myTensor): 
    # ... 

...這將近似地表示爲:

from tensorflow.python.ops import control_flow_ops as cfo 

i = tf.constant(0) 
condition = lambda i: tf.less(i, tf.rank(myTensor)) 
body = lambda x: ... 
inital_accumulator = ... # will be bound to `x` in first iteration of `body`. 

# `result` will contain the value returned from the final iteration of `body`. 
result = cfo.While(condition, body, [initial_accumulator]) 

注意,While()操作員要求您指定所有初始值的循環變量(在這種情況下僅爲initial_accumulator)。循環常量將像正常的Python lambda一樣捕獲。

+0

再次感謝,mrry! –