将张量流中的相似值分组

时间:2019-11-02 15:01:13

标签: 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]]

我正在尝试使用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))

以下是错误:

---------------------------------------------------------------------------
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)

1 个答案:

答案 0 :(得分:1)

@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)

输出看起来像这样:

  

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