【问题标题】:How to fix: on Android TensorFlow Lite inference is much slower than standard TensorFlow inference如何修复:在 Android 上,TensorFlow Lite 推理比标准 TensorFlow 推理慢得多
【发布时间】:2019-10-05 14:57:38
【问题描述】:

我使用 TensorFlow 和 Keras 开发并训练了一个卷积神经网络。现在,我想将此模型部署到 Android 设备上,我需要它用于实时应用程序。

我找到了两种将 Keras 模型部署到 Android 的方法:

  1. 将图形冻结为 .pb 文件(例如,“model.pb”),然后使用 Android 设备上的“TensorFlowInferenceInterface”。
  2. 将冻结图转换为 .tflite 模型(例如“model.tflite”) 然后在 Android 设备上使用 TesorFlow Lite 解释器。

这两种方法都适用于 Android 设备并产生预期的结果。然而,令我惊讶的是,使用 TensorFlow Lite 解释器进行推理所需的时间至少是使用 TensorFlowInterface 进行推理的时间的两倍(当然,在同一设备上)。我在各种设备上进行了检查,结果在所有情况下都相似。

为了创建 tflite-model,我使用以下代码:

tflite_convert --graph_def_file=" + frozen_graph_name + "
--output_file=" + TFLite_file_name + " --inference_type=FLOAT 
--input_type=FLOAT --input_shape=1,768,64,1 
--input_format=TENSORFLOW_GRAPHDEF --output_format=TFLITE 
--input_arrays=input_1 --output_arrays=conv2d_10/Sigmoid" \ 

或者,我尝试了以下 python 代码

import tensorflow as tf
converter = tf.lite.TFLiteConverter.from_keras_model_file('keras_model.h5')        
tflite_model = converter.convert()
open(TFLite_file_name, "wb").write('model.tflite')

在这两种情况下,结果是相同的 - 在所有 Android 设备上,tflite 推理都比 TensorFlowInterface 推理慢得多。添加优化标志“OPTIMIZE_FOR_LATENCY”将 tflite 推理时间增加了两倍。

我检查了TensorFlow Lite quantization fails to improve inference latency、Why is TensorFlow Lite slower than TensorFlow on desktop?和Tensorflow Object Detection inference slow on CPU,但没有得到任何满意的答案。

根据所有文档,我发现 TFLite 在 Android 设备上应该更快。那么我能做些什么来加快我在 Android 上的 TFLite 推理速度呢?在我的 PC 上,TFLite 确实更快,这更令人惊讶。

非常感谢任何帮助!

【问题讨论】:

    标签: android performance tensorflow


    【解决方案1】:

    您可能希望使用 TFLite Benchmark tool 分析您的模型,它可以为您提供平均推理时间甚至是操作级延迟。

    如果您观察到的延迟明显大于基准工具显示的延迟,则您的推理代码可能存在效率低下的问题。如果没有,那么某些操作可能是瓶颈,您可以为此提交 Github 问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-27
      相关资源
      最近更新 更多