本頁面說明如何使用 TensorFlow Lite 轉換工具,將 TensorFlow 模型轉換為 TensorFlow Lite 模型 (副檔名為 .tflite
的最佳化 FlatBuffer 格式)。
轉換工作流程
下圖說明轉換模型的整體工作流程:
圖 1 轉換器工作流程。
您可以使用下列其中一個選項轉換模型:
- Python 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 支援:許可清單中缺少 TF 運算 (TFLite 支援的 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