Reputation: 451
I would like to use the mle2 function to produce mles for weibull shape and scale parameters. I have written the following code, but got the error:
So which component is NULL and I should change to numeric? Is there any other problems with my code to obtain the mles?
x2<- rweibull(n, shape = 1, scale = 1.5)
library(bbmle)
loglik2 <- function(theta, x){
shape<- theta[1]
scale<- theta[2]
K<- length(theta)
n<- length(x2)
out<- rep(0,K)
for(k in 1:K){
out[k] <- sum(dweibull(x2, shape, scale, log=TRUE))
}
return(out)
}
theta.start<- c(1, 1.4)
(mod <- mle2(loglik2,start=list(theta.start),data=list(x2)))
Error in validObject(.Object) :
invalid class “mle2” object: invalid object for slot "fullcoef" in class "mle2": got class "NULL", should be or extend class "numeric"
Upvotes: 1
Views: 287
Reputation: 25854
Edit following Ben Bolkers comments below:
You can pass the parameters individually rather than as a vector or
you can pass a named vector as input instead: see the vecpar
argument in the docs (and use parnames(nllfun) <- ...
on your negative log-likelihood function).
Passing individual parameters:
# some example data
library(bbmle)
set.seed(1)
n = 1000
x2 = rweibull(n, shape = 1, scale = 1.5)
Rewrite the likelihood function to return the minus LL
loglik2 = function(shape, scale, x)
-sum(dweibull(x, shape=shape, scale=scale, log=TRUE))
Estimate: naming the start parameters (also set lower parameters limits to avoid warnings)
mle2(loglik2, start=list(shape=1, scale=1),
method="L-BFGS-B",lower=list(shape=0, scale=0),
data=list(x=x2))
#Coefficients:
# shape scale
#1.007049 1.485067
# you can also use the formula notation
mle2(x~dweibull(shape=shape, scale=scale),
start=list(shape=1, scale=1),
method="L-BFGS-B",lower=list(shape=0, scale=0),
data=list(x=x2))
Passing a named vector for the parameters:
Also note in this example that the parameters are forced to be greater than zero by using a log link. From Ben's comment "I would probably recommend a log-link rather than box constraints" -- this is instead of using the lower
optimisation parameter in the above example.
loglik2 = function(theta, x)
-sum(dweibull(x, shape=exp(theta[1]), scale=exp(theta[2]), log=TRUE))
# set the parameter names & set `vecpar` to TRUE
parnames(loglik2) = c("shape", "scale")
m = mle2(loglik2,
start=list(shape=0, scale=0),
data=list(x=x2), vecpar=TRUE)
exp(coef(m)) # exponentiate to get coefficients
# or the formula notation
mle2(x~dweibull(shape=exp(logshape),scale=exp(logscale)),
start=list(logshape=0, logscale=0),
data=list(x=x2))
A couple of comments on your code; from ?bblme
help page:
"Note that the minuslogl function should return the negative log-likelihood" which yours didn't, and the start
parameters should be a named list.
Upvotes: 2