如何在TensorFlow圖中添加if條件? - How to add if condition in a TensorFlow graph? -开发者知识库

如何在TensorFlow圖中添加if條件? - How to add if condition in a TensorFlow graph? -开发者知识库,第1张

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 if statement work in the calculation (I do not think so)? If not, how can I add an if statement into the TensorFlow calculation graph?

if語句是否適用於計算(我不這么認為)?如果沒有,我如何在TensorFlow計算圖中添加if語句?

1 个解决方案

#1


62  

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.)

你是正確的,if語句在這里不起作用,因為條件是在圖形構造時計算的,而大概你希望條件依賴於在運行時提供給占位符的值。 (實際上,它總是需要第一個分支,因為condition> 0計算為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 condition is a scalar tf.int32 value for simplicity:

為了支持條件控制流,TensorFlow提供了tf.cond()運算符,該運算符根據布爾條件計算兩個分支中的一個。為了向您展示如何使用它,我將重寫您的程序,以便條件是標量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)

最佳答案:

本文经用户投稿或网站收集转载,如有侵权请联系本站。

发表评论

0条回复