TensorFlow Lite サポート ライブラリを使用して入出力データを処理する

モバイルアプリのデベロッパーは通常、ビットマップなどの型付きオブジェクトや、整数などのプリミティブを操作します。ただし、オンデバイスの ML モデルを実行する TensorFlow Lite インタープリタ API は ByteBuffer という形式のテンソルを使用するため、デバッグや操作が困難な場合があります。TensorFlow Lite Android サポート ライブラリは、TensorFlow Lite モデルの入力と出力を処理し、TensorFlow Lite インタープリタを使いやすくするように設計されています。

はじめに

Gradle の依存関係とその他の設定をインポートする

.tflite モデルファイルを、モデルが実行される Android モジュールのアセット ディレクトリにコピーします。ファイルを圧縮しないことを指定し、TensorFlow Lite ライブラリをモジュールの build.gradle ファイルに追加します。

android {
    // Other settings

    // Specify tflite file should not be compressed for the app apk
    aaptOptions {
        noCompress "tflite"
    }

}

dependencies {
    // Other dependencies

    // Import tflite dependencies
    implementation 'org.tensorflow:tensorflow-lite:0.0.0-nightly-SNAPSHOT'
    // The GPU delegate library is optional. Depend on it as needed.
    implementation 'org.tensorflow:tensorflow-lite-gpu:0.0.0-nightly-SNAPSHOT'
    implementation 'org.tensorflow:tensorflow-lite-support:0.0.0-nightly-SNAPSHOT'
}

サポート ライブラリのさまざまなバージョンについては、MavenCentral でホストされる TensorFlow Lite サポート ライブラリ AAR をご覧ください。

基本的な画像操作と変換

TensorFlow Lite サポート ライブラリには、切り抜きやサイズ変更などの基本的な画像操作方法のスイートが用意されています。これを使用するには、ImagePreprocessor を作成して必要なオペレーションを追加します。画像を TensorFlow Lite インタープリタが必要とするテンソル形式に変換するには、入力として使用する TensorImage を作成します。

import org.tensorflow.lite.DataType;
import org.tensorflow.lite.support.image.ImageProcessor;
import org.tensorflow.lite.support.image.TensorImage;
import org.tensorflow.lite.support.image.ops.ResizeOp;

// Initialization code
// Create an ImageProcessor with all ops required. For more ops, please
// refer to the ImageProcessor Architecture section in this README.
ImageProcessor imageProcessor =
    new ImageProcessor.Builder()
        .add(new ResizeOp(224, 224, ResizeOp.ResizeMethod.BILINEAR))
        .build();

// Create a TensorImage object. This creates the tensor of the corresponding
// tensor type (uint8 in this case) that the TensorFlow Lite interpreter needs.
TensorImage tensorImage = new TensorImage(DataType.UINT8);

// Analysis code for every frame
// Preprocess the image
tensorImage.load(bitmap);
tensorImage = imageProcessor.process(tensorImage);

テンソルの DataType は、メタデータ抽出ライブラリやその他のモデル情報から読み取ることができます。

基本的な音声データ処理

TensorFlow Lite サポート ライブラリでは、基本的な音声データ処理メソッドをラップする TensorAudio クラスも定義されています。主に AudioRecord と組み合わせて使用され、音声サンプルをリングバッファにキャプチャします。

import android.media.AudioRecord;
import org.tensorflow.lite.support.audio.TensorAudio;

// Create an `AudioRecord` instance.
AudioRecord record = AudioRecord(...)

// Create a `TensorAudio` object from Android AudioFormat.
TensorAudio tensorAudio = new TensorAudio(record.getFormat(), size)

// Load all audio samples available in the AudioRecord without blocking.
tensorAudio.load(record)

// Get the `TensorBuffer` for inference.
TensorBuffer buffer = tensorAudio.getTensorBuffer()

出力オブジェクトを作成してモデルを実行する

モデルを実行する前に、結果を格納するコンテナ オブジェクトを作成する必要があります。

import org.tensorflow.lite.DataType;
import org.tensorflow.lite.support.tensorbuffer.TensorBuffer;

// Create a container for the result and specify that this is a quantized model.
// Hence, the 'DataType' is defined as UINT8 (8-bit unsigned integer)
TensorBuffer probabilityBuffer =
    TensorBuffer.createFixedSize(new int[]{1, 1001}, DataType.UINT8);

モデルを読み込んで推論を実行します。

import java.nio.MappedByteBuffer;
import org.tensorflow.lite.InterpreterFactory;
import org.tensorflow.lite.InterpreterApi;

// Initialise the model
try{
    MappedByteBuffer tfliteModel
        = FileUtil.loadMappedFile(activity,
            "mobilenet_v1_1.0_224_quant.tflite");
    InterpreterApi tflite = new InterpreterFactory().create(
        tfliteModel, new InterpreterApi.Options());
} catch (IOException e){
    Log.e("tfliteSupport", "Error reading model", e);
}

// Running inference
if(null != tflite) {
    tflite.run(tImage.getBuffer(), probabilityBuffer.getBuffer());
}

結果にアクセスする

