问题
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:
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.
来源:https://stackoverflow.com/questions/45171900/optim-function-with-infinite-value