如何在Windows上进行并行化 - 例如?

Car*_*bon 24 parallel-processing r

如何在Windows中使用r的代码并行化代码?包括一个简单的例子.发布这个自我回答的问题,因为这对于工作是相当不愉快的.你会发现包并行不能单独工作,但包雪工作得非常好.

Car*_*bon 33

发布这个是因为这让我感到血腥永远.这是r中并行化的一个简单示例,它可以让您测试事情是否适合您并让您走上正确的道路.

library(snow)
z=vector('list',4)
z=1:4
system.time(lapply(z,function(x) Sys.sleep(1)))
cl<-makeCluster(###YOUR NUMBER OF CORES GOES HERE ###,type="SOCK")
system.time(clusterApply(cl, z,function(x) Sys.sleep(1)))
stopCluster(cl)
Run Code Online (Sandbox Code Playgroud)

您还应该使用库doSNOW将foreach注册到snow集群,这将导致许多程序包自动并行化.要注册的命令是registerDoSNOW(cl)(带有cl返回值makeCluster()),撤消注册的命令是registerDoSEQ().不要忘记关闭群集.


San*_*ord 12

这对我有用,我用的是doParallel包,需要3行代码:

# process in parallel
library(doParallel) 
cl <- makeCluster(detectCores(), type='PSOCK')
registerDoParallel(cl)

# turn parallel processing off and run sequentially again:
registerDoSEQ()
Run Code Online (Sandbox Code Playgroud)

随机森林的计算从180秒减少到120秒(在具有4个核心的Windows计算机上).


小智 5

根据此处的信息我能够将以下代码转换为可在 Windows 7 上的 R Studio 下运行的并行版本。

原始代码:

#
# Basic elbow plot function
#
wssplot <- function(data, nc=20, seed=1234){
    wss <- (nrow(data)-1)*sum(apply(data,2,var))
    for (i in 2:nc){
        set.seed(seed)
        wss[i] <- sum(kmeans(data, centers=i, iter.max=30)$withinss)}
    plot(1:nc, wss, type="b", xlab="Number of clusters", 
       ylab="Within groups sum of squares")
}
Run Code Online (Sandbox Code Playgroud)

并行代码:

library("parallel")

workerFunc <- function(nc) {
  set.seed(1234)
  return(sum(kmeans(my_data_frame, centers=nc, iter.max=30)$withinss)) }

num_cores <- detectCores()
cl <- makeCluster(num_cores)
clusterExport(cl, varlist=c("my_data_frame")) 
values <- 1:20 # this represents the "nc" variable in the wssplot function
system.time(
  result <- parLapply(cl, values, workerFunc) )  # paralel execution, with time wrapper
stopCluster(cl)
plot(values, unlist(result), type="b", xlab="Number of clusters", ylab="Within groups sum of squares")
Run Code Online (Sandbox Code Playgroud)

并不是说它是完美的,甚至是最好的,只是一个初学者证明并行似乎在 Windows 下工作。希望能帮助到你。