在 Android 上使用 TensorFlow Lite 模型與機器學習套件進行推理

您可以使用 ML Kit 通過TensorFlow Lite模型執行設備上推理。

此 API 需要 Android SDK 級別 16 (Jelly Bean) 或更高版本。

在你開始之前

  1. 如果您尚未將 Firebase 添加到您的 Android 項目中,請將其添加到您的 Android 項目中。
  2. 將 ML Kit Android 庫的依賴項添加到模塊(應用程序級)Gradle 文件(通常app/build.gradle ):
    apply plugin: 'com.android.application'
    apply plugin: 'com.google.gms.google-services'
    
    dependencies {
      // ...
    
      implementation 'com.google.firebase:firebase-ml-model-interpreter:22.0.3'
    }
    
  3. 將您要使用的 TensorFlow 模型轉換為 TensorFlow Lite 格式。請參閱TOCO:TensorFlow Lite 優化轉換器

託管或捆綁您的模型

在您的應用程序中使用 TensorFlow Lite 模型進行推理之前,您必須使該模型可用於 ML Kit。 ML Kit 可以使用通過 Firebase 遠程託管的 TensorFlow Lite 模型、與應用程序二進製文件捆綁在一起或兩者兼而有之。

通過在 Firebase 上託管模型,您可以更新模型而無需發布新的應用版本,並且可以使用遠程配置和 A/B 測試向不同的用戶組動態提供不同的模型。

如果您選擇僅通過 Firebase 託管來提供模型,而不是將其與您的應用捆綁在一起,則可以減少應用的初始下載大小。但請記住,如果模型未與您的應用程序捆綁在一起,則在您的應用程序首次下載模型之前,任何與模型相關的功能都將不可用。

通過將模型與應用捆綁在一起,您可以確保應用的 ML 功能在 Firebase 託管模型不可用時仍然有效。

Firebase 上的主機模型

要在 Firebase 上託管 TensorFlow Lite 模型,請執行以下操作:

  1. Firebase 控制台ML Kit部分中,單擊自定義選項卡。
  2. 單擊添加自定義模型(或添加其他模型)。
  3. 指定用於在 Firebase 項目中識別模型的名稱,然後上傳 TensorFlow Lite 模型文件(通常以.tflite.lite結尾)。
  4. 在應用程序的清單中,聲明需要 INTERNET 權限:
    <uses-permission android:name="android.permission.INTERNET" />
    

將自定義模型添加到 Firebase 項目後,您可以使用指定的名稱在應用中引用該模型。您可以隨時上傳新的 TensorFlow Lite 模型,您的應用程序將下載新模型並在應用程序下次重新啟動時開始使用它。您可以定義應用程序嘗試更新模型所需的設備條件(見下文)。

將模型與應用程序捆綁在一起

要將 TensorFlow Lite 模型與應用程序捆綁在一起,請將模型文件(通常以.tflite.lite結尾)複製到應用程序的assets/文件夾中。 (您可能需要首先右鍵單擊app/文件夾,然後單擊新建 > 文件夾 > 資產文件夾來創建文件夾。)

然後,將以下內容添加到應用程序的build.gradle文件中,以確保 Gradle 在構建應用程序時不會壓縮模型:

android {

    // ...

    aaptOptions {
        noCompress "tflite"  // Your model's file extension: "tflite", "lite", etc.
    }
}

模型文件將包含在應用程序包中,並可作為原始資產提供給 ML Kit。

加載模型

要在應用中使用 TensorFlow Lite 模型,請首先使用模型可用的位置配置 ML Kit:遠程使用 Firebase、在本地存儲中或兩者兼而有之。如果您同時指定本地模型和遠程模型,則可以使用遠程模型(如果可用);如果遠程模型不可用,則可以回退到本地存儲的模型。

配置 Firebase 託管模型

如果您使用 Firebase 託管模型,請創建一個FirebaseCustomRemoteModel對象,並指定您上傳模型時為該模型分配的名稱:

Java

FirebaseCustomRemoteModel remoteModel =
        new FirebaseCustomRemoteModel.Builder("your_model").build();

Kotlin+KTX

val remoteModel = FirebaseCustomRemoteModel.Builder("your_model").build()

然後,啟動模型下載任務,指定允許下載的條件。如果設備上沒有模型,或者有更新版本的模型可用,則任務將從 Firebase 異步下載模型:

Java

FirebaseModelDownloadConditions conditions = new FirebaseModelDownloadConditions.Builder()
        .requireWifi()
        .build();
FirebaseModelManager.getInstance().download(remoteModel, conditions)
        .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                // Success.
            }
        });

Kotlin+KTX

val conditions = FirebaseModelDownloadConditions.Builder()
    .requireWifi()
    .build()
FirebaseModelManager.getInstance().download(remoteModel, conditions)
    .addOnCompleteListener {
        // Success.
    }

許多應用程序在其初始化代碼中啟動下載任務,但您可以在需要使用模型之前隨時執行此操作。

配置本地模型

如果您將模型與應用程序捆綁在一起,請創建一個FirebaseCustomLocalModel對象,並指定 TensorFlow Lite 模型的文件名:

