美文网首页
iOS11 新特性-Core ML (三) Core ML 实

iOS11 新特性-Core ML (三) Core ML 实

作者: RichardLH | 来源:发表于2017-06-13 09:25 被阅读0次

上篇中我们已经生成了一个 Core ML 模型文件:HousePricer.mlmodel,本篇将介绍如何将文件引入到项目中并调用相应的接口。

导入HousePricer.mlmodel到项目中

1.1 文件导入方式同一般文件导入,采用拖拽或者菜单导入,选中导入的文件,我们可以查看模型的元数据及输入,输出信息(图一)

图一

1.2 导入文件添加到编译资源

上一步中导入的文件是不会自动添加到编译资源列表中(图二),我们需要手动添加到编译资源中,否则无法调用接口

图二

此时,我们再次选中 模型文件,在元数据信息面板,我们可以看到 在 Model class 部分 多了一个 可以点击的 向右箭头(图三)

图三

点击 箭头,则进入 自动生成的 类文件 HousePricer.swift, 其中包含三个类:

HousePricerInput         输入参数

HousePricerOutput      输出参数

HousePricer                 用于预测接口的调用

接口调用

调用类中 生成 模型实例:

[objc]view plaincopy

...

let model = HousePricer()

...

模型预测接口调用:

模型中为我们生成了两个预测接口,代码如下:

[objc]view plaincopy

func prediction(input: HousePricerInput) throws -> HousePricerOutput {

let outFeatures =trymodel.prediction(from: input)

let result = HousePricerOutput(Price: outFeatures.featureValue(for:"Price")!.doubleValue)

returnresult

}

func prediction(Square_Feet: Double) throws -> HousePricerOutput {

let input_ = HousePricerInput(Square_Feet: Square_Feet)

returntryself.prediction(input: input_)

}

我们可以选择其中之一调用即可:

[objc]view plaincopy

let input = HousePricerInput(Square_Feet: size);

guard let marsHabitatPricerOutput =try? model.prediction(input:input)else{

fatalError("Unexpected runtime error.")

}

let price = marsHabitatPricerOutput.Price

是不是很简单,完整代码示例,请移步Github

相关文章

网友评论

      本文标题: iOS11 新特性-Core ML (三) Core ML 实

      本文链接:https://www.haomeiwen.com/subject/wltdqxtx.html