2013-08-24 130 views
1

所以我一直在研究一個腳本來計算基於4個參數的對數似然性,並將它們放入一個特定的log-lik函數中。該腳本沒問題。問題在於優化它 - 每當我嘗試時,它都會說找不到對象(對於所討論的參數)。爲了簡單起見,我將只使用一個更簡單的腳本,它在使用optim()函數時給我一個相同的錯誤。有趣的是,我實際上是直接從「MLE in R」教程中取出這個腳本。我甚至沒有重寫它,我從字面上複製/粘貼PDF。這裏是教程中的似然函數:R函數optim():找不到對象

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 

這讓我立刻意識到這是談論如何ÿ是函數中的一個特定對象,不是全局對象,但同時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

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 

注:請參閱「An Introduction to R」來了解功能的基礎知識。

更新:按批語:你可以嘗試做,看看會發生什麼:

y<-X%*%theta.true++ rnorm(100) 
Error in X %*% theta.true : non-conformable arguments 
+0

好是有道理的。但是,事情是,爲什麼如果y只依賴於前兩個(如theta.true [1:2]部分所見),爲什麼用3個值定義theta.true?對於我的特定代碼,只需輸入一個包含4個值的向量w即可輸出對數似然值。我想最大化這些,但我不知道如何做到這一點。 – saltthehash

+0

這裏你正在做矩陣乘法,所以它需要服從矩陣乘法規則。查看上面的更新。 – Metrics