Java

FirebaseCustomLocalModel localModel = new FirebaseCustomLocalModel.Builder()
        .setAssetFilePath("your_model.tflite")
        .build();

Kotlin+KTX

val localModel = FirebaseCustomLocalModel.Builder()
    .setAssetFilePath("your_model.tflite")
    .build()

從您的模型創建解釋器

配置模型源後,從其中之一創建一個FirebaseModelInterpreter對象。

如果您只有本地捆綁的模型,只需從FirebaseCustomLocalModel對象創建一個解釋器:

Java

FirebaseModelInterpreter interpreter;
try {
    FirebaseModelInterpreterOptions options =
            new FirebaseModelInterpreterOptions.Builder(localModel).build();
    interpreter = FirebaseModelInterpreter.getInstance(options);
} catch (FirebaseMLException e) {
    // ...
}

Kotlin+KTX

val options = FirebaseModelInterpreterOptions.Builder(localModel).build()
val interpreter = FirebaseModelInterpreter.getInstance(options)

如果您有遠程託管模型,則必須在運行之前檢查它是否已下載。您可以使用模型管理器的isModelDownloaded()方法檢查模型下載任務的狀態。

儘管您只需在運行解釋器之前確認這一點,但如果您同時擁有遠程託管模型和本地捆綁模型,則在實例化模型解釋器時執行此檢查可能是有意義的:如果滿足以下條件,則從遠程模型創建解釋器:它已被下載,否則是從本地模型下載的。

Java

FirebaseModelManager.getInstance().isModelDownloaded(remoteModel)
        .addOnSuccessListener(new OnSuccessListener<Boolean>() {
            @Override
            public void onSuccess(Boolean isDownloaded) {
                FirebaseModelInterpreterOptions options;
                if (isDownloaded) {
                    options = new FirebaseModelInterpreterOptions.Builder(remoteModel).build();
                } else {
                    options = new FirebaseModelInterpreterOptions.Builder(localModel).build();
                }
                FirebaseModelInterpreter interpreter = FirebaseModelInterpreter.getInstance(options);
                // ...
            }
        });

Kotlin+KTX

FirebaseModelManager.getInstance().isModelDownloaded(remoteModel)
    .addOnSuccessListener { isDownloaded -> 
    val options =
        if (isDownloaded) {
            FirebaseModelInterpreterOptions.Builder(remoteModel).build()
        } else {
            FirebaseModelInterpreterOptions.Builder(localModel).build()
        }
    val interpreter = FirebaseModelInterpreter.getInstance(options)
}

如果您只有遠程託管模型,則應禁用與模型相關的功能(例如,灰顯或隱藏部分 UI),直到確認模型已下載。您可以通過將偵聽器附加到模型管理器的download()方法來實現此目的:

Java

FirebaseModelManager.getInstance().download(remoteModel, conditions)
        .addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void v) {
              // Download complete. Depending on your app, you could enable
              // the ML feature, or switch from the local model to the remote
              // model, etc.
            }
        });

Kotlin+KTX

FirebaseModelManager.getInstance().download(remoteModel, conditions)
    .addOnCompleteListener {
        // Download complete. Depending on your app, you could enable the ML
        // feature, or switch from the local model to the remote model, etc.
    }

指定模型的輸入和輸出

接下來,配置模型解釋器的輸入和輸出格式。

TensorFlow Lite 模型將一個或多個多維數組作為輸入並生成輸出。這些數組包含byteintlongfloat值。您必須使用模型使用的數組的數量和維度(“形狀”)來配置 ML Kit。

如果您不知道模型輸入和輸出的形狀和數據類型,可以使用 TensorFlow Lite Python 解釋器來檢查模型。例如:

import tensorflow as tf

interpreter = tf.lite.Interpreter(model_path="my_model.tflite")
interpreter.allocate_tensors()

# Print input shape and type
print(interpreter.get_input_details()[0]['shape'])  # Example: [1 224 224 3]
print(interpreter.get_input_details()[0]['dtype'])  # Example: <class 'numpy.float32'>

# Print output shape and type
print(interpreter.get_output_details()[0]['shape'])  # Example: [1 1000]
print(interpreter.get_output_details()[0]['dtype'])  # Example: <class 'numpy.float32'>

確定模型輸入和輸出的格式後,您可以通過創建FirebaseModelInputOutputOptions對象來配置應用的模型解釋器。

例如,浮點圖像分類模型可能將N x224x224x3 float值數組作為輸入,表示一批N 224x224 三通道 (RGB) 圖像,並生成 1000 個float值列表作為輸出,每個浮點值表示圖像屬於模型預測的 1000 個類別之一的概率。

對於這樣的模型,您將配置模型解釋器的輸入和輸出,如下所示:

Java

FirebaseModelInputOutputOptions inputOutputOptions =
        new FirebaseModelInputOutputOptions.Builder()
                .setInputFormat(0, FirebaseModelDataType.FLOAT32, new int[]{1, 224, 224, 3})
                .setOutputFormat(0, FirebaseModelDataType.FLOAT32, new int[]{1, 5})
                .build();

Kotlin+KTX

val inputOutputOptions = FirebaseModelInputOutputOptions.Builder()
        .setInputFormat(0, FirebaseModelDataType.FLOAT32, intArrayOf(1, 224, 224, 3))
        .setOutputFormat(0, FirebaseModelDataType.FLOAT32, intArrayOf(1, 5))
        .build()

對輸入數據進行推理

最後,要使用模型執行推理,請獲取輸入數據並對數據執行必要的轉換,以獲得適合模型的輸入數組。

例如,如果您有一個輸入形狀為 [1 224 224 3] 浮點值的圖像分類模型,則可以從Bitmap對像生成輸入數組,如下例所示:

Java

Bitmap bitmap = getYourInputImage();
bitmap = Bitmap.createScaledBitmap(bitmap, 224, 224, true);

int batchNum = 0;
float[][][][] input = new float[1][224][224][3];
for (int x = 0; x < 224; x++) {
    for (int y = 0; y < 224; y++) {
        int pixel = bitmap.getPixel(x, y);
        // Normalize channel values to [-1.0, 1.0]. This requirement varies by
        // model. For example, some models might require values to be normalized
        // to the range [0.0, 1.0] instead.
        input[batchNum][x][y][0] = (Color.red(pixel) - 127) / 128.0f;
        input[batchNum][x][y][1] = (Color.green(pixel) - 127) / 128.0f;
        input[batchNum][x][y][2] = (Color.blue(pixel) - 127) / 128.0f;
    }
}

Kotlin+KTX

val bitmap = Bitmap.createScaledBitmap(yourInputImage, 224, 224, true)

val batchNum = 0
val input = Array(1) { Array(224) { Array(224) { FloatArray(3) } } }
for (x in 0..223) {
    for (y in 0..223) {
        val pixel = bitmap.getPixel(x, y)
        // Normalize channel values to [-1.0, 1.0]. This requirement varies by
        // model. For example, some models might require values to be normalized
        // to the range [0.0, 1.0] instead.
        input[batchNum][x][y][0] = (Color.red(pixel) - 127) / 255.0f
        input[batchNum][x][y][1] = (Color.green(pixel) - 127) / 255.0f
        input[batchNum][x][y][2] = (Color.blue(pixel) - 127) / 255.0f
    }
}

然後,使用輸入數據創建一個FirebaseModelInputs對象,並將其以及模型的輸入和輸出規範傳遞給模型解釋器run方法:

Java

FirebaseModelInputs inputs = new FirebaseModelInputs.Builder()
        .add(input)  // add() as many input arrays as your model requires
        .build();
firebaseInterpreter.run(inputs, inputOutputOptions)
        .addOnSuccessListener(
                new OnSuccessListener<FirebaseModelOutputs>() {
                    @Override
                    public void onSuccess(FirebaseModelOutputs result) {
                        // ...
                    }
                })
        .addOnFailureListener(
                new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        // Task failed with an exception
                        // ...
                    }
                });

Kotlin+KTX

val inputs = FirebaseModelInputs.Builder()
        .add(input) // add() as many input arrays as your model requires
        .build()
firebaseInterpreter.run(inputs, inputOutputOptions)
        .addOnSuccessListener { result ->
            // ...
        }
        .addOnFailureListener { e ->
            // Task failed with an exception
            // ...
        }

如果調用成功,您可以通過調用傳遞給成功偵聽器的對象的getOutput()方法來獲取輸出。例如:

Java

float[][] output = result.getOutput(0);
float[] probabilities = output[0];

Kotlin+KTX

val output = result.getOutput<Array<FloatArray>>(0)
val probabilities = output[0]

如何使用輸出取決於您所使用的型號。

例如,如果您正在執行分類,下一步,您可以將結果的索引映射到它們表示的標籤:

Java

BufferedReader reader = new BufferedReader(
        new InputStreamReader(getAssets().open("retrained_labels.txt")));
for (int i = 0; i < probabilities.length; i++) {
    String label = reader.readLine();
    Log.i("MLKit", String.format("%s: %1.4f", label, probabilities[i]));
}

Kotlin+KTX

val reader = BufferedReader(
        InputStreamReader(assets.open("retrained_labels.txt")))
for (i in probabilities.indices) {
    val label = reader.readLine()
    Log.i("MLKit", String.format("%s: %1.4f", label, probabilities[i]))
}

附錄:模型安全性

無論您如何使 TensorFlow Lite 模型可供 ML Kit 使用,ML Kit 都會將它們以標準序列化 protobuf 格式存儲在本地存儲中。

從理論上講,這意味著任何人都可以復制您的模型。然而,在實踐中,大多數模型都是特定於應用程序的,並且由於優化而變得模糊,因此風險類似於競爭對手反彙編和重用您的代碼。儘管如此,在應用程序中使用自定義模型之前,您應該意識到這種風險。

在 Android API 級別 21 (Lollipop) 及更高版本上,模型將下載到自動備份中排除的目錄。

在 Android API 級別 20 及更早版本上,模型將下載到應用程序私有內部存儲中名為com.google.firebase.ml.custom.models的目錄中。如果您使用BackupAgent啟用文件備份,您可以選擇排除此目錄。