tf中用if是不行的,用==也是不行的
因为是先建图,建图的时候也只是用tensor来进行判断
You're correct that the if
statement 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 > 0
evaluates to a Tensor
, which is "truthy" in 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 condition
is a scalar tf.int32
value for simplicity:
x = tf.