如何使用 Tensorflow 将训练好的模型转换为 Core ML

Wil*_*jay 3 ios tensorflow

苹果今年在 iOS11 上引入了Core ML。有一个Core ML 工具可以将训练好的模型转换为 Core ML 格式 (.mlmodel)。

是否可以使用 Tensorflow 转换 Core ML 模型?如何?

And*_*ang 5

tf-coreml

您可以使用tf-coreml包将某些常见的 Tensorflow 模型转换为 CoreML 。在撰写本文时(1 月 16 日),它仍然是相当新的。它看起来是由几位 Apple 工程师创建的。

概述

根据他们的示例,您首先使用 冻结 TF 模型tensorflow.python.tools.freeze_graph,然后使用该tfcoreml.convert方法生成 CoreML 对象。

例子

引用他们的一个例子

"""
Step 1: "Freeze" your tensorflow model - convert your TF model into a 
stand-alone graph definition file
Inputs: 
(1) TensorFlow code
(2) trained weights in a checkpoint file
(3) The output tensors' name you want to use in inference
(4) [Optional] Input tensors' name to TF model
Outputs: 
(1) A frozen TensorFlow GraphDef, with trained weights frozen into it
"""

# Provide these to run freeze_graph:
# Graph definition file, stored as protobuf TEXT
graph_def_file = './model.pbtxt'
# Trained model's checkpoint name
checkpoint_file = './checkpoints/model.ckpt'
# Frozen model's output name
frozen_model_file = './frozen_model.pb'
# Output nodes. If there're multiple output ops, use comma separated string, e.g. "out1,out2".
output_node_names = 'Softmax' 


# Call freeze graph
freeze_graph(input_graph=graph_def_file,
             input_saver="",
             input_binary=False,
             input_checkpoint=checkpoint_file,
             output_node_names=output_node_names,
             restore_op_name="save/restore_all",
             filename_tensor_name="save/Const:0",
             output_graph=frozen_model_file,
             clear_devices=True,
             initializer_nodes="")

"""
Step 2: Call converter
"""

# Provide these inputs in addition to inputs in Step 1
# A dictionary of input tensors' name and shape (with batch)
input_tensor_shapes = {"Placeholder:0":[1,784]} # batch size is 1
# Output CoreML model path
coreml_model_file = './model.mlmodel'
output_tensor_names = ['Softmax:0']


# Call the converter
coreml_model = tfcoreml.convert(
        tf_model_path=frozen_model_file, 
        mlmodel_path=coreml_model_file, 
        input_name_shape_dict=input_tensor_shapes,
        output_feature_names=output_tensor_names)
Run Code Online (Sandbox Code Playgroud)