Google Play 服务 Java API 中的 TensorFlow Lite

除了原生 API 之外,您还可以使用 Java API 访问 Google Play 服务中的 TensorFlow Lite。特别是,Google Play 服务中的 TensorFlow Lite 可通过 TensorFlow Lite Explainer API 获得。

使用 Explainer API

TensorFlow 运行时提供的 TensorFlow Lite Explainer API 提供了一个用于构建和运行机器学习模型的通用接口。您可以按照以下步骤通过 Google Play 服务运行时中的 TensorFlow Lite 通过 Explainer API 进行推断。

1. 添加项目依赖项

将以下依赖项添加到您的应用项目代码中,以访问适用于 TensorFlow Lite 的 Play 服务 API:

dependencies {
...
    // Tensorflow Lite dependencies for Google Play services
    implementation 'com.google.android.gms:play-services-tflite-java:16.0.1'
    // Optional: include Tensorflow Lite Support Library
    implementation 'com.google.android.gms:play-services-tflite-support:16.0.1'
...
}

2. 添加 TensorFlow Lite 的初始化

在使用 TensorFlow Lite API 之前,请先初始化 Google Play 服务 API 的 TensorFlow Lite 组件:

Kotlin

val initializeTask: Task<Void> by lazy { TfLite.initialize(this) }

Java

Task<Void> initializeTask = TfLite.initialize(context);

3. 创建解释器并设置运行时选项

使用 InterpreterApi.create() 创建解释器,并通过调用 InterpreterApi.Options.setRuntime() 将其配置为使用 Google Play 服务运行时,如以下示例代码所示:

Kotlin

import org.tensorflow.lite.InterpreterApi
import org.tensorflow.lite.InterpreterApi.Options.TfLiteRuntime
...
private lateinit var interpreter: InterpreterApi
...
initializeTask.addOnSuccessListener {
  val interpreterOption =
    InterpreterApi.Options().setRuntime(TfLiteRuntime.FROM_SYSTEM_ONLY)
  interpreter = InterpreterApi.create(
    modelBuffer,
    interpreterOption
  )}
  .addOnFailureListener { e ->
    Log.e("Interpreter", "Cannot initialize interpreter", e)
  }

Java

import org.tensorflow.lite.InterpreterApi
import org.tensorflow.lite.InterpreterApi.Options.TfLiteRuntime
...
private InterpreterApi interpreter;
...
initializeTask.addOnSuccessListener(a -> {
    interpreter = InterpreterApi.create(modelBuffer,
      new InterpreterApi.Options().setRuntime(TfLiteRuntime.FROM_SYSTEM_ONLY));
  })
  .addOnFailureListener(e -> {
    Log.e("Interpreter", String.format("Cannot initialize interpreter: %s",
          e.getMessage()));
  });

您应该使用上述实现,因为它可以避免阻塞 Android 界面线程。如果您需要更密切地管理线程执行,可以在创建解释器时添加 Tasks.await() 调用:

Kotlin

import androidx.lifecycle.lifecycleScope
...
lifecycleScope.launchWhenStarted { // uses coroutine
  initializeTask.await()
}

Java

@BackgroundThread
InterpreterApi initializeInterpreter() {
    Tasks.await(initializeTask);
    return InterpreterApi.create(...);
}

4. 运行推断

使用您创建的 interpreter 对象,调用 run() 方法来生成推断。

Kotlin

interpreter.run(inputBuffer, outputBuffer)

Java

interpreter.run(inputBuffer, outputBuffer);

硬件加速

借助 TensorFlow Lite,您可以使用图形处理单元 (GPU) 等专用硬件处理器来加快模型的性能。您可以通过称为委托的硬件驱动程序来利用这些专用处理器。

GPU 代理通过 Google Play 服务提供并动态加载,就像 Explainer API 的 Play 服务版本一样。

正在检查设备兼容性

并非所有设备都支持通过 TFLite 进行 GPU 硬件加速。为了减少错误和潜在的崩溃问题,请使用 TfLiteGpu.isGpuDelegateAvailable 方法检查设备是否与 GPU 代理兼容。

使用此方法可以确认设备是否与 GPU 兼容,并在 GPU 不受支持时将 CPU 用作后备选项。

useGpuTask = TfLiteGpu.isGpuDelegateAvailable(context)

