TensorFlow Lite 上手教程
关联项目:TensorFlow Lite
前置要求:Python 3.9+;熟悉 TensorFlow / Keras 基础;了解量化与移动端部署的基本概念。
预计耗时:环境安装约 15 分钟;跑通一次转换与推理约 30 分钟。
官方仓库:github.com/tensorflow/tensorflow
本教程带你完成从环境准备到跑通核心工作流的完整过程。命令与示例针对主流环境给出,实际版本参数请以官方文档为准。
一、环境准备
推荐 Python 3.9–3.11,安装完整 TensorFlow(含 TFLite Converter):
python -m pip install --upgrade pip
pip install "tensorflow>=2.15"
python -c "import tensorflow as tf; print(tf.__version__)"
只部署、不转换模型时可尝试轻量运行时(包名与平台支持以官方文档为准):
pip install tflite-runtime
二、安装部署
验证解释器可用:
python -c "import tensorflow as tf; print(hasattr(tf.lite, 'Interpreter'))"
预期输出:True;无报错即表示 TFLite 组件可用。
三、快速上手:跑通第一个示例
转换一个最小 Keras 模型并推理:
import numpy as np
import tensorflow as tf
model = tf.keras.Sequential([tf.keras.Input(shape=(3,)), tf.keras.layers.Dense(1)])
model.save("saved_model_dir")
converter = tf.lite.TFLiteConverter.from_saved_model("saved_model_dir")
tflite_model = converter.convert()
with open("model.tflite", "wb") as f:
f.write(tflite_model)
interpreter = tf.lite.Interpreter(model_path="model.tflite")
interpreter.allocate_tensors()
inp = interpreter.get_input_details()[0]
out = interpreter.get_output_details()[0]
x = np.zeros(inp["shape"], dtype=inp["dtype"])
interpreter.set_tensor(inp["index"], x)
interpreter.invoke()
print(interpreter.get_tensor(out["index"]))
from_saved_model() 指定输入模型;allocate_tensors() 分配张量内存;输入/输出的 shape 与 dtype 一律从 get_input_details() 读取,避免硬编码。
四、核心工作流
任务:把一个分类模型量化为 INT8 并验证推理
- 准备 SavedModel:复用
t_quickstart中的model.save("saved_model_dir")。 - 开启默认量化并绑定代表性样本(样本形状与真实输入一致):
converter = tf.lite.TFLiteConverter.from_saved_model("saved_model_dir")
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.representative_dataset = lambda: (
np.zeros((1, 3), dtype=np.float32) for _ in range(10)
)
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.int8
converter.inference_output_type = tf.int8
with open("model_int8.tflite", "wb") as f:
f.write(converter.convert())
预期结果:生成 model_int8.tflite,体积通常小于浮点版本。
3. 验证输入输出 dtype:interpreter.get_input_details()[0]["dtype"] 应为 np.int8。
4. Android 集成:在 Gradle 中加入 org.tensorflow:tensorflow-lite 依赖,版本以官方文档为准。
5. 性能调优:按设备选择 NNAPI / GPU delegate,可用性与参数以官方文档为准。
6. 迁移评估:新功能开发改用 LiteRT,按官方文档的迁移说明重新转换模型。
五、进阶实践
- 训练后量化:
converter.optimizations = [tf.lite.Optimize.DEFAULT],可选 FP16 / INT8(以官方文档为准)。 - 自定义算子:
converter.target_spec.supported_ops加入tf.lite.OpsSet.SELECT_TF_OPS。 - 微控制器部署:用
xxd -i model.tflite > model.cc把模型转成 C 数组后编译进固件。 - GPU 委托:通过
tf.lite.experimental.load_delegate(...)加载,委托库路径以官方文档为准。 - 迁移到 LiteRT:使用 Compiled Model API 与 LiteRT 工具链,接口以官方文档为准。
六、常见问题
Q:新项目还能直接用 TensorFlow Lite 吗? A:官方 LiteRT README 建议新项目优先 LiteRT;TFLite 已进入维护模式。
Q:tensorflow/lite/ 维护模式意味着什么?
A:仅修复安全与稳定性问题,不再接受新特性,存量系统仍可稳定运行。
Q:仓库地址是哪一个?
A:TFLite 在 tensorflow/tensorflow;LiteRT 在 google-ai-edge/LiteRT,用户给出的组织页不是仓库。
Q:转换时报 unsupported op 怎么办?
A:启用 SELECT_TF_OPS、实现自定义算子,或改写模型;也可评估 LiteRT 的转换路径。