DEOptim 不断告诉:目标函数的 NaN 值

dan*_*ani 5 c++ parameters optimization r deoptimization

我用 C++ 编写了一个模拟程序,并且喜欢使用 DEoptim 在 R 中查找参数。有时一切都运行良好,有时 DEoptim 会停下来并告诉我们:

Error in DEoptim(simulate, lower = lb, upper = ub, control = opt) : 
  NaN value of objective function! 
Perhaps adjust the bounds.
Run Code Online (Sandbox Code Playgroud)

我的 R 脚本定义了一个调用外部二进制文件的函数。参数附加到命令中。我测试了我的 C++ 程序,但从未见过 NaN 返回。此外,为了进行调查,我检查 R 函数中是否存在 NaN simulate(),这样它就会停止并告知实际上存在一个 NaN 值。然而,它永远不会停在那里 - 但后来在 DEoptim 中。问题是什么?这是一个 DEoptim-Bug 吗?

library("DEoptim")
setwd("some-path")

simulate <- function(theta)
{
  strcom <- paste(c("./ExternalBinary", theta),collapse=" ")
  ret <- as.numeric(system(strcom, intern=T)) #will return a couple of integer numbers
  ret <- mean(ret) #average those numbers
  if(any(is.nan(ret))){ #check against NaNs
    stop('Found a NaN?!') #this line is NEVER called, even if DEoptim stops
  }
  return(ret)
}

lb <- rep(-10.,18) #18 parameters in the range of -10...10
ub <- -lb

opt <- list(NP=500,itermax=10, storepopfrom=1, storepopfreq=1, parallelType=1)
est <- DEoptim(simulate,lower=lb,upper=ub, control=opt)
Run Code Online (Sandbox Code Playgroud)

编辑:我发现返回实际上不是 NaN 而是 NA。simulate()如果我替换is.nan(ret)为,该功能将停止is.na(ret)。我还再次检查了我的 C++ 程序,但找不到在不向 .c++ 写入数字的情况下如何退出的方法cout。因此我问了这个问题: main() 可以在所有 cout 写入控制台之前返回吗?

Emm*_*mel 0

为了使用 DEoptim 解决这个问题,当存在 NaN 或 NA 时,我返回一个高值。如果你想最小化函数模拟,它应该可以工作。我经常在 DEoptim 中使用这个“技巧”。

simulate <- function(theta)
{
  strcom <- paste(c("./ExternalBinary", theta), collapse =" ")
  ret <- as.numeric(system(strcom, intern = TRUE)) 
  ret <- mean(ret) 
  
  if(any(is.nan(ret))|any(is.na(ret)))
  { 
    return(10 ^ 30)
    
  }else
  {
    return(ret)
  }
}

Run Code Online (Sandbox Code Playgroud)

这向 DEoptim 表明这些参数不是候选解决方案。