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

问题描述 投票:0回答:1

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

输入一维张量

[ 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()步骤中获得重复值,这意味着我在结果中重复了True。我可以在此问题中使用任何功能吗?

tensorflow duplicates unique tensor indices
1个回答
0
投票

您应该能够执行以下操作并获得所需的输出。我们执行以下操作。对于唯一值中的每个值,您将获得一个布尔张量并通过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))
© www.soinside.com 2019 - 2024. All rights reserved.