【发布时间】:2020-09-10 17:06:39
【问题描述】:
我有下面的R 脚本,它需要超过 24 小时才能运行,但最终在 10-gigabyte ram 和 core M7 的 Windows 10 上运行。该脚本执行以下操作:
这就是我想用R做的事情
-
A.我已经生成了 50 个时间序列数据集。
-
B.我将相同的时间序列数据集分割成以下大小的块:
2,3,...,48,49使我从上面的步骤 1 中形成了 48 个不同的时间序列。 -
C.我将每个 48 时间序列数据集划分为
train和test集,因此我可以使用Metrics包中的rmse函数来获取步骤 2 中形成的 48 个子序列的均方根误差 (RMSE)。 -
D.然后根据其块大小将每个系列的 RMSE 制成表格
-
E.我为每个 48 个不同的时间序列数据集获得了最好的
ARIMA模型。
我的 R 脚本
# 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 to be 1 < l < n (i.e to be between 1 and n exclusively)
# vector to store block means
RMSEblk <- matrix(nrow = 1, ncol = length(li))
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
# initialize vector to receive result from for loop
singleblock <- vector()
for(i in 1:1000){
res<-sample(blk, replace=T, 10000) # 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(future$mean) # makes the `future` object a vector
RMSE <- rmse(test, nfuture) # use the `rmse` function from `Metrics` package
singleblock[i] <- RMSE # Assign RMSE value to final result vector element i
}
RMSEblk[b] <- mean(singleblock) # store into matrix
}
RMSEblk
R 脚本实际运行,但需要超过 24 小时才能完成。 loops 中的运行次数(10000 和 1000)是使任务完美所需的最小值。
请问我该怎么做才能在更短的时间内完成脚本?
【问题讨论】:
-
如果我正确地遵循了您的代码,您是否正在尝试通过
auto.arima()估计 48,000 个 ARIMA 模型?如果我不得不猜测,那是你的瓶颈。一些随机的想法:1)你可以并行运行吗?我看不到每次迭代之间有任何依赖关系,因此您可以利用每个可用的核心。 2) 你可以将任何示例代码移出内部 for 循环吗? 3) 是否可以设置 w/iauto.arima()来加快计算速度? 4)您是否分析了代码以确认瓶颈在哪里?如果没有,这里有一篇好文章:adv-r.had.co.nz/Profiling.html -
@Chase 48 ARIMA 模型不是 48,000
-
object
li的值为 2:49(长度为 48)。内部循环迭代 1000 次,这是调用auto.arima的地方。那么这不是对auto.arima的 48 * 1000 = 48000 次调用吗?无论如何,我上面的所有 cmets 仍然适用...对于此代码需要 24 小时意味着您可能会增长/迭代一个对象...R 可能必须重新分配内存 48000 次,并且在每次迭代时它必须找到一个更大的内存块......由于显而易见的原因,这是低效的。 -
如果你不相信我,把这个贴在
auto.arima()的调用上方,看看有多少值被吐到屏幕上print(paste0(b, "-", i))。 -
接替@Chase:根本问题是,无论为什么你这样做,你确实在运行
auto.arima()函数48000次。跨度>