モバイル アプリケーション デベロッパーは通常、ビットマップなどの型付きオブジェクトや、整数などのプリミティブを操作します。ただし、オンデバイス ML モデルを実行する LiteRT インタープリタ API は ByteBuffer 形式のテンソルを使用するため、デバッグや操作が難しい場合があります。LiteRT Android サポート ライブラリは、LiteRT モデルの入出力を処理し、LiteRT インタープリタを使いやすくするために設計されています。
スタートガイド
Gradle 依存関係とその他の設定をインポートする
.tflite モデルファイルを、モデルが実行される Android モジュールの assets ディレクトリにコピーします。ファイルを圧縮しないように指定し、モジュールの build.gradle ファイルに LiteRT ライブラリを追加します。
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 'com.google.ai.edge.litert:litert-gpu:0.0.0-nightly-SNAPSHOT'
implementation 'com.google.ai.edge.litert:litert-support:0.0.0-nightly-SNAPSHOT'
}
さまざまなバージョンの Support Library については、MavenCentral でホストされている LiteRT Support Library AAR をご覧ください。
基本的な画像操作と変換
LiteRT サポート ライブラリには、切り抜きやサイズ変更などの基本的な画像操作メソッドのスイートがあります。これを使用するには、ImagePreprocessor を作成して必要なオペレーションを追加します。LiteRT インタープリタに必要なテンソル形式に画像を変換するには、入力として使用する 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 LiteRT interpreter needs.
TensorImage tensorImage = new TensorImage(DataType.UINT8);
// Analysis code for every frame
// Preprocess the image
tensorImage.load(bitmap);
tensorImage = imageProcessor.process(tensorImage);
テンソルの DataType は、メタデータ抽出ライブラリや他のモデル情報から読み取ることができます。
基本的な音声データ処理
LiteRT サポート ライブラリは、基本的な音声データ処理メソッドをラップする 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(可能性が最も高い)の範囲で取得する必要があります。
省略可: 結果をラベルにマッピングする
デベロッパーは、結果をラベルにマッピングすることもできます。まず、ラベルを含むテキスト ファイルをモジュールの assets ディレクトリにコピーします。次に、次のコードを使用してラベルファイルを読み込みます。
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();
}
現在のユースケースの対応範囲
LiteRT サポート ライブラリの現在のバージョンでは、次のものが対象となります。
- 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 と同じになり、実装はオペレーティング システムに依存しません。
デベロッパーはカスタム プロセッサを作成することもできます。このような場合は、トレーニング プロセスと整合性を保つことが重要です。つまり、再現性を高めるために、トレーニングと推論の両方に同じ前処理を適用する必要があります。
量子化
TensorImage や TensorBuffer などの入力オブジェクトまたは出力オブジェクトを初期化する場合は、それらの型を 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);
テンソルの量子化パラメータは、メタデータ抽出ライブラリで読み取ることができます。