使用 %dopar% 时如何打印 [英] How can I print when using %dopar%
问题描述
我有一个 foreach
循环,它使用 %dopar%
和 doSNOW
作为后端.我怎样才能让循环在每次迭代中打印出一些东西?
I have a foreach
loop that uses %dopar%
with doSNOW
as the back-end. How can I have the loop print something out each iteration?
我下面的代码是我目前正在使用的代码,但它没有打印任何内容.
My code below is what I'm currently using, but its not printing anything.
foreach(ntree=rep(25,2),.combine=combine,.packages='randomForest',
.inorder=FALSE) %dopar% {
print("RANDOM FOREST")
randomForest(classForm,data=data,na.action=na.action,do.trace=do.trace,ntree=ntree,mtry=mtry)
}
推荐答案
这里发布了许多很好的解决方案,但我发现登录到套接字并使用单独的进程在控制台中输出日志调用最简单.
There are a number of good solutions posted here, but I find it easiest to log to a socket and use a separate process to output the log calls in a console.
我使用以下函数:
log.socket <- make.socket(port=4000)
Log <- function(text, ...) {
msg <- sprintf(paste0(as.character(Sys.time()), ": ", text, "
"), ...)
cat(msg)
write.socket(log.socket, msg)
}
然后您可以在代码中放置日志语句,例如:
You can then place log statements in the code such as:
Log("Processing block %d of %d", i, n.blocks)
可以使用任何简单的套接字侦听工具实时查看日志输出.例如,在 Linux 上使用 netcat:
Log output can viewed in real-time using any simple socket listening tool. For example, using netcat on Linux:
nc -l 4000
上面的日志语句将在 netcat 终端中显示为:
The above log statement would display in the netcat terminal as:
2014-06-25 12:30:45: Processing block 2 of 13
这种方法的优点是远程工作,并提供您想记录的尽可能详细的输出.
This method has the advantage of working remotely and provides as detailed output as you care to log.
ps 对于 Windows 用户,请参阅 Jon Craton 的 netcat 端口.
p.s. For those on Windows, see Jon Craton's netcat port.
pps 我猜 write.socket
R 函数可能不是线程安全的,但除非你以高频率记录,否则你不太可能遇到任何问题.不过有一点需要注意.
p.p.s I'm guessing the write.socket
R function probably isn't thread-safe, but unless you're logging at high frequency, you're unlikely to run into any issue. Something to be aware of though.
这篇关于使用 %dopar% 时如何打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!