【问题标题】:how do I fix the following bugs in my ARIMA model?如何修复 ARIMA 模型中的以下错误?
【发布时间】:2020-04-19 06:12:39
【问题描述】:

我已经建立了 ARIMA 模型来预测我的时间序列数据。 click this link 访问数据文件。

我的代码中出现了一些错误。

代码:

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))

当我运行上面的代码时,我遇到了以下错误:

  1. 根据 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的参数值有什么问题?

  2. 我收到警告:

    C:\ProgramData\Anaconda3\lib\site-packages\statsmodels\tsa\base\tsa_model.py:162:ValueWarning:未提供频率信息,因此将使用推断频率 MS。 % 频率,值警告) C:\ProgramData\Anaconda3\lib\site-packages\statsmodels\tsa\base\tsa_model.py:162:ValueWarning:未提供频率信息,因此将使用推断频率 MS。 % 频率,值警告)

    这个警告的原因是什么?我该如何解决?

  3. 我收到参数 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

    如何解决这个错误?

【问题讨论】:

    标签: python pandas numpy matplotlib arima


    【解决方案1】:

    statsmodel, parameter order is (p,d,q)的ARIMA模型中。你的参数顺序是错误的。正确的顺序是(1,0,1)。

    model = ARIMA(data_log, order=(1, 0, 1))
    

    【讨论】:

    • 参数 d 必须为 0 正确,因为我必须将其区别一次才能使系列静止,所以顺序是 1,1,1 正确
    • 是的,你可以用 d=0 来区分和输入数据,或者让算法用 d=1 来区分。
    • 所以如果我输入原始数据(对数变换)那么 d =1。如果您观察我的代码,我的输入是我的原始数据而不是差异数据。所以 d =1 是正确的...问题出在 q 值上。当我的 q 值为 1 时出现错误
    • 尝试在ARIMA模型中设置start_ar_lags参数
    • 如何获得 start_ar_lags 的最佳价值
    猜你喜欢
    • 2019-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-07
    • 2017-10-11
    • 1970-01-01
    • 2017-02-10
    • 2019-12-18
    相关资源
    最近更新 更多