如何在 TensorFlow 中将unique_with_counts应用于 2D 数组



我有这个张量:

tf_a1 = [[0 3 1 22]
[3 5 2  2]
[2 6 3 13]
[1 7 0 3 ]
[4 9 11 10]]

我想做的是找到在所有列中重复超过threshold的唯一值。

例如,在这里,34 columns重复。02 columns重复.23 columns重复,依此类推。

我希望我的输出是这样的(假设阈值是2,所以重复超过 2 次的索引将被屏蔽(。

[[F T F F]
[T F T T]
[T F T F]
[F F F T]
[F F F F]]

这是我所做的:

y, idx, count = tf.unique_with_counts(tf_a1)   
tf.where(tf.where(count, tf_a1, tf.zeros_like(tf_a1)))

但它引发了错误:

tensorflow.python.framework.errors_impl。无效参数错误:唯一 期望一个 1D 矢量。[操作:UniqueWithCounts]

谢谢。

目前,支持 axis 的unique_with_counts的 API 尚未公开。如果你想用多点张量unique_with_counts,你可以在 tf 1.14 中这样调用它:

from tensorflow.python.ops import gen_array_ops
# tensor 'x' is [[1, 0, 0],
#                [1, 0, 0],
#                [2, 0, 0]]
y, idx, count = gen_array_ops.unique_with_counts_v2(x, [0])
y ==> [[1, 0, 0],
[2, 0, 0]]
idx ==> [0, 0, 1]
count ==> [2, 1]

因为我无法评论@sariii帖子。应该是tf.greater(count,2).另外,我认为此解决方案不能满足问题的要求。例如,如果第一个 col 都是 2,而其余的 col 没有 2。根据您的要求,2 应计为 1 次。但是在您的解决方案中,如果您先重新塑造为 1d,那么您将丢失此信息。如果我错了,请纠正我。

问题#16503

似乎unique_with_count应该支持多维和轴,但是我在文档中找不到任何内容。

对我来说,解决方法是首先将我的张量重塑为 1d 数组,然后应用unique_with_count然后将其重新塑造回原始大小:

感谢@a_guest分享这个想法

token_idx = tf.reshape(tf_a1, [-1])
y, idx, count = tf.unique_with_counts(token_idx)
masked = tf.greater_equal(count, 2)
backed_same_size = tf.gather(masked, idx)
tf.reshape(backed_same_size, shape=tf.shape(tf_a1))

最新更新