美文网首页
时间序列笔记-自回归模型(二)

时间序列笔记-自回归模型(二)

作者: 新云旧雨 | 来源:发表于2019-07-25 08:16 被阅读0次

    笔记说明

    在datacamp网站上学习“Time Series with R ”track
    “Introduction to Time Series Analysis”课程 做的对应笔记。
    学识有限,错误难免,还请不吝赐教。
    如无特殊说明,笔记中所使用数据均来自datacamp课程

    自回归模型部分的笔记分为(一)(二)两个部分发布,第一部分主要包括自回归过程简介、不同参数情况下自回归过程的特点和数据模拟;第二部分主要是自回归模型的拟合和预测。(这样我每日一更打卡的压力也能小一些。。。)

    拟合自回归模型

    arima是自回归滑动平均混合模型(Autoregressive Integrated Moving Average model)的简称,模型有p,d,q三个参数:自回归阶数p,差分阶数d,移动平均阶数q,这三个参数会在以后讲解中再行详述。现在只需要知道ARIMA(1,0,0)模型就是一个自回归模型,因此我们可以用order为c(1,0,0)的arima()函数对给定时间序列进行自回归模型的拟合。(我们这里只关注1阶的情景,最简单的自回归过程)
    拟合后给出的结果中,ar1即为\phi的估计值,intercept即为μ的估计值,sigma^2即为σ_ε^2的估计值。
    有了这些估计值后,就可以根据公式计算出各时间点序列数据的拟合值:
       \hat {Y_t}=\hat μ+\hat \phi(Y_{t-1}-\hat μ)
    以及残差(实际值与拟合值之差):
       \hat {ε_t}=Y_t-\hat {Y_t}
    将residuals()函数作用于拟合的模型对象(arima()函数的结果)可以提取拟合的模型对所拟合数据生成的残差数据,利用残差公式可以进一步生成拟合的模型对所拟合数据生成的拟合值。用points()函数可以将生成的各拟合值画在原时间序列图上。下面是实践:

    # Fit the AR model to AirPassengers
    AR <- arima(AirPassengers, order = c(1, 0, 0))
    print(AR)
    
    # Plot the series and fitted values
    ts.plot(AirPassengers)
    AR_fitted <- AirPassengers - residuals(AR)
    points(AR_fitted, type = "l", col = 2, lty = 2)
    

    拟合自回归模型后的参数估计结果:
    ar1:0.9646, 标准误0.0214
    intercept:278.4649,标准误67.1141
    sigma^2:1119
    log likelihood=-711.09
    aic=1428.18


    ts.plot(AirPassengers)
    添加了拟合值的ts.plot(AirPassengers)

    拟合自回归模型后进行简单的预测

    建立自回归模型后可以用predict()函数进行进行预测,在predict()函数生成的对象中,$pred值为预测值,$se值为预测值的标准误。
    predict()函数的n.ahead参数用来指定你想在现有数据以后生成的预测值数,默认为1(即只会返回下一个时间点的预测值)。
    下面进行实践,实践使用的数据Nile记录了1871年至1970年Nile河的年流量(来自于datacamp课程练习)
    代码的最后利用预测值±1.96倍预测值标准误对应生成了预测值的95%置信区间的上下限。并同预测值一起附加在了原时间序列图上。

    # Fit an AR model to Nile
    AR_fit <-arima(Nile, order  = c(1,0,0))
    print(AR_fit)
    
    # Use predict() to make a 1-step forecast
    predict_AR <- predict(AR_fit)
    
    # Obtain the 1-step forecast using $pred[1]
    predict_AR$pred[1]
    
    # Use predict to make 1-step through 10-step forecasts
    predict(AR_fit, n.ahead = 10)
    
    # Plot the Nile series plus the forecast and 95% prediction intervals
    ts.plot(Nile, xlim = c(1871, 1980))
    AR_forecast <- predict(AR_fit, n.ahead = 10)$pred
    AR_forecast_se <- predict(AR_fit, n.ahead = 10)$se
    points(AR_forecast, type = "l", col = 2)
    points(AR_forecast - 1.96*AR_forecast_se, type = "l", col = 2, lty = 2)
    points(AR_forecast + 1.96*AR_forecast_se, type = "l", col = 2, lty = 2)
    

    拟合自回归模型后的参数估计结果:
    ar1:0.5063, 标准误0.0867
    intercept:919.5685,标准误29.1410
    sigma^2:21125
    log likelihood=-639.95
    aic=1285.9



    可以看出来预测区间相当宽,这是Nile数据的持续性(persisitence)较低造成的。

    相关文章

      网友评论

          本文标题:时间序列笔记-自回归模型(二)

          本文链接:https://www.haomeiwen.com/subject/zpxfrctx.html