デベロッパーは probabilityBuffer.getFloatArray() を介して直接出力にアクセスできます。モデルが量子化された出力を生成する場合は、結果を変換することを忘れないでください。MobileNet 量子化モデルの場合、デベロッパーは各出力値を 255 で割って、カテゴリごとに 0(最も低い)から 1(最も可能性が高い)の範囲の確率を取得する必要があります。

省略可: 結果をラベルにマッピングする

デベロッパーは、必要に応じて結果をラベルにマッピングすることもできます。まず、ラベルを含むテキスト ファイルをモジュールのアセット ディレクトリにコピーします。次に、以下のコードを使用してラベルファイルを読み込みます。

import org.tensorflow.lite.support.common.FileUtil;

final String ASSOCIATED_AXIS_LABELS = "labels.txt";
List<String> associatedAxisLabels = null;

try {
    associatedAxisLabels = FileUtil.loadLabels(this, ASSOCIATED_AXIS_LABELS);
} catch (IOException e) {
    Log.e("tfliteSupport", "Error reading label file", e);
}

次のスニペットは、確率をカテゴリラベルに関連付ける方法を示しています。

import java.util.Map;
import org.tensorflow.lite.support.common.TensorProcessor;
import org.tensorflow.lite.support.common.ops.NormalizeOp;
import org.tensorflow.lite.support.label.TensorLabel;

// Post-processor which dequantize the result
TensorProcessor probabilityProcessor =
    new TensorProcessor.Builder().add(new NormalizeOp(0, 255)).build();

if (null != associatedAxisLabels) {
    // Map of labels and their corresponding probability
    TensorLabel labels = new TensorLabel(associatedAxisLabels,
        probabilityProcessor.process(probabilityBuffer));

    // Create a map to access the result based on label
    Map<String, Float> floatMap = labels.getMapWithFloatValue();
}

現在のユースケースの対象範囲

現在のバージョンの TensorFlow Lite サポート ライブラリは、以下に対応しています。

  • tflite モデルの入力と出力として一般的な データ型(float、uint8、画像、音声、これらのオブジェクトの配列)を 使用します
  • 基本的な画像操作(画像の切り抜き、サイズ変更、回転)。
  • 正規化と量子化の
  • ファイル ユーティリティ

今後のバージョンでは、テキスト関連アプリケーションのサポートが改善されます。

ImageProcessor アーキテクチャ

ImageProcessor の設計により、画像操作オペレーションを事前に定義し、ビルドプロセス中に最適化することができました。ImageProcessor は現在、以下のコード スニペットの 3 つのコメントで説明されているように、3 つの基本的な前処理オペレーションをサポートしています。

import org.tensorflow.lite.support.common.ops.NormalizeOp;
import org.tensorflow.lite.support.common.ops.QuantizeOp;
import org.tensorflow.lite.support.image.ops.ResizeOp;
import org.tensorflow.lite.support.image.ops.ResizeWithCropOrPadOp;
import org.tensorflow.lite.support.image.ops.Rot90Op;

int width = bitmap.getWidth();
int height = bitmap.getHeight();

int size = height > width ? width : height;

ImageProcessor imageProcessor =
    new ImageProcessor.Builder()
        // Center crop the image to the largest square possible
        .add(new ResizeWithCropOrPadOp(size, size))
        // Resize using Bilinear or Nearest neighbour
        .add(new ResizeOp(224, 224, ResizeOp.ResizeMethod.BILINEAR));
        // Rotation counter-clockwise in 90 degree increments
        .add(new Rot90Op(rotateDegrees / 90))
        .add(new NormalizeOp(127.5, 127.5))
        .add(new QuantizeOp(128.0, 1/128.0))
        .build();

正規化と量子化の詳細については、こちらをご覧ください。

サポート ライブラリの最終的な目標は、すべての tf.image 変換をサポートすることです。つまり、変換は TensorFlow と同じで、実装はオペレーティング システムから独立します。

デベロッパーがカスタム プロセッサを作成することもできます。このような場合は、トレーニング プロセスに合わせることが重要です。つまり、再現性を高めるために、トレーニングと推論の両方に同じ前処理を適用する必要があります。

量子化

TensorImageTensorBuffer などの入力オブジェクトや出力オブジェクトを開始するときは、その型を DataType.UINT8 または DataType.FLOAT32 に指定する必要があります。

TensorImage tensorImage = new TensorImage(DataType.UINT8);
TensorBuffer probabilityBuffer =
    TensorBuffer.createFixedSize(new int[]{1, 1001}, DataType.UINT8);

TensorProcessor を使用すると、入力テンソルを量子化したり、出力テンソルを逆量子化したりできます。たとえば、量子化された出力 TensorBuffer を処理する場合、デベロッパーは DequantizeOp を使用して、結果を 0 ~ 1 の間の浮動小数点確率に逆量子化できます。

import org.tensorflow.lite.support.common.TensorProcessor;

// Post-processor which dequantize the result
TensorProcessor probabilityProcessor =
    new TensorProcessor.Builder().add(new DequantizeOp(0, 1/255.0)).build();
TensorBuffer dequantizedBuffer = probabilityProcessor.process(probabilityBuffer);

テンソルの量子化パラメータは、メタデータ抽出ライブラリから読み取ることができます。