为什么混合模型的MLE等于flexmix?

时间:2019-07-06 00:23:03

标签: r statistics probability mle

每个人。我想在mle中为有限混合模型编写一个R,但是模型估计的系数与包flexmix估计的系数不同。 我想知道您是否可以指出我的错误。

我的代码如下:

#prepare data
slope1 <- -.3;slope2 <- .3;slope3 <- 1.8; slope4 <- 0.5;intercept1 <- 1.5    
age <- sample(seq(18,60,len=401), 200) 
grade <- sample(seq(0,100,len=401), 200) 
not_smsa <- sample(seq(-2,2,len=401), 200) 
unemployment <- rnorm(200,mean=0,sd=1)
wage <- intercept1 + slope1*age +slope2*grade + slope3*not_smsa + rnorm(length(age),0,.15) 
y <- wage 
X  <- cbind(1, age , grade , not_smsa)
mydata <- cbind.data.frame(X,y)
anso <- lm(wage ~ age + grade + not_smsa, 
           data = mydata)
vi <- c(coef(anso),0.01,0.02,0.03,0.04,0.1)
#function
fmm <- function(beta) {

  mu1 <- c(X %*% beta[1:4])
  mu2 <- c(X %*% beta[5:8])

  p1 <- 1 / (1 + exp(-beta[9]))
  p2 <- 1-p1

  llk <- p1*dnorm(y,mu1)+p2*dnorm(y,mu2)
  -sum(log(llk),na.rm=T)
}

fit <- optim(vi,fmm , method = "BFGS", control = list(maxit=50000), hessian = TRUE)
fit$par

library(flexmix)
flexfit <- flexmix(wage ~ age + grade + not_smsa, data = mydata, k = 2)
flexfit$par
c1 <- parameters(flexfit,component=1)
c2 <- parameters(flexfit, component=2)

感谢您的耐心配合,我们期待您的反馈

0 个答案:

没有答案