[英]R optimise log-likelihood
I have a function that takes in lambda and a data sample, and finds the corresponding log-likelihood value for each data point:我有一个函数接受 lambda 和一个数据样本,并为每个数据点找到相应的对数似然值:
data <- rpois(n=25, lambda=4)
generateLogLikelihood <- function(lambda, y){
return(dpois(y, lambda, log=TRUE))
}
LogLikelihood = generateLogLikelihood (4,data)
LogLikelihood
I'm asking for a solution to fit this requirement:我要求一个解决方案来满足这个要求:
I need to use the optimise function to return the value of lambda which maximises the log-likelihood for the given data sample, but I'm getting stuck (this is my first attempt at using optimise).我需要使用优化函数来返回 lambda 的值,该值最大化给定数据样本的对数似然,但我被卡住了(这是我第一次尝试使用优化)。 I need to adapt the function to only take 'data' as an input.
我需要调整函数以仅将“数据”作为输入。
Where I'm getting stuck: I'm not sure how/when to apply optimise... given the requirement that my function only takes one input (the data - now called newdata), do I need to optimise outside of the function (but my function requires lambda values), so I'm not sure how to do this.我陷入困境的地方:我不确定如何/何时应用优化...考虑到我的函数只接受一个输入(数据 - 现在称为 newdata)的要求,我是否需要在函数之外进行优化(但我的函数需要 lambda 值),所以我不知道该怎么做。
My current code, which represents 2 separate parts that I don't know how to combine (or may be entirely wrong), is below:我当前的代码,代表我不知道如何组合(或可能完全错误)的 2 个独立部分,如下所示:
newdata <- c(23,16,18,14,19,20,12,15,15,21)
newlambdas <- seq(min(newdata),max(newdata),0.5)
generateLogLikelihoodNew <- function(y){
return(dpois(y, lambda, log=TRUE))
}
LogLikelihood = optimise(generateLogLikelihoodNew,newdata,lower = min(newlambdas), upper = max(newlambdas), maximum = TRUE)
LogLikelihood
If you only want to check which of the provided lambda's returns the best fit you can do如果您只想检查提供的 lambda 返回中的哪一个最适合您
generateLogLikelihoodNew <- function(y){
-sum(dpois(newdata, y, log=TRUE))
}
which.min(lapply(newlambdas,generateLogLikelihoodNew))
If however you want to find such value of lambda then you do not need to provide a lambda sequence vector但是,如果您想找到这样的 lambda 值,则不需要提供 lambda 序列向量
optimise(
function(x){-sum(dpois(newdata,x,log=TRUE))},
c(0,100)
)
$minimum
[1] 17.3
$objective
[1] 26.53437
There are several problems here:这里有几个问题:
Thus we have:因此我们有:
LL <- function(lambda, y) sum(dpois(y, lambda, log = TRUE))
optimize(LL, range(newdata), y = newdata, maximum = TRUE)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.