メタデータを使用してモデル インターフェースを生成する

TensorFlow Lite メタデータを使用すると、デベロッパーは Android での統合を可能にするラッパーコードを生成できます。ほとんどのデベロッパーにとって、Android Studio ML Model Binding のグラフィカル インターフェースが最も簡単に使用できます。さらにカスタマイズが必要な場合や、コマンドライン ツールを使用している場合は、TensorFlow Lite Codegen も利用できます。

Android Studio ML Model Binding を使用する

メタデータで拡張された TensorFlow Lite モデルの場合、デベロッパーは Android Studio ML Model Binding を使用してプロジェクトの設定を自動的に構成し、モデル メタデータに基づいてラッパークラスを生成できます。ラッパーコードにより、ByteBuffer を直接操作する必要がなくなります。代わりに、デベロッパーは BitmapRect などの型付きオブジェクトを使用して TensorFlow Lite モデルを操作できます。

Android Studio に TensorFlow Lite モデルをインポートする

  1. TFLite モデルを使用するモジュールを右クリックするか、File をクリックしてから [New] > [Other] > [TensorFlow Lite Model] をクリックします。

  2. TFLite ファイルの場所を選択します。ツールが ML モデルのバインディングを使用してモジュールの依存関係を構成し、すべての依存関係を Android モジュールの build.gradle ファイルに自動的に挿入します。

    省略可: GPU アクセラレーションを使用する場合は、TensorFlow GPU をインポートする 2 番目のチェックボックスをオンにします。

  3. [Finish] をクリックします。

  4. インポートが正常に完了すると、次の画面が表示されます。モデルの使用を開始するには、Kotlin または Java を選択し、コードをコピーして Sample Code セクションに貼り付けます。この画面に戻るには、Android Studio の ml ディレクトリにある TFLite モデルをダブルクリックします。

モデル推論の高速化

ML Model Binding では、デリゲートとスレッド数を使用することで、デベロッパーがコードを高速化できます。

ステップ 1: モジュールの build.gradle ファイルをチェックして、次の依存関係が含まれていることを確認します。

    dependencies {
        ...
        // TFLite GPU delegate 2.3.0 or above is required.
        implementation 'org.tensorflow:tensorflow-lite-gpu:2.3.0'
    }

ステップ 2. デバイスで実行されている GPU が TensorFlow GPU デリゲートと互換性があるかどうかを検出します(複数の CPU スレッドを使用してモデルを実行していない場合)。

Kotlin

    import org.tensorflow.lite.gpu.CompatibilityList
    import org.tensorflow.lite.gpu.GpuDelegate

    val compatList = CompatibilityList()

    val options = if(compatList.isDelegateSupportedOnThisDevice) {
        // if the device has a supported GPU, add the GPU delegate
        Model.Options.Builder().setDevice(Model.Device.GPU).build()
    } else {
        // if the GPU is not supported, run on 4 threads
        Model.Options.Builder().setNumThreads(4).build()
    }

    // Initialize the model as usual feeding in the options object
    val myModel = MyModel.newInstance(context, options)

    // Run inference per sample code
      

Java

    import org.tensorflow.lite.support.model.Model
    import org.tensorflow.lite.gpu.CompatibilityList;
    import org.tensorflow.lite.gpu.GpuDelegate;

    // Initialize interpreter with GPU delegate
    Model.Options options;
    CompatibilityList compatList = CompatibilityList();

    if(compatList.isDelegateSupportedOnThisDevice()){
        // if the device has a supported GPU, add the GPU delegate
        options = Model.Options.Builder().setDevice(Model.Device.GPU).build();
    } else {
        // if the GPU is not supported, run on 4 threads
        options = Model.Options.Builder().setNumThreads(4).build();
    }

    MyModel myModel = new MyModel.newInstance(context, options);

    // Run inference per sample code
      

TensorFlow Lite コード生成ツールでモデル インターフェースを生成する

