開始使用免費開始

由已估計 AR 模型做簡單預測

你已經用 arima() 指令為資料建好模型,現在可以依此模型做簡單的預測。predict() 函式可用於對已估計的 AR 模型產生預測。在 predict() 產生的物件中,$pred 是預測值,而 $se 是該預測的標準誤。

若要對最後一筆觀測值之後的多個期間做預測,可以在 predict() 指令中使用 n.ahead 參數。這個參數會設定預測視窗(h),也就是要往前預測的期數。預測會從時間序列尾端遞迴地生成,自 1 步到 h 步之前。

在本練習中,你將以套用到 Nile 資料的 AR 模型來做簡單的預測。Nile 記錄 1871 年到 1970 年間尼羅河流量的年度觀測值。

本練習屬於課程

R 的時間序列分析

檢視課程

練習說明

  • 使用 arima()Nile 時間序列配適 AR 模型,並將結果存為 AR_fit
  • 使用 predict() 預測 1971 年的尼羅河流量。
  • 搭配使用 predict_AR$pred[1] 取得 1 步預測。
  • 再呼叫一次 predict(),產生自 1 步到 10 步(1971 至 1980 年)的預測;請將 n.ahead 參數設為 10
  • 執行已寫好的程式碼,將 Nile 資料、預測結果與 95% 預測區間繪圖。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Fit an AR model to Nile
AR_fit <- arima(___, order  = ___)
print(AR_fit)

# Use predict() to make a 1-step forecast
predict_AR <- predict(___)

# Obtain the 1-step forecast using $pred[1]


# Use predict to make 1-step through 10-step forecasts
predict(___, n.ahead = ___)

# Run to 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 - 2*AR_forecast_se, type = "l", col = 2, lty = 2)
points(AR_forecast + 2*AR_forecast_se, type = "l", col = 2, lty = 2)
編輯並執行程式碼