DigiHouse
繁體中文

TECH ARTICLE · NCU · 5 MIN READ

Blog / NCU

補充 3|🧠 TensorFlow Lite (TFLite) 教學入門指南

🧠 TensorFlow Lite (TFLite) 教學入門指南 ✅ 一、什麼是 TensorFlow Lite? TensorFlow Lite 是 Google 推出的 輕量級深度學習推論引擎,專為行動裝置、嵌入式系統(如 Raspberry Pi、Edge TPU)設計。 📌 與 TensorFlow 的

✅ 一、什麼是 TensorFlow Lite?

TensorFlow Lite 是 Google 推出的 輕量級深度學習推論引擎,專為行動裝置、嵌入式系統(如 Raspberry Pi、Edge TPU)設計。

📌 與 TensorFlow 的差異:

項目 TensorFlow TensorFlow Lite

對象 雲端訓練 / GPU 邊緣裝置 / 嵌入式

格式 .pb, .h5, SavedModel .tflite

模型大小 較大 較小(可量化壓縮)

推論速度 快(有硬體資源) 超快(可用 Edge TPU)

是否可訓練 ✅ ❌ 僅推論

🏗️ 二、工作流程總覽

text
訓練模型(TensorFlow)
       ↓
轉換為 .tflite(使用 TFLite Converter)
       ↓
部署至行動裝置 / IoT / 嵌入式系統
       ↓
使用 TFLite Interpreter 做推論

🧪 三、TFLite 模型轉換(以 Python 為例)

1️⃣ 安裝 TensorFlow

text
pip install tensorflow

2️⃣ 將已訓練模型轉成 .tflite

text
import tensorflow as tf

converter = tf.lite.TFLiteConverter.from_saved_model("my_model")  # 資料夾
tflite_model = converter.convert()

# 儲存為 .tflite 檔
with open("model.tflite", "wb") as f:
    f.write(tflite_model)
text
model = tf.keras.models.load_model("model.h5")
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()

📦 四、TFLite 推論範例(Python)

安裝推論庫:

text
pip install tflite-runtime

🔍 使用 tflite-runtime 推論

補充 3

text
import numpy as np
import tflite_runtime.interpreter as tflite

# 載入模型
interpreter = tflite.Interpreter(model_path="model.tflite")
interpreter.allocate_tensors()

# 取得輸入 / 輸出資訊
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

# 模擬一筆輸入資料
input_data = np.array([[0.1, 0.2, 0.3]], 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)

🎯 五、進階功能:模型量化(減小檔案大小 & 提升效能)

量化(Quantization)會將 float32 模型轉為 int8,極大減少模型大小,並加快推論速度。

🔧 範例:整數量化

text
converter.optimizations = [tf.lite.Optimize.DEFAULT]
tflite_model = converter.convert()

💡 六、Raspberry Pi 上部署 TFLite 模型

text
pip install tflite-runtime

支援硬體:

Raspberry Pi

Coral Edge TPU(搭配 quantized 模型)

Nvidia Jetson(使用 Jetson 特製版本)

🧰 七、應用案例

領域 範例模型 應用平台

影像分類 MobileNet, EfficientNet Android, Pi, Microcontroller

物件偵測 SSD, YOLOv5 TFLite 版 Raspberry Pi, Coral

姿勢估計 MoveNet, BlazePose 健身、互動裝置

NLP 文本分類 BERT (Distilled) 聊天機器人

手勢辨識 MediaPipe Hand + 自訓分類器 IoT 手勢控制

🔗 官方資源

TensorFlow Lite 官方

量化教學

TFLite 模型範例

原始文章來源:https://liusming.pixnet.net/blog/posts/14223033888