1. 环境搭建与模型转换流程
任务目标
本案例完成两项核心工作:搭建STM32模型部署所需的PC端软件环境,并将一个TensorFlow Keras模型转换为TensorFlow Lite格式。转换后的.tflite文件将作为后续STM32工程部署的输入模型。
环境需求
- Python 3.8~3.11(推荐3.10)
- TensorFlow 2.13(CPU版即可)
- STM32CubeMX(用于生成STM32工程框架,本案例仅验证环境连通性)
- STM32CubeIDE 或 Keil MDK(编译烧录工具,本案例不涉及具体硬件代码)
环境安装命令
# 创建虚拟环境(可选但推荐)
python -m venv tflite_env
# Windows激活: tflite_env\Scripts\activate
# Linux/Mac激活: source tflite_env/bin/activate
# 安装TensorFlow CPU版
pip install tensorflow-cpu==2.13.0
# 验证安装
python -c "import tensorflow as tf; print(tf.__version__)"
模型转换完整代码
以下代码创建一个简单的正弦波拟合模型(全连接网络),训练后转换为TFLite格式,并验证转换结果。
import numpy as np
import tensorflow as tf
from tensorflow import keras
# 1. 生成训练数据:y = sin(x)
x_train = np.linspace(0, 2*np.pi, 1000, dtype=np.float32).reshape(-1, 1)
y_train = np.sin(x_train).astype(np.float32)
# 2. 构建简单全连接模型
model = keras.Sequential([
keras.layers.Dense(32, activation='relu', input_shape=(1,)),
keras.layers.Dense(32, activation='relu'),
keras.layers.Dense(1)
])
model.compile(optimizer='adam', loss='mse')
# 3. 训练模型(少量epoch即可)
model.fit(x_train, y_train, epochs=50, verbose=0)
# 4. 转换为TFLite
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
# 5. 保存.tflite文件
with open('sine_model.tflite', 'wb') as f:
f.write(tflite_model)
# 6. 验证转换结果
interpreter = tf.lite.Interpreter(model_path='sine_model.tflite')
interpreter.allocate_tensors()
# 获取输入输出详情
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
print(f"输入shape: {input_details[0]['shape']}")
print(f"输出shape: {output_details[0]['shape']}")
print(f"输入dtype: {input_details[0]['dtype']}")
# 7. 测试推理一致性
test_input = np.array([[1.0]], dtype=np.float32)
interpreter.set_tensor(input_details[0]['index'], test_input)
interpreter.invoke()
tflite_output = interpreter.get_tensor(output_details[0]['index'])
# 与原始Keras模型对比
keras_output = model.predict(test_input, verbose=0)
print(f"TFLite输出: {tflite_output[0][0]:.6f}")
print(f"Keras输出: {keras_output[0][0]:.6f}")
print(f"误差: {abs(tflite_output[0][0] - keras_output[0][0]):.6f}")
运行方式
# 将上述代码保存为 convert_tflite.py
python convert_tflite.py
验证方法与通过条件
- 环境验证:TensorFlow成功导入且版本号为2.13.x。
- 转换验证:当前目录生成
sine_model.tflite文件,文件大小通常为1~3KB。 - 一致性验证:控制台输出的TFLite推理结果与Keras模型推理结果误差小于0.001,说明转换后模型精度未发生明显损失。
- 部署前置验证:输入shape为
[1, 1],dtype为float32,该信息将用于后续STM32工程的TensorFlow Lite for Microcontrollers配置。
常见问题
- 转换报错:若提示缺少
keras,执行pip install keras==2.13.1;若提示numpy版本冲突,执行pip install numpy==1.24.3。 - STM32CubeMX集成说明:本案例生成的
sine_model.tflite文件,后续在STM32CubeMX中通过X-CUBE-AI扩展包或TensorFlow Lite for Microcontrollers库导入,即可生成C数组或调用解释器进行推理。该步骤属于后续案例内容,本案例仅完成模型准备。