简体   繁体   English

如何将foreach%dopar%日志写入单独的文件

[英]How to write foreach %dopar% logs to separate files

I use R to run Ant Colony Optimization and usually repeat the same optimization several times to cross-validate my results. 我使用R来运行Ant Colony Optimization,并且通常会多次重复相同的优化以交叉验证我的结果。 I want to save time by running the processes in parallel with the foreach and doParallel packages. 我希望通过与foreachdoParallel包并行运行进程来节省时间。

A reproducible example of my code would be very long so I'm hoping this is sufficient. 我的代码的可重现的例子会很长,所以我希望这就足够了。 I think I managed to get the code running like this: 我想我设法让代码运行如下:

result <- list()

short <- function(n){
            for(n in 1:10){
               result[[n]] <- ACO(data, ...)}}

foreach(n=1:50) %dopar% short(n)

Within the ACO() function I continuously create objects with intermediate results (eg the current pheromone levels) which I save using write.table(..., append=TRUE) to keep track of the iterations and their results. 在ACO()函数中,我连续创建具有中间结果的对象(例如当前的信息素级别),我使用write.table(..., append=TRUE)来保存,以跟踪迭代及其结果。 Now that I'm running the processes in parallel, the file I write contains results from all processes and I'm not able to tell which process the data belongs to. 现在我正在并行运行进程,我写的文件包含所有进程的结果,我无法分辨数据属于哪个进程。 Therefore, I'd like to write different files for each process. 因此,我想为每个进程编写不同的文件。

What's the best way, in general, to save intermediate results when using parallel processing? 一般来说,在使用并行处理时保存中间结果的最佳方法是什么?

You can use the log4r package to write info needed in a log file. 您可以使用log4r包来写入日志文件中所需的信息。 More info about the package here . 关于包的更多信息这里

An example of the code which you have to put in your short function: 您必须在short函数中添加的代码示例:

# Import the log4r package. 
library('log4r')
# Create a new logger object with create.logger(). 
logger <- create.logger()
# Set the logger's file output. 
logfile(logger) <- 'base.log'
# Set the current level of the logger. 
level(logger) <- 'INFO'
# Try logging messages with different priorities. # At priority level INFO, a call to debug() won't print anything. 
debug(logger, 'Iretation and result info') 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM