快速入门:使用 Python 构建基于 Linux 的设备

将 TensorFlow Lite 与 Python 搭配使用非常适合基于 Linux 的嵌入式设备,例如 Raspberry Pi采用 Edge TPU 的 Coral 设备等。

本页面介绍了如何在几分钟内开始使用 Python 运行 TensorFlow Lite 模型。您只需要一个已转换为 TensorFlow Lite 的 TensorFlow 模型。(如果您还没有转换的模型,可以使用以下链接示例中提供的模型进行实验。)

TensorFlow Lite 运行时软件包简介

如需快速开始使用 Python 执行 TensorFlow Lite 模型,您可以仅安装 TensorFlow Lite 解释器,而不是安装所有 TensorFlow 软件包。我们将此简化版 Python 软件包称为 tflite_runtime

tflite_runtime 软件包的大小比整个 tensorflow 软件包少很多,其中包含使用 TensorFlow Lite 运行推理所需的最少量代码(主要是 Interpreter Python 类)。如果您只需要执行 .tflite 模型并避免在大型 TensorFlow 库上浪费磁盘空间,那么这个小型软件包就是理想之选。

安装 Python 版 TensorFlow Lite

您可以使用 pip 在 Linux 上安装:

python3 -m pip install tflite-runtime

支持的平台

tflite-runtime Python wheel 是针对以下平台预先构建好的,并提供:

  • Linux armv7l(例如,运行 Raspberry Pi OS 32 位的 Raspberry Pi 2、3、4 和 Zero 2)
  • Linux aarch64(例如,运行 Debian ARM64 的 Raspberry Pi 3、4)
  • Linux x86_64

如果您想在其他平台上运行 TensorFlow Lite 模型,则应使用完整的 TensorFlow 软件包从源代码构建 tflite-runtime 软件包

如果您将 TensorFlow 与 Coral Edge TPU 搭配使用,则应遵循相应的 Coral 设置文档

使用 tflite_runtime 运行推理

现在,您需要从 tflite_runtime 导入,而不是从 tensorflow 模块导入 Interpreter

例如,安装上述软件包后,复制并运行 label_image.py 文件。该操作将(可能)失败,因为您没有安装 tensorflow 库。要修复此错误,请修改文件的下面一行:

import tensorflow as tf

因此,它改为读取:

import tflite_runtime.interpreter as tflite

然后更改下面一行代码:

interpreter = tf.lite.Interpreter(model_path=args.model_file)

代码对应的是:

interpreter = tflite.Interpreter(model_path=args.model_file)

现在,再次运行 label_image.py。大功告成!您现在正在执行 TensorFlow Lite 模型。

了解详情