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 (具体的な関数を生成する) のいずれかを使用して生成されます。その結果、次の 3 つのオプションがあります (例は次のいくつかのセクションで説明します)。

次の例は、 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)

その他の機能

  • 最適化を適用します。使用される一般的な最適化はトレーニング後の量子化です。これにより、精度の低下を最小限に抑えながらモデルのレイテンシとサイズをさらに削減できます。

  • メタデータを追加すると、デバイスにモデルをデプロイするときにプラットフォーム固有のラッパー コードを簡単に作成できます。

変換エラー

一般的な変換エラーとその解決策は次のとおりです。

コマンドラインツール

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 インタープリターを使用して、クライアント デバイス (モバイル、組み込みなど) で推論を実行します。