如何在 CoreML 中初始化 MLMultiArray

Lau*_*ert 6 swift ios11 xcode9-beta coreml xcode9

我有一个由 40 个数组组成的数组,其中包含 12 个双重特征,所以类型是 [[double]]。目前我正在将此数据发送到 Google Cloud ML API 以获得相关预测。

由于 Apple 最近推出了 CoreML 和 coremltools,我将我的模型从 keras 转换为 .mlmodel 以避免数千次 google cloud api 调用并直接在我的 iPhone 上进行推理:

coreml_model = coremltools.converters.keras.convert(new_Model, input_names=['accelerations'],
                                                    output_names=['scores'])
coreml_model.save('PredictionModel.mlmodel')
Run Code Online (Sandbox Code Playgroud)

将模型添加到我的 Xcode 项目后,它看起来像: 在此处输入图片说明

我不知道这些其他输入和输出来自哪里。要获得预测,我需要将我的 12 个双精度数组数组转换为 MLMultiArray,但我不知道如何执行此操作。有没有人遇到过类似的问题?这是我目前未完成的方法:

_predictionModel = PredictionModel()
guard let mlMultiArray = try? MLMultiArray(dataPointer: <#T##UnsafeMutableRawPointer#>, shape: <#T##[NSNumber]#>, dataType: <#T##MLMultiArrayDataType#>, strides: <#T##[NSNumber]#>, deallocator: <#T##((UnsafeMutableRawPointer) -> Void)?##((UnsafeMutableRawPointer) -> Void)?##(UnsafeMutableRawPointer) -> Void#>) else {
        fatalError("Unexpected runtime error.")
    }
guard let predictionOutput = try? _predictionModel.prediction(accelerations: mlMultiArray, lstm_1_h_in: nil, lstm_1_c_in: nil, lstm_2_h_in: nil, lstm_2_c_in: nil) else {
        fatalError("Unexpected runtime error.")
    }
Run Code Online (Sandbox Code Playgroud)

相关文档可以在这里找到。

Lau*_*ert 7

我通过阅读此博客实现了它:)

let data = _currentScaledMotionArrays.reduce([], +) //result is of type [Double] with 480 elements
guard let mlMultiArray = try? MLMultiArray(shape:[40,12], dataType:MLMultiArrayDataType.double) else {
    fatalError("Unexpected runtime error. MLMultiArray")
}
for (index, element) in data.enumerated() {
    mlMultiArray[index] = NSNumber(floatLiteral: element)
}
let input = PredictionModelInput(accelerations: mlMultiArray)
guard let predictionOutput = try? _predictionModel.prediction(input: input) else {
        fatalError("Unexpected runtime error. model.prediction")
}
Run Code Online (Sandbox Code Playgroud)