EM问题涉及3个硬币

时间:2011-04-16 01:03:36

标签: algorithm r

我正在使用EM算法研究估算问题。问题如下:

你有3个硬币,分别是头部P1,P2和P3的概率。你翻转硬币1.如果硬币1 = H,那么你翻硬币2;如果硬币1 = T,那么你翻转硬币3.你只记录硬币2或3是头还是尾,而不是硬币被翻转。所以观察结果是头部和尾部的串,但没有别的。问题是估计P1,P2和P3。

我的R代码如下所示。它不起作用,我无法弄清楚原因。任何想法都会受到赞赏,因为我认为这是一个非常狡猾的问题。

###############
#simulate data
p1<-.8
p2<-.8
p3<-.3
tosses<-1000
rbinom(tosses,size=1,prob=p1)->coin.1
pv<-rep(p3,tosses)
pv[coin.1==1]<-p2
#face now contains the probabilities of a head
rbinom(tosses,size=1,prob=pv)->face
rm(list=(ls()[ls()!="face"])) 
#face is all you get to see!

################
#e-step
e.step<-function(x,theta.old) {
    fun<-function(p,theta.old,x) {
        theta.old[1]->p1
        theta.old[2]->p2
        theta.old[3]->p3
        log(p1*p2^x*(1-p2)^(1-x))*(x*p1*p2+(1-x)*p1*(1-p2))->tmp1 #this is the first part of the expectation
        log((1-p1)*p3^x*(1-p3)^(1-x))*(x*(1-p1)*p3+(1-x)*(1-p1)*(1-p3))->tmp2 #this is the second
        mean(tmp1+tmp2)
    }
    return(fun)
}
#m-step
m.step<-function(fun,theta.old,face) {
    nlminb(start=runif(3),objective=fun,theta.old=theta.old,x=face,lower=rep(.01,3),upper=rep(.99,3))$par
}

#initial estimates
length(face)->N
iter<-200
theta<-matrix(NA,iter,3)
c(.5,.5,.5)->theta[1,]
for (i in 2:iter) {
    e.step(face,theta[i-1,])->tmp
    m.step(tmp,theta[i-1,],face)->theta[i,]
    print(c(i,theta[i,]))
    if (max(abs(theta[i,]-theta[i-1,]))<.005) break("conv")
}
#note that this thing isn't going anywhere!

1 个答案:

答案 0 :(得分:3)

您无法单独估算P1,P2和P3。唯一有用的信息是记录头的比例和翻转的总数(每组翻转是独立的,因此顺序无关紧要)。这就像试图解决三个未知数的一个方程,而且无法完成。

记录头部的概率为P1*P2 + (1-P1)*P3,在您的示例中为0.7

和尾部是一个减去那个,即你的例子中的P1*(1-P2) + (1-P1)*(1-P3) 0.3

这是一个简单的模拟器

#simulate data
sim <- function(tosses, p1, p2, p3) { 
          coin.1   <- rbinom(tosses, size=1, prob=p1)
          coin.2   <- rbinom(tosses, size=1, prob=p2)
          coin.3   <- rbinom(tosses, size=1, prob=p3)
          ifelse(coin.1 == 1, coin.2, coin.3) # returned 
    }

以下是所有产生0.7(有一些随机波动)的插图

> mean(sim(100000, 0.8, 0.8, 0.3))
[1] 0.70172
> mean(sim(100000, 0.2, 0.3, 0.8))
[1] 0.69864
> mean(sim(100000, 0.5, 1.0, 0.4))
[1] 0.69795
> mean(sim(100000, 0.3, 0.7, 0.7))
[1] 0.69892
> mean(sim(100000, 0.5, 0.5, 0.9))
[1] 0.70054
> mean(sim(100000, 0.6, 0.9, 0.4))
[1] 0.70201

随后你无能为力。