"""在模拟需求上计算 GM(1,1),预测期包含设计好的减速情形。""" import json # NumPy 算累加、最小二乘与误差,Matplotlib 对比相同起点的曲线。 import matplotlib.pyplot as plt import numpy as np def main(): # 用四期稳定增长记录拟合,之后的四期只用于评分。 observed = np.array([10, 12, 14.4, 17.28, 20.1, 23.3, 25.0, 25.4]) n_train = 4 train, test = observed[:n_train], observed[n_train:] horizon = np.arange(1, test.size + 1) # 一次累加降低相对波动,以相邻累加值的均值作为背景值。 cumulative = np.cumsum(train) background = 0.5 * (cumulative[:-1] + cumulative[1:]) # 设计矩阵每行是 [-z(k), 1],目标为第 2 到 4 期的观测。 # lstsq 的第一个返回值是最小化原差分方程平方残差的 [a, b]。 design = np.column_stack((-background, np.ones(background.size))) a, b = np.linalg.lstsq(design, train[1:], rcond=None)[0] # 对响应式作差得到原尺度预测。expm1 避免 a 接近零时的相消。 response_factor = -np.expm1(-a) / a if a != 0 else 1.0 period = np.arange(1, observed.size + 1) # 首期由初值给定。其余各期原尺度估计按比例 exp(-a) 变化。 fitted = np.concatenate(( [train[0]], (b - a * train[0]) * response_factor * np.exp(-a * (period[1:] - 2)), )) prediction = fitted[n_train:] # 同一预测起点。留出期实测不参与任何一种方法的预测。 flat = np.full(test.shape, train[-1]) linear = train[-1] + horizon * np.mean(np.diff(train)) gm_error = np.abs(test - prediction) naive_error = np.abs(test - flat) linear_error = np.abs(test - linear) # 左图对比外推水平,右图逐步比较误差,避免四步平均掩盖后期外推偏差。 _, (curves, scores) = plt.subplots(1, 2, figsize=(10, 4), layout="constrained") curves.plot(period, observed, "ko-", label="Observed") curves.plot(period, fitted, "s--", label="GM(1,1)") curves.plot(n_train + horizon, flat, ":", label="Last value") curves.plot(n_train + horizon, linear, ".-.", label="Linear drift") curves.axvline(n_train + 0.5, linestyle="--", color="grey") curves.set(xlabel="Period", ylabel="Demand (units)") width = 0.25 scores.bar(horizon - width, gm_error, width, label="GM(1,1)") scores.bar(horizon, naive_error, width, label="Last value") scores.bar(horizon + width, linear_error, width, label="Linear drift") scores.set(xlabel="Forecast horizon", ylabel="Absolute error (units)", xticks=horizon) for axis in (curves, scores): axis.grid(alpha=0.25) axis.legend() result = { "a": float(a), "b": float(b), "background": background.tolist(), "prediction": prediction.tolist(), "gm_mae": float(gm_error.mean()), "naive_mae": float(naive_error.mean()), "linear_mae": float(linear_error.mean()), } print("LAB_RESULT " + json.dumps(result)) plt.show() if __name__ == "__main__": main()