TensorFlow Lite 转换器会根据输入的 TensorFlow 模型生成 TensorFlow Lite 模型(一种优化的 FlatBuffer 格式,以 .tflite
为文件扩展名)。若要使用此转换器,您可以采用以下两个选项之一:
- Python API(推荐):它让您可以更轻松地在模型开发流水线中对模型进行转换、应用优化、添加元数据,并且拥有更多功能。
- 命令行:它仅支持基本模型转换。
Python API
辅助程序代码:若要确定已安装的 TensorFlow 版本,请运行 print(tf.__version__)
;若要详细了解 TensorFlow Lite converter API,请运行 print(help(tf.lite.TFLiteConverter))
。
如果您已安装 TensorFlow 2.x,会有以下两个选项:(如果您已安装 TensorFlow 1.x,请参阅 GitHub)
使用
tf.lite.TFLiteConverter
转换 TensorFlow 2.x 模型。TensorFlow 2.x 模型是使用 SavedModel 格式存储的,并通过高阶tf.keras.*
API(Keras 模型)或低阶tf.*
API(用于生成具体函数)生成。因此,您有以下三个选项(示例包含在接下来的几节中):使用
tf.compat.v1.lite.TFLiteConverter
转换 TensorFlow 1.x 模型(示例位于 GitHub 上):tf.compat.v1.lite.TFLiteConverter.from_saved_model()
:转换 SavedModel。tf.compat.v1.lite.TFLiteConverter.from_keras_model_file()
:转换 Keras 模型。tf.compat.v1.lite.TFLiteConverter.from_session()
:从会话转换 GraphDef。tf.compat.v1.lite.TFLiteConverter.from_frozen_graph()
:从文件转换 Frozen GraphDef。如果您有检查点,请先将其转换为 Frozen GraphDef 文件,然后使用此 API(如此处所示)。
转换 SavedModel(推荐)
以下示例展示了如何将 SavedModel 转换为 TensorFlow Lite 模型。
import tensorflow as tf
# Convert the model
converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir) # path to the SavedModel directory
tflite_model = converter.convert().
# Save the model.
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
转换 Keras 模型
以下示例展示了如何将 Keras 模型转换为 TensorFlow Lite 模型。
import tensorflow as tf
# Create a model using high-level tf.keras.* APIs
model = tf.keras.models.Sequential([
tf.keras.layers.Dense(units=1, input_shape=[1])
tf.keras.layers.Dense(units=16, activation='relu'),
tf.keras.layers.Dense(units=1)
])
model.compile(optimizer='sgd', loss='mean_squared_error') # compile the model
model.fit(x=[-1, 0, 1], y=[-3, -1, 1], epochs=5) # train the model
# (to generate a SavedModel) tf.saved_model.save(model, "saved_model_keras_dir")
# Convert the model.
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
# Save the model.
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
转换具体函数
以下示例展示了如何将具体函数转换为 TensorFlow Lite 模型。
import tensorflow as tf
# Create a model using low-level tf.* APIs
class Squared(tf.Module):
@tf.function
def __call__(self, x):
return tf.square(x)
model = Squared()
# (ro run your model) result = Squared(5.0) # This prints "25.0"
# (to generate a SavedModel) tf.saved_model.save(model, "saved_model_tf_dir")
concrete_func = model.__call__.get_concrete_function()
# Convert the model
converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])
tflite_model = converter.convert()
# Save the model.
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
其他功能
处理不受支持的操作。如果您的模型有运算符,您可以采用以下选项:
TensorFlow Lite 支持,但 TensorFlow Lite 不支持:如果您有大小限制,则需要创建 TensorFlow Lite 运算符,否则在 TensorFlow Lite 模型中直接使用 TensorFlow 运算符。
TensorFlow 不支持:您需要创建 TensorFlow 运算符,然后创建 TensorFlow Lite 运算符。如果您未成功创建 TensorFlow 运算符或不想创建此运算符(不推荐,请谨慎操作),您仍然可以使用
custom_opdefs
属性进行转换,然后直接创建 TensorFlow Lite 运算符。custom_opdefs
属性是一个字符串,其中包含一个/一系列 OpDef(运算符定义 proto)。以下是包含 1 个输入、1 个输出和 2 个属性的TFLiteAwesomeCustomOp
示例:
converter.custom_opdefs="""name: 'TFLiteAwesomeCustomOp' input_arg: { name: 'In' type: DT_FLOAT } output_arg: { name: 'Out' type: DT_FLOAT } attr : { name: 'a1' type: 'float'} attr : { name: 'a2' type: 'list(float)'}"""
命令行工具
强烈建议您尽可能使用上文列出的 Python API。
如果您已从 pip 安装了 TensorFlow 2.x,请按下文所示使用 tflite_convert
命令:(如果您已从源代码安装了 TensorFlow 2.x,可以在接下来的几节中将“tflite_convert
”替换为“bazel run
//tensorflow/lite/python:tflite_convert --
”;如果您已安装了 TensorFlow 1.x,请参阅 GitHub [参考文档、示例])
tflite_convert
- 若要查看所有可用标记,请使用以下命令:
$ tflite_convert --help
`--output_file`. Type: string. Full path of the output file.
`--saved_model_dir`. Type: string. Full path to the SavedModel directory.
`--keras_model_file`. Type: string. Full path to the Keras H5 model file.
`--enable_v1_converter`. Type: bool. (default False) Enables the converter and flags used in TF 1.x instead of TF 2.x.
You are required to provide the `--output_file` flag and either the `--saved_model_dir` or `--keras_model_file` flag.
转换 SavedModel
tflite_convert \
--saved_model_dir=/tmp/mobilenet_saved_model \
--output_file=/tmp/mobilenet.tflite
转换 Keras H5 模型
tflite_convert \
--keras_model_file=/tmp/mobilenet_keras_model.h5 \
--output_file=/tmp/mobilenet.tflite
后续步骤
- 添加元数据,从而在设备上部署模型时可以更轻松地创建平台专用封装容器代码。
- 使用 TensorFlow Lite 解释器在客户端设备(例如移动设备、嵌入式设备)上运行推断。