【发布时间】:2017-05-27 20:40:21
【问题描述】:
我无法理解如何使我的代码并行化。我的愿望是从 20 个矩阵中找到 3 个向量,它们产生与我的测量变量最接近的线性回归(这意味着总共有 1140 种不同的组合)。目前,我能够使用 3 个嵌套的 foreach 循环来返回最佳向量。但是,我的愿望是让外循环(或全部?)并行工作。任何帮助将不胜感激!
这是我的代码:
NIR= matrix(rexp(100, rate=0.01),ncol=20, nrow = 4) #Creating the matrix with 20 vectors
colnames(NIR)=c(1:20)
S.measured=c(7,9,11,13) #Measured variable
bestvectors<-matrix(data=NA,ncol = 3+1, nrow= 1) #creating a vector to save in it the best results
###### Parallel stuff
no_cores <- detectCores() - 1
cl<-makeCluster(no_cores)
registerDoParallel(cl)
#nested foreach loop to exhaustively find the best vectors
foreach(i=1:numcols) %:%
foreach(j=i:numcols) %:%
foreach(k=j:numcols) %do% {
if(i==j|i==k|j==k){ #To prevent same vector from being used twice
}
else{
lm<-lm(S.measured~NIR[,c(i,j,k)]-1) # package that calculates the linear regression
S.pred<-as.matrix(lm$fitted.values) # predicted vector to be compared with the actual measured one
error<-sqrt(sum(((S.pred-S.measured)/S.measured)^2)) # The 'Error' which is the product of the comparison which we want to minimize
#if the error is smaller than the last best one, it replaces it. If not nothing changes
if(error<as.numeric(bestvectors[1,3+1])|is.na(bestvectors[1,3+1])){
bestvectors[1,]<-c(colnames(NIR)[i],colnames(NIR)[j],colnames(NIR)[k],as.numeric(error))
bestvectors[,3+1]<-as.numeric(bestvectors[,3+1])
}
}
}
【问题讨论】:
-
枚举 1140 个组合然后并行化而不是使用多个嵌套循环可能是最简单的。 (我没有用过
foreach,所以没有完整的答案。) -
我使用的例子是一个简单的例子。实际上,我正在寻找 150 个中最好的 5 个向量,最终得到 591,600,030 个组合。我认为列举所有的组合并不实用。
-
也许它比 R 编程相关的更多
stats.stackexchange.com。有一些方法可以处理组合爆炸,例如逐步选择 -
详尽的搜索变量选择对于这么大的集合是不切实际的。
leaps包使向前/向后选择变得简单,或者只使用套索。阅读:Chapter 6 of the venerable ISLR. -
不幸的是,向前和向后选择并不一定会给我最好的结果。我知道详尽的搜索并不是最实用的方法,但我仍然有兴趣将其应用到我的研究中。
leaps包也有详尽的计算,但我相信他们的方法和我的没有区别。我想做的是让我的外循环并行工作,这意味着在这种情况下,如果我有 20 个处理器同时工作,那么它所花费的时间将相当于 2 个for循环而不是 3 个。知道如何这个可以吗?
标签: r foreach linear-regression parallel.foreach