有了 useGpuTask 等变量后,您可以使用它来确定设备是否使用 GPU 代理。

Kotlin

val interpreterTask = useGpuTask.continueWith { task ->
  val interpreterOptions = InterpreterApi.Options()
      .setRuntime(TfLiteRuntime.FROM_SYSTEM_ONLY)
  if (task.result) {
      interpreterOptions.addDelegateFactory(GpuDelegateFactory())
  }
  InterpreterApi.create(FileUtil.loadMappedFile(context, MODEL_PATH), interpreterOptions)
}
    

Java

Task<InterpreterApi.Options> interpreterOptionsTask = useGpuTask.continueWith({ task ->
  InterpreterApi.Options options =
      new InterpreterApi.Options().setRuntime(TfLiteRuntime.FROM_SYSTEM_ONLY);
  if (task.getResult()) {
     options.addDelegateFactory(new GpuDelegateFactory());
  }
  return options;
});
    

带有解释器 API 的 GPU

如需将 GPU 代理与 Explainer API 搭配使用,请执行以下操作:

  1. 更新项目依赖项以使用 Play 服务中的 GPU 代理:

    implementation 'com.google.android.gms:play-services-tflite-gpu:16.1.0'
    
  2. 在 TFlite 初始化中启用 GPU 委托选项:

    Kotlin

        TfLite.initialize(context,
          TfLiteInitializationOptions.builder()
           .setEnableGpuDelegateSupport(true)
           .build())
        

    Java

        TfLite.initialize(context,
          TfLiteInitializationOptions.builder()
           .setEnableGpuDelegateSupport(true)
           .build());
        
  3. 在解释器选项中启用 GPU 委托:通过调用 addDelegateFactory() withinExplainerApi.Options()` 将委托工厂设置为 GpuDelegateFactory:

    Kotlin

    val interpreterOption = InterpreterApi.Options()
    .setRuntime(TfLiteRuntime.FROM_SYSTEM_ONLY)
    .addDelegateFactory(GpuDelegateFactory())
    

    Java

    Options interpreterOption = InterpreterApi.Options()
    .setRuntime(TfLiteRuntime.FROM_SYSTEM_ONLY) .addDelegateFactory(new
    GpuDelegateFactory());
    

从独立版 TensorFlow Lite 迁移

如果您计划将应用从独立 TensorFlow Lite 迁移到 Play 服务 API,请查看以下有关更新应用项目代码的其他指南:

  1. 请查看本页面的限制部分,确保您的用例受支持。
  2. 在更新代码之前,请对模型进行性能和准确性检查,尤其是当您使用的 TensorFlow Lite 版本低于 2.1 时,这样才能获得与新实现进行比较的基准。
  3. 如果您已将所有代码迁移到适用于 TensorFlow Lite 的 Play 服务 API,则应从 build.gradle 文件中移除现有的 TensorFlow Lite 运行时库依赖项(包含 org.tensorflow:tensorflow-lite:* 的条目),以便缩减应用大小。
  4. 确定代码中 new Interpreter 对象创建的所有事件,并修改每个实例,以便使用 ExplainerApi.create() 调用。新的 TfLite.initialize 是异步的,这意味着在大多数情况下它都不是简易的替换:您必须在调用完成时注册监听器。请参阅第 3 步中的代码段。
  5. 使用 org.tensorflow.lite.Interpreterorg.tensorflow.lite.InterpreterApi 类将 import org.tensorflow.lite.InterpreterApi;import org.tensorflow.lite.InterpreterApi.Options.TfLiteRuntime; 添加到任何源文件中。
  6. 如果对 InterpreterApi.create() 生成的任何调用只包含一个参数,请将 new InterpreterApi.Options() 附加到参数列表。
  7. .setRuntime(TfLiteRuntime.FROM_SYSTEM_ONLY) 附加到对 InterpreterApi.create() 的任何调用的最后一个参数。
  8. 将所有其他出现的 org.tensorflow.lite.Interpreter 类替换为 org.tensorflow.lite.InterpreterApi

如果您想同时使用独立的 TensorFlow Lite 和 Play 服务 API,则必须使用 TensorFlow Lite 2.9(或更高版本)。TensorFlow Lite 2.8 及更低版本与 Play Services API 版本不兼容。