【问题标题】:Tensorflow: split tensor of unknown size into chunks of given sizeTensorflow:将未知大小的张量拆分为给定大小的块
【发布时间】:2019-08-30 07:38:46
【问题描述】:

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

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

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

【问题讨论】:

    标签: python tensorflow split


    【解决方案1】:

    回答

    总结:张量流中将张量拆分为的最佳方法是什么 如果我现在没有张量的大小而只有 所需的块大小?

    我不知道有内置的 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 并不准确,因为:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-14
      • 1970-01-01
      • 2017-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-13
      相关资源
      最近更新 更多