optim function with infinite value

2019-09-16 09:48发布

To minimize a function with respect to 3 parameters, I use the optim function and "L-BFGS-B" method. Here is the error message :

Error in optim(c(3, 0.01, 0.75), fn = f, lower = c(0.6, 0.0001, 0.1), : L-BFGS-B needs finite values of 'fn'

I already checked the values of the function when at least one of the three parameters reaches the "border" (ie the lower or the upper values) but it never gives an infinite value.

How to know which values gave an infinite value in the optim function?

1条回答
老娘就宠你
2楼-- · 2019-09-16 10:52

A quick and dirty way would be to wrap your function and just print out the parameters being passed to it. Here is an example session of doing that.

f <- function(par, data){
    if(0.1 < par & par < .9){
        return(Inf)
    }else{
        sqrt(abs(par))
    }
}

and call it using optim...

> optim(2, f, method = "L-BFGS-B", lower = -1)
Error in optim(2, f, method = "L-BFGS-B", lower = -1) : 
  L-BFGS-B needs finite values of 'fn'

Now wrap the code...

wrap_f <- function(par, ...){
    cat(par, "\n")
    f(par, ...)
}

And now we can see what is being called...

> optim(2, wrap_f, method = "L-BFGS-B", lower = -1)
2 
2.001 
1.999 
1.646447 
1.647447 
1.645447 
1.256777 
1.257777 
1.255777 
-0.3018999 
-0.3008999 
-0.3028999 
0.7441084 
Error in optim(2, wrap_f, method = "L-BFGS-B", lower = -1) : 
  L-BFGS-B needs finite values of 'fn'

So in this example it ended up trying to evaluate .7441084 which gave an error by how the function was defined.

查看更多
登录 后发表回答