將 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
匯入 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 模型。
瞭解詳情
如需關於
Interpreter
API 的更多詳細資訊,請閱讀在 Python 中載入和執行模型。如果您有 Raspberry Pi,請查看關於如何使用 TensorFlow Lite 在 Raspberry Pi 上執行物件偵測的系列影片。
如果您使用 Coral ML 加速器,請查看 GitHub 上的 Coral 範例。
若要將其他 TensorFlow 模型轉換為 TensorFlow Lite,請閱讀關於 TensorFlow Lite Converter 的資訊。
如果您想建構
tflite_runtime
Wheel,請閱讀建構 TensorFlow Lite Python Wheel 套件