Skip to main content
 首页 » 编程设计

python之如何在一维张量中查找重复元素

2025年05月04日27zfyouxi

我想获取在一维张量中出现不止一次的元素。准确地说,我想创建一个与 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]