将较大的[MLMultiArray]拆分为较小的块[[MLMultiArray]]?

时间:2020-05-10 17:49:27

标签: swift multidimensional-array coreml

我有一个长度为15360的大型MLMultiArray。

示例:

Float32 1 x 15360
[14.78125,-0.6308594,5.609375,13.57812,-1.871094,-19.65625,9.5625,8.640625,-2.728516,3.654297,-3.189453,-1.740234...]

有没有一种方法可以将这个巨大的数组转换为120个小MLMultiArray,每个MLMultiArray具有128个元素,而又不改变该数组的顺序,并且以最有效的方式进行?

Link

中包含15360个元素的整个数组

1 个答案:

答案 0 :(得分:1)

let chunkSize = 2
let shape = yourLargeArray.shape
let chunkedArrays = try? stride(from: 0, to: shape.count, by: chunkSize)
    .map { offset -> MLMultiArray in
        let startIndex = shape.index(shape.startIndex, offsetBy: offset)
        let endIndex = shape.index(startIndex, offsetBy: chunkSize, limitedBy: shape.endIndex) ?? shape.endIndex

        return try MLMultiArray(
            shape: Array(shape[startIndex ..< endIndex]), 
            dataType: yourLargeArray.dataType
        )
    }