"""用时间有序的验证窗口选择简单指数平滑的系数。""" import json # NumPy 用按列数组并行处理多个系数,Matplotlib 展示预测轨迹和验证误差。 import matplotlib.pyplot as plt import numpy as np def main(): # 前 8 期用于初始化和更新水平。随后用 4 期选参数、4 期评分。 orders = np.array([20, 22, 21, 19, 20, 24, 23, 22, 21, 26, 25, 24, 23, 25, 22, 24], dtype=float) alpha = np.array([0.2, 0.5, 0.8]) # 0 起始且不含右端,slice(8, 12) 对应业务期次 9 到 12。 validation = slice(8, 12) test = slice(12, 16) # 每列是一种 alpha。在读入当天订单前,先保存对当天的预测。 # 首期只有初始水平,预测留空。alpha 越大,水平越跟随最新订单。 level = np.full(alpha.shape, orders[0]) prediction = np.full((orders.size, alpha.size), np.nan) for t in range(1, orders.size): prediction[t, :] = level level = alpha * orders[t] + (1 - alpha) * level # 加一个长度为 1 的列维,使每期观测与各种 alpha 的预测逐列相减。 # 取 axis=0 上的均值后,每个 alpha 得到一个验证 MAE。 validation_mae = np.mean(np.abs(orders[validation, None] - prediction[validation]), axis=0) selected = int(np.argmin(validation_mae)) test_prediction = prediction[test, selected] # 上期值基线使用完全相同的四个测试目标期。 last_observation = orders[test.start - 1:test.stop - 1] test_mae = np.mean(np.abs(orders[test] - test_prediction)) naive_mae = np.mean(np.abs(orders[test] - last_observation)) # 左图竖线分开训练、验证和测试阶段。右图展示选参时实际使用的三个分数。 _, (curves, scores) = plt.subplots(1, 2, figsize=(10, 4), layout="constrained") period = np.arange(1, orders.size + 1) curves.plot(period, orders, "k.-", label="Observed") for i, coefficient in enumerate(alpha): curves.plot(period[1:], prediction[1:, i], ".-", label=f"alpha = {coefficient:.2f}") curves.axvline(8.5, linestyle="--", color="grey") curves.axvline(12.5, linestyle="--", color="grey") curves.set(xlabel="Period", ylabel="Orders") curves.legend() curves.grid(alpha=0.25) scores.bar([f"{value:.2f}" for value in alpha], validation_mae) scores.set(xlabel="Smoothing parameter", ylabel="Validation MAE (orders)") scores.grid(axis="y", alpha=0.25) # level 已吸收最后一期实测,预测的是第 17 期。 result = { "alpha_candidates": alpha.tolist(), "validation_mae": validation_mae.tolist(), "selected_alpha": float(alpha[selected]), "test_prediction": test_prediction.tolist(), "test_mae": float(test_mae), "naive_test_mae": float(naive_mae), "next_prediction": float(level[selected]), } print("LAB_RESULT " + json.dumps(result)) plt.show() if __name__ == "__main__": main()