gpt4 book ai didi

python - Tensorflow:查找张量中元素第一次出现的索引

转载 作者:太空宇宙 更新时间:2023-11-03 14:09:42 25 4
gpt4 key购买 nike

假设我有一个张量,x = [1, 2, 6, 6, 4, 2, 3, 2]
我想找到 x 中每个唯一元素第一次出现的索引。
输出应为 [0, 1, 6, 4, 2]。我基本上想要 numpy.unique(x,return_index=True) 的第二个输出。 tf.unique 似乎不支持此功能。在 tensorflow 中是否有解决方法,无需使用任何循环?

最佳答案

x = [1, 2, 6, 6, 4, 2, 3, 2]
x_count = tf.cumsum(tf.ones_like(x))-1
unique, unique_id = tf.unique(x)
unique_first = tf.unsorted_segment_min(x_count, unique_id, tf.shape(unique)[0])
with tf.Session() as sess:
print(sess.run(tf.stack([unique, unique_first],0)))

给予:

[[1 2 6 4 3]
[0 1 2 4 6]]

关于python - Tensorflow:查找张量中元素第一次出现的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48595802/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com