将张量流中的相似值分组

Ans*_*mar 5 python tensorflow

我想将类似的张量组合在一起。例如:

input: [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5]
output: [[1],[2,2],[3,3,3],[4,4,4,4],[5,5,5,5,5]]
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用unique_with_countssplit功能,但出现错误。这是我的代码:

import tensorflow as tf

value = tf.constant([1,2,2,3,3,3,4,4,4,4,5,5,5,5,5])
y, idx, count = tf.unique_with_counts(value)
splitted = tf.split(value, count, 0)

with tf.compat.v1.Session() as sess:
    print(sess.run(splitted))
Run Code Online (Sandbox Code Playgroud)

以下是错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-161-aba9fdba9ef6> in <module>
      1 value = tf.constant([1,2,2,3,3,3,4,4,4,4,5,5,5,5,5])
      2 y, idx, count = tf.unique_with_counts(value)
----> 3 splitted = tf.split(value, count, 0)
      4 
      5 with tf.compat.v1.Session() as sess:

/usr/local/lib/python3.7/site-packages/tensorflow/python/ops/array_ops.py in split(value, num_or_size_splits, axis, num, name)
   1513       num = size_splits_shape[0]
   1514     if num is None:
-> 1515       raise ValueError("Cannot infer num from shape %s" % num_or_size_splits)
   1516 
   1517   return gen_array_ops.split_v(

ValueError: Cannot infer num from shape Tensor("UniqueWithCounts_6:2", shape=(?,), dtype=int32)
Run Code Online (Sandbox Code Playgroud)

Ans*_*mar 2

@zihaozhihao 给出的解决方案适用于这种特殊情况,但提前知道唯一元素的数量并不总是可能的。但我事先知道唯一元素的最大数量,所以我使用dynamic_partition如下:

value = tf.constant([1,2,2,3,3,3,4,4,4,4,5,5,5,5,5])
y, idx, count = tf.unique_with_counts(value)
out = tf.dynamic_partition(value, idx, 10)
Run Code Online (Sandbox Code Playgroud)

输出如下所示:

[[数组([1], dtype=int32), 数组([2, 2], dtype=int32), 数组([3, 3, 3], dtype=int32), 数组([4, 4, 4, 4], dtype=int32), 数组([5, 5, 5, 5, 5], dtype=int32), 数组([], dtype=int32), 数组([], dtype=int32), 数组([ ], dtype=int32), 数组([], dtype=int32), 数组([], dtype=int32)]]