一、概述
如果您的模型是被支持的第三方機(jī)器學(xué)習(xí)框架創(chuàng)建和訓(xùn)練的,您可以通過Core ML 的工具或者第三方的轉(zhuǎn)換工具,比如MXNet Converter或者TensorFlow converter,使用這些工具來轉(zhuǎn)換您的模型為Core ML格式。否則,您需要創(chuàng)建您自己的轉(zhuǎn)換工具。
二、使用Core ML工具
Core ML Tools是一個Python包,它可以將不同類型的Model轉(zhuǎn)換為Core ML格式的模型。下表列出了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 |
三、轉(zhuǎn)換模型
使用與模型的第三方框架相應(yīng)的Core ML轉(zhuǎn)換器來轉(zhuǎn)換您的模型。調(diào)用轉(zhuǎn)換器的轉(zhuǎn)換方法并保存轉(zhuǎn)換完成的Model保存為Core ML模型格式(.mlmodel)。
比如,如果您的模型是使用Caffe創(chuàng)建的,那么將Caffe model (.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')
依據(jù)您的模型,您可能需要更新輸入、輸出和標(biāo)簽,或者您可能需要生命圖片的名字、類型和格式。轉(zhuǎn)換工具和更多的文件綁定在一起,因?yàn)榭捎玫倪x項(xiàng)因工具而異。關(guān)于Core ML Tools更多的信息,請參閱Package Documentation。
四、編寫自己的轉(zhuǎn)換工具
當(dāng)您需要轉(zhuǎn)換一個不包含在上邊列表中的支持的格式類型時,可以創(chuàng)建自己的轉(zhuǎn)換工具。
編寫您自己的轉(zhuǎn)換工具涉及到將您的模型的輸入、輸出和體系結(jié)構(gòu)的表示轉(zhuǎn)換為Core ML模型格式。您可以通過定義模型架構(gòu)的每一層及它與其他層的連接來實(shí)現(xiàn)這一點(diǎn)。以Core ML Tools提供的轉(zhuǎn)換工具為例,他們演示了如何將從第三方框架創(chuàng)建的各種模型類型轉(zhuǎn)換為Core ML模型格式。
注:
Core ML 模型類型是由一組協(xié)議緩沖區(qū)文件定義,并在Core ML Model Specification中有詳細(xì)描述。