本页介绍如何使用 TensorFlow Lite 转换器将 TensorFlow 模型转换为 TensorFlow Lite 模型(一种经过优化的 FlatBuffer 格式,由 .tflite
文件扩展名标识)。
转化工作流程
下图展示了转换模型的简要工作流:
图 1. 转换器工作流。
您可以使用以下选项之一转换模型:
- Python API(推荐):使用该 API,您可以将转换集成到开发流水线、应用优化、添加元数据以及许多可简化转换过程的其他任务。
- 命令行:这仅支持基本模型转换。
Python API
辅助代码:如需详细了解 TensorFlow Lite 转换器 API,请运行 print(help(tf.lite.TFLiteConverter))
。
使用 tf.lite.TFLiteConverter
转换 TensorFlow 模型。TensorFlow 模型使用 SavedModel 格式存储,并使用高阶 tf.keras.*
API(Keras 模型)或低阶 tf.*
API(用于生成具体函数)生成。因此,您有以下三个选项(示例将在接下来的几部分中提供):
tf.lite.TFLiteConverter.from_saved_model()
(推荐):转换 SavedModel。tf.lite.TFLiteConverter.from_keras_model()
:转换 Keras 模型。tf.lite.TFLiteConverter.from_concrete_functions()
:转换具体函数。
转换 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(input_signature=[tf.TensorSpec(shape=[None], dtype=tf.float32)])
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],
model)
tflite_model = converter.convert()
# Save the model.
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
其他功能
转换错误
下面是常见的转换错误及其解决方案:
错误:
Some ops are not supported by the native TFLite runtime, you can enable TF kernels fallback using TF Select.
解决方案:之所以发生该错误,是因为您的模型具有 TF 操作没有相应的 TFLite 实现。您可以通过使用 TFLite 模型中的 TF 操作来解决此问题(推荐)。如果您想生成仅包含 TFLite 操作的模型,可以在 GitHub 问题 21526 中为缺失的 TFLite 操作添加请求(如果尚未提及您的请求,请留言),或自行创建 TFLite 操作。
错误:
.. is neither a custom op nor a flex op
解决方案:如果此 TF 操作是:
在 TF 中受支持:之所以出现该错误,是因为许可名单(TFLite 支持的 TF 操作的详尽列表)中缺少 TF 操作。您可以按如下方法解决此问题:
在 TF 中不受支持:之所以发生该错误,是因为 TFLite 不知道您定义的自定义 TF 运算符。您可以按如下方法解决此问题:
- 创建 TF 操作。
- 将 TF 模型转换为 TFLite 模型。
- 创建 TFLite 操作,并通过将其关联到 TFLite 运行时来运行推理。
命令行工具
如果您已从 pip 安装了 TensorFlow 2.x,请使用 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.
如果您下载了 TensorFlow 2.x 源代码,并且希望在不构建和安装软件包的情况下从该源代码运行转换器,可以在命令中将“tflite_convert
”替换为“bazel run tensorflow/lite/python:tflite_convert --
”。
转换 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