AI時代系列(2) 機器學習三部曲: 🔹 第二部:《深度學習 —— 神經網路的革命》
97/100 第十週:📌 部署、壓縮與邊緣 AI 應用(Edge AI & Deployment)📦
97.TensorFlow Lite 與移動端部署 📱 AI 跑在手機不是夢!
關鍵字: TFLite、Edge AI、Android/iOS 部署、模型壓縮、即時預測
適合對象: 想讓自己的 AI 模型能在手機、IoT 裝置上跑起來的開發者與工程師
________________________________________
🎯 為什麼要用 TensorFlow Lite?
在移動設備或 IoT 裝置上跑 AI 模型,面臨的挑戰包括:
• 計算資源有限(沒有 GPU)
• 電池壽命要求(耗電不能太高)
• 回應時間必須即時
TensorFlow Lite(TFLite) 是 Google 推出的輕量級推論框架,能把 TensorFlow 模型轉換成更小、更快的格式,專門用於手機、嵌入式設備。
________________________________________
🧱 基本架構與流程
🔄 模型轉換流程
A[已訓練 TensorFlow 模型] --> B[轉換為 .tflite 格式]
B --> C[部署至 Android/iOS 應用程式]
C --> D[設備端即時推論]
已訓練完成的 TensorFlow 模型(A)通常以 .pb 或 .h5 格式儲存,為了在行動裝置上高效執行,需先轉換為 .tflite 格式(B),這個格式是 TensorFlow Lite 的輕量版本,支援壓縮與量化以提升速度與降低資源消耗。轉換後的 .tflite 模型可部署至 Android 或 iOS 的應用程式中(C),整合進 App 的本地推論功能。最終,當使用者在裝置上執行 App 時,模型便可在手機或平板等終端即時進行推論(D),實現快速的 AI 回應,如圖像分類、人臉辨識、語音識別等功能。
________________________________________
🛠 第一步:建立並訓練 TF 模型
python
import tensorflow as tf
from tensorflow import keras
# 建立簡單模型(以 MNIST 為例)
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dense(10)
])
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
# 訓練模型
mnist = tf.keras.datasets.mnist
(x_train, y_train), _ = mnist.load_data()
model.fit(x_train, y_train, epochs=5)
# 儲存模型
model.save('mnist_model')
這段程式碼示範如何建立一個簡單的手寫數字辨識神經網路,使用 TensorFlow/Keras 訓練 MNIST 資料集。模型包含扁平化層、一個隱藏層和一個輸出層,並使用 Adam 最佳化器與稀疏分類交叉熵進行訓練。完成訓練後,模型被儲存為 SavedModel 格式,可作為後續轉換為 .tflite 模型、部署到 Android 或 iOS 行動裝置端進行即時推論的基礎。
________________________________________
🧰 第二步:轉換為 .tflite 格式
python
# 轉換模型
converter = tf.lite.TFLiteConverter.from_saved_model('mnist_model')
tflite_model = converter.convert()
# 儲存為檔案
with open('mnist_model.tflite', 'wb') as f:
f.write(tflite_model)
✅ 若要壓縮模型大小與效能:
python
converter.optimizations = [tf.lite.Optimize.DEFAULT]
這段程式碼將訓練完成的 TensorFlow SavedModel 轉換為適用於行動裝置的 .tflite 格式,並儲存為檔案。透過 TFLiteConverter 將模型轉換後,若進一步設定 converter.optimizations = [tf.lite.Optimize.DEFAULT],即可啟用 TensorFlow Lite 的預設最佳化策略,進行模型壓縮與加速,例如使用權重量化,以減少模型大小並提升推論效率,特別適合部署於資源有限的 Android 或 iOS 裝置上。
________________________________________
🤖 第三步:部署到 Android App(Java/Kotlin)
1. 加入 Gradle 相依套件:
gradle
複製編輯
implementation 'org.tensorflow:tensorflow-lite:2.13.0'
2. 把 .tflite 模型放入 assets/ 資料夾
3. 使用 TensorFlow Lite 解譯器:
Interpreter tflite = new Interpreter(loadModelFile(context));
float[][] input = new float[1][784]; // MNIST 展平格式
float[][] output = new float[1][10];
tflite.run(input, output);
這段流程說明如何在 Android App 中整合 TensorFlow Lite 模型進行即時推論:首先在 build.gradle 加入 tensorflow-lite 相依套件,接著將 .tflite 模型檔案放入 assets/ 資料夾中,最後透過 Interpreter 載入模型並執行推論。以 MNIST 為例,將 28x28 的影像攤平成 784 維輸入向量,輸出為 10 類別的預測結果。這使得訓練好的模型能夠在手機端高效地執行,實現離線 AI 功能。
________________________________________
📲 第四步:iOS Swift 使用方式
使用 TensorFlowLiteSwift 套件即可在 iOS App 中推論 TFLite 模型,推薦搭配 CoreML 或 AVFoundation 做影像輸入。
________________________________________
🚀 延伸應用與優化技巧
TensorFlow Lite 模型在邊緣裝置上優化效能的關鍵工具:
量化(Quantization) 將原本的 float32 權重壓縮成 int8,不僅減少模型大小,也大幅提升推論速度;代表性資料集(Representative Dataset) 可在量化過程中提供實際樣本,進一步提升精度;TensorFlow Lite Delegate 可呼叫 GPU 或 Android 的 NNAPI 等硬體加速器,使模型運算更高效;若搭配 Google Coral 裝置,還能透過 Edge TPU 達到極速的離線推論效能,實現即時且省電的 AI 應用。
________________________________________
💡 結語:AI 進入手機時代
TensorFlow Lite 就像是 AI 模型的「壓縮打包工具 + 行動執行引擎」,讓你不再只能在伺服器跑模型,而是真正把 AI 帶入人們日常使用的手機、穿戴裝置、智能家居中。
AI 不只是雲端的夢想,也是掌上現實。