1

因此,我一直在编写一个脚本来根据具体的 4 个参数计算对数似然性,并将它们放入特定的 log-like 函数中。那个剧本不错 问题是优化它 - 每当我尝试时,它都会说找不到对象(对于有问题的参数)。为了简单起见,我将只使用一个更简单的脚本,当我使用 optim() 函数时,它会给我一个相同的错误。有趣的是,我实际上直接从“ R 中的 MLE ”教程中提取了这个脚本。我什至没有重写它,我从 PDF 中复制/粘贴了它。这是教程中的似然函数:

normal.lik1<-function(theta,y){
mu<-theta[1]
sigma2<-theta[2]
n<-nrow(y)
logl<- -.5*n*log(2*pi) -.5*n*log(sigma2) - (1/(2*sigma2))*sum((y-mu)**2)
return(-logl)
}

这个功能本身就可以很好地工作。但是,当我尝试优化它时,我收到一条错误消息,指出找不到对象,该对象是我要优化的参数。下一行也是从教程中复制/粘贴的:

optim(c(0,1),normal.lik1,y=y,method="BFGS")

当我运行这一行时,R 给了我以下错误:

Error in nrow(y) : object 'y' not found

这立即让我意识到它是在谈论 y 是如何专门在函数中的对象,而不是全局对象,但同时 optim() 应该正在评估该函数!所以,我不知道为什么它表现得像 y 不存在。

编辑:

现在我明白它是如何工作的了。但我的总体目标仍然存在问题。为了更深入地了解它,这是我现在正在使用的代码:

w.loglik<-function(w){ 
  # w is just a vector with 4 values: two means (w(1) and w(2) below) and the position
  # of two decision bounds (w(3) and w(4))

  #create data matrix
  data<-matrix(c(140,36,34,40,89,91,4,66,85,5,90,70,20,59,8,163),nrow=4,ncol=4,byrow=TRUE)  

  # get means
  means<-matrix(0,4,2,byrow=TRUE)
  means[2,1]<-w[1]
  means[3,2]<-w[2]
  means[4,1]<-w[1]
  means[4,2]<-w[2]

  # get covariance matrices (fix variances to 1)
  covmat<-list()
  covmat[[1]]<-diag(2)
  covmat[[2]]<-diag(2)
  covmat[[3]]<-diag(2)
  covmat[[4]]<-diag(2)

  # get decision bound parameters
  b<-diag(2)
  c<-matrix(c(w[3],w[4]),2,1)

  L<-matrixloglik(data,means,covmat,b,c)
  return(L)
}

matrixloglik 只是一个输出对数似然的函数(它运行良好)。如何运行 optim() 以优化向量 w?

4

1 回答 1

4

y是您的数据,而您尚未在代码中指定它。因此错误 Error in nrow(y) : object 'y' not found

如果您使用同一个 pdf 文件的示例 5 并使用如下定义的数据 y,您将得到一个输出:

X<-cbind(1,runif(100))
theta.true<-c(2,3,1)
y<-X%*%theta.true[1:2] + rnorm(100)

> optim(c(0,1),normal.lik1,y=y,method="BFGS")
$par
[1] 3.507266 1.980783

$value
[1] 176.0685

$counts
function gradient 
      49       23 

$convergence
[1] 0

$message
NULL

Warning messages:
1: In log(sigma2) : NaNs produced
2: In log(sigma2) : NaNs produced
3: In log(sigma2) : NaNs produced

注意:请参阅“ R 简介”以了解函数的基础知识。

更新:根据评论:您可以尝试做,看看会发生什么:

y<-X%*%theta.true++ rnorm(100)
Error in X %*% theta.true : non-conformable arguments
于 2013-08-24T17:56:06.657 回答