如何解决如何使我的功能可以接受为R中的MonteCarlo模拟输入
我写了下面的R
函数来完成以下任务:
- 通过
ARIMA
函数从arima.sim()
模型中模拟10个时间序列数据集 - 将系列划分为可能的
2s
,3s
,4s
,5s
,6s
,7s
,{{ 1}}和8s
。 - 对于每种大小,对块进行重新采样并进行替换,以得到新的序列,并通过
9s
函数从每个块大小的子序列中获得最佳的ARIMA
模型。 - 获取每个块大小
auto.arima()
的每个子系列。
。
RMSE
## Load packages and prepare multicore process
library(forecast)
library(future.apply)
plan(multisession)
library(parallel)
library(foreach)
library(doParallel)
n_cores <- detectCores()
cl <- makeCluster(n_cores)
registerDoParallel(cores = detectCores())
## simulate ARIMA(1,0)
#n=10; phi <- 0.6; order <- c(1,0)
bootstrap1 <- function(n,phi){
ts <- arima.sim(n,model = list(ar=phi,order = c(1,0)),sd = 1)
########################################################
## create a vector of block sizes
t <- length(ts) # the length of the time series
lb <- seq(n-2)+1 # vector of block sizes to be 1 < l < n (i.e to be between 1 and n exclusively)
########################################################
## This section create matrix to store block means
BOOTSTRAP <- matrix(nrow = 1,ncol = length(lb))
colnames(BOOTSTRAP) <-lb
########################################################
## This section use foreach function to do detail in the brace
BOOTSTRAP <- foreach(b = 1:length(lb),.combine = 'cbind') %do%{
l <- lb[b]# block size at each instance
m <- ceiling(t / l) # number of blocks
blk <- split(ts,rep(1:m,each=l,length.out = t)) # divides the series into blocks
######################################################
res<-sample(blk,replace=T,10) # resamples the blocks
res.unlist <- unlist(res,use.names = FALSE) # unlist the bootstrap series
train <- head(res.unlist,round(length(res.unlist) - 10)) # Train set
test <- tail(res.unlist,length(res.unlist) - length(train)) # Test set
nfuture <- forecast::forecast(train,model = forecast::auto.arima(train),lambda=0,biasadj=TRUE,h = length(test))$mean # makes the `forecast of test set
RMSE <- Metrics::rmse(test,nfuture) # RETURN RMSE
BOOTSTRAP[b] <- RMSE
}
BOOTSTRAPS <- matrix(BOOTSTRAP,nrow = 1,ncol = length(lb))
colnames(BOOTSTRAPS) <- lb
BOOTSTRAPS
return(list(BOOTSTRAPS))
}
我得到以下结果:
bootstrap1(10,0.6)
我尝试使用##$BOOTSTRAPS
## 2 3 4 5 6 7 8 9
##[1,] 1.287224 2.264574 2.998069 2.349261 1.677791 1.183126 2.021157 1.357658
函数使我的函数运行三(3)次不同且不同的时间。
Monte Carlo
我得到了以下param_list=list("n"=10,"phi"=0.6)
library(MonteCarlo)
MC_result<-MonteCarlo(func = bootstrap1,nrep=3,param_list = param_list)
:
MonteCarlo中的错误(func = bootstrap1,nrep = 3,param_list = param_list): func必须返回包含命名组件的列表。每个分量都必须是标量的。
请帮助我纠正我在函数或error message
函数上所做的错误。
解决方法
根据错误消息,我将尝试用以下内容替换函数的结尾:
names(BOOTSTRAPS) <- letters[1:10]
return(as.list(BOOTSTRAPS))
然后,结果输出是一个名为letters[1:10]
的命名列表。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。