python - 如何修复 ARIMA 模型中的以下错误?
问题描述
我已经建立了 ARIMA 模型来预测我的时间序列数据。单击此链接访问数据文件。
我的代码中几乎没有错误。
代码:
import pandas as pd
import seaborn as sb
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
data = pd .read_csv('datasets/car_sales.csv')
print(data.head())
data['Month']= pd.to_datetime(data['Month'], infer_datetime_format = True)
indexed_data = data.set_index(['Month'])
print(indexed_data.head())
fig, ax = plt.subplots(figsize = (8,6))
sb.lineplot(data = indexed_data, ax = ax)
plt.show()
#define a function to check stationarity of the data (rolling stats and Dickey-fuller tst)
def test_stationary(timeseries):
#Determing rolling statistics
moving_avg = timeseries.rolling(window=12).mean()
moving_std = timeseries.rolling(window=12).std()
#Plot rolling statistics:
fig, ax = plt.subplots(figsize = (10,4))
sb.lineplot(data = timeseries, legend = False, label = 'Original')
sb.lineplot(data = moving_avg, palette = ['red'], legend = False, label = 'Rollmean')
sb.lineplot(data = moving_std, palette = ['black'], legend = False, label = 'Rollstd')
plt.title('Rolling statistics to check stationarity')
plt.legend(loc='best')
plt.show()
#Perform Dickey-Fuller test:
from statsmodels.tsa.stattools import adfuller
print('Results of Dickey-Fuller Test:')
dftest = adfuller(timeseries, autolag='AIC')
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)
test_stationary(indexed_data)
# data is non stationary, Therefore we have to make it stationary
# apply differencing technique to make the data stationary
data_log = np.log(indexed_data)
data_log_diff = data_log - data_log.shift()
data_log_diff.dropna(inplace = True)
test_stationary(data_log_diff)
# we observe the data is stationary and can be used for prediction
# prediction is done using ARIMA
# let us plot ACF and PACF to determine p and q parameters for ARIMA model
from statsmodels.tsa.stattools import acf, pacf
lag_acf = acf(data_log_diff, nlags=20, fft=True)
lag_pacf = pacf(data_log_diff, nlags=20, method='ols')
#Plot ACF:
fig, ax = plt.subplots(figsize = (10,6))
sb.lineplot(data = lag_acf, ax = ax)
ax.set_xticks(range(1,len(lag_acf)))#Plot PACF:
fig, ax = plt.subplots(figsize = (10,6))
sb.lineplot(data = lag_pacf, ax = ax)
ax.set_xticks(range(1,len(lag_pacf)))
plt.axhline(y=0,linestyle='--',color='gray')
plt.axhline(y=-1.96/np.sqrt(len(data_log_diff)),linestyle='--',color='gray')
plt.axhline(y=1.96/np.sqrt(len(data_log_diff)),linestyle='--',color='gray')
plt.title('Partial Autocorrelation Function')
plt.show()
#Plot PACF:
fig, ax = plt.subplots(figsize = (10,6))
sb.lineplot(data = lag_pacf, ax = ax)
ax.set_xticks(range(1,len(lag_pacf)))
plt.axhline(y=0,linestyle='--',color='gray')
plt.axhline(y=-1.96/np.sqrt(len(data_log_diff)),linestyle='--',color='gray')
plt.axhline(y=1.96/np.sqrt(len(data_log_diff)),linestyle='--',color='gray')
plt.title('Partial Autocorrelation Function')
plt.show()
# based on acf and pacf plots the ARMA parameter can be p = 1, q = 1
#ARIMA model for data
from statsmodels.tsa.arima_model import ARIMA
model = ARIMA(data_log, order=(1, 1, 0))
results_ARIMA = model.fit(disp = -1)
plt.plot(data_log_diff)
plt.plot(results_ARIMA.fittedvalues, color='red')
plt.title('RSS: %.4f'% sum((results_ARIMA.fittedvalues-data_log_diff)**2))
当我运行上面的代码时,我遇到了以下错误:
根据 acf 和 pacf 图,发现 p 和 q 参数为 p=1 和 q=1。但是我的 arima 模型不起作用。
(我得到 ValueError:计算的初始 MA 系数不可逆您应该诱导可逆性,选择不同的模型顺序,或者您可以传递自己的 start_params。)对于 p=1,q=1。相反,它适用于 p=1,q=0。
p=1, q=1 参数值有什么问题?
我收到警告:
C:\ProgramData\Anaconda3\lib\site-packages\statsmodels\tsa\base\tsa_model.py:162:ValueWarning:未提供频率信息,因此将使用推断频率 MS。% freq, ValueWarning) C:\ProgramData\Anaconda3\lib\site-packages\statsmodels\tsa\base\tsa_model.py:162:ValueWarning:未提供频率信息,因此将使用推断频率 MS。% 频率,值警告)
这个警告的原因是什么,我该如何解决?
我收到参数 p=1、q=0 的错误。该错误与绘制 RSS 值一致
TypeError Traceback(最近一次调用最后一次)
----> 6 plt.title('RSS: %.4f'% sum((results_ARIMA.fittedvalues-data_log_diff)**2))
TypeError:不再支持带时间戳的整数和整数数组的加法/减法。而不是加/减
n
,使用 `n * obj.freq如何修复此错误?
解决方案
在statsmodel 的 ARIMA 模型中,参数顺序是(p,d,q)。您的参数顺序是错误的。正确的顺序是 (1,0,1)。
model = ARIMA(data_log, order=(1, 0, 1))
推荐阅读
- python-3.x - 在不删除数据库的情况下关闭 django dev 项目的正确方法是什么
- vba - 是否可以从 MDL 文件中提取源代码?
- dialogflow-es - 什么是行动项目的ClientID
- python - 与其他一些语言相比,为什么 Python JSON 序列化如此“参与”
- html - 如何在 CSS 中创建水平居中的菜单,同时菜单项之间的距离不同
- google-compute-engine - 使用具有计算实例管理员(测试版)IAM 角色的服务帐户创建 VM 时出错
- python - Wiki Scraping 缺失数据
- python - 如何转置 3D numpy 数组
- flutter - 如何在 Flutter 中更改颜色的色调、饱和度或值?
- django - 网站没有 www 就不能打开,但是用它打开