【问题标题】:How to ignore the warnings in R tryCatch in do parallel loop如何在并行循环中忽略 R tryCatch 中的警告
【发布时间】:2017-09-26 19:01:21
【问题描述】:

我正在 R 中构建 Arima 模型。我正在尝试使用 tryCatch 来处理模型训练中的异常 - 特别是在我没有足够数据来构建模型的情况下。由于我训练了很多模型(大约 380 个),我尝试使用 R 中的 doParallel 包来实现它。 但我注意到有些警告我只需要忽略。下面给出的是我尝试过的。但我可以看到一些线程只是卡住了。我只是想知道警告处理代码是否将线程置于无限循环中,因为我尝试在警告中调用相同的表达式。

        #some sample data
ops <- ['Android', 'iOS']
country <- ['US', 'CA']
apps <- ['A', 'B', 'C']


nCores <- detectCores()
registerDoParallel(cores = nCores)

foreach(os=ops)%:% foreach(country=countries) %:% foreach(app=apps)%dopar%{ 
modeling <- function(y_data) 
{
#the function model is implemented inside the models.R #source file
#it basically uses auto.arima with some fourier regressors 
#and returns to model

source("models.R")

#for each condition get data as y_data
tryCatch( 
{ 
suppressWarnings ( 
out <- model(data=y_data)
) 
}, 

warning=function(w)
{ 
print(w) 
suppressWarnings ( 
out <- model(data=y_data) 
) 
},
error=function(e) {
print(e) 
return(NULL) }

write.table(out$AICC, "results.csv")
}


modeling(y_data)
}

请注意,我首先尝试了 4 次循环迭代,第一次运行速度非常快,但其他 3 次迭代一直在运行。

【问题讨论】:

  • 为什么要在循环中加载 models.r 的源代码,而不是在循环之前加载?

标签: r foreach try-catch warnings doparallel


【解决方案1】:

您想忽略警告但在suppressWarning 中打印警告?

...
warning=function(w)
{ 
print(w) 
suppressWarnings ( 
...

您没有提供可重现的示例,但我会尝试从一组最少的行开始:

...
nCores <- detectCores()
registerDoParallel(cores = nCores)
source("models.R")

modeling <- function(y_data) {
  tryCatch({
    suppressWarnings(out <- model(data=y_data))
    })
}

foreach(os=ops) %:% foreach(country=countries) %:% foreach(app=apps) %dopar% {
  modeling(y_data)
}

【讨论】:

  • 感谢您的有用建议。并行模型有效。但是,第一次迭代完成得更快,在 8 分钟内完成,而其余迭代需要更长的时间,即使每次迭代中的数据点数量没有那么不同。关于可能是什么原因的任何想法? (使用 4 个内核,仅经过 4 次迭代测试)
  • 如果你提供一个可重现的例子......但我认为,这是一个新问题。
猜你喜欢
  • 1970-01-01
  • 2013-02-24
  • 2016-06-17
  • 1970-01-01
  • 1970-01-01
  • 2015-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多