在R中编写适当的正常对数似然 [英] Writing a proper normal log-likelihood in R
问题描述
我对以下型号有疑问
我想对μ进行推断的位置而tau,u是已知向量,x是数据向量.对数似然是
where I want to make inference on μ and tau, u is a known vector and x is the data vector. The log-likelihood is
我在用R写对数似然时遇到问题.
I have a problem writing a log-likelihood in R.
x <- c(3.3569,1.9247,3.6156,1.8446,2.2196,6.8194,2.0820,4.1293,0.3609,2.6197)
mu <- seq(0,10,length=1000)
normal.lik1<-function(theta,x){
u <- c(1,3,0.5,0.2,2,1.7,0.4,1.2,1.1,0.7)
mu<-theta[1]
tau<-theta[2]
n<-length(x)
logl <- sapply(c(mu,tau),function(mu,tau){logl<- -0.5*n*log(2*pi) -0.5*n*log(tau^2+u^2)- (1/(2*tau^2+u^2))*sum((x-mu)^2) } )
return(logl)
}
#test if it works for mu=1, tau=2
head(normal.lik1(c(1,2),x))
#Does not work..
我希望能够为mu插入向量,并以固定的tau值(例如2)将其绘制在mu上.我还希望使用optim函数找出tau和mu的MLE.我试过了:
I want to be able to plug in the vector for mu and plot it over mu for a fixed value of tau, say 2. I also want to find out the MLE's of tau and mu using the optim function. I tried:
theta.hat<-optim(c(1,1),loglike2,control=list(fnscale=-1),x=x,,method="BFGS")$par
但是它不起作用.关于如何写可能性的任何建议?
But it does not work.. Any suggestions to how I can write the likelihood?
推荐答案
首先,正如您对问题的评论中提到的那样,无需使用sapply()
.您可以简单地使用sum()
–就像logLikelihood的公式一样.
First, as has been mentioned in the comments to your question, there is no need to use sapply()
. You can simply use sum()
– just as in the formula of the logLikelihood.
我在normal.lik1()
中更改了此部分,并将分配给logl
的表达式乘以负1,以便该函数计算负对数似然.您想在theta上搜索 minimum ,因为该函数返回正值.
I changed this part in normal.lik1()
and multiplied the expression that is assigned to logl
by minus 1 such that the function computes the minus logLikelihood. You want to search for the minimum over theta since the function returns positive values.
x < c(3.3569,1.9247,3.6156,1.8446,2.2196,6.8194,2.0820,4.1293,0.3609,2.6197)
u <- c(1,3,0.5,0.2,2,1.7,0.4,1.2,1.1,0.7)
normal.lik1 <- function(theta,x,u){
mu <- theta[1]
tau <- theta[2]
n <- length(x)
logl <- - n/2 * log(2*pi) - 1/2 * sum(log(tau^2+u^2)) - 1/2 * sum((x-mu)^2/(tau^2+u^2))
return(-logl)
}
例如,可以使用nlm()
完成此操作
This can be done using nlm()
, for example
nlm(normal.lik1, c(0,1), hessian=TRUE, x=x,u=u)$estimate
其中c(0,1)
是算法的起始值.
要绘制一系列值mu
和某些固定的tau
的logLikelihood,可以调整函数,使mu
和tau
是单独的数字参数.
To plot the logLikelihood for a range of values of mu
and some fixed tau
you can adjust the function such that mu
and tau
are separate numeric arguments.
normal.lik2 <- function(mu,tau,x,u){
n <- length(x)
logl <- - n/2 * log(2*pi) - 1/2 * sum(log(tau^2+u^2)) - 1/2 * sum((x-mu)^2/(tau^2+u^2))
return(logl)
}
然后为mu
定义一些范围,计算对数似然并使用plot()
.
Then define some range for mu
, compute the loglikelihood and use plot()
.
range.mu <- seq(-10,20,0.1)
loglik <- sapply(range.mu, function(m) normal.lik2(mu=m,tau=2,x=x,u=u))
plot(range.mu, loglik, type = "l")
我敢肯定有更多优雅的方法可以做到这一点,但这可以解决问题.
I'm sure there are more elegant ways to do this but this does the trick.
这篇关于在R中编写适当的正常对数似然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!