【tfcoreml】tensorflow向CoreML模型的转换工具封装

安装tf向apple coreml模型转换包tfcoreml
基于苹果自己的转换工具coremltools进行封装

tfcoreml

为了将训练的模型转换到apple中使用,需要将模型转换为ios支持的mlmodel形式。目前苹果官方的推荐使用Core ML tools来进行转换。
它支持

Scikit Learn
LIBSVM
Caffe
Keras
XGBoost.
Tensorflow
MXNet

等工具包的模型转换。
但为了更方便的使用tensorflow的模型,在github中找到了tfcoreml的封装,直接对tensorflow的pb模型进行转换。

首选需要安装tfcoreml的依赖:

tensorflow >= 1.5.0
coremltools >= 0.8
numpy >= 1.6.2
protobuf >= 3.1.0
six >= 1.10.0

在安装CoreMLtools时会遇到以下问题:

  • 1.coremltools的pip 安装只在python2.7下work,pip
  • 2.tensorflow的win版本只支持python3.x
    直接pip install coremltools会报错:ERROR: Could not find a version that satisfies the requirement coremltools

为了在这台win上安装coremltools,只能选择从源码编译安装了,在release中找到合适的版本
cd coremltools-2.1
这里可以看到setup.cfg:

[bdist_wheel]
plat-name=any
python-tag=2.7   #这里将2.7改为目前平台的python版本3.5

随后运行wheel安装:
python setup.py install
即可编译安装coremltools。

随后即可pip安装tfcoreml
pip install -U tfcoreml

模型转换demo

这一封装选择了pb(protobuf )模型,如果输入输出确定的情况下可以直接转换:

import tfcoreml as tf_converter
tf_converter.convert(tf_model_path = 'path/to/your_tf_model.pb',
                     mlmodel_path = 'path/to/your_apple_model.mlmodel',
                     output_feature_names = ['softmax:0'])

如果需要指定输入大小的话,可以利用input_name_shape_dict关键字:

import tfcoreml as tf_converter
tf_converter.convert(tf_model_path = 'path/to/your_tf_model.pb',
                     mlmodel_path = 'path/to/your_apple_model.mlmodel',
                     output_feature_names = ['softmax:0'],
                     input_name_shape_dict = {'your_input:0' : [1, 227, 227, 3]})

ref:
https://stackoverflow.com/questions/44510701/no-matching-distribution-found-for-coremltools
https://stackoverflow.com/questions/44612991/error-installing-coremltools
https://github.com/apple/coremltools/issues/228
ssd_demo:https://github.com/vonholst/SSDMobileNet_CoreML/tree/master/SSDMobileNet/SSDMobileNet
coreml:https://developer.apple.com/documentation/coreml
在这里插入图片描述

posted @ 2019-05-04 14:31  hitrjj  Views(1109)  Comments(0Edit  收藏  举报