メタデータで拡張された TensorFlow Lite モデルの場合、デベロッパーは TensorFlow Lite Android ラッパーコード生成ツールを使用して、プラットフォーム固有のラッパーコードを作成できます。ラッパーコードにより、ByteBuffer を直接操作する必要がなくなります。代わりに、デベロッパーは BitmapRect などの型付きオブジェクトを使用して TensorFlow Lite モデルを操作できます。

コード生成ツールの有用性は、TensorFlow Lite モデルのメタデータ エントリの完全性によって異なります。Codegen ツールが各フィールドを解析する方法については、metadata_schema.fbs の関連フィールドにある <Codegen usage> セクションをご覧ください。

ラッパーコードを生成する

ターミナルに次のツールをインストールする必要があります。

pip install tflite-support

完了したら、次の構文を使用してコード生成ツールを使用できます。

tflite_codegen --model=./model_with_metadata/mobilenet_v1_0.75_160_quantized.tflite \
    --package_name=org.tensorflow.lite.classify \
    --model_class_name=MyClassifierModel \
    --destination=./classify_wrapper

生成されたコードは宛先ディレクトリに配置されます。Google Colab やその他のリモート環境を使用している場合は、結果を ZIP アーカイブに圧縮して Android Studio プロジェクトにダウンロードする方が簡単な場合があります。

# Zip up the generated code
!zip -r classify_wrapper.zip classify_wrapper/

# Download the archive
from google.colab import files
files.download('classify_wrapper.zip')

生成されたコードの使用

ステップ 1: 生成されたコードをインポートする

必要に応じて、生成されたコードをディレクトリ構造に解凍します。生成されるコードのルートは SRC_ROOT とみなされます。

TensorFlow Lite モデルを使用する Android Studio プロジェクトを開き、[File] -> [New] -> [Import Module] -> [SRC_ROOT] を選択して、生成されたモジュールをインポートします。

上記の例では、インポートされたディレクトリとモジュールの名前は classify_wrapper になります。

ステップ 2: アプリの build.gradle ファイルを更新する

生成されたライブラリ モジュールを使用するアプリ モジュール:

android セクションに、以下を追加します。

aaptOptions {
   noCompress "tflite"
}

依存関係のセクションに、以下を追加します。

implementation project(":classify_wrapper")

ステップ 3: モデルを使用する

// 1. Initialize the model
MyClassifierModel myImageClassifier = null;

try {
    myImageClassifier = new MyClassifierModel(this);
} catch (IOException io){
    // Error reading the model
}

if(null != myImageClassifier) {

    // 2. Set the input with a Bitmap called inputBitmap
    MyClassifierModel.Inputs inputs = myImageClassifier.createInputs();
    inputs.loadImage(inputBitmap));

    // 3. Run the model
    MyClassifierModel.Outputs outputs = myImageClassifier.run(inputs);

    // 4. Retrieve the result
    Map<String, Float> labeledProbability = outputs.getProbability();
}

モデル推論の高速化

生成されたコードは、デリゲートとスレッド数を使用することで、コードを高速化できます。これらは 3 つのパラメータを受け取るため、モデル オブジェクトの初期化時に設定できます。

  • Context: Android のアクティビティまたはサービスからのコンテキスト
  • (省略可)Device: TFLite アクセラレーション デリゲート。例: GPUDelegate
  • (省略可)numThreads: モデルの実行に使用されるスレッド数。デフォルトは 1 です。

たとえば、GPU デリゲートと最大 3 つのスレッドを使用するには、次のようにモデルを初期化します。

try {
    myImageClassifier = new MyClassifierModel(this, Model.Device.GPU, 3);
} catch (IOException io){
    // Error reading the model
}

トラブルシューティング

「java.io.FileNotFoundException: This file can not be open as a file Descriptor; it is might becompress」というエラーが発生した場合は、ライブラリ モジュールを使用するアプリ モジュールの Android セクションに次の行を挿入します。

aaptOptions {
   noCompress "tflite"
}