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

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)

最佳答案

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

输出看起来像这样:

关于python - 将 tensorflow 中的相似值分组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58672278/

10-09 18:49