2016-02-24 19 views
2

我有一個由4個浮點組成的張量,稱爲label如何在張量的單個元素上執行減法

我如何以50%的機率執行x[0] = 1 - x[0]

現在我有:

label = tf.constant([0.35, 0.5, 0.17, 0.14]) # just an example 
uniform_random = tf.random_uniform([], 0, 1.0) 

# Create a tensor with [1.0, 0.0, 0.0, 0.0] if uniform_random > 50% 
# else it's only zeroes 
inv = tf.pack([tf.round(uniform_random), 0.0, 0.0, 0.0]) 

label = tf.sub(inv, label) 
label = tf.abs(label) # need abs because it inverted the other elements 
# output will be either [0.35, 0.5, 0.17, 0.14] or [0.65, 0.5, 0.17, 0.14] 

其工作,但看起來非常難看。沒有更聰明/更簡單的方法嗎?

相關問題:如何對兩個元素應用某個op(例如sqrt)?我猜我必須刪除這兩個元素,執行操作,然後將它們連接回原始矢量?

回答

3

tf.selecttf.cond適用於需要對張量元素進行有條件計算的情況。對於你的例子,以下將工作:

label = tf.constant([0.35, 0.5, 0.17, 0.14]) 
inv = tf.pack([1.0, 0.0, 0.0, 0.0]) 
mask = tf.pack([1.0, -1.0, -1.0, -1.0]) 
output = tf.cond(tf.random_uniform([], 0, 1.0) > 0.5, 
       lambda: label, 
       lambda: (inv - label) * mask) 
with tf.Session(''): 
    print(output.eval()) 
+0

嗨,感謝您的快速回復!我有這樣的印象,建議儘可能避免觸及控制流程,是這種情況還是不是那麼重要? – Clash

相關問題