coremltools
Core ML 是苹果提供的一个易于集成到app中的机器学习库. 它目前支持iOS, watchOS,macOS 和 tvOS. Core ML 引入了公共文件格式 (.mlmodel) ,它支持机器学习方法包括深度神经网络 (卷积和循环), 基于树的集合 (boosted trees, 随机森林, 决策树) 和广义 线性模型. Core ML 名可以直接集成到 Xcode中.
coremltools
是一个Python 工具包,用于:
- 将由知名的机器学习工具(包括 Keras, Caffe, scikit-learn, libsvm 和 XGBoost)训练的模型 转换为 Core ML 格式的模型(.mlmodel).
- 采用简单的API 编写 Core ML 格式模型.
- 做预测.
安装
coremltools
依赖以下库:
- numpy (1.12.1+)
- protobuf (3.1.0+)
此外, 如果你想转换第三方的训练模型,那么请安装以下依赖库:
- Keras (==1.2.2) with Tensorflow (1.0.x, 1.1.x)
- Xgboost (0.6+)
- scikit-learn (0.15+)
- libSVM
安装 coremltools
参考standard python package installation steps. 假如你已经安装python, 执行:
pip install -U coremltools
即可安装 coremltools
.
模型转换
coremltools 使用支持的库来便捷的转换模型. 以下案例 展示了 如何将 Caffe 模型 (Inception) 转换为 Core ML格式 (.mlmodel)
支持的文件: bvlc_alexnet.caffemodel, deploy.prototxt, class_labels.txt
import coremltools
# Convert a caffe model to a classifier in Core ML
coreml_model = coremltools.converters.caffe.convert(('bvlc_alexnet.caffemodel', 'deploy.prototxt'),
predicted_feature_name='class_labels.txt'
)
# Now save the model
coreml_model.save('BVLCObjectClassifier.mlmodel')
Here is another example with scikit-learn:
from sklearn.linear_model import LinearRegression
import pandas as pd
# Load data
data = pd.read_csv('houses.csv')
# Train a model
model = LinearRegression()
model.fit(data[["bedroom", "bath", "size"]], data["price"])
# Convert and save the scikit-learn model
import coremltools
coreml_model = coremltools.converters.sklearn.convert(model, ["bedroom", "bath", "size"], "price")
模型接口
模型转换完, 你可以编辑模型的元数据,这些信息可以在XCode中展示出来. 许可证信息, 作者信息和其他的信息以及输入和输出描述信息.
# Set model metadata
coreml_model.author = 'John Smith'
coreml_model.license = 'BSD'
coreml_model.short_description = 'Predicts the price of a house in the Seattle area.'
# Set feature descriptions manually
model.input_description['bedroom'] = 'Number of bedrooms'
model.input_description['bathrooms'] = 'Number of bathrooms'
model.input_description['size'] = 'Size (in square feet)'
# Set the output descriptions
model.output_description['price'] = 'Price of the house'
# Save the model
model.save('HousePricer.mlmodel')
模型评估
模型转换完毕, 你可以使用Core ML 验证预测的结果并同原始模型进行对比. 为了采用代码的方式进行验证, 我们提供了一个简便的模型评估方式.
以下案例 我们采用已经转换后的HousePricer.mlmodel
来做预测:
import coremltools
# Load the model
model = coremltools.models.MLModel('HousePricer.mlmodel')
# Make predictions
predictions = model.predict({'bedroom': 1.0, 'bath': 1.0, 'size': 1240})
支持的转换
Core ML 支持许多集成工具训练模型的转换. 下表列出了模型类型支持的转换工具:
模型 类型 | 支持的工具包 |
---|---|
神经网络 | Keras (1.2.2), Caffe 1.0 |
基于树的集合 | XGboost (0.6), scikit-learn 0.18.1 |
广义线性回归 | scikit-learn (0.18.1) |
支持向量机 | libSVM (3.22), scikit-learn (0.18.1) |
特征工程 | scikit-learn (0.18.1) |
Pipelines | scikit-learn (0.18.1) |