我想要获取在一维张量中出现多次的元素。准确地说,我想创建一个与 tf.unique 相反的函数。例如,如果 x = [1, 1, 2, 3, 4, 5, 6, 7, 4, 5, 4]
我需要输出为 [1,1,4 ,4,4,5,5]
,同时还检索源张量中这些元素的索引。
我的最终目标是批量获取标 checkout 现多次的示例。
最佳答案
您可以使用现有的 Tensorflow 操作以稍微迂回的方式来完成此操作,方法是对唯一项进行计数以创建唯一项的密集索引集,然后使用 tf.unsorted_segment_sum 对其进行计数>。获得计数后,使用 tf.greater
选择带有 > N
的项目,并将它们重新收集到一个密集列表中:
import tensorflow as tf
a = tf.constant([8, 7, 8, 1, 3, 4, 5, 9, 5, 0, 5])
init = tf.initialize_all_variables()
unique_a_vals, unique_idx = tf.unique(a)
count_a_unique = tf.unsorted_segment_sum(tf.ones_like(a),
unique_idx,
tf.shape(a)[0])
more_than_one = tf.greater(count_a_unique, 1)
more_than_one_idx = tf.squeeze(tf.where(more_than_one))
more_than_one_vals = tf.squeeze(tf.gather(unique_a_vals, more_than_one_idx))
# If you want the original indexes:
not_duplicated, _ = tf.listdiff(a, more_than_one_vals)
dups_in_a, indexes_in_a = tf.listdiff(a, not_duplicated)
with tf.Session() as s:
s.run(init)
a, dupvals, dupidxes, dia = s.run([a, more_than_one_vals,
indexes_in_a, dups_in_a])
print "Input: ", a
print "Duplicate values: ", dupvals
print "Indexes of duplicates in a: ", dupidxes
print "Dup vals with dups: ", dia
Input: [8 7 8 1 3 4 5 9 5 0 5]
Duplicate values: [8 5]
Indexes of duplicates in a: [ 0 2 6 8 10]
Dup vals with dups: [8 8 5 5 5]
关于python - 如何查找一维张量中的重复元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34370040/