2016-01-05 35 views
3

tf.logical_or,tf.logical_andtf.select函數非常有用。確定值是否在張量流中設置爲

但是,假設您的價值爲x,並且您想查看它是否在set(a, b, c, d, e)中。在Python中,你會簡單的寫:

if x in set([a, b, c, d, e]): 
    # Do some action. 

據我所知,在TensorFlow做到這一點的唯一方法,就是嵌套「tf.logical_or」與「tf.equal」一起。我只是提供一個低於這個概念的迭代:

tf.logical_or(
    tf.logical_or(tf.equal(x, a), tf.equal(x, b)), 
    tf.logical_or(tf.equal(x, c), tf.equal(x, d)) 
) 

我覺得必須有TensorFlow做到這一點更簡單的方法。在那兒?

回答

2

看看此相關的問題:Count number of "True" values in boolean Tensor

你應該能夠建立由[A,B,C,d,E]張量,然後檢查是否有任何行等於x使用tf.equal(.)

+0

感謝:tf.reduce_any沿着昏暗最後將返回true,如果任何平鋪值是s,得到最終的結果。 Reduce_sum是最好的選擇。 – LeavesBreathe

+0

你也可以用'tf.listdiff'完成同樣的事情。 – dga

0

爲了提供更具體的答案,說你要檢查的張量x的最後一維是否包含從1D張s任何值,你可以做到以下幾點:

tile_multiples = tf.concat([tf.ones(tf.shape(tf.shape(x)), dtype=tf.int32), tf.shape(s)], axis=0) 
x_tile = tf.tile(tf.expand_dims(x, -1), tile_multiples) 
x_in_s = tf.reduce_any(tf.equal(x_tile, s), -1)) 

例如,對於sx

s = tf.constant([3, 4]) 
x = tf.constant([[[1, 2, 3, 0, 0], 
        [4, 4, 4, 0, 0]], 
       [[3, 5, 5, 6, 4], 
        [4, 7, 3, 8, 9]]]) 

x具有形狀[2, 2, 5]s具有形狀[2]所以tile_multiples = [1, 1, 1, 2],這意味着我們將瓦片的x 2次(一次在s每個元件)沿一個新的最後一維尺寸。所以,x_tile會像:

[[[[1 1] 
    [2 2] 
    [3 3] 
    [0 0] 
    [0 0]] 

    [[4 4] 
    [4 4] 
    [4 4] 
    [0 0] 
    [0 0]]] 

[[[3 3] 
    [5 5] 
    [5 5] 
    [6 6] 
    [4 4]] 

    [[4 4] 
    [7 7] 
    [3 3] 
    [8 8] 
    [9 9]]]] 

x_in_s將在s每個平鋪值的比較值之一。爲深入瞭解

[[[False False True False False] 
    [ True True True False False]] 

[[ True False False False True] 
    [ True False True False False]]] 
相關問題