轉換 TensorFlow 模型

本頁面說明如何使用 TensorFlow Lite 轉換工具,將 TensorFlow 模型轉換為 TensorFlow Lite 模型 (副檔名為 .tflite 的最佳化 FlatBuffer 格式)。

轉換工作流程

下圖說明轉換模型的整體工作流程:

TFLite 轉換工具工作流程

圖 1 轉換器工作流程。

您可以使用下列其中一個選項轉換模型:

  1. Python 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