如何删除tensorflow中的连续重复项?

How to remove consecutive duplicates in tensorflow?

例如输入一维张量:

l_in = [1,1,2,2,3,4,5,5,1,3,5]

我想删除 连续的重复项 ,这意味着输出应该是:

l_out = [1,2,3,4,5,1,3,5]

但是tf.unique函数只returns唯一元素,说明最后三个元素也会被淘汰。 tf.unique 的输出是:

[1,2,3,4,5], [0,0,1,1,2,3,4,4,0,2,4] = tf.unique(l_in)

其中第二项是相应的 ID。

有没有办法只删除连续的重复项,同时保留非重复和非唯一的元素?

不了解 tensorflow,但由于它似乎是一个简单的列表,您可以很容易地使用 itertools 中的 groupby:

from itertools import groupby  
l_out = [x[0] for x in groupby(l_in)]
print(l_out) # prints [1, 2, 3, 4, 5, 1, 3, 5]

另请参阅:Removing elements that have consecutive duplicates in Python

对于一维张量,使用数组rotation/shifting:

import tensorflow as tf

l_in = tf.constant([1,1,2,2,3,4,5,5,1,3,5])
l_left_shift = tf.concat((l_in[1:], [0]), axis=0)
mask_left_shift = tf.not_equal(l_in - l_left_shift, 0)
mask = tf.concat(([True], mask_left_shift[:-1]), axis=0)
l_out = tf.boolean_mask(l_in, mask)

with tf.Session() as sess:
    print(sess.run(l_out))
# [1 2 3 4 5 1 3 5]

(即思想是将每个元素与其右邻居相减,然后如果相减结果为0则屏蔽掉邻居)