"""用差分均值估计 ARIMA(0,1,0) 的漂移,并与 statsmodels 对照。""" import json # NumPy 负责差分和评价,statsmodels 提供独立的状态空间对照,Matplotlib 用于读图。 import matplotlib.pyplot as plt import numpy as np from statsmodels.tsa.arima.model import ARIMA def main(): # 人工给定的等间隔教学读数。前 11 期拟合,最后 4 期评分。 observed = np.array([50, 52, 55, 56, 60, 62, 63, 66, 70, 71, 73, 77, 79, 80, 84], dtype=float) n_train = 11 train, test = observed[:n_train], observed[n_train:] # horizon 是从训练末期出发的步数,从 1 开始。NumPy 切片右端不包含。 horizon = np.arange(1, test.size + 1) # 长度为 11 的训练序列给出 10 个增量。拟合一个常数时,平方残差和 # 在样本均值处取得最小值;这里的创新方差按最大似然口径除以 10。 increments = np.diff(train) drift = increments.mean() variance = np.mean((increments - drift) ** 2) # 先预测每期增量,再累加回原尺度。两个方法均固定在第 11 期做四步预测。 prediction = train[-1] + horizon * drift naive = np.full(test.shape, train[-1]) mae = np.mean(np.abs(test - prediction)) naive_mae = np.mean(np.abs(test - naive)) # 原序列的线性时间趋势在一阶差分后成为漂移项。 # 状态空间求解器数值估计参数,可用手算结果检查本特例的点预测。 fit = ARIMA(train, order=(0, 1, 0), trend="t").fit(method="statespace") library_prediction = np.asarray(fit.forecast(steps=test.size)) np.testing.assert_allclose(library_prediction, prediction, atol=1e-3, rtol=0) # 左图虚线后是留出期,实测只供评分。右图比较十个训练增量及其平均值。 _, (curves, changes) = plt.subplots(1, 2, figsize=(10, 4), layout="constrained") curves.plot(np.arange(1, observed.size + 1), observed, "ko-", label="Observed") future_period = n_train + np.arange(test.size + 1) curves.plot(future_period, np.concatenate(([train[-1]], prediction)), "s--", label="ARIMA with drift") curves.plot(future_period, np.concatenate(([train[-1]], naive)), ":", label="Last value") curves.axvline(n_train + 0.5, linestyle="--", color="grey") curves.set(xlabel="Period", ylabel="Reading (units)") curves.legend() changes.stem(np.arange(2, n_train + 1), increments) changes.axhline(drift, linestyle="--", label="Mean increment") changes.set(xlabel="Period", ylabel="Change per period (units)") changes.legend() for axis in (curves, changes): axis.grid(alpha=0.25) # 将 NumPy 标量和数组转换为 JSON 类型,便于与 MATLAB 的输出逐项核对。 result = { "drift": float(drift), "innovation_variance": float(variance), "prediction": prediction.tolist(), "holdout_mae": float(mae), "naive_holdout_mae": float(naive_mae), } print("LAB_RESULT " + json.dumps(result)) plt.show() if __name__ == "__main__": main()