Tensorflow:将未知大小的张量分成给定大小的块

Min*_*nze 6 python split tensorflow

我想将张量分成大小相等或接近相等的多个子张量。由于我事先不知道张量的大小,因此并不总是保证分裂成大小均匀的块。然而,tf.split似乎期望均匀分裂,因此有时会失败!

在 numpy 中,np.split如果数组不能分成大小均匀的块,它也会引发异常。为了避免这个问题,可以使用np.array_split,它允许使用不同大小的最后一个块。这正是我在 tensorflow 中寻找的行为。

总结:如果我现在不知道张量的大小而只有所需的块大小,那么在 tensorflow 中将张量分成多个块的最佳方法是什么?是否有类似的功能np.array_split我还没有找到?

AMT*_*AMT 0

回答

总结:如果我现在不知道张量的大小,而只知道所需的块大小,那么张量流中将张量拆分为多个块的最佳方法是什么?

我不知道有内置的 Tensorflow 函数。在 Eager 执行中,您可以使用 将张量转换为 numpy 数组tensor.numpy()。在图形模式下,您可以以 RaggedTensor 返回结果

@tf.function
def split_with_reminder(x, max_size):
  # Reshape the tensor without the reminder.
  length = tf.shape(x)[0]
  l = length - length % max_size
  dense = tf.reshape(x[:l], [l // max_size, max_size])
  dense = tf.RaggedTensor.from_tensor(dense)
  if l == length:
    return dense

  # If there is a reminder add it
  reminder = tf.reshape(x[l:], [1, -1])
  return tf.concat([dense, reminder], axis=0)
Run Code Online (Sandbox Code Playgroud)

输出

split_with_reminder(tf.constant([1, 2, 3, 4, 5]), 2)
# [[1, 2], [3, 4], [5]]
split_with_reminder(tf.constant([1, 2, 3, 4, 5]), 3)
# [[1, 2, 3], [4, 5]]
split_with_reminder(tf.constant([1, 2, 3, 4, 5]), 5)
# [[1, 2, 3, 4, 5]]
split_with_reminder(tf.constant([1, 2, 3, 4, 5]), 6)
# [[1, 2, 3, 4, 5]]
Run Code Online (Sandbox Code Playgroud)

请注意,您提到的 np.array_split 并不准确,因为:

  • 它需要块的数量而不是“所需的更改大小”。
  • 它允许多个“不同大小的最后一块”。