循环张量中的值并计数直到值改变

Looping over Values in Tensor and count until value changes

我的数据集如下所示:

**user_id** 

0   38094   
1   38094   
2   8937    
3   126440
4   126440


WANTED EXAMPLE-OUTPUT: 2,1,2 (because line 0 and 1 are identical -> 2 (...))

我需要一个循环遍历它并打印出有多少行是相同的(顺序)。我不知道是否有任何 Tensorflow 操作,但这会很有帮助。

这可以使用 tf.unique_with_counts

你的情况:

import tensorflow as tf

input_tensor = tf.convert_to_tensor([38094, 38094, 8937, 126440, 126440])

_, _, output_tensor = tf.unique_with_counts(input_tensor)
print(output_tensor)

这段代码会输出

tf.Tensor([2 1 2], shape=(3,), dtype=int32)