本頁面說明如何使用 TensorFlow Lite 轉換器,將 TensorFlow 模型轉換為 TensorFlow Lite 模型 (一種最佳化的 FlatBuffer 格式,以 .tflite
副檔名識別)。
轉換工作流程
下圖說明模型轉換的高階工作流程
圖 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)
其他功能
轉換錯誤
以下是常見的轉換錯誤及其解決方案
錯誤:
有些運算子不受原生 TFLite 執行階段支援,您可以透過 TF Select 啟用 TF 核心回退機制。請參閱操作說明:<a href="https://tensorflow.dev.org.tw/lite/guide/ops_select">https://tensorflow.dev.org.tw/lite/guide/ops_select</a> TF Select 運算子:...、...、...
解決方案:發生此錯誤的原因是您的模型中有 TFLite 實作中沒有對應項目的 TF 運算子。您可以在 TFLite 模型中使用 TF 運算子 (建議) 來解決此問題。如果您只想產生僅含 TFLite 運算子的模型,您可以前往 Github 問題 #21526 提出缺少 TFLite 運算子的要求 (如果您的要求尚未提及,請留言),或自行建立 TFLite 運算子。
錯誤:
.. 既不是自訂運算子,也不是彈性運算子
解決方案:如果這個 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
後續步驟
使用 TensorFlow Lite 解譯器,在用戶端裝置 (例如行動裝置、嵌入式裝置) 上執行推論。