Created
January 10, 2020 02:17
-
-
Save JacopoMangiavacchi/a98eb4b08afb29ffcc1a969e3e653ac5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import CoreML | |
func compileCoreML(path: String) -> (MLModel, URL) { | |
let modelUrl = URL(fileURLWithPath: path) | |
let compiledUrl = try! MLModel.compileModel(at: modelUrl) | |
print("Compiled Model Path: \(compiledUrl)") | |
return try! (MLModel(contentsOf: compiledUrl), compiledUrl) | |
} | |
func inferenceCoreML(model: MLModel, x: Float) -> Float { | |
let inputName = "dense_input" | |
let multiArr = try! MLMultiArray(shape: [1], dataType: .double) | |
multiArr[0] = NSNumber(value: x) | |
let inputValue = MLFeatureValue(multiArray: multiArr) | |
let dataPointFeatures: [String: MLFeatureValue] = [inputName: inputValue] | |
let provider = try! MLDictionaryFeatureProvider(dictionary: dataPointFeatures) | |
let prediction = try! model.prediction(from: provider) | |
return Float(prediction.featureValue(for: "output")!.multiArrayValue![0].doubleValue) | |
} | |
let (coreModel, compiledModelUrl) = compileCoreML(path: coreMLFilePath) | |
let prediction = inferenceCoreML(model: coreModel, x: 1.0) | |
print(prediction) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment