将[MLMultiArray]转换为Float?

时间:2020-05-10 08:22:11

标签: arrays swift coreml

我有一个MLMultiArray,它是ML模型的结果。 我需要将其转换为Float,以便可以将其进一步存储在Realm中。

下面是MLMultiArray之一的示例。 ML模型的结果包含120个相同的向量,因此它是MLMultiArrays的数组,即Float32 1 x 128矩阵的数组。

Float32 1 x 128 matrix
[4.476562,1.179688,0.07141113,6.976562,-0.2858887,-7.378906,0.6445312,3.695312,1.399414,2.486328,-3.988281,-0.2636719,1.000977,-4.480469,-7.832031,1.59082,0.8515625,-1.296875,-1.435547,7.839844,5.851562,0.3701172,-2.492188,7.273438,2.404297,-3.3125,-5.699219,-0.6816406,0.2807617,-3.882812,-3.982422,5.339844,4.125,-3.871094,0.6225586,1.712891,-10.02344,0.7119141,4.472656,3.566406,-0.559082,-1.049805,-4.679688,10.07812,-1.459961,4.707031,-6.078125,1.675781,-0.6259766,2.519531,3.472656,-3.400391,-6.714844,-4.933594,-1.733398,1.095703,-6.15625,9.234375,3.693359,-9.492188,0.8637695,0.8203125,-2.814453,-4.4375,-1.092773,3.332031,0.1623535,3.583984,-11.25781,-0.9941406,-0.3491211,1.464844,-1.579102,4.558594,2.703125,4.601562,5.914062,-2.402344,-5.46875,-0.355957,11.39062,2.070312,-7.289062,-0.4470215,-0.1595459,9.148438,1.833008,-2.097656,-3.9375,6.699219,-4.347656,-6.835938,-1.179688,3.910156,-13.07812,-1.947266,-0.9238281,-0.949707,-4.398438,2.363281,4.421875,4.632812,2.607422,8.773438,0.9106445,9.21875,-14.0625,-1.301758,-4.875,0.6054688,6.496094,-2.021484,3.898438,-4.644531,0.9853516,7.253906,3.066406,-1.051758,-8.09375,-6.527344,3.890625,5.175781,0.3701172,-0.5683594,-1.341797,0.1497803,4.074219,0.5932617]

有什么方法可以将MLMultiArray数组转换为Float32?

任何帮助将不胜感激<3

2 个答案:

答案 0 :(得分:3)

您可以先将MLMultiArray转换为UnsafeBufferPointer,然后再转换为常规Array

import CoreML

var a: [Float] = [ 1, 2, 3 ]
var m = try! MLMultiArray(a)

if let b = try? UnsafeBufferPointer<Float>(m) {
  let c = Array(b)
  print(c)
}

答案 1 :(得分:0)

这是一个老问题,但这可以帮助某人: 要将 MLMultiArray 转换为原始数组,您可以使用此函数,您只需要更改输出类型

func convertToArray(from mlMultiArray: MLMultiArray) -> [Double] {
    
    // Init our output array
    var array: [Double] = []
    
    // Get length
    let length = mlMultiArray.count
    
    // Set content of multi array to our out put array
    for i in 0...length - 1 {
        array.append(Double(truncating: mlMultiArray[[0,NSNumber(value: i)]]))
    }
    
    return array
}

要将数组转换为 MLMultiArray 使用此方法,您可能需要相应地更改形状

func convertToMLMultiArray(from array: [Double]) -> MLMultiArray {
    let length = NSNumber(value: array.count)
    
    // Define shape of array
    guard let mlMultiArray = try? MLMultiArray(shape:[1, length], dataType:MLMultiArrayDataType.double) else {
        fatalError("Unexpected runtime error. MLMultiArray")
    }
    
    // Insert elements
    for (index, element) in array.enumerated() {
        mlMultiArray[index] = NSNumber(floatLiteral: element)
    }
    
    return mlMultiArray
}