使用 Python 的 Linux 裝置快速入門導覽課程

TensorFlow Lite 適用於採用 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 輪子是預先建構的,適用於下列平台:

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

如要在其他平台上執行 TensorFlow Lite 模型,請使用完整的 TensorFlow 套件,或是從原始碼建構 tflite-runtime 套件

如果您將 TensorFlow 與 Coral Edge TPU 搭配使用,請改為參閱適當的 Coral 設定說明文件

使用 tflite_runtime 執行推論

現在,您必須從 tflite_runtime 匯入 Interpreter,而不是從 tensorflow 模組匯入。

舉例來說,在您安裝上述套件後,請複製並執行 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 模型。

瞭解詳情