我如何迭代运行foreach?

时间:2014-08-03 04:53:15

标签: r foreach parallel-processing iterator warnings

当我运行此代码时,我收到警告,我想要有11行结果,但它只出现了一行 我应该插入循环吗?如果是这样,你们可以在代码中指定它吗? 此外,我尝试了(i in 1:length(alpha)),但它也没有用。

 require(useful)
 iris1<-iris[1:100,]
 acsx<-build.x(Species~ Sepal.Length+ Sepal.Width+ Petal.Length +Petal.Width-
  1,data=iris1,contrasts=FALSE)
 acsy<-build.y(Species~ Sepal.Length+ Sepal.Width+ Petal.Length +Petal.Width-1,data=iris1)
 theFolds<-sample(rep(x=1:5,length.out=nrow(acsx)))
 alphas<-seq(from=0.5, to =1, by=0.05)


 result<-foreach(i=1:length(alphas), .errorhandling="remove",
               .inorder=FALSE, multicombine=TRUE,
               .export=c("acsx","acsy","alphas","theFolds"),
               .packages="glmnet") %dopar%
   {  for(i in 1:length(alphas) )
  print(alphas[i])
  cv.glmnet(x=acsx,y=acsy,family="binomial",nfold=5,foldid=theFolds, alpha=alphas[i])  
   } 

警告讯息

  

在e $ fun(obj,替换(ex),parent.frame(),e $ data)中:     已导出变量:acsx,acsy,alphas,theFolds`

1 个答案:

答案 0 :(得分:3)

您的代码没有返回任何结果,因为:

  1. cv.glmnet失败会引发错误:
  2. 您告诉foreach禁止错误。
  3. 尝试此代码,然后逐步调试:

    library(foreach)
    library(glmnet)
    result <- foreach(i = 1:length(alphas), 
                      .errorhandling = "pass", 
                      .inorder = FALSE, 
                      .multicombine = TRUE, 
                      .packages = "glmnet") %do% {
      cv.glmnet(x=acsx, y=acsy, family="multinomial", nfold=5, foldid=theFolds, alpha=alphas[i]) 
    }
    
    result
    

    [[1]]
    <simpleError: from glmnet Fortran code (error code 8003); Null probability for class 3 < 1.0e-5>
    
    [[2]]
    <simpleError: from glmnet Fortran code (error code 8003); Null probability for class 3 < 1.0e-5>
    
    [[3]]
    <simpleError: from glmnet Fortran code (error code 8003); Null probability for class 3 < 1.0e-5>