3. Hello World 模型:训练一个简单的正弦波预测模型,导出为 TFLite 格式
各位同学,欢迎来到第三章。
这一章,我们来做一件很有意思的事——训练一个能预测正弦波的模型。你可能会问,正弦波这么简单的东西,还需要用深度学习?嗯,别小看它。这个模型虽然小,但它完整走通了「数据准备 → 模型训练 → 导出 TFLite」的整个流程。说白了,它就是嵌入式 AI 领域的「Hello World」。
我个人习惯,每接触一个新平台,先跑通这个例子。为什么?因为它能帮你快速验证工具链是否正常,也能让你对模型量化和部署有个直观感受。我在项目中遇到过不少新手,一上来就搞复杂的图像分类,结果被各种坑卡住,最后连模型都导不出来。所以,咱们还是老老实实从正弦波开始。
3.1 为什么是正弦波?
正弦波有一个很好的特性:它是连续的、平滑的、有规律的。我们训练一个神经网络,让它学会根据输入的时间点,预测对应的正弦值。这本质上是一个回归问题。
你想想看,如果连这种简单的函数拟合都做不好,那更复杂的任务就更别想了。而且,正弦波模型很小,参数量通常只有几百个,非常适合在微控制器上运行。我记得第一次在 STM32 上跑通这个模型时,看到 LED 按照预测值呼吸闪烁,那种感觉,真的很奇妙。
3.2 数据准备
数据是模型的粮食。我们先来生成训练数据。
这里有个小技巧:不要直接用原始的时间点,而是把输入归一化到 0 到 2π 之间。这样模型更容易收敛。
import numpy as np
import matplotlib.pyplot as plt
# 生成训练数据
x_values = np.linspace(0, 2 * np.pi, 1000)
y_values = np.sin(x_values)
# 划分训练集和验证集
split = int(0.8 * len(x_values))
x_train, x_val = x_values[:split], x_values[split:]
y_train, y_val = y_values[:split], y_values[split:]
# 归一化输入(其实这里已经是 0~2π,但为了通用性,我们缩放到 0~1)
x_train = x_train / (2 * np.pi)
x_val = x_val / (2 * np.pi)
print(f"训练样本数: {len(x_train)}")
print(f"验证样本数: {len(x_val)}")
为什么要归一化?因为神经网络的激活函数(比如 ReLU、tanh)对输入范围很敏感。如果不归一化,数值大的特征会主导梯度更新,导致训练不稳定。我曾经见过有人直接用原始时间戳训练,结果 loss 死活降不下去,归一化后立马收敛。
3.3 构建模型
模型结构很简单:一个输入层,两个隐藏层,一个输出层。激活函数用 ReLU,输出层用线性激活(因为是回归任务)。
import tensorflow as tf
from tensorflow.keras import layers, models
model = models.Sequential([
layers.Dense(16, activation='relu', input_shape=(1,)),
layers.Dense(16, activation='relu'),
layers.Dense(1) # 线性输出
])
model.compile(optimizer='adam', loss='mse', metrics=['mae'])
model.summary()
这个模型只有 16×16 + 16×1 = 272 个参数,加上偏置,总共不到 300 个参数。你想想看,这么小的模型,在微控制器上跑起来几乎不费吹灰之力。
3.4 训练模型
训练过程没什么特别的。我们用 MSE 作为损失函数,训练 500 个 epoch。为什么是 500?因为模型小,训练很快,500 个 epoch 也就几秒钟。
history = model.fit(
x_train, y_train,
validation_data=(x_val, y_val),
epochs=500,
verbose=0 # 不打印每个 epoch 的日志
)
# 画个 loss 曲线看看
plt.plot(history.history['loss'], label='train_loss')
plt.plot(history.history['val_loss'], label='val_loss')
plt.legend()
plt.show()
训练完成后,你可以用模型预测一下,看看效果如何。
# 预测
x_test = np.linspace(0, 1, 100) # 注意输入是归一化后的
y_pred = model.predict(x_test)
# 反归一化(其实不需要,因为输出本来就是 -1~1)
plt.plot(x_test * 2 * np.pi, np.sin(x_test * 2 * np.pi), label='真实值')
plt.plot(x_test * 2 * np.pi, y_pred, label='预测值', linestyle='--')
plt.legend()
plt.show()
如果两条曲线几乎重合,恭喜你,模型训练成功了。
3.5 导出为 TFLite 格式
这是本章的重头戏。我们要把训练好的模型导出为 TensorFlow Lite 格式,并且进行 int8 量化。
为什么要量化?因为微控制器通常没有浮点运算单元(FPU),或者 FPU 性能很弱。int8 运算比 float32 快 4 倍以上,而且模型体积缩小 4 倍。代价是精度会有一点损失,但对于正弦波预测这种任务,完全够用。
# 转换为 TFLite 格式
converter = tf.lite.TFLiteConverter.from_keras_model(model)
# 配置量化
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.representative_dataset = lambda: [x_train[0:100]] # 取前100个样本作为校准集
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.int8
converter.inference_output_type = tf.int8
tflite_model = converter.convert()
# 保存模型
with open('sine_model_quantized.tflite', 'wb') as f:
f.write(tflite_model)
print(f"量化模型大小: {len(tflite_model)} bytes")
导出的模型通常只有 1KB 左右。你没看错,就是 1KB。这就是量化的威力。
3.6 验证量化模型
导出之后,一定要验证一下量化模型的精度。我见过有人导出模型后直接部署,结果发现预测值完全不对,最后排查发现是量化参数设置错了。
# 加载量化模型
interpreter = tf.lite.Interpreter(model_content=tflite_model)
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# 获取量化参数
input_scale, input_zero_point = input_details[0]['quantization']
output_scale, output_zero_point = output_details[0]['quantization']
# 准备测试数据
x_test_quant = (x_test / input_scale + input_zero_point).astype(np.int8)
# 推理
interpreter.set_tensor(input_details[0]['index'], x_test_quant.reshape(-1, 1))
interpreter.invoke()
y_pred_quant = interpreter.get_tensor(output_details[0]['index'])
# 反量化
y_pred = (y_pred_quant.astype(np.float32) - output_zero_point) * output_scale
# 计算误差
mse = np.mean((np.sin(x_test * 2 * np.pi) - y_pred.flatten()) ** 2)
print(f"量化模型 MSE: {mse:.6f}")
如果 MSE 小于 0.001,说明量化精度损失在可接受范围内。
3.7 知识体系总览
下面这张图展示了本章的核心逻辑。从数据生成到模型训练,再到量化导出,最后验证,每一步都有它的意义。
3.8 避坑指南
最后,分享几个我踩过的坑。
- 量化校准集不够:我曾经只用 10 个样本做校准,结果量化后的模型在波峰和波谷处误差很大。后来改用 100 个样本,问题就解决了。
- 输入输出类型不匹配:导出时指定了 int8,但部署时忘了处理量化参数,导致输入值直接当 float 用。嗯,这个坑我踩了两次。
- 训练 epoch 太多导致过拟合:虽然正弦波很简单,但如果模型太大(比如 64 个神经元),训练 1000 个 epoch 后,验证集 loss 反而上升。建议用 early stopping。
xxd -i sine_model_quantized.tflite 命令把模型转成 C 数组,方便在嵌入式代码中直接包含。这个我们下一章会详细讲。
好了,这一章的内容就到这里。你现在应该能独立完成一个正弦波预测模型的训练和量化导出了。记住,这个流程是通用的,以后无论做什么模型,都离不开这几步。