Lea*_*the 5 python set tensorflow
的tf.logical_or,tf.logical_and和tf.select功能是非常有用的.
但是,假设你有价值x,并且你想看看它是否在set(a, b, c, d, e).在python中你只需写:
if x in set([a, b, c, d, e]):
# Do some action.
Run Code Online (Sandbox Code Playgroud)
据我所知,在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))
)
Run Code Online (Sandbox Code Playgroud)
我觉得在TensorFlow中必须有一种更简单的方法.在那儿?
为了提供更具体的答案,假设您想检查张量的最后一个维度是否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))
Run Code Online (Sandbox Code Playgroud)
例如,对于s和x:
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]]])
Run Code Online (Sandbox Code Playgroud)
xhas shape[2, 2, 5]并且shas shape [2]so tile_multiples = [1, 1, 1, 2],这意味着我们将沿新维度平铺最后一个维度x2 次(对于 中的每个元素一次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]]]]
Run Code Online (Sandbox Code Playgroud)
并且x_in_s将每个平铺值的比较中值之一s。tf.reduce_any如果任何平铺值在 中s,则沿着最后一个 dim 将返回 true ,给出最终结果:
[[[False False True False False]
[ True True True False False]]
[[ True False False False True]
[ True False True False False]]]
Run Code Online (Sandbox Code Playgroud)
看看这个相关问题:Count number of "True" value in boolean Tensor
您应该能够构建一个由 [a, b, c, d, e] 组成的张量,然后使用以下命令检查是否有任何行等于 xtf.equal(.)
| 归档时间: |
|
| 查看次数: |
2623 次 |
| 最近记录: |