2017-08-09 37 views
1

是否可以定義多個條件來終止tensorflow中的tf.while_loop?例如取決於實現兩個特定值的兩個張量值。例如。 i==2j==3是否有可能在tf.while_loop中定義多個條件

我也可以在身體中有幾塊代碼?在文檔中的所有示例中,似乎該主體更像是返回值或元組的單個語句。我想執行一組幾個「順序」的正文。

回答

2

tf.while_loop接受必須返回布爾張量的通用可調用函數(用def定義的python函數)或lambda函數)。

可以,因此,使用logical operators的條件,如tf.logical_andtf.logical_or,身體內鏈的多個條件...

即使body是一般蟒蛇調用,因此你不侷限於lambda表達式和單個語句功能。

類似的東西是完全可以接受的,並且效果很好:

import tensorflow as tf 
import numpy as np 


def body(x): 
    a = tf.random_uniform(shape=[2, 2], dtype=tf.int32, maxval=100) 
    b = tf.constant(np.array([[1, 2], [3, 4]]), dtype=tf.int32) 
    c = a + b 
    return tf.nn.relu(x + c) 


def condition(x): 
    x = tf.Print(x, [x]) 
    return tf.logical_or(tf.less(tf.reduce_sum(x), 1000), tf.equal(x[0, 0], 15)) 


x = tf.Variable(tf.constant(0, shape=[2, 2])) 
result = tf.while_loop(condition, body, [x]) 

init = tf.global_variables_initializer() 
with tf.Session() as sess: 
    sess.run(init) 
    print(sess.run(result)) 
+0

感謝您的詳細解釋 –

相關問題