2016-03-06 61 views
26

比方说,我有以下代码:如何在TensorFlow图中添加条件?

x = tf.placeholder("float32", shape=[None, ins_size**2*3], name = "x_input") 
condition = tf.placeholder("int32", shape=[1, 1], name = "condition") 
W = tf.Variable(tf.zeros([ins_size**2*3,label_option]), name = "weights") 
b = tf.Variable(tf.zeros([label_option]), name = "bias") 

if condition > 0: 
    y = tf.nn.softmax(tf.matmul(x, W) + b) 
else: 
    y = tf.nn.softmax(tf.matmul(x, W) - b) 

将在计算if声明的工作(我不这么认为)?如果不是,我怎样才能将一个if语句添加到TensorFlow计算图中?

回答

51

由于条件是在图构建时评估的,因此您确定if语句在此处不起作用,而假设您希望条件取决于在运行时向该占位符提供的值。 (事实上​​,它将始终以第一分支,因为condition > 0计算结果为Tensor,这是"truthy" in Python。)

为了支持条件的控制流程,TensorFlow提供tf.cond()操作者,其评估两个中的一个分支,这取决于一个布尔条件。为了向你展示如何使用它,我会重写你的程序,以便condition是简单的标tf.int32值:

x = tf.placeholder(tf.float32, shape=[None, ins_size**2*3], name="x_input") 
condition = tf.placeholder(tf.int32, shape=[], name="condition") 
W = tf.Variable(tf.zeros([ins_size**2 * 3, label_option]), name="weights") 
b = tf.Variable(tf.zeros([label_option]), name="bias") 

y = tf.cond(condition > 0, lambda: tf.matmul(x, W) + b, lambda: tf.matmul(x, W) - b) 
+1

谢谢你这么多的解释,详细! –

+1

@mrry两个分支默认都执行了吗?我有tf.cond(c,lambda x:train_op1,lambda x:train_op2),并且每次执行cond时都会执行两次train_ops,而与c的值无关。难道我做错了什么? –

+5

@PiotrDabkowski这是'tf.cond()'有时令人惊讶的行为,在[文档](https://www.tensorflow.org/api_docs/python/tf/cond)中被触及。简而言之,您需要创建您想要在各自的lambda表达式中有条件运行的操作。您在lambdas之外创建但在两个分支中引用的所有内容都将在两种情况下执行。 – mrry