别再死记硬背ARIMA了用Python从零到一手把手教你搞定时间序列预测附完整代码时间序列预测是数据分析领域的核心技能之一但很多初学者在面对ARIMA模型时往往被p、d、q这些参数搞得晕头转向。本文将用Python代码带你一步步完成从数据预处理到预测的全流程让你真正理解每个步骤背后的逻辑而不仅仅是死记硬背公式。1. 环境准备与数据加载在开始之前我们需要确保安装了必要的Python库。打开你的Jupyter Notebook或Python环境运行以下命令!pip install statsmodels pandas numpy matplotlib接下来我们加载一个示例数据集。这里使用经典的航空乘客数据集它记录了1949-1960年间每月的航空乘客数量import pandas as pd import matplotlib.pyplot as plt from statsmodels.datasets import get_rdataset # 加载数据集 data get_rdataset(AirPassengers).data data[date] pd.to_datetime(data[time], format%Y.%m) data.set_index(date, inplaceTrue) ts data[value] # 可视化数据 plt.figure(figsize(12,6)) plt.plot(ts) plt.title(Monthly Airline Passengers (1949-1960)) plt.xlabel(Date) plt.ylabel(Passengers) plt.grid(True) plt.show()这段代码会输出一个时间序列图你可以清楚地看到数据有明显的上升趋势和季节性波动。这正是我们需要用ARIMA模型来解决的问题。2. 平稳性检验与差分处理ARIMA模型要求时间序列是平稳的。我们可以通过ADF检验来验证数据的平稳性from statsmodels.tsa.stattools import adfuller def test_stationarity(timeseries): # 执行ADF检验 print(ADF检验结果:) dftest adfuller(timeseries, autolagAIC) dfoutput pd.Series(dftest[0:4], index[Test Statistic,p-value,#Lags Used,Number of Observations Used]) for key,value in dftest[4].items(): dfoutput[Critical Value (%s)%key] value print(dfoutput) # 可视化滚动统计量 rolmean timeseries.rolling(window12).mean() rolstd timeseries.rolling(window12).std() plt.figure(figsize(12,6)) orig plt.plot(timeseries, colorblue, labelOriginal) mean plt.plot(rolmean, colorred, labelRolling Mean) std plt.plot(rolstd, colorblack, labelRolling Std) plt.legend(locbest) plt.title(Rolling Mean Standard Deviation) plt.show() test_stationarity(ts)如果p值大于0.05通常的显著性水平我们就需要差分处理。对于有明显趋势的数据一阶差分通常就足够了# 一阶差分 ts_diff ts.diff().dropna() test_stationarity(ts_diff)如果仍然不平稳可以尝试二阶差分。但要注意过度差分会导致信息损失。3. 确定ARIMA模型的p、d、q参数确定ARIMA模型的参数是建模中最具挑战性的部分。我们可以通过以下方法d参数通过差分次数确定我们已经通过平稳性检验确定了d1p和q参数可以通过ACF和PACF图来初步判断from statsmodels.graphics.tsaplots import plot_acf, plot_pacf plt.figure(figsize(12,8)) plt.subplot(211) plot_acf(ts_diff, lags40, axplt.gca()) plt.subplot(212) plot_pacf(ts_diff, lags40, axplt.gca()) plt.show()ACF和PACF图可以帮助我们初步判断p和q的值但更可靠的方法是使用网格搜索寻找AIC最小的组合import itertools import warnings from statsmodels.tsa.arima.model import ARIMA # 定义p、d、q的取值范围 p range(0, 3) d range(1, 2) q range(0, 3) # 生成所有可能的(p,d,q)组合 pdq list(itertools.product(p, d, q)) # 忽略警告信息 warnings.filterwarnings(ignore) best_aic float(inf) best_pdq None for param in pdq: try: model ARIMA(ts, orderparam) results model.fit() if results.aic best_aic: best_aic results.aic best_pdq param except: continue print(f最佳ARIMA参数: {best_pdq}, AIC: {best_aic})4. 模型训练与预测确定了最佳参数后我们就可以训练模型并进行预测了# 使用最佳参数训练模型 model ARIMA(ts, orderbest_pdq) results model.fit() # 打印模型摘要 print(results.summary()) # 绘制诊断图 results.plot_diagnostics(figsize(12,8)) plt.show()诊断图可以帮助我们评估模型的质量。理想情况下标准化残差应该没有明显的趋势直方图加上估计密度曲线应该近似于正态分布正态Q-Q图应该大致沿着直线分布相关图(右下)应该显示没有显著的自相关现在我们可以用训练好的模型进行预测# 预测未来24个月的数据 forecast results.get_forecast(steps24) forecast_index pd.date_range(ts.index[-1], periods25, freqM)[1:] forecast_values forecast.predicted_mean confidence_intervals forecast.conf_int() # 可视化预测结果 plt.figure(figsize(12,6)) plt.plot(ts, labelObserved) plt.plot(forecast_index, forecast_values, colorr, labelForecast) plt.fill_between(forecast_index, confidence_intervals.iloc[:,0], confidence_intervals.iloc[:,1], colorpink, alpha0.3) plt.title(AirPassengers Forecast) plt.xlabel(Date) plt.ylabel(Passengers) plt.legend() plt.grid(True) plt.show()5. 模型评估与改进为了评估模型的预测效果我们可以将数据集分为训练集和测试集# 分割数据集 train ts[:1958-12-31] test ts[1959-01-31:] # 在训练集上训练模型 model ARIMA(train, orderbest_pdq) results model.fit() # 预测测试集 forecast results.get_forecast(stepslen(test)) forecast_values forecast.predicted_mean confidence_intervals forecast.conf_int() # 计算RMSE from sklearn.metrics import mean_squared_error import numpy as np rmse np.sqrt(mean_squared_error(test, forecast_values)) print(fRMSE: {rmse}) # 可视化预测效果 plt.figure(figsize(12,6)) plt.plot(train, labelTraining) plt.plot(test, labelActual) plt.plot(test.index, forecast_values, colorr, labelPredicted) plt.fill_between(test.index, confidence_intervals.iloc[:,0], confidence_intervals.iloc[:,1], colorpink, alpha0.3) plt.title(ARIMA Model Evaluation) plt.xlabel(Date) plt.ylabel(Passengers) plt.legend() plt.grid(True) plt.show()如果发现模型表现不佳可以考虑以下改进方法尝试季节性ARIMA(SARIMA)模型添加外部变量尝试其他时间序列模型如Prophet6. 季节性ARIMA(SARIMA)模型对于有明显季节性的数据标准的ARIMA模型可能不够。我们可以使用SARIMA模型from statsmodels.tsa.statespace.sarimax import SARIMAX # 定义SARIMA参数 order best_pdq # 非季节性部分 seasonal_order (1, 1, 1, 12) # 季节性部分(P,D,Q,s) # 训练模型 model SARIMAX(ts, orderorder, seasonal_orderseasonal_order) results model.fit() # 预测 forecast results.get_forecast(steps24) forecast_values forecast.predicted_mean confidence_intervals forecast.conf_int() # 可视化 plt.figure(figsize(12,6)) plt.plot(ts, labelObserved) plt.plot(forecast_values.index, forecast_values, colorr, labelForecast) plt.fill_between(forecast_values.index, confidence_intervals.iloc[:,0], confidence_intervals.iloc[:,1], colorpink, alpha0.3) plt.title(SARIMA Forecast for AirPassengers) plt.xlabel(Date) plt.ylabel(Passengers) plt.legend() plt.grid(True) plt.show()SARIMA模型的参数选择更为复杂通常需要结合ACF/PACF图和网格搜索来确定最佳参数组合。