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

Python 如何在TensorFlow图中添加if条件?,python,if-statement,tensorflow,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.

假设我有以下代码:

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
语句在这里不起作用,因为条件是在图形构造时计算的,而您可能希望条件取决于运行时提供给占位符的值。(事实上,它将始终采用第一个分支,因为
条件>0
的计算结果为
张量,即。)

为了支持条件控制流,TensorFlow提供了运算符,该运算符根据布尔条件计算两个分支中的一个。为了向您展示如何使用它,我将重写您的程序,使
条件
是一个标量
tf.int32
值,以简单起见:

x=tf.placeholder(tf.float32,shape=[None,ins\u size**2*3],name=“x\u input”)
condition=tf.placeholder(tf.int32,shape=[],name=“condition”)
W=tf.Variable(tf.zero([ins_size**2*3,label_option]),name=“weights”)
b=tf.变量(tf.零([label_option]),name=“bias”)
y=tf.cond(条件>0,lambda:tf.matmul(x,W)+b,lambda:tf.matmul(x,W)-b)
TensorFlow 2.0 它允许您将python代码JIT编译为图形执行。这意味着您可以使用python控制流语句(是的,这包括
if
语句)。从文件来看

AutoGraph支持常见的Python语句,如
while
for
if
中断
继续
返回
,支持嵌套。那意味着你 可以在
while
if
语句,或在
for
循环中迭代张量

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

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>
将tensorflow导入为tf
@功能
def总和(偶数)(项目):
s=0
对于项目中的c:
如果tf.相等(c%2,0):
s+=c
返回s
求和偶数(tf.常数([10,12,15,20]))
#  

@mrry默认情况下是否执行两个分支?我有tf.cond(c,lambda x:train_op1,lambda x:train_op2),两个train_ops在每次cond执行时都独立于c的值执行。我做错什么了吗?@PiotrDabkowski这是
tf.cond()
的一个有时令人惊讶的行为,它被提到过。简而言之,您需要创建希望在相应的lambda中有条件地运行的ops。您在lambda外部创建但在任一分支中引用的所有内容都将在这两种情况下执行。@mrry Wow,这太出乎意料了:)谢谢您的回答,在函数中定义ops解决了问题。条件/(逻辑的应用)元素是否明智?为什么要使用
tf.equal()
?难道你不能使用
==
并让签名自动编译吗?@problemofficer这是个好问题。我(和你一样)也这么想,但是被咬了。我问了一个关于这种行为的问题: