使用中繼資料產生模型介面

開發人員可使用 TensorFlow Lite 中繼資料產生包裝函式程式碼,在 Android 上進行整合。對大多數開發人員來說,Android Studio ML Model Binding 的圖形介面是最容易使用的方式。如果您需要進一步自訂或使用指令列工具,您也可以使用 TensorFlow Lite Codegen

使用 Android Studio 機器學習模型繫結

如果是以中繼資料強化的 TensorFlow Lite 模型,開發人員可以使用 Android Studio 機器學習模型繫結來自動配置專案的設定,並根據模型中繼資料產生包裝函式類別。包裝函式程式碼不再需要直接與 ByteBuffer 互動。開發人員可以改為使用 BitmapRect 等類型物件與 TensorFlow Lite 模型互動。

在 Android Studio 中匯入 TensorFlow Lite 模型

  1. 在您要使用 TFLite 模型的模組上按一下滑鼠右鍵,或依序點選 FileNew > Other > TensorFlow Lite Model

  2. 選取 TFLite 檔案的位置。請注意,此工具會透過機器學習模型繫結代您設定模組的依附元件,且所有依附元件都會自動插入 Android 模組的 build.gradle 檔案中。

    選用:如要使用 GPU 加速功能,請選取第二個核取方塊來匯入 TensorFlow GPU。

  3. 按一下「Finish」。

  4. 匯入成功後,會顯示以下畫面。如要開始使用模型,請選取 Kotlin 或 Java,然後複製程式碼並貼到 Sample Code 區段下方。如要返回這個畫面,請按兩下 Android Studio 中 ml 目錄下的 TFLite 模型。

加快模型推論速度

機器學習模型繫結可讓開發人員使用委派項目和執行緒數量,加快程式碼速度。

步驟 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 模型中繼資料項目的完整性。請參閱 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 專案,並透過以下方式匯入產生的模組:And 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();
}

加快模型推論速度

產生的程式碼可讓開發人員使用「委派」和執行緒數量加快程式碼速度。由於需要三個參數,您可以在初始化模型物件時,設定這些參數:

  • Context:Android 活動或服務的內容
  • (選用) Device:TFLite 加速委派。例如:GPUDelegate
  • (選用) numThreads:用來執行模型的執行緒數量 - 預設值為一。

舉例來說,如要使用 GPU 委派和最多三個執行緒,您可以透過下列方式初始化模型:

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

疑難排解

如果看到「java.io.FileNotFoundException:這個檔案無法以檔案描述元開啟;可能已遭壓縮」的錯誤,請在會使用程式庫模組的應用程式模組的 Android 區段下方插入以下幾行:

aaptOptions {
   noCompress "tflite"
}