我有一个非常奇怪的DEoptim
错误,我已经“修复”了,但不明白。
当我将DEoptim
' 的并行功能与parallel
包(即pType=1
)一起使用时,我没有遇到任何问题。但是,当我改用foreach
它时(我必须在可用的网格计算设置上使用它),我遇到了问题。以下是我遇到的问题的简化版本的 MRE。pType=1
有效,pType=2
当foreachArgs
指定时返回错误:
目标函数结果的长度与参数矩阵不同
当我不指定foreachArgs
时,问题就消失了。有人对这个问题的根本原因有想法吗?
library(zoo)
library(parallel)
library(doParallel)
library(DEoptim)
myfunc1 <- function(params){
s <- myfunc2(params,ncal,n_left_cens,astats, X_ret, disc_length, X_acq, POP_0, POP_ann_growth)
loss_func(s)
}
myfunc2 = function(params,ncal,n_left_cens,astats, X_ret, disc_length, X_acq, POP_0, POP_ann_growth){
sum(params) + ncal + n_left_cens + astats + X_ret + disc_length + X_acq + POP_0 + POP_ann_growth
}
loss_func = function(s){
s
}
# General setup
ncal = 1
n_left_cens = 1
astats= 1
disc_length = 1
POP_0 = 1
POP_ann_growth = 1
X_acq = 1
X_ret = 1
params = c(1,1)
W = 1
paral = TRUE
itermax=100
ncores = detectCores()
cltype <- ifelse(.Platform$OS.type != "windows", "FORK", "PSOCK")
trace=TRUE
# bounds for search for DEoptim
lower = rep(-1,length(params))
upper = lower*-1
# parallel: works
pType = 1
parVar = c("myfunc1","myfunc2","loss_func","W","ncal","n_left_cens","astats","X_ret","disc_length",
"X_acq","POP_0","POP_ann_growth")
foreachArguments <- list("myfunc1","myfunc2","loss_func","ncal","n_left_cens","astats","X_ret","disc_length",
"X_acq","POP_0","POP_ann_growth")
clusters <- makeCluster(ncores, type = cltype)
registerDoParallel(clusters)
clusterExport(cl=clusters, varlist=foreachArguments, envir=environment())
results <- DEoptim(fn=myfunc1,lower=lower,upper=upper,
DEoptim.control(itermax=itermax,trace=trace,parallelType=pType,
parVar=parVar))
showConnections(all = TRUE)
closeAllConnections()
# foreach with foreachArgs specified: doesn't work
pType = 2
clusters <- makeCluster(ncores, type = cltype)
registerDoParallel(clusters)
clusterExport(cl=clusters, varlist=foreachArguments, envir=environment())
results <- DEoptim(fn=myfunc1,lower=lower,upper=upper,
DEoptim.control(itermax=itermax,trace=trace,parallelType=pType,
foreachArgs=foreachArguments))
showConnections(all = TRUE)
closeAllConnections()
# foreach with foreachArgs unspecified: works
pType = 2
foreachArguments <- list("myfunc1","myfunc2","loss_func","ncal","n_left_cens","astats","X_ret","disc_length",
"X_acq","POP_0","POP_ann_growth")
clusters <- makeCluster(ncores, type = cltype)
registerDoParallel(clusters)
clusterExport(cl=clusters, varlist=foreachArguments, envir=environment())
results <- DEoptim(fn=myfunc1,lower=lower,upper=upper,
DEoptim.control(itermax=itermax,trace=trace,parallelType=pType))
showConnections(all = TRUE)
closeAllConnections()