在 R 中对 运行 个不同的分类器使用 "foreach"
using "foreach" for running different classifiers in R
我正在尝试对我的数据使用 foreach 运行 不同的分类器,但它不起作用。事实上,它 return 对我没有任何影响。
我的目的是并行化我的过程。这是我的代码的简化版:
library(foreach)
library(doParallel)
no_cores <- detectCores() - 1
cl<-makeCluster(no_cores)
registerDoParallel(cl)
registerDoParallel(no_cores)
model_list<-foreach(i = 1:2,
.combine = c,.packages=c("e1071","randomeForest")) %dopar%
if (i==1){
model1<-svm(x = X,y = as.factor(Y),type = "C-classification",probability = T)
}
if (i==2){
mode2<-randomForest(x = X,y = as.factor(Y), ntree=100, norm.votes=FALSE,importance = T)
}
我的并行化方式总体上是正确的吗?
真的谢谢。
主要问题是您没有将 foreach 循环的主体括在花括号中。因为 %dopar%
是二元运算符,所以您必须注意优先级,这就是为什么我建议始终使用花括号。
此外,您不应该使用 c
作为组合函数。由于 svm
和 randomForest
return 对象,returning 列表中结果的默认行为是合适的。将它们与 c
结合起来会得到一个垃圾结果。
最后,两次调用registerDoParallel
没有意义。它没有坏处,但会使您的代码混乱。
我建议:
library(doParallel)
no_cores <- detectCores() - 1
registerDoParallel(no_cores)
model_list <- foreach(i = 1:2,
.packages=c("e1071","randomForest")) %dopar% {
if (i==1) {
svm(x = X,y = as.factor(Y),type = "C-classification",
probability = T)
} else {
randomForest(x = X,y = as.factor(Y), ntree=100, norm.votes=FALSE,
importance = T)
}
}
我还删除了对 model1
和 model2
的两个不必要的变量赋值。这些变量不会在 master 上正确定义,并且它掩盖了 foreach 循环的真正工作方式。
我正在尝试对我的数据使用 foreach 运行 不同的分类器,但它不起作用。事实上,它 return 对我没有任何影响。
我的目的是并行化我的过程。这是我的代码的简化版:
library(foreach)
library(doParallel)
no_cores <- detectCores() - 1
cl<-makeCluster(no_cores)
registerDoParallel(cl)
registerDoParallel(no_cores)
model_list<-foreach(i = 1:2,
.combine = c,.packages=c("e1071","randomeForest")) %dopar%
if (i==1){
model1<-svm(x = X,y = as.factor(Y),type = "C-classification",probability = T)
}
if (i==2){
mode2<-randomForest(x = X,y = as.factor(Y), ntree=100, norm.votes=FALSE,importance = T)
}
我的并行化方式总体上是正确的吗?
真的谢谢。
主要问题是您没有将 foreach 循环的主体括在花括号中。因为 %dopar%
是二元运算符,所以您必须注意优先级,这就是为什么我建议始终使用花括号。
此外,您不应该使用 c
作为组合函数。由于 svm
和 randomForest
return 对象,returning 列表中结果的默认行为是合适的。将它们与 c
结合起来会得到一个垃圾结果。
最后,两次调用registerDoParallel
没有意义。它没有坏处,但会使您的代码混乱。
我建议:
library(doParallel)
no_cores <- detectCores() - 1
registerDoParallel(no_cores)
model_list <- foreach(i = 1:2,
.packages=c("e1071","randomForest")) %dopar% {
if (i==1) {
svm(x = X,y = as.factor(Y),type = "C-classification",
probability = T)
} else {
randomForest(x = X,y = as.factor(Y), ntree=100, norm.votes=FALSE,
importance = T)
}
}
我还删除了对 model1
和 model2
的两个不必要的变量赋值。这些变量不会在 master 上正确定义,并且它掩盖了 foreach 循环的真正工作方式。