ARIMA航班预测模型报错:ValueError: endog需为1维却为2维
解决ARIMA模型的ValueError: endog is required to have ndim 1 but has ndim 2问题
嘿,我一眼就看出问题所在了——你现在给ARIMA模型喂的是多列数据,但ARIMA本质是单变量时间序列模型,它只接受一维的时间序列作为输入(也就是你要预测的Historical Flights这一列),而不是包含Year、GDP的多维数组,这才触发了这个维度不匹配的错误。
下面是具体的修正步骤和代码:
核心问题拆解
你代码里的X = df.iloc[:, :].values把整个DataFrame的三列都转成了二维数组(每一行是[Year, Historical Flights, Country GDP]),后续的train、test、history也都是二维结构,而ARIMA的endog参数要求必须是一维数组,这就直接导致了报错。
修正后的代码
from pandas import read_excel from statsmodels.tsa.arima.model import ARIMA from sklearn.metrics import mean_squared_error # 读取数据并保留需要的列 df = read_excel('dataset.xlsx') df = df[['Year', 'Historical Flights','Country GDP']] print(df.head()) # 只提取要预测的时间序列列——Historical Flights,转成一维数组 flight_series = df['Historical Flights'].values size = int(len(flight_series) * 0.66) train, test = flight_series[0:size], flight_series[size:len(flight_series)] # 初始化历史数据为训练集的一维数组 history = [x for x in train] predictions = list() for t in range(len(test)): # 传入一维的历史数据到ARIMA模型 model = ARIMA(history, order=(2,1,2)) model_fit = model.fit(disp=0) output = model_fit.forecast() yhat = output[0] predictions.append(yhat) # 只追加测试集中的航班量观测值(一维) obs = test[t] history.append(obs) print('predicted=%f, expected=%f' % (yhat, obs)) # 计算MSE时,测试集和预测值都是一维结构,匹配无误 error = mean_squared_error(test, predictions) print('Test MSE: %.3f' % error)
额外提示:如果要加入GDP作为外生变量
如果你想把Country GDP作为影响因素加入模型,那普通ARIMA就不够用了,需要用ARIMAX模型(带外生变量的ARIMA)。这时候你需要分别准备一维的因变量(航班量)和二维的外生变量(GDP),代码大致调整如下:
# 提取外生变量GDP exog_data = df['Country GDP'].values train_exog, test_exog = exog_data[0:size], exog_data[size:len(exog_data)] # 在模型中传入exog参数 model = ARIMA(history, order=(2,1,2), exog=train_exog[:len(history)]) model_fit = model.fit(disp=0) # 预测时也要传入对应测试步的外生变量 output = model_fit.forecast(exog=[test_exog[t]])
这样就能同时利用GDP数据来提升预测效果啦。
内容的提问来源于stack exchange,提问作者john smith




