将已训练模型转换为 Core ML

将由第三⽅方机器学习工具所创建的已训练模型,转换为 Core ML 模型格式。

概述

如果您已经使用了第三方机器学习工具来创建和训练模型,只要这个工具是受支持的,那么就 可以使用 Core ML Tools 或者第三方工具(如: MXNet converter 或者 TensorFlow converter)来将这些模型转换为 Core ML 模型格式。否则你只能自己创建转换工具。

使用Core ML Tools

Core ML Tools 是⼀一个 Python 包 (coremltools),并挂载在 Python Package Index (PyPI) 上。 要了了解关于 Python 包的更更多信息,请参阅 Python Packaging User Guide。

表 1 列列出了了我们支持的模型和第三⽅方⼯工具。

Table 1 

Models and third-party frameworks supported by Core ML Tools

Model type

Supported models

Supported frameworks

Neural networks

Feedforward, convolutional, recurrent

Caffe v1

Keras 1.2.2+

Tree ensembles

Random forests, boosted trees, decision trees

scikit-learn 0.18

XGBoost 0.6

Support vector machines

Scalar regression, multiclass classification

scikit-learn 0.18

LIBSVM 3.22

Generalized linear models

Linear regression, logistic regression

scikit-learn 0.18

Feature engineering

Sparse vectorization, dense vectorization, categorical processing

scikit-learn 0.18

Pipeline models

Sequentially chained models 

scikit-learn 0.18

模型转换

您可以使⽤用 Core ML 转换器,并根据对应的模型第三⽅方⼯工具,来对模型进⾏行行转换。通过调⽤用 转换器的 convert ⽅方法,然后再将结果保存为 Core ML 模型格式 (.mlmodel)。 例例如,如果您的模型是使⽤用 Caffe 来创建的,您可以将 Caffe 模型 (.caffemodel) 传递给coremltools.converters.caffe.convert ⽅方法。

import coremltools
coreml_model = coremltools.converters.caffe.convert('my_caffe_model.caffemodel')

然后将结果保存为 Core ML 模型格式。

coremltools.utils.save_spec(coreml_model, 'my_model.mlmodel')
根据您模型的不同,您可能会需要更更新输入、输出以及相关的参数标签,或者您还可能会需要声明图片名称、类型以及格式。转换⼯工具内置了了更更详细的⽂文档,因为可⽤用的选项因⼯工具⽽而异。

或者,还可以编写⾃自定义的转换⼯工具

如果您需要转换的格式不在表 1 当中,那么您可以创建⾃自⼰己的转换⼯工具。

编写⾃自定义的转换⼯工具,包括了了将模型的输入、输出和架构表⽰示转换为 Core ML 模型格式。 您可以通过将每⼀一层模型架构,以及层之间的连接关系进⾏行行定义,来实现这个操作。您可以通 过 Core ML Tools 所提供的转换⼯工具作为参考;它们演⽰示了了如何将各种第三⽅方⼯工具创建的模型

类型,转换为 Core ML 模型格式。

注意
Core ML 模型格式由⼀一系列列 Protocol Buffer ⽂文件所定义,具体信息请参⻅见 Core ML Model Specification。
 

猜你喜欢

转载自blog.csdn.net/mandagod/article/details/85392811
ML