Skip to main content
 首页 » 编程设计

python之如何提高 R 在机器学习中的性能

2025年04月02日14TianFang

我同时使用 R 和 python(Anaconda)。当涉及到建模时,R 在同一操作上花费了更多时间。在 R 中是否有并行操作或多线程的方法?

请您参考如下方法:

在 R 中使用机器学习算法时,您可以调用一些允许并行化的库。在下面的示例中,差异是巨大的。

您可以这样调用它们(请注意,“2”取决于您的集群数量):

library(doParallel) 
cl <- makeCluster(2) 
registerDoParallel(cl) 

本例摘自https://cran.r-project.org/web/packages/doParallel/vignettes/gettingstartedParallel.pdf

> x <- iris[which(iris[,5] != "setosa"), c(1,5)] 
> trials <- 10000 
> ptime <- system.time({ 
+ r <- foreach(icount(trials), .combine=cbind) %dopar% { 
+ ind <- sample(100, 100, replace=TRUE) 
+ result1 <- glm(x[ind,2]~x[ind,1], family=binomial(logit)) 
+ coefficients(result1) 
+ } 
+ })[3] 
> ptime  

而且比

快得多
> stime <- system.time({ 
+ r <- foreach(icount(trials), .combine=cbind) %do% { 
+ ind <- sample(100, 100, replace=TRUE) 
+ result1 <- glm(x[ind,2]~x[ind,1], family=binomial(logit)) 
+ coefficients(result1) 
+ } 
+ })[3] 
> stime