Question

[Solved] Optimization of optim() in R ( L-BFGS-B needs finite values of ‘fn’)

I’m having some trouble using optim() in R to solve for a likelihood involving an integral. I get an error that says “Error in optim(par = c(0.1, 0.1), LLL, method = “L-BFGS-B”, lower = c(0, : L-BFGS-B needs finite values of ‘fn'”. Below is my code:

s1=c(1384,1,1219,1597,2106,145,87,1535,290,1752,265,588,1188,160,745,237,479,39,99,56,1503,158,916,651,1064,166,635,19,553,51,79,155,85,1196,142,108,325  
     ,135,28,422,1032,1018,128,787,1704,307,854,6,896,902)


LLL=function (par) {

  integrand1 <- function(x){ (x-s1[i]+1)*dgamma(x, shape=par[1], rate=par[2]) }
  integrand2 <- function(x){ (-x+s1[i]+1)*dgamma(x, shape=par[1],rate=par[2]) }



  likelihood = vector() 

  for(i in 1:length(s1)) {likelihood[i] = 
    log( integrate(integrand1,lower=s1[i]-1,upper=s1[i])$value+ integrate(integrand2,lower=s1[i],upper=s1[i]+1)$value )  
  }

  like= -sum(likelihood)
  return(like)

}




optim(par=c(0.1,0.1),LLL,method="L-BFGS-B", lower=c(0,0))

Thanks for your help.

Best,

YM

Enquirer: Y. Ma

||

Solution #1:

The objective function evaluated at the lower bounds of the parameters you provided is infinity.

LLL(c(0,0))
# [1] Inf

That’s why L-BFGS-B fails. Try a different lower bound, e.g., c(0.001,0.001) and you will get a solution.

optim(par=c(0.1,0.1),LLL,method="L-BFGS-B", lower=c(0.001,0.001))

$par
[1] 0.6865841 0.0010000

$value
[1] 369.5532

$counts
function gradient 
      14       14 

$convergence
[1] 0

$message
[1] "CONVERGENCE: REL_REDUCTION_OF_F <= FACTR*EPSMCH"

To get the 95% confidence intervals for the parameters try this:

res <- optim(par=c(0.1,0.1),LLL,method="L-BFGS-B", lower=c(0.005,0.005), hessian=TRUE)
n <- length(s1)
res$par # solution
# [1] 1.900928 0.005000
res$par - 1.96*sqrt(diag(solve(res$hessian)))/n # lower limit for 95% confint
# [1] 1.888152372 0.004963286
res$par + 1.96*sqrt(diag(solve(res$hessian)))/n # upper limit for 95% confint
# [1] 1.913703040 0.005036714

refer to this article: http://www.ms.uky.edu/~mai/sta321/MLEexample.pdf

Respondent: Sandipan Dey

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy