回答
总结:张量流中将张量拆分为的最佳方法是什么
如果我现在没有张量的大小而只有
所需的块大小?
我不知道有内置的 Tensorflow 函数。在 Eager 执行中,您可以使用 tensor.numpy() 将张量转换为 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)
输出
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]]
请注意,您提到的 np.array_split 并不准确,因为:
- 它采用块的数量,而不是“所需的更改大小”。
- 它允许多个“不同大小的最后一块”。