【问题标题】:Pre-heat CoreML MLModel预热 CoreML MLModel
【发布时间】:2021-08-17 23:32:52
【问题描述】:
在我对MLModel 的第一次预测中,我发现结果慢了 3 到 4 倍。似乎一旦您运行第一个预测,它就会加热模型。找不到任何有关它的官方信息。
预热模型的正确方法是什么?在应用启动时使用虚拟数据在异步线程上调用它?
【问题讨论】:
-
似乎在第一次请求时延迟加载模型(隐式)。 iOS 14+ 包含一个显式异步 loading function,它会在加载完成时通过回调通知您,因此如果您针对 iOS 14 之前的版本,您的解决方法听起来像是一个有效的选择。
标签:
ios
swift
coreml
mlmodel
【解决方案1】:
正如@Alladinian 所说,从iOS 14 开始,您可以使用MLModel.load(contentsOf:...) 函数。
下面是一个预加载本地.mlmodel文件的使用示例:
if let url = Bundle.main.url(forResource: "myModel", withExtension: "mlmodelc") {
let config = MLModelConfiguration()
MLModel.load(contentsOf: url, configuration: config) { [weak self] result in
switch result {
case .success(let model):
print("Model loaded and ready.")
let modelWrapper = MyModelWrapper(model: model)
case .failure(let error):
print("Error loading model: \(error)")
}
}
}
如果您要预加载外部获取的模型,请确保使用 MLModel.compileModel(at:) 对其进行编译。