如何在Python中导入tensorflow lite解释器?

时间:2018-06-18 02:36:38

标签: python tensorflow raspberry-pi3 pytorch tensorflow-lite

我正在使用Raspberry Pi 3b上的TF lite开发一个Tensorflow嵌入式应用程序,运行Raspbian Stretch。我已经将图形转换为flatbuffer(lite)格式,并在Pi上本地构建了TFLite静态库。到现在为止还挺好。但是应用程序是Python,似乎没有可用的Python绑定。 Tensorflow Lite开发指南(https://www.tensorflow.org/mobile/tflite/devguide)指出“有Python绑定和演示应用程序的计划。”然而,/ tensorflow / contrib / lite / python / interpreter_wrapper中有包装代码,它具有所有需要的解释器方法。然而,从Python中调用它可以避免我。

我已经生成了SWIG包装器,但构建步骤失败并出现许多错误。没有readme.md描述interpreter_wrapper的状态。所以,我想知道包装器是否适用于其他人,我应该坚持或者它是否从根本上被打破,我应该寻找其他地方(PyTorch)?有人找到了通往Pi3的TFLite Python绑定的路径吗?

2 个答案:

答案 0 :(得分:4)

我能够编写python脚本来对计算机上的计算机进行分类1,对象检测(已通过SSD MobilenetV {1,2}测试)2和图像语义分割3。运行Ubuntu的x86和运行Debian的ARM64板。

  • 如何为TF Lite代码构建Python绑定:使用最近的TensorFlow master分支构建pip并安装它(是的,这些绑定位于TF 1.8中。但是,我不知道为什么未安装它们)。有关如何构建和安装TensorFlow pip软件包的信息,请参见4

答案 1 :(得分:4)

关于使用来自Python的TensorFlow Lite解释器,以下示例是从documentation复制而来的。该代码在TensorFlow GitHubmaster分支上可用。

使用模型文件中的解释器

以下示例显示了提供TensorFlow Lite FlatBuffer文件时如何使用TensorFlow Lite Python解释器。该示例还演示了如何对随机输入数据进行推理。在Python终端中运行help(tf.contrib.lite.Interpreter),以获取有关解释器的详细文档。

import numpy as np
import tensorflow as tf

# Load TFLite model and allocate tensors.
interpreter = tf.contrib.lite.Interpreter(model_path="converted_model.tflite")
interpreter.allocate_tensors()

# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

# Test model on random input data.
input_shape = input_details[0]['shape']
input_data = np.array(np.random.random_sample(input_shape), dtype=np.float32)
interpreter.set_tensor(input_details[0]['index'], input_data)

interpreter.invoke()
output_data = interpreter.get_tensor(output_details[0]['index'])
print(output_data)
相关问题