首页 > 解决方案 > tf.unique 不重复索引

问题描述

我的输入是例如的张量[8,8,8,2,2,3,1,1,8,8]。我的输出应该是一个张量,它引用这个张量的每个部分,看起来像这样[0,0,0,1,1,2,3,3,4,4]:我必须在张量流中计算它。

tf.unique([8,8,8,2,2,3,1,1,8,8])计算一个[0,0,0,1,1,2,3,3,0,0]以 0 而不是 4 结尾的张量。

有谁知道如何解决这个问题?

标签: pythontensorflowdeep-learninguniquetensor

解决方案


你想做的操作其实和 没有太大关系tf.unique。实现该结果的一种方法是:

import tensorflow as tf

def identify_blocks(a):
    neq = tf.not_equal(a[1:], a[:-1])
    c = tf.cumsum(tf.dtypes.cast(neq, tf.int32))
    return tf.concat([[0], c], axis=0)

a = tf.constant([8, 8, 8, 2, 2, 3, 1, 1, 8, 8])
b = identify_blocks(a)
print(b.numpy())
# [0 0 0 1 1 2 3 3 4 4]

推荐阅读