使用元数据生成模型接口

使用 TensorFlow Lite Metadata,开发者可以生成封装容器代码,以便在 Android 上实现集成。对于大多数开发者来说,Android Studio 机器学习模型绑定的图形界面是最方便使用的。如果您需要进行更多自定义设置或使用命令行工具,也可以使用 TensorFlow Lite Codegen

使用 Android Studio 机器学习模型绑定

对于使用元数据增强的 TensorFlow Lite 模型,开发者可以使用 Android Studio 机器学习模型绑定自动配置项目的设置,并基于模型元数据生成封装容器类。使用封装容器代码时,无需直接与 ByteBuffer 交互。相反,开发者可以使用类型化对象(例如 BitmapRect)与 TensorFlow Lite 模型进行交互。

在 Android Studio 中导入 TensorFlow Lite 模型

  1. 右键点击您想要使用 TFLite 模型的模块,或点击 File,然后依次点击 New > 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 模型元数据条目的完整性。如需了解 Codegen 工具如何解析每个字段,请参阅 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"
}

在“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 的上下文
  • (可选)Device:TFLite 加速委托。例如:GPUDelegate
  • (可选)numThreads:用于运行模型的线程数 - 默认值为 1。

例如,如需使用一个 GPU 代理和最多三个线程,可以按如下方式初始化模型:

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

问题排查

如果您收到“java.io.FileNotFoundException: This file is not could not be open as a file descriptor; it could be updated”错误,请在将使用库模块的应用模块的 android 部分下插入以下代码行:

aaptOptions {
   noCompress "tflite"
}