我無法理解如何使代碼並行。我的願望是從20個矩陣中找出3個向量,對我的測量變量產生最接近的線性迴歸(這意味着總共有1140個不同的組合)。目前,我能夠使用3個嵌套的foreach
循環返回最佳向量。但是,我的願望是讓外部循環(或全部)平行工作。任何幫助,將不勝感激!使用'foreach'在R中運行所有可能的排列
這裏是我的代碼:
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',所以沒有完整的答案。) – Frank
我使用的例子很簡單。實際上,我正在尋找150箇中最好的5個向量,其結果是591,600,030個組合。我不認爲列舉所有的組合將是實際的。 – Jones
也許它比'stats.stackexchange.com'更接近R編程。有一些方法可以處理組合式爆炸,如逐步選擇 –