猿问

如何在张量流中对二维数组应用 unique_with_counts

我有这个张量:


tf_a1 = [[0 3 1 22]

        [3 5 2  2]

        [2 6 3 13]

        [1 7 0 3 ]

        [4 9 11 10]]

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


例如这里,3在 中重复4 columns。0中重复2 columns。2重复在3 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.InvalidArgumentError: unique 需要一维向量。[操作:UniqueWithCounts]


谢谢。


杨魅力
浏览 248回答 2
2回答

森栏

目前,支持轴的APIunique_with_counts尚未公开。如果你想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,那么您将丢失此信息。如果我错了,请纠正我。

鸿蒙传说

它似乎unique_with_count应该支持多维和轴,但是我在文档中找不到任何内容。我的解决方法是首先将我的张量重塑为一维数组,然后应用然后将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))
随时随地看视频慕课网APP

相关分类

Python
我要回答