How to initialize a MLMultiArray in CoreML

前端 未结 2 1674
被撕碎了的回忆
被撕碎了的回忆 2021-01-18 17:32

I\'ve got an array of 40 arrays with 12 double features, so the type is [[double]]. Currently I\'m sending this data to Google Cloud ML API to get a related prediction.

相关标签:
2条回答
  • 2021-01-18 18:16

    I achieved it by reading this blog :)

    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")
    }
    
    0 讨论(0)
  • 2021-01-18 18:34

    This is how I did it. Probably not the best way to handle optionals but gets the job done for testing

    Create an instance of the MLMultiArray object with shape and data type

    let mlArray = try? MLMultiArray(shape: [3], dataType: MLMultiArrayDataType.float32)
    

    mlArray does not have an append function so you literally have to iterate through it and add values

    for i in 0..<array.count {
         mlArray?[i] = NSNumber(value: input[i])
    }
    

    Full function

        func convertToMLArray(_ input: [Int]) -> MLMultiArray {
    
            let mlArray = try? MLMultiArray(shape: [3], dataType: MLMultiArrayDataType.float32)
    
    
            for i in 0..<array.count {
                mlArray?[i] = NSNumber(value: input[i])
            }
    
    
            return arr!
        }
    
    0 讨论(0)
提交回复
热议问题