開發人員可以使用 TensorFlow Lite 中繼資料,產生包裝函式程式碼以在 Android 上啟用整合功能。對於大多數開發人員來說,Android Studio ML 模型繫結的圖形介面最容易使用。如果您需要更多自訂功能,或正在使用命令列工具,則 TensorFlow Lite Codegen 也可供使用。
使用 Android Studio ML 模型繫結
對於透過中繼資料強化的 TensorFlow Lite 模型,開發人員可以使用 Android Studio ML 模型繫結,根據模型中繼資料自動設定專案設定並產生包裝函式類別。包裝函式程式碼免除了直接與 ByteBuffer
互動的需要。反之,開發人員可以使用類型物件 (例如 Bitmap
和 Rect
) 與 TensorFlow Lite 模型互動。
在 Android Studio 中匯入 TensorFlow Lite 模型
在您要使用 TFLite 模型的模組上按一下滑鼠右鍵,或按一下
File
,然後依序按一下New
>Other
>TensorFlow Lite Model
選取您的 TFLite 檔案位置。請注意,此工具會在您執行 ML 模型繫結時,代表您設定模組的依附元件,且所有依附元件都會自動插入您的 Android 模組
build.gradle
檔案中。選用:如果您想使用 GPU 加速,請選取第二個核取方塊以匯入 TensorFlow GPU。
按一下
Finish
。成功匯入後,會出現以下畫面。若要開始使用模型,請選取 Kotlin 或 Java,然後複製並貼上
Sample Code
區段下的程式碼。您可以按兩下 Android Studio 中ml
目錄下的 TFLite 模型,返回此畫面。
加速模型推論
ML 模型繫結提供開發人員透過使用委派和執行緒數量來加速程式碼的方法。
步驟 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
互動的需要。反之,開發人員可以使用類型物件 (例如 Bitmap
和 Rect
) 與 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 專案,並匯入產生的模組:然後依序按一下 File -> New -> Import Module -> 選取 SRC_ROOT
以上述範例來說,匯入的目錄和模組會稱為 classify_wrapper
。
步驟 2:更新應用程式的 build.gradle
檔案
在將使用產生程式庫模組的應用程式模組中
在 android 區段下,新增以下內容
aaptOptions {
noCompress "tflite"
}
在 dependencies 區段下,新增以下內容
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 Activity 或 Service 的 Context- (選用)
Device
:TFLite 加速委派,例如 GPUDelegate 或 NNAPIDelegate - (選用)
numThreads
:用於執行模型的執行緒數量 - 預設值為 1。
例如,若要使用 NNAPI 委派和最多三個執行緒,您可以像這樣初始化模型
try {
myImageClassifier = new MyClassifierModel(this, Model.Device.NNAPI, 3);
} catch (IOException io){
// Error reading the model
}
疑難排解
如果您收到「java.io.FileNotFoundException: This file can not be opened as a file descriptor; it is probably compressed」錯誤,請將以下程式碼行插入將使用程式庫模組的應用程式模組的 android 區段下
aaptOptions {
noCompress "tflite"
}