使用循环为订单

时间:2016-04-24 19:46:27

标签: r loops time-series forecasting

我尝试使用循环为p = 15到1,d = 2到0,q = 15到1的所有组合创建模型,然后使用滚动预测来评估这些模型,然后选择说出具有最低mape的那个(准确度(fc $ mean,test)[,5])。

我对循环不太好,所以任何提示都非常感谢。我有一个工作"在代码之前"代码如下,"代码"显示我想如何修改它。

代码之前:

library("fpp")

h <- 5
tsTrain <- window(hsales,end=1989.99)
tsTest <- window(hsales,start=1990)
n <- length(tsTest) - h + 1
ModFit <- Arima(tsTrain, order=c(15,2,15)
fc <- ts(numeric(n), start=1990+(h-1)/12, freq=12)
for(i in 1:n)
{  
  x <- window(hsales, end=1989.99 + (i-1)/12)
  reModFit <- Arima(x, model=ModFit)
  fc[i] <- forecast(reModFit, h=h)$mean[h]
}

代码之后:

library("fpp")

h <- 5
tsTrain <- window(hsales,end=1989.99)
tsTest <- window(hsales,start=1990)
n <- length(tsTest) - h + 1

##Create models for all combinations of p 15 to 0, d 2 to 0, q 15 to 0

ModFit1 <- Arima(tsTrain, order=c(15,2,15)
ModFit2 <- Arima(tsTrain, order=c(9,2,15)
ModFit3 <- Arima(tsTrain, order=c(8,2,15)
.
.
.
ModFit15 <- Arima(tsTrain, order=c(0,2,15)
fc1 <- ts(numeric(n), start=1990+(h-1)/12, freq=12)
fc2 <- ts(numeric(n), start=1990+(h-1)/12, freq=12)
fc3 <- ts(numeric(n), start=1990+(h-1)/12, freq=12)
.
.
.
fc15 <- ts(numeric(n), start=1990+(h-1)/12, freq=12)
for(i in 1:n)
{  
  x <- window(hsales, end=1989.99 + (i-1)/12)
  reModFit1 <- Arima(x, model=ModFit1)
  reModFit2 <- Arima(x, model=ModFit2)
  reModFit3 <- Arima(x, model=ModFit3)
  .
  .
  .
  reModFit15 <- Arima(x, model=ModFit15)
  fc1[i] <- forecast(reModFit1, h=h)$mean[h]
  fc2[i] <- forecast(reModFit2, h=h)$mean[h]
  fc3[i] <- forecast(reModFit3, h=h)$mean[h]
  .
  .
  .
  fc15[i] <- forecast(reModFit15, h=h)$mean[h]
}

##Calculating mape for forecasts

Accuracy(fc1$mean,tsTest)[,5]
Accuracy(fc2$mean,tsTest)[,5]
Accuracy(fc3$mean,tsTest)[,5]
.
.
.
Accuracy(fc15$mean,tsTest)[,5]

##Return the order of the Arima model that has the lowest mape
ModFit5 ARIMA(10,2,15)  ##This is just an example, I don't know if this really the one with the lowest mape. 

更新

pvar<-1:15
dvar<-1:2
qvar<-1:15

OrderGrid<-expand.grid(pvar,dvar,qvar)


ModFit <-function(a,b,c,dat){
          m=Arima(tsTrain, order=c(a,b,c))
          return(m)
                            } 


Fits<-apply(OrderGrid,1,ModFit)

错误:

Arima中的错误(tsTrain,order = c(a,b,c)):   论证&#34; c&#34;缺少,没有默认

更新

ModFit <- function(x, dat){
m=Arima(dat, order=c(x[[1]], x[[2]], x[[3]]),method="ML")
return(m)
} 

Fits <- plyr::alply(OrderGrid, 1, ModFit, dat = tsTrain)

1 个答案:

答案 0 :(得分:0)

expand.gridalply用作apply将简化为arima对象的矩阵,这将是一种痛苦

pvar<-1:15
dvar<-1:2
qvar<-1:15

OrderGrid<-expand.grid(pvar,dvar,qvar)

ModFit <- function(x, dat){
          m=Arima(dat, order=c(x[[1]], x[[2]], x[[3]]))
          return(m)
} 

Fits <- plyr::alply(OrderGrid, 1, ModFit, dat = tsTrain)

Fits将成为一个列表。