【问题标题】:How can I use foreach function for parallel coding?如何使用 foreach 函数进行并行编码?
【发布时间】:2020-04-26 17:59:37
【问题描述】:

按照 Jared Lander 的教科书“R for Everyone”(第 19 章),我一直在尝试使用 Elastic Net。 教科书使用下面的“foreach”代码,通过并行编码找到最优参数值。 然而,即使我编写和运行完全相同的代码,生成的对象“acsDouble”也不是一个包含 11 个 cv.glmnet 对象实例的列表。相反,它是一个空白列表。

我检查了教科书代码并在运行前清除了环境,但问题没有解决。 这里似乎有什么问题?

acs <- read.table("http://jaredlander.com/data/acs_ny.csv", sep=",",
                  header=TRUE, stringsAsFactors = FALSE)
require(useful)
# make a binary Income variable for building a logistic regression
acs$Income <- with(acs, FamilyIncome >= 150000)
# build predictor matrix
# do not include the intercept as glmnet will add that automatically
acsX <- build.x(Income ~ NumBedrooms + NumChildren + NumPeople +
                  NumRooms + NumUnits + NumVehicles + NumWorkers +
                  OwnRent + YearBuilt + ElectricBill + FoodStamp +
                  HeatingFuel + Insurance + Language - 1,
                data=acs, contrasts = FALSE)
# build response predictor
acsY <- build.y(Income ~ NumBedrooms + NumChildren + NumPeople +
                  NumRooms + NumUnits + NumVehicles + NumWorkers +
                  OwnRent + YearBuilt + ElectricBill + FoodStamp +
                  HeatingFuel + Insurance + Language - 1, data=acs)
require(glmnet)
require(parallel)
require(doParallel)
# set the seed for repeatability of random results
set.seed(2834673)
# create folds, we want observations to be in the same fold each time
# it is run
theFolds <- sample(rep(x = 1:5, length.out = nrow(acsX)))
# make sequence of alpha values
alphas <- seq(from = 0.5, to = 1, by = 0.05)
# set the seed for the repeatbility of random results
set.seed(5127151)
# start a cluster with two workers
cl <- makeCluster(2)
# regiser the workers
registerDoParallel(cl)
# keep track of timing
before <- Sys.time()
# build foreach loop to run in parallel
## several arguments
acsDouble <- foreach(i=1:length(alphas), .errorhandling = "remove",
                     .inorder = FALSE, .multicombine = TRUE,
                     .export = c("acsX", "acsY", "alphas", "theFolds"),
                     .packages = "glmnet") %dopar%
  {
    print(alphas[i])
    cv.glmnet(x=acsX, y=acsY, family="binamial", nfolds=5,
              foldid = theFolds, alpha = alphas[i])
  }
# stop timing
after <- Sys.time()
# make sure to stop the cluster when done
stopCluster(cl)
# time difference
# this will depend on speed, memory & number of cores of the machine
after - before

【问题讨论】:

    标签: r foreach parallel-processing glmnet


    【解决方案1】:

    您的cv.glmnet 通话中有错字。应该是family="binomial";不是二元的。

    在您的 foreach 循环中包含 .verbose=TRUE 将显示您是否从集群节点收到任何错误。

    【讨论】:

    • 非常感谢,现在效果很好!抱歉打错了。
    • 如果我的回答对您有帮助,我可以请您批准吗?
    猜你喜欢
    • 2019-02-18
    • 1970-01-01
    • 1970-01-01
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多