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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35833011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:02:42  来源:igfitidea点击:

How to add if condition in a TensorFlow graph?

pythonif-statementtensorflow

提问by Yee Liu

Let's say I have following code:

假设我有以下代码:

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)  

Would the ifstatement work in the calculation (I do not think so)? If not, how can I add an ifstatement into the TensorFlow calculation graph?

if语句在计算中是否有效(我不这么认为)?如果没有,如何if在 TensorFlow 计算图中添加语句?

回答by mrry

You're correct that the ifstatement doesn't work here, because the condition is evaluated at graph construction time, whereas presumably you want the condition to depend on the value fed to the placeholder at runtime. (In fact, it will always take the first branch, because condition > 0evaluates to a Tensor, which is "truthy" in Python.)

您是正确的,该if语句在这里不起作用,因为条件是在图形构建时评估的,而大概您希望条件取决于在运行时提供给占位符的值。(实际上,它总是采用第一个分支,因为condition > 0计算结果为 a Tensor,这在 Python 中“真实的”。)

To support conditional control flow, TensorFlow provides the tf.cond()operator, which evaluates one of two branches, depending on a boolean condition. To show you how to use it, I'll rewrite your program so that conditionis a scalar tf.int32value for simplicity:

为了支持条件控制流,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)

回答by cs95

TensorFlow 2.0

TensorFlow 2.0

TF 2.0 introduces a feature called AutoGraphwhich lets you JIT compile python code into Graph executions. This means you can use python control flow statements (yes, this includes ifstatements). From the docs,

TF 2.0 引入了一个称为 AutoGraph 的功能,它允许您将 Python 代码 JIT 编译为 Graph 执行。这意味着您可以使用 python 控制流语句(是的,这包括if语句)。从文档中,

AutoGraph supports common Python statements like while, for, if, break, continueand return, with support for nesting. That means you can use Tensor expressions in the condition of whileand ifstatements, or iterate over a Tensor in a forloop.

签名支持常用的Python之类的语句whileforifbreakcontinuereturn,与嵌套支持。这意味着您可以在whileandif语句的条件中使用张量表达式,或者在循环中迭代张量for

You will need to define a function implementing your logic and annotate it with tf.function. Here is a modified example from the documentation:

您将需要定义一个函数来实现您的逻辑并使用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>