R中的rmse函数问题
我有一个R中的rmse函数问题,r,forecast,R,Forecast,我有一个R代码,其中包含一些嵌套的循环括号,我使用了Metrics包中的rmse()函数。我在没有函数的情况下尝试了它,但在嵌套的R代码中没有 以下是我希望使用R 我已经生成了50个时间序列数据集 我将相同的时间序列数据集分为以下大小的块:2,3,…,48,49使我有48个不同的时间序列,这些时间序列是从上面的步骤1形成的 我将每个48个时间序列数据集划分为train和test集,这样我就可以使用Metrics包中的rmse函数来获得步骤2中形成的48个子序列的均方根误差(rmse) 然后根据块
R
代码,其中包含一些嵌套的循环括号,我使用了Metrics
包中的rmse()
函数。我在没有函数的情况下尝试了它,但在嵌套的R
代码中没有
以下是我希望使用R
2,3,…,48,49
使我有48个不同的时间序列,这些时间序列是从上面的步骤1形成的train
和test
集,这样我就可以使用Metrics
包中的rmse
函数来获得步骤2中形成的48个子序列的均方根误差(rmse)ARIMA
模型 # simulate arima(1,0,0)
library(forecast)
library(Metrics)
n <- 50
phi <- 0.5
set.seed(1)
wn <- rnorm(n, mean=0, sd=1)
ar1 <- sqrt((wn[1])^2/(1-phi^2))
for(i in 2:n){
ar1[i] <- ar1[i - 1] * phi + wn[i]
}
ts <- ar1
t<-length(ts)# the length of the time series
li <- seq(n-2)+1 # vector of block sizes(i.e to be between 1 and n exclusively)
RMSEblk<-matrix(nrow = 1, ncol = length(li))#vector to store block means
colnames(RMSEblk)<-li
for (b in 1:length(li)){
l<- li[b]# block size
m <- ceiling(t / l) # number of blocks
blk<-split(ts, rep(1:m, each=l, length.out = t)) # divides the series into blocks
singleblock <- vector() #initialize vector to receive result from for loop
for(i in 1:10){
res<-sample(blk, replace=T, 100) # resamples the blocks
res.unlist<-unlist(res, use.names = F) # unlist the bootstrap series
# Split the series into train and test set
train <- head(res.unlist, round(length(res.unlist) * 0.6))
h <- length(res.unlist) - length(train)
test <- tail(res.unlist, h)
# Forecast for train set
model <- auto.arima(train)
future <- forecast(test, model=model,h=h)
nfuture <- as.numeric(out$mean) # makes the `future` object a vector
# use the `rmse` function from `Metrics` package
RMSE <- rmse(test, nn)
singleblock[i] <- RMSE # Assign RMSE value to final result vector element i
}
#singleblock
RMSEblk[b]<-mean(singleblock) #store into matrix
}
RMSEblk
但是当我写的时候
library(forecast)
train <- head(ar1, round(length(ar1) * 0.6))
h <- length(ar1) - length(train)
test <- tail(ar1, h)
model <- auto.arima(train)
#forecast <- predict(model, h)
out <- forecast(test, model=model,h=h)
nn <- as.numeric(out$mean)
rmse(test, nn)
库(预测)
train在for循环中做了两个非常小的修改后,我能够运行您的代码。请参见两行注释:
for(1中的b:长度(li)){
l在for循环中做了两个非常小的修改后,我可以运行您的代码。请参阅两行注释:
for(1中的b:长度(li)){
l您的代码没有定义nn。其他有效的代码有nn。要以干净的状态启动代码,请使用此行作为第一个可执行行:
rm(list=ls())
您的代码未定义nn。其他有效的代码具有nn。若要以干净的状态启动代码,请将此行用作第一个可执行行:
rm(list=ls())