转换 TensorFlow 模型

本页介绍如何使用 TensorFlow Lite 转换器将 TensorFlow 模型转换为 TensorFlow Lite 模型(一种经过优化的 FlatBuffer 格式,由 .tflite 文件扩展名标识)。

转化工作流程

下图展示了转换模型的简要工作流:

TFLite 转换器工作流

图 1. 转换器工作流。

您可以使用以下选项之一转换模型:

  1. Python API推荐):使用该 API,您可以将转换集成到开发流水线、应用优化、添加元数据以及许多可简化转换过程的其他任务。
  2. 命令行:这仅支持基本模型转换。

Python API

辅助代码:如需详细了解 TensorFlow Lite 转换器 API,请运行 print(help(tf.lite.TFLiteConverter))

使用 tf.lite.TFLiteConverter 转换 TensorFlow 模型。TensorFlow 模型使用 SavedModel 格式存储,并使用高阶 tf.keras.* API(Keras 模型)或低阶 tf.* API(用于生成具体函数)生成。因此,您有以下三个选项(示例将在接下来的几部分中提供):

以下示例展示了如何将 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)

其他功能

  • 应用优化。一种常用的优化是训练后量化,它可以进一步缩短模型延迟时间和大小,同时最大限度地降低准确率损失。

  • 添加元数据,以便在在设备上部署模型时更轻松地创建平台专用封装容器代码。

转换错误

下面是常见的转换错误及其解决方案:

命令行工具

如果您已从 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