我无法理解如何使代码并行。我的愿望是从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])
}
}
}
答案 0 :(得分:2)
使用foreach
的一般建议:
如果您希望代码在多个核心上运行,请使用foreach(i=1:numcols) %dopar% { ... }
。 %do%
装饰器不完美地模拟并行性,但在单个核心上运行。
在循环运行时,%dopar%
生成的进程无法相互通信。因此,设置代码以输出R对象,如data.frame
或vector
,然后进行比较。在您的情况下,if(error<as.numeric ...
行中的逻辑应在主foreach
循环后按顺序执行(不是并行执行)。
嵌套%dopar%
循环的行为在操作系统中不一致,并且在跨核心生成进程的方式上不清楚。为了获得最佳性能和可移植性,请在最外层循环中使用单个foreach
循环,然后在其中使用vanilla for
循环。