如果您想使用forecast 包,您需要将您的数据转换为ts (mts) 对象。要做到这一点,将您的数据从长格式转换为宽格式(根据您在上面发布的图像,我假设您的数据是长格式的)。然后使用ts() 函数创建一个ts() 对象,见下例。
让我们生成一些示例 ts 数据
sales.xts_m <- ts(data.frame(AA = arima.sim(list(order=c(1,0,0), ar=.5), n=100,
mean = 12),
AB = arima.sim(list(order=c(1,0,0), ar=.5), n=100,
mean = 12),
AC = arima.sim(list(order=c(1,0,0), ar=.5), n=100,
mean = 11),
BA = arima.sim(list(order=c(1,0,0), ar=.5), n=100,
mean = 10),
BB = arima.sim(list(order=c(1,0,0), ar=.5), n=100,
mean = 14)), start = c(2000, 1),
frequency = 12)
nts <- ncol(sales.xts_m) # number of time series
h <- 12 # forecast horizon
示例 xreg
dummies_hd_m <- forecast::seasonaldummy(sales.xts_m[,1])
dummies_hd_m_future <- forecast::seasonaldummy(sales.xts_m[,1], h = h)
mylist <- list()
fc <- matrix(nrow = h, ncol = nts)
如果您需要保留模型--------
模型将在 mylist 中,并在 fc 中为每个 ts 预测点
for (i in 1:nts) {
mylist[[i]] <- auto.arima(sales.xts_m[,i],xreg=dummies_hd_m, biasadj = TRUE,
max.p=7,max.q=7,seasonal= FALSE,test=c("kpss"),
lambda = "auto",num.cores=15,stationary = TRUE )
fc[,i] <- forecast(mylist[[i]], h=h, xreg = dummies_hd_m_future)$mean
}
#ts names
colnames(fc) <- colnames(sales.xts_m)
如果您不需要保留模型--------
fc <- matrix(nrow = h, ncol = nts)
for (i in 1:nts) {
fc[,i] <- forecast(auto.arima(sales.xts_m[,i],xreg=dummies_hd_m, biasadj = TRUE,
max.p=7,max.q=7,seasonal=FALSE,test=c("kpss"),
lambda = "auto",num.cores=15,stationary = TRUE ), h=h,
xreg = dummies_hd_m_future)$mean
}
#ts names
colnames(fc) <- colnames(sales.xts_m)
如果您想在项目中使用 ML 模型
devtools::install_github("Akai01/caretForecast")
library(caretForecast)
nts <- ncol(sales.xts_m) # mumber of time series
h <- 12 # forecast horizon
fc <- matrix(nrow = h, ncol = nts)
示例:具有线性核的支持向量机。您只需更改 caret_method 参数即可使用其他模型,例如 caret_method = "ridge" 或 caret_method = "rf" 等。参考:https://github.com/Akai01/caretForecast
for (i in 1:nts) {
fc[,i] <- forecast(ARml(sales.xts_m[,i], maxlag = 12, xreg = dummies_hd_m,
caret_method = "svmLinear", seasonal = FALSE ),
h=h, xreg = dummies_hd_m_future)$mean
}
colnames(fc) <- colnames(sales.xts_m)