我正在尝试在R中实现本地级别模型 - 作为参考,请参阅http://personal.vu.nl/s.j.koopman/documents/LLIntro2011.pdf。我已经实现了以下代码。对于任何输入数据mydata
,最大似然估计为sigma_n和sigma_e提供相同的数字。我不知道问题的根源是什么。
locallevel <- function(x,data) {
sigma_e <- exp(x[1])
sigma_n <- exp(x[2])
len <- length(data)
y <- matrix(data,nrow=len,ncol=1)
a <- matrix(0,nrow=len,ncol=1)
v <- matrix(0,nrow=len,ncol=1)
F <- matrix(0,nrow=len,ncol=1)
P <- matrix(0,nrow=len,ncol=1)
K <- matrix(0,nrow=len,ncol=1)
for (i in 1:len) {
if(i==1) {
a[i]=y[i]
P[i]=sigma_e+sigma_n
F[i]=P[i]+sigma_e
v[i]=y[i]-a[i]
} else {
a[i]=a[i-1]+((P[i-1])/(P[i-1]+sigma_e))*(y[i-1]-a[i-1])
P[i]=((P[i-1]*sigma_e)/(P[i-1]+sigma_e))+sigma_n
F[i]=P[i]+sigma_e
v[i]=y[i]-a[i]
}
}
loglik = -(len/2)*log(2*pi)-0.5*sum(log(abs(F))+((v^2)/F))
loglik = -loglik
}
mlest<-optim(c(log(var(mydata)),log(var(mydata))),function(x) {locallevel(mydata,x)})