1. 环境搭建与模型转换流程
任务目标
本案例完成TFLite开发环境搭建,并将一个Keras训练的全连接网络模型转换为TensorFlow Lite格式,验证转换结果可用于后续STM32部署。最终产出:.tflite模型文件及转换流程验证结论。
环境依赖
- Python 3.8+,安装TensorFlow 2.x(CPU版即可):
pip install tensorflow==2.13.0 - STM32部署所需:STM32CubeMX、X-CUBE-AI扩展包(本案例仅完成模型转换,不涉及烧录)
完整实现代码
import tensorflow as tf
import numpy as np
# 1. 生成简单数据集:y = 2x + 1
x_train = np.array([1.0, 2.0, 3.0, 4.0, 5.0], dtype=np.float32)
y_train = np.array([3.0, 5.0, 7.0, 9.0, 11.0], dtype=np.float32)
# 2. 构建并训练Keras模型
model = tf.keras.Sequential([
tf.keras.layers.Dense(1, input_shape=[1])
])
model.compile(optimizer='sgd', loss='mse')
model.fit(x_train, y_train, epochs=200, verbose=0)
# 3. 转换为TFLite模型
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
# 4. 保存模型文件
with open('linear_model.tflite', 'wb') as f:
f.write(tflite_model)
# 5. 验证转换结果
interpreter = tf.lite.Interpreter(model_path='linear_model.tflite')
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# 输入输出张量形状验证
assert input_details[0]['shape'].tolist() == [1, 1], "输入形状应为[1,1]"
assert output_details[0]['shape'].tolist() == [1, 1], "输出形状应为[1,1]"
# 推理验证:输入x=6,预期输出接近13
test_input = np.array([[6.0]], dtype=np.float32)
interpreter.set_tensor(input_details[0]['index'], test_input)
interpreter.invoke()
output = interpreter.get_tensor(output_details[0]['index'])
print(f"输入x=6,模型输出: {output[0][0]:.4f}")
# 6. 量化信息检查(确认当前为float32模型)
quant_params = input_details[0].get('quantization', None)
print(f"量化参数: {quant_params}")
print("模型转换与验证完成")
运行方式
python tflite_convert_demo.py
验证方法与通过条件
- 文件生成:当前目录出现
linear_model.tflite文件,大小约数百字节至1KB。 - 形状断言:脚本中两个assert通过,无异常抛出。
- 推理输出:控制台打印的输出值接近13.0(误差在±0.5内视为正常,因训练随机性)。
- 量化参数:打印结果为
(0, 0)或None,表示当前为float32模型,可直接用于X-CUBE-AI后续量化部署。
STM32部署接入说明
将生成的linear_model.tflite导入STM32CubeMX中的X-CUBE-AI扩展,选择STM32目标芯片后执行Analyze,确认RAM/Flash占用满足芯片资源即可生成C代码工程。本案例不涉及具体烧录与板级验证。
常见问题
- TensorFlow版本不兼容:若
from_keras_model报错,确认使用TF 2.x而非1.x。 - 模型输入形状:STM32端调用时输入必须为
[1,1]的float32数组,否则推理结果异常。 - 量化必要性:当前float32模型在STM32F4系列可直接运行,若芯片Flash小于256KB,需在转换时添加
converter.optimizations = [tf.lite.Optimize.DEFAULT]进行int8量化。