このページでは、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 (具体的な関数を生成する) のいずれかを使用して生成されます。その結果、次の 3 つのオプションがあります (例は次のいくつかのセクションにあります)。
-
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. See instructions: <a href="https://www.tensorflow.org/lite/guide/ops_select">https://www.tensorflow.org/lite/guide/ops_select</a> TF Select ops: ..., .., ...
解決策: モデルに対応する TFLite 実装がない TF 演算があると、このエラーが発生します。これは、TFLite モデルの TF 演算を使用することで解決できます (推奨)。 TFLite 演算のみを使用してモデルを生成したい場合は、不足している TFLite 演算のリクエストをGithub 問題 #21526に追加するか (リクエストがまだ言及されていない場合はコメントを残してください)、 TFLite 演算を自分で作成することができます。
エラー:
.. is neither a custom op nor a flex op
解決策: この TF 操作が次の場合:
TF でサポートされている: TF op がホワイトリスト(TFLite でサポートされている TF op の完全なリスト) にないためにエラーが発生します。これは次のように解決できます。
TF でサポートされていない: TFLite がユーザーが定義したカスタム TF 演算子を認識しないため、エラーが発生します。これは次のように解決できます。
- TF オペレーションを作成します。
- TF モデルを TFLite モデルに変換します。
- TFLite 演算を作成し、それを TFLite ランタイムにリンクして推論を実行します。
コマンドラインツール
TensorFlow 2.x を pip からインストールした場合は、 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 インタープリターを使用して、クライアント デバイス (モバイル、組み込みなど) で推論を実行します。