如何在TensorFlow图中添加if条件?

时间:2016-03-06 21:47:47

标签: python if-statement 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语句会在计算中起作用吗(我不这么认为)?如果没有,我如何在TensorFlow计算图中添加if语句?

2 个答案:

答案 0 :(得分:80)

你是正确的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 :(得分:0)

TensorFlow 2.0

TF 2.0 introduces a feature called AutoGraph,您可以通过JIT将python代码编译为Graph执行。这意味着您可以使用python控制流语句(是的,这包括if语句)。在文档中,

  

AutoGraph支持常见的Python语句,例如whileforif,   breakcontinuereturn,并支持嵌套。那意味着你   可以在whileif的条件下使用Tensor表达式   语句,或在for循环中遍历张量。

您将需要定义一个实现逻辑的函数,并用tf.function对其进行注释。这是文档中的修改示例:

import tensorflow as tf

@tf.function
def sum_even(items):
  s = 0
  for c in items:
    if tf.equal(c % 2, 0): 
        s += c
  return s

sum_even(tf.constant([10, 12, 15, 20]))
#  <tf.Tensor: id=1146, shape=(), dtype=int32, numpy=42>