使用优化使r中的可能性最大化时出错 [英] Error in using optim to maximise the likelihood in r
本文介绍了使用优化使r中的可能性最大化时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
因此,我具有以下功能:
So, I have these functions:
funk1 <- function(a,x,l,r) {
x^2*exp(-(l*(1-exp(-r*a))/r))}
funk2 <- function(x,l,r) {
sapply(x, function (s) {
integrate(funk1, lower = 0, upper = s, x=s, l=l, r=r)$value })}
用来解释y中的数据
z <- data.frame(ts = 1:100,
y = funk2(1:100, l = 1, r = 1) + rpois(100, 1:100))
我希望使用优化来最大化可能性,所以我定义了可能性函数:
I wish to use optim to maximise the likelihood, so I defined a likelihood function:
LL_funk <- function(l,r) {
n=nrow(z)
R = sum((funk2(ts,l,r) - y)^2)
logl = -((n/2)*log(R))
return(-logl)
}
我尝试使用优化来适应
fit <- optim(par=c(0.5,0.5), fn= LL_funk, method="Nelder-Mead")
但是我得到一个错误:
Error in integrate(funk1, lower = 0, upper = s, x = s, l = l, r = r) :
a limit is missing
我不确定为什么吗?我可以运行将funk2(x,l,r)拟合为y的nls
I am not sure why? I could run nls fitting funk2(x,l,r) to y
nls(y ~ funk2(ts,l,r), data = z, start = list(l = 0.5, r = 0.5))
这意味着funk2正在运行.我想这是我设计的LL功能的问题,我无法弄清楚!!请帮忙!
That means funk2 is working. I guess its the problem with LL function that I have designed, which I cant figure out!! Please Help!
推荐答案
是的!您的功能存在两个问题.这对我有用:
Yup! There were two problems with your function. This worked for me:
LL_funk <- function(params) {
n=nrow(z)
l = params[1]
r = params[2]
R = sum((funk2(z$ts,l,r) - z$y)^2)
logl = -((n/2)*log(R))
return(-logl)
}
以前的问题:
-
LL_funk
仅接受1个参数,这是参数的向量. - 在分配
R
的LHS中,ts
和y
实际上没有引用数据集中的列.
LL_funk
only takes 1 argument, which is the vector of parameters.- In LHS of the assignment of
R
,ts
andy
were not actually referring to columns in your dataset.
这篇关于使用优化使r中的可能性最大化时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文