tensorflow如何在tensorflow张量中获得唯一值的索引?

tensorflow如何在tensorflow张量中获得唯一值的索引?,tensorflow,duplicates,unique,tensor,indices,Tensorflow,Duplicates,Unique,Tensor,Indices,假设我有一个输入一维张量,我想得到一维张量中唯一元素的索引 输入1D张量 [ 1 3 0 0 0 3 5 6 8 9 12 2 5 7 0 11 6 7 0 0] 预期产出 Values: [1, 3, 0, 5, 6, 8, 9, 12, 2, 7, 11] indices: [0, 1, 2, 6, 7, 8, 9, 10, 11, 13, 15] 这是我现在的策略。 input = [ 1, 3, 0, 0, 0, 3, 5, 6,

假设我有一个输入一维张量,我想得到一维张量中唯一元素的索引

输入1D张量

[ 1  3  0  0  0  3  5  6  8  9 12  2  5  7  0 11  6  7  0  0]
预期产出

Values:  [1, 3, 0, 5, 6, 8, 9, 12,  2,  7, 11]
indices: [0, 1, 2, 6, 7, 8, 9, 10, 11, 13, 15]
这是我现在的策略。

input = [ 1,  3,  0,  0,  0,  3,  5,  6,  8,  9, 12,  2,  5,  7,  0, 11,  6,  7,  0,  0,]
unique_value_in_input, _ = tf.unique(input) # [1 3 0 5 6 8 9 12 2 7 11]
number_of_unique_value = tf.shape(unique_value_in_input)[0] #11
y = tf.reshape(y, (number_of_unique_value, 1)) #[[1], [3], [0], [5], [6], [8], [9], ..]

input_matrix = tf.tile(input, [number_of_unique_value]) # repeat the tensor for tf.equal()
input_matrix = tf.reshape(input, [number_of_unique_value,-1]) 

cols = tf.where(tf.equal(input_matrix, y))[:,-1] #[[ 0  0] [ 1  1] [ 1  5] [ 2  6] [ 2 12] ...]
因为我将在tf.where()步骤中有repeat值,这意味着我在结果中复制了True。
在本期中,我可以使用任何函数吗?

您应该能够执行以下操作并获得所需的输出。我们做以下工作。对于唯一值中的每个值,您将获得一个布尔张量,并通过
tf.argmax
获得最大索引(即仅第一个最大索引)

import tensorflow as tf

input = tf.constant([ 1,  3,  0,  0,  0,  3,  5,  6,  8,  9, 12,  2,  5,  7,  0, 11,  6,  7,  0,  0,], tf.int64)

unique_vals, _ = tf.unique(input) 
res = tf.map_fn(
    lambda x: tf.argmax(tf.cast(tf.equal(input, x), tf.int64)), 
    unique_vals)

with tf.Session() as sess:
  print(sess.run(res))

您使用的是TF2还是TF1?我使用的是TF1.14.0。我应该提到我在开始时使用的版本。