EM算法中的错误消息,用于估计比例参数

时间:2018-10-11 09:53:27

标签: r

这是我的EM算法代码,用于估算圆形分布的比例参数。我首先从二元正态模拟数据开始,然后转换为角度以获得圆形分布。函数中写入的scale参数为(varrr)。相应的估计值为(EMest2)。

library(OpenMx) ## to use vec2diag command
library (MASS)  ## Simulate from a Multivariate Normal Distribution
n=10 # sample size
eps=10^-8#stopping value
mu=c(1,0.9425) # true values of the mean vector of bivariate normal 
variables
var.1 =1 # sigma.1.squared for first normal variable
var.2=1#sigma.2.squared of second normal variable
cov.1.2=0 # covariance between the two normal variables
var.cov<-matrix(c(var.1,cov.1.2,cov.1.2,var.2),nrow=2,ncol=2,byrow=T)#variance covariance matrix of the bivariate normal random variables    
y= mvrnorm(n, mu, var.cov)#generating the bivariate normal random variables
theta.rad=rep(NA,times=n)
  for (ii in 1:n){
    if (y[ii,1] > 0 & y[ii,2]>=0) {theta.rad[ii]=atan(y[ii,2]/y[ii,1])}
    else if (y[ii,1] < 0) {theta.rad[ii]=(atan(y[ii,2]/y[ii,1]))+pi}
    else if (y[ii,1] > 0 & y[ii,2]<0) {theta.rad[ii]=atan(y[ii,2]/y[ii,1])+2*pi}
    else if (y[ii,1] == 0 & y[ii,2]>0) {theta.rad[ii]=pi/2}
    else if (y[ii,1] ==0 & y[ii,2]<0) {theta.rad[ii]=3*pi/2}
  }# calculating the angles
   u=cbind(cos(theta.rad),sin(theta.rad)) #constructing the main matrix
  var.1.initial=var(y[,1])
  EM.est=function(uu,varrr){
    tta=as.vector(1/sqrt(varrr))
    tt=tta*uu%*%mu
    phidash=(pnorm(tt)/((tt*pnorm(tt))+dnorm(tt)))+tt  
    m=vec2diag(phidash)
    aa=2*varrr-((sum(m%*%tt))/n)+(t(mu)%*%mu)
    return(aa)
  }
  w=0      ###counter 
  diff=1
  while(diff>eps){ 
    EMest1=var.1.initial
    EMest2=EM.est(u,EMest1)
    var.1.initial=EMest2
    diff=max(abs((EMest2-EMest1)/EMest1))
    w=w+1
  }
  print(EMest2)

每次运行程序时,都会收到如下错误消息:Error in while (diff > eps) {:missing value where TRUE/FALSE needed并且估计值(EMest2)为无穷大。 实际上,我不知道编写的程序有什么错误。

0 个答案:

没有答案