Как я могу использовать функцию foreach для параллельного кодирования? - PullRequest
2 голосов
/ 09 января 2020

Следуя учебнику Джареда Ландера «R для всех» (глава 19), я пытался использовать Elasti c Net. В учебнике используется следующий код «foreach» для поиска оптимального значения параметра с использованием параллельного кодирования. Однако, даже если я пишу и запускаю точно такой же код, результирующий объект «acsDouble» не является списком с 11 экземплярами объектов cv.gl mnet, как и должно быть. Вместо этого это пустой список.

Я проверил коды учебника, а также очистил среду перед запуском, но проблема не устранена. В чем здесь проблема?

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

1 Ответ

0 голосов
/ 09 января 2020

У вас есть опечатка в вашем cv.glmnet звонке. Должно быть family="binomial"; * не является бинарным

...