转换 TensorFlow 模型

本页介绍了如何使用 LiteRT 转换器将 TensorFlow 模型转换为 LiteRT 模型(一种优化的 FlatBuffer 格式,以 .tflite 为文件扩展名)。

转换工作流程

下图展示了转换模型的高级工作流:

TFLite 转换器工作流程

图 1. 转换器工作流程。

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

  1. Python API推荐):借助此 API,您可以将转换集成到开发流水线中,应用优化、添加元数据,并执行许多其他任务来简化转换流程。
  2. 命令行:它仅支持基本模型转换。

Python API

辅助程序代码:如需详细了解 LiteRT 转换器 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)

转换具体函数

以下示例演示了如何将具体函数转换为 LiteRT 模型。

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