确定一个值是否在 TensorFlow 中的一个集合中

Determining if A Value is in a Set in TensorFlow

tf.logical_ortf.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 中一定有更简单的方法来做到这一点。有吗?

看看这个相关问题:

您应该能够构建一个由 [a, b, c, d, e] 组成的张量,然后使用 tf.equal(.)

检查是否有任何行等于 x

为了提供更具体的答案,假设您想检查张量的最后一个维度 x 是否包含一维张量 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 中的一个值进行比较。 tf.reduce_any 如果任何平铺值在 s 中,最后一个 dim 将 return 为真,给出最终结果:

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

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

这里有两个解决方案,我们要检查 query 是否在 whitelist

whitelist = tf.constant(["CUISINE", "DISH", "RESTAURANT", "ADDRESS"])
query = "RESTAURANT"

#use broadcasting for element-wise tensor operation
broadcast_equal = tf.equal(whitelist, query)

#method 1: using tensor ops
broadcast_equal_int = tf.cast(broadcast_equal, tf.int8)
broadcast_sum = tf.reduce_sum(broadcast_equal_int)

#method 2: using some tf.core API
nz_cnt = tf.count_nonzero(broadcast_equal)

sess.run([broadcast_equal, broadcast_sum, nz_cnt])
#=> [array([False, False,  True, False]), 1, 1]

因此,如果输出为 > 0,则该项目在